diff --git a/Content.Client/AI/ClientAiDebugSystem.cs b/Content.Client/AI/ClientAiDebugSystem.cs index fb3a657c4b..81a81b4fe9 100644 --- a/Content.Client/AI/ClientAiDebugSystem.cs +++ b/Content.Client/AI/ClientAiDebugSystem.cs @@ -18,7 +18,7 @@ namespace Content.Client.AI [Dependency] private readonly IEyeManager _eyeManager = default!; private AiDebugMode _tooltips = AiDebugMode.None; - private readonly Dictionary _aiBoxes = new(); + private readonly Dictionary _aiBoxes = new(); public override void Update(float frameTime) { @@ -37,22 +37,22 @@ namespace Content.Client.AI return; } - var deletedEntities = new List(0); + var deletedEntities = new List(0); foreach (var (entity, panel) in _aiBoxes) { - if (entity.Deleted) + if (Deleted(entity)) { deletedEntities.Add(entity); continue; } - if (!_eyeManager.GetWorldViewport().Contains(entity.Transform.WorldPosition)) + if (!_eyeManager.GetWorldViewport().Contains(EntityManager.GetComponent(entity).WorldPosition)) { panel.Visible = false; continue; } - var (x, y) = _eyeManager.CoordinatesToScreen(entity.Transform.Coordinates).Position; + var (x, y) = _eyeManager.CoordinatesToScreen(EntityManager.GetComponent(entity).Coordinates).Position; var offsetPosition = new Vector2(x - panel.Width / 2, y - panel.Height - 50f); panel.Visible = true; @@ -78,8 +78,7 @@ namespace Content.Client.AI if ((_tooltips & AiDebugMode.Thonk) != 0) { // I guess if it's out of range we don't know about it? - var entityManager = IoCManager.Resolve(); - var entity = entityManager.GetEntity(message.EntityUid); + var entity = message.EntityUid; TryCreatePanel(entity); // Probably shouldn't access by index but it's a debugging tool so eh @@ -95,8 +94,7 @@ namespace Content.Client.AI { if ((_tooltips & AiDebugMode.Paths) != 0) { - var entityManager = IoCManager.Resolve(); - var entity = entityManager.GetEntity(message.EntityUid); + var entity = message.EntityUid; TryCreatePanel(entity); var label = (Label) _aiBoxes[entity].GetChild(0).GetChild(1); @@ -110,8 +108,7 @@ namespace Content.Client.AI { if ((_tooltips & AiDebugMode.Paths) != 0) { - var entityManager = IoCManager.Resolve(); - var entity = entityManager.GetEntity(message.EntityUid); + var entity = message.EntityUid; TryCreatePanel(entity); var label = (Label) _aiBoxes[entity].GetChild(0).GetChild(1); @@ -154,7 +151,7 @@ namespace Content.Client.AI } } - private bool TryCreatePanel(IEntity entity) + private bool TryCreatePanel(EntityUid entity) { if (!_aiBoxes.ContainsKey(entity)) { diff --git a/Content.Client/AI/ClientPathfindingDebugSystem.cs b/Content.Client/AI/ClientPathfindingDebugSystem.cs index f81918ad9f..1068bcae54 100644 --- a/Content.Client/AI/ClientPathfindingDebugSystem.cs +++ b/Content.Client/AI/ClientPathfindingDebugSystem.cs @@ -18,6 +18,12 @@ namespace Content.Client.AI #if DEBUG public class ClientPathfindingDebugSystem : EntitySystem { + [Dependency] private readonly IOverlayManager _overlayManager = default!; + [Dependency] private readonly IPrototypeManager _prototypeManager = default!; + [Dependency] private readonly IEyeManager _eyeManager = default!; + [Dependency] private readonly IPlayerManager _playerManager = default!; + + private PathfindingDebugMode _modes = PathfindingDebugMode.None; private float _routeDuration = 4.0f; // How long before we remove a route from the overlay private DebugPathfindingOverlay? _overlay; @@ -91,7 +97,7 @@ namespace Content.Client.AI } var overlayManager = IoCManager.Resolve(); - _overlay = new DebugPathfindingOverlay {Modes = _modes}; + _overlay = new DebugPathfindingOverlay(EntityManager, _eyeManager, _playerManager, _prototypeManager) {Modes = _modes}; overlayManager.AddOverlay(_overlay); return _overlay; @@ -179,6 +185,7 @@ namespace Content.Client.AI { private readonly IEyeManager _eyeManager; private readonly IPlayerManager _playerManager; + private readonly IEntityManager _entities; // TODO: Add a box like the debug one and show the most recent path stuff public override OverlaySpace Space => OverlaySpace.ScreenSpace; @@ -209,11 +216,12 @@ namespace Content.Client.AI public readonly List AStarRoutes = new(); public readonly List JpsRoutes = new(); - public DebugPathfindingOverlay() + public DebugPathfindingOverlay(IEntityManager entities, IEyeManager eyeManager, IPlayerManager playerManager, IPrototypeManager prototypeManager) { - _shader = IoCManager.Resolve().Index("unshaded").Instance(); - _eyeManager = IoCManager.Resolve(); - _playerManager = IoCManager.Resolve(); + _entities = entities; + _eyeManager = eyeManager; + _playerManager = playerManager; + _shader = prototypeManager.Index("unshaded").Instance(); } #region Graph @@ -286,8 +294,8 @@ namespace Content.Client.AI private void DrawCachedRegions(DrawingHandleScreen screenHandle, Box2 viewport) { - var attachedEntity = _playerManager.LocalPlayer?.ControlledEntity; - if (attachedEntity == null || !CachedRegions.TryGetValue(attachedEntity.Transform.GridID, out var entityRegions)) + var transform = _entities.GetComponentOrNull(_playerManager.LocalPlayer?.ControlledEntity); + if (transform == null || !CachedRegions.TryGetValue(transform.GridID, out var entityRegions)) { return; } @@ -305,7 +313,7 @@ namespace Content.Client.AI screenTile.X + 15.0f, screenTile.Y + 15.0f); - screenHandle.DrawRect(box, _cachedRegionColors[attachedEntity.Transform.GridID][region]); + screenHandle.DrawRect(box, _cachedRegionColors[transform.GridID][region]); } } } @@ -336,7 +344,8 @@ namespace Content.Client.AI private void DrawRegions(DrawingHandleScreen screenHandle, Box2 viewport) { var attachedEntity = _playerManager.LocalPlayer?.ControlledEntity; - if (attachedEntity == null || !Regions.TryGetValue(attachedEntity.Transform.GridID, out var entityRegions)) + if (!_entities.TryGetComponent(attachedEntity, out TransformComponent? transform) || + !Regions.TryGetValue(transform.GridID, out var entityRegions)) { return; } @@ -356,7 +365,7 @@ namespace Content.Client.AI screenTile.X + 15.0f, screenTile.Y + 15.0f); - screenHandle.DrawRect(box, _regionColors[attachedEntity.Transform.GridID][chunk][region]); + screenHandle.DrawRect(box, _regionColors[_entities.GetComponent(attachedEntity.Value).GridID][chunk][region]); } } } diff --git a/Content.Client/AME/Visualizers/AMEControllerVisualizer.cs b/Content.Client/AME/Visualizers/AMEControllerVisualizer.cs index 99243fdb37..d4c1a19427 100644 --- a/Content.Client/AME/Visualizers/AMEControllerVisualizer.cs +++ b/Content.Client/AME/Visualizers/AMEControllerVisualizer.cs @@ -1,6 +1,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.AME.SharedAMEControllerComponent; namespace Content.Client.AME.Visualizers @@ -8,10 +9,10 @@ namespace Content.Client.AME.Visualizers [UsedImplicitly] public class AMEControllerVisualizer : AppearanceVisualizer { - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapSet(Layers.Display, sprite.AddLayerState("control_on")); sprite.LayerSetVisible(Layers.Display, false); @@ -20,7 +21,7 @@ namespace Content.Client.AME.Visualizers public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (component.TryGetData(AMEControllerVisuals.DisplayState, out var state)) { switch (state) diff --git a/Content.Client/AME/Visualizers/AMEVisualizer.cs b/Content.Client/AME/Visualizers/AMEVisualizer.cs index eaf691cba0..98910b0b6d 100644 --- a/Content.Client/AME/Visualizers/AMEVisualizer.cs +++ b/Content.Client/AME/Visualizers/AMEVisualizer.cs @@ -1,6 +1,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.AME.SharedAMEShieldComponent; namespace Content.Client.AME.Visualizers @@ -8,10 +9,10 @@ namespace Content.Client.AME.Visualizers [UsedImplicitly] public class AMEVisualizer : AppearanceVisualizer { - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapSet(Layers.Core, sprite.AddLayerState("core")); sprite.LayerSetVisible(Layers.Core, false); sprite.LayerMapSet(Layers.CoreState, sprite.AddLayerState("core_weak")); @@ -21,7 +22,7 @@ namespace Content.Client.AME.Visualizers public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (component.TryGetData(AMEShieldVisuals.Core, out var core)) { if (core == "isCore") diff --git a/Content.Client/Access/UI/IdCardConsoleBoundUserInterface.cs b/Content.Client/Access/UI/IdCardConsoleBoundUserInterface.cs index e9e8a01d97..819ac7f442 100644 --- a/Content.Client/Access/UI/IdCardConsoleBoundUserInterface.cs +++ b/Content.Client/Access/UI/IdCardConsoleBoundUserInterface.cs @@ -11,6 +11,7 @@ namespace Content.Client.Access.UI public class IdCardConsoleBoundUserInterface : BoundUserInterface { [Dependency] private readonly IPrototypeManager _prototypeManager = default!; + [Dependency] private readonly IEntityManager _entityManager = default!; public IdCardConsoleBoundUserInterface(ClientUserInterfaceComponent owner, object uiKey) : base(owner, uiKey) { @@ -22,7 +23,7 @@ namespace Content.Client.Access.UI { base.Open(); - _window = new IdCardConsoleWindow(this, _prototypeManager) {Title = Owner.Owner.Name}; + _window = new IdCardConsoleWindow(this, _prototypeManager) {Title = _entityManager.GetComponent(Owner.Owner).EntityName}; _window.OnClose += Close; _window.OpenCentered(); } diff --git a/Content.Client/Actions/ActionsSystem.cs b/Content.Client/Actions/ActionsSystem.cs index 5c64a51d66..e56112b2c5 100644 --- a/Content.Client/Actions/ActionsSystem.cs +++ b/Content.Client/Actions/ActionsSystem.cs @@ -85,7 +85,7 @@ namespace Content.Client.Actions { var playerEntity = _playerManager.LocalPlayer?.ControlledEntity; if (playerEntity == null || - !playerEntity.TryGetComponent(out var actionsComponent)) return false; + !EntityManager.TryGetComponent(playerEntity.Value, out var actionsComponent)) return false; actionsComponent.HandleHotbarKeybind(slot, args); return true; @@ -98,8 +98,7 @@ namespace Content.Client.Actions return new((in PointerInputCmdHandler.PointerInputCmdArgs args) => { var playerEntity = _playerManager.LocalPlayer?.ControlledEntity; - if (playerEntity == null || - !playerEntity.TryGetComponent( out var actionsComponent)) return false; + if (!EntityManager.TryGetComponent(playerEntity, out var actionsComponent)) return false; actionsComponent.HandleChangeHotbarKeybind(hotbar, args); return true; @@ -110,8 +109,7 @@ namespace Content.Client.Actions private bool TargetingOnUse(in PointerInputCmdHandler.PointerInputCmdArgs args) { var playerEntity = _playerManager.LocalPlayer?.ControlledEntity; - if (playerEntity == null || - !playerEntity.TryGetComponent( out var actionsComponent)) return false; + if (!EntityManager.TryGetComponent(playerEntity, out var actionsComponent)) return false; return actionsComponent.TargetingOnUse(args); } @@ -119,8 +117,7 @@ namespace Content.Client.Actions private void ToggleActionsMenu() { var playerEntity = _playerManager.LocalPlayer?.ControlledEntity; - if (playerEntity == null || - !playerEntity.TryGetComponent( out var actionsComponent)) return; + if (!EntityManager.TryGetComponent(playerEntity, out var actionsComponent)) return; actionsComponent.ToggleActionsMenu(); } diff --git a/Content.Client/Actions/ClientActionsComponent.cs b/Content.Client/Actions/ClientActionsComponent.cs index 69858c3bb9..1032a63ae4 100644 --- a/Content.Client/Actions/ClientActionsComponent.cs +++ b/Content.Client/Actions/ClientActionsComponent.cs @@ -1,7 +1,5 @@ using Content.Client.Actions.Assignments; using Content.Client.Actions.UI; -using Content.Client.Hands; -using Content.Client.Inventory; using Content.Client.Items.Managers; using Content.Shared.Actions.Components; using Content.Shared.Actions.Prototypes; @@ -226,17 +224,17 @@ namespace Content.Client.Actions /// Highlights the item slot (inventory or hand) that contains this item /// /// - public void HighlightItemSlot(IEntity item) + public void HighlightItemSlot(EntityUid item) { StopHighlightingItemSlots(); - _highlightedEntity = item.Uid; - _itemSlotManager.HighlightEntity(item.Uid); + _highlightedEntity = item; + _itemSlotManager.HighlightEntity(item); } /// /// Stops highlighting any item slots we are currently highlighting. - /// + /// H public void StopHighlightingItemSlots() { if (_highlightedEntity == default) diff --git a/Content.Client/Actions/UI/ActionSlot.cs b/Content.Client/Actions/UI/ActionSlot.cs index 36702eddd9..b6fc2bb2c4 100644 --- a/Content.Client/Actions/UI/ActionSlot.cs +++ b/Content.Client/Actions/UI/ActionSlot.cs @@ -62,7 +62,7 @@ namespace Content.Client.Actions.UI /// Item the action is provided by, only valid if Action is an ItemActionPrototype. May be null /// if the item action is not yet tied to an item. /// - public IEntity? Item { get; private set; } + public EntityUid? Item { get; private set; } /// /// Whether the action in this slot should be shown as toggled on. Separate from Depressed. @@ -231,8 +231,8 @@ namespace Content.Client.Actions.UI { ActionPrototype actionPrototype => new ActionAttempt(actionPrototype), ItemActionPrototype itemActionPrototype => - (Item != null && Item.TryGetComponent(out var itemActions)) ? - new ItemActionAttempt(itemActionPrototype, Item, itemActions) : null, + (Item != null && IoCManager.Resolve().TryGetComponent(Item, out var itemActions)) ? + new ItemActionAttempt(itemActionPrototype, Item.Value, itemActions) : null, _ => null }; return attempt; @@ -246,7 +246,7 @@ namespace Content.Client.Actions.UI DrawModeChanged(); if (Action is not ItemActionPrototype) return; if (Item == null) return; - _actionsComponent.HighlightItemSlot(Item); + _actionsComponent.HighlightItemSlot(Item.Value); } protected override void MouseExited() @@ -376,7 +376,7 @@ namespace Content.Client.Actions.UI if (Action != null && Action == action) return; Action = action; - Item = null; + Item = default; _depressed = false; ToggledOn = false; ActionEnabled = actionEnabled; @@ -395,10 +395,10 @@ namespace Content.Client.Actions.UI public void Assign(ItemActionPrototype action) { // already assigned - if (Action != null && Action == action && Item == null) return; + if (Action != null && Action == action && Item == default) return; Action = action; - Item = null; + Item = default; _depressed = false; ToggledOn = false; ActionEnabled = false; @@ -415,7 +415,7 @@ namespace Content.Client.Actions.UI /// action to assign /// item the action is provided by /// whether action should initially appear enable or disabled - public void Assign(ItemActionPrototype action, IEntity item, bool actionEnabled) + public void Assign(ItemActionPrototype action, EntityUid item, bool actionEnabled) { // already assigned if (Action != null && Action == action && Item == item) return; @@ -439,7 +439,7 @@ namespace Content.Client.Actions.UI { if (!HasAssignment) return; Action = null; - Item = null; + Item = default; ToggledOn = false; _depressed = false; Cooldown = null; @@ -502,9 +502,9 @@ namespace Content.Client.Actions.UI SetActionIcon(Action.Icon.Frame0()); } - if (Item != null) + if (Item != default) { - SetItemIcon(Item.TryGetComponent(out var spriteComponent) ? spriteComponent : null); + SetItemIcon(IoCManager.Resolve().TryGetComponent(Item, out var spriteComponent) ? spriteComponent : null); } else { diff --git a/Content.Client/Actions/UI/ActionsUI.cs b/Content.Client/Actions/UI/ActionsUI.cs index 7544bece52..260a6656d0 100644 --- a/Content.Client/Actions/UI/ActionsUI.cs +++ b/Content.Client/Actions/UI/ActionsUI.cs @@ -378,10 +378,10 @@ namespace Content.Client.Actions.UI private void UpdateActionSlot(EntityUid item, ItemActionType itemActionType, ActionSlot actionSlot, ActionAssignment? assignedActionType) { - if (!_entityManager.TryGetEntity(item, out var itemEntity)) return; + if (!_entityManager.EntityExists(item)) return; if (_actionManager.TryGet(itemActionType, out var action)) { - actionSlot.Assign(action, itemEntity, true); + actionSlot.Assign(action, item, true); } else { @@ -420,7 +420,7 @@ namespace Content.Client.Actions.UI // if we are targeting with an action now on cooldown, stop targeting if we should if (SelectingTargetFor?.Action != null && SelectingTargetFor.Action == action && - SelectingTargetFor.Item == itemEntity && + SelectingTargetFor.Item == item && actionState.IsOnCooldown(_gameTiming) && action.DeselectOnCooldown) { StopTargeting(); diff --git a/Content.Client/Administration/AdminNameOverlay.cs b/Content.Client/Administration/AdminNameOverlay.cs index 7b84e17d5d..6cc37a3028 100644 --- a/Content.Client/Administration/AdminNameOverlay.cs +++ b/Content.Client/Administration/AdminNameOverlay.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; -using Content.Shared.Administration.Events; -using Robust.Client.Graphics; +using Robust.Client.Graphics; using Robust.Client.ResourceManagement; using Robust.Shared.Enums; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Administration @@ -35,13 +34,14 @@ namespace Content.Client.Administration foreach (var playerInfo in _system.PlayerList) { // Otherwise the entity can not exist yet - if (!_entityManager.TryGetEntity(playerInfo.EntityUid, out var entity)) + var entity = playerInfo.EntityUid; + if (!_entityManager.EntityExists(entity)) { continue; } // if not on the same map, continue - if (entity.Transform.MapID != _eyeManager.CurrentMap) + if (IoCManager.Resolve().GetComponent(entity).MapID != _eyeManager.CurrentMap) { continue; } diff --git a/Content.Client/Administration/UI/ManageSolutions/EditSolutionsWindow.xaml.cs b/Content.Client/Administration/UI/ManageSolutions/EditSolutionsWindow.xaml.cs index ed0f86a274..4264eda0b0 100644 --- a/Content.Client/Administration/UI/ManageSolutions/EditSolutionsWindow.xaml.cs +++ b/Content.Client/Administration/UI/ManageSolutions/EditSolutionsWindow.xaml.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using Content.Shared.Chemistry.Components; using Robust.Client.AutoGenerated; using Robust.Client.Console; @@ -7,8 +9,6 @@ using Robust.Client.UserInterface.XAML; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using System; -using System.Collections.Generic; namespace Content.Client.Administration.UI.ManageSolutions { @@ -46,8 +46,8 @@ namespace Content.Client.Administration.UI.ManageSolutions { _target = target; - var targetName = _entityManager.TryGetEntity(target, out var entity) - ? entity.Name + var targetName = _entityManager.EntityExists(target) + ? IoCManager.Resolve().GetComponent(target).EntityName : string.Empty; Title = Loc.GetString("admin-solutions-window-title", ("targetName", targetName)); diff --git a/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs b/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs index 11390ea3b8..b7ecf9704f 100644 --- a/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs +++ b/Content.Client/Administration/UI/Tabs/AtmosTab/AddAtmosWindow.xaml.cs @@ -6,6 +6,7 @@ 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; @@ -22,7 +23,8 @@ namespace Content.Client.Administration.UI.Tabs.AtmosTab _data = IoCManager.Resolve().GetAllGrids().Where(g => (int) g.Index != 0); foreach (var grid in _data) { - var playerGrid = IoCManager.Resolve().LocalPlayer?.ControlledEntity?.Transform.GridID; + var player = IoCManager.Resolve().LocalPlayer?.ControlledEntity; + var playerGrid = IoCManager.Resolve().GetComponentOrNull(player)?.GridID; GridOptions.AddItem($"{grid.Index} {(playerGrid == grid.Index ? " (Current)" : "")}"); } diff --git a/Content.Client/Administration/UI/Tabs/AtmosTab/AddGasWindow.xaml.cs b/Content.Client/Administration/UI/Tabs/AtmosTab/AddGasWindow.xaml.cs index 1d43aeeb23..0549543d6e 100644 --- a/Content.Client/Administration/UI/Tabs/AtmosTab/AddGasWindow.xaml.cs +++ b/Content.Client/Administration/UI/Tabs/AtmosTab/AddGasWindow.xaml.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; using Content.Client.Atmos.EntitySystems; -using Content.Shared.Atmos; using Content.Shared.Atmos.Prototypes; using JetBrains.Annotations; using Robust.Client.AutoGenerated; @@ -28,7 +27,8 @@ namespace Content.Client.Administration.UI.Tabs.AtmosTab _gridData = IoCManager.Resolve().GetAllGrids().Where(g => (int) g.Index != 0); foreach (var grid in _gridData) { - var playerGrid = IoCManager.Resolve().LocalPlayer?.ControlledEntity?.Transform.GridID; + var player = IoCManager.Resolve().LocalPlayer?.ControlledEntity; + var playerGrid = IoCManager.Resolve().GetComponentOrNull(player)?.GridID; GridOptions.AddItem($"{grid.Index} {(playerGrid == grid.Index ? " (Current)" : "")}"); } diff --git a/Content.Client/Administration/UI/Tabs/AtmosTab/FillGasWindow.xaml.cs b/Content.Client/Administration/UI/Tabs/AtmosTab/FillGasWindow.xaml.cs index 6c51f34357..f89863dd7b 100644 --- a/Content.Client/Administration/UI/Tabs/AtmosTab/FillGasWindow.xaml.cs +++ b/Content.Client/Administration/UI/Tabs/AtmosTab/FillGasWindow.xaml.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; using Content.Client.Atmos.EntitySystems; -using Content.Shared.Atmos; using Content.Shared.Atmos.Prototypes; using JetBrains.Annotations; using Robust.Client.AutoGenerated; @@ -28,7 +27,8 @@ namespace Content.Client.Administration.UI.Tabs.AtmosTab _gridData = IoCManager.Resolve().GetAllGrids().Where(g => (int) g.Index != 0); foreach (var grid in _gridData) { - var playerGrid = IoCManager.Resolve().LocalPlayer?.ControlledEntity?.Transform.GridID; + var player = IoCManager.Resolve().LocalPlayer?.ControlledEntity; + var playerGrid = IoCManager.Resolve().GetComponentOrNull(player)?.GridID; GridOptions.AddItem($"{grid.Index} {(playerGrid == grid.Index ? " (Current)" : "")}"); } diff --git a/Content.Client/Administration/UI/Tabs/AtmosTab/SetTemperatureWindow.xaml.cs b/Content.Client/Administration/UI/Tabs/AtmosTab/SetTemperatureWindow.xaml.cs index a5be641a21..72458fefdd 100644 --- a/Content.Client/Administration/UI/Tabs/AtmosTab/SetTemperatureWindow.xaml.cs +++ b/Content.Client/Administration/UI/Tabs/AtmosTab/SetTemperatureWindow.xaml.cs @@ -6,6 +6,7 @@ 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; @@ -22,7 +23,8 @@ namespace Content.Client.Administration.UI.Tabs.AtmosTab _data = IoCManager.Resolve().GetAllGrids().Where(g => (int) g.Index != 0); foreach (var grid in _data) { - var playerGrid = IoCManager.Resolve().LocalPlayer?.ControlledEntity?.Transform.GridID; + var player = IoCManager.Resolve().LocalPlayer?.ControlledEntity; + var playerGrid = IoCManager.Resolve().GetComponentOrNull(player)?.GridID; GridOptions.AddItem($"{grid.Index} {(playerGrid == grid.Index ? " (Current)" : "")}"); } diff --git a/Content.Client/Animations/AnimationsTestComponent.cs b/Content.Client/Animations/AnimationsTestComponent.cs index 234a509eb4..92100ce33e 100644 --- a/Content.Client/Animations/AnimationsTestComponent.cs +++ b/Content.Client/Animations/AnimationsTestComponent.cs @@ -3,6 +3,7 @@ using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.Animations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Animations @@ -16,7 +17,7 @@ namespace Content.Client.Animations { base.Initialize(); - var animations = Owner.GetComponent(); + var animations = IoCManager.Resolve().GetComponent(Owner); animations.Play(new Animation { Length = TimeSpan.FromSeconds(20), diff --git a/Content.Client/Animations/ReusableAnimations.cs b/Content.Client/Animations/ReusableAnimations.cs index fc718d1cfd..59b333e20f 100644 --- a/Content.Client/Animations/ReusableAnimations.cs +++ b/Content.Client/Animations/ReusableAnimations.cs @@ -3,6 +3,7 @@ using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.Animations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -11,22 +12,24 @@ namespace Content.Client.Animations { public static class ReusableAnimations { - public static void AnimateEntityPickup(IEntity entity, EntityCoordinates initialPosition, Vector2 finalPosition) + public static void AnimateEntityPickup(EntityUid entity, EntityCoordinates initialPosition, Vector2 finalPosition, IEntityManager? entMan = null) { - var animatableClone = entity.EntityManager.SpawnEntity("clientsideclone", initialPosition); - animatableClone.Name = entity.Name; + IoCManager.Resolve(ref entMan); + var animatableClone = entMan.SpawnEntity("clientsideclone", initialPosition); + string val = entMan.GetComponent(entity).EntityName; + entMan.GetComponent(animatableClone).EntityName = val; - if (!entity.TryGetComponent(out SpriteComponent? sprite0)) + if (!entMan.TryGetComponent(entity, out SpriteComponent? sprite0)) { - Logger.Error("Entity ({0}) couldn't be animated for pickup since it doesn't have a {1}!", entity.Name, nameof(SpriteComponent)); + Logger.Error("Entity ({0}) couldn't be animated for pickup since it doesn't have a {1}!", entMan.GetComponent(entity).EntityName, nameof(SpriteComponent)); return; } - var sprite = animatableClone.GetComponent(); + var sprite = entMan.GetComponent(animatableClone); sprite.CopyFrom(sprite0); - var animations = animatableClone.GetComponent(); + var animations = entMan.GetComponent(animatableClone); animations.AnimationCompleted += (_) => { - animatableClone.Delete(); + entMan.DeleteEntity(animatableClone); }; animations.Play(new Animation diff --git a/Content.Client/Atmos/Visualizers/AtmosPlaqueVisualizer.cs b/Content.Client/Atmos/Visualizers/AtmosPlaqueVisualizer.cs index cd843e3266..5bf7c324d6 100644 --- a/Content.Client/Atmos/Visualizers/AtmosPlaqueVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/AtmosPlaqueVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Atmos.Visualizers @@ -12,18 +13,18 @@ namespace Content.Client.Atmos.Visualizers [DataField("layer")] private int Layer { get; } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - entity.GetComponentOrNull()?.LayerMapReserveBlank(Layer); + IoCManager.Resolve().GetComponentOrNull(entity); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (!IoCManager.Resolve().TryGetComponent(component.Owner, out SpriteComponent? sprite)) { return; } diff --git a/Content.Client/Atmos/Visualizers/EnabledAtmosDeviceVisualizer.cs b/Content.Client/Atmos/Visualizers/EnabledAtmosDeviceVisualizer.cs index 24af950e1e..754358c84f 100644 --- a/Content.Client/Atmos/Visualizers/EnabledAtmosDeviceVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/EnabledAtmosDeviceVisualizer.cs @@ -2,6 +2,7 @@ using System; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Atmos.Visualizers @@ -20,7 +21,8 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) return; if(component.TryGetData(DataKey, out bool enabled) && sprite.LayerMapTryGet(LayerMap, out var layer)) diff --git a/Content.Client/Atmos/Visualizers/FireVisualizer.cs b/Content.Client/Atmos/Visualizers/FireVisualizer.cs index db7d36e1a2..bac26efaa7 100644 --- a/Content.Client/Atmos/Visualizers/FireVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/FireVisualizer.cs @@ -1,8 +1,8 @@ using Content.Shared.Atmos; -using Content.Shared.Atmos.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Atmos.Visualizers @@ -22,11 +22,11 @@ namespace Content.Client.Atmos.Visualizers [DataField("sprite")] private string? _sprite; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapReserveBlank(FireVisualLayers.Fire); sprite.LayerSetVisible(FireVisualLayers.Fire, false); @@ -49,7 +49,7 @@ namespace Content.Client.Atmos.Visualizers private void SetOnFire(AppearanceComponent component, bool onFire, float fireStacks) { - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (_sprite != null) { diff --git a/Content.Client/Atmos/Visualizers/GasAnalyzerVisualizer.cs b/Content.Client/Atmos/Visualizers/GasAnalyzerVisualizer.cs index b57d3fb7c7..ca5eca40a6 100644 --- a/Content.Client/Atmos/Visualizers/GasAnalyzerVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/GasAnalyzerVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Atmos.Visualizers @@ -18,7 +19,8 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { return; } diff --git a/Content.Client/Atmos/Visualizers/GasCanisterVisualizer.cs b/Content.Client/Atmos/Visualizers/GasCanisterVisualizer.cs index 916a8b8abf..99ba7c2539 100644 --- a/Content.Client/Atmos/Visualizers/GasCanisterVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/GasCanisterVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Atmos.Visualizers @@ -15,11 +16,11 @@ namespace Content.Client.Atmos.Visualizers [DataField("insertedTankState")] private readonly string _insertedTankState = string.Empty; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapSet(Layers.PressureLight, sprite.AddLayerState(_statePressure[0])); sprite.LayerSetShader(Layers.PressureLight, "unshaded"); @@ -31,7 +32,8 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { return; } diff --git a/Content.Client/Atmos/Visualizers/GasPortableVisualizer.cs b/Content.Client/Atmos/Visualizers/GasPortableVisualizer.cs index 417d690d46..42251edaaf 100644 --- a/Content.Client/Atmos/Visualizers/GasPortableVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/GasPortableVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Atmos.Piping.Unary.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Atmos.Visualizers @@ -12,11 +13,11 @@ namespace Content.Client.Atmos.Visualizers [DataField("stateConnected")] private string? _stateConnected; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); if (_stateConnected != null) { @@ -29,7 +30,8 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { return; } diff --git a/Content.Client/Atmos/Visualizers/PipeColorVisualizer.cs b/Content.Client/Atmos/Visualizers/PipeColorVisualizer.cs index 7994a2b7de..d3da329cc0 100644 --- a/Content.Client/Atmos/Visualizers/PipeColorVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/PipeColorVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Atmos.Piping; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Atmos.Visualizers @@ -13,7 +14,7 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (!IoCManager.Resolve().TryGetComponent(component.Owner, out SpriteComponent? sprite)) return; if (component.TryGetData(PipeColorVisuals.Color, out Color color)) diff --git a/Content.Client/Atmos/Visualizers/PipeConnectorVisualizer.cs b/Content.Client/Atmos/Visualizers/PipeConnectorVisualizer.cs index 9da44150d8..bab0d8134c 100644 --- a/Content.Client/Atmos/Visualizers/PipeConnectorVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/PipeConnectorVisualizer.cs @@ -37,11 +37,12 @@ namespace Content.Client.Atmos.Visualizers Logger.Error($"{nameof(PipeConnectorVisualizer)} could not load to load RSI {rsiString}."); } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (!entity.TryGetComponent(out var sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(entity, out var sprite)) return; if (_connectorRsi == null) @@ -52,7 +53,7 @@ namespace Content.Client.Atmos.Visualizers sprite.LayerMapReserveBlank(layerKey); var layer = sprite.LayerMapGet(layerKey); sprite.LayerSetRSI(layer, _connectorRsi); - var layerState = _baseState + ((PipeDirection) layerKey).ToString(); + var layerState = _baseState + ((PipeDirection) layerKey); sprite.LayerSetState(layer, layerState); } } @@ -61,10 +62,11 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var xform)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out var xform)) return; - if (!component.Owner.TryGetComponent(out var sprite)) + if (!entities.TryGetComponent(component.Owner, out var sprite)) return; if (!component.TryGetData(PipeColorVisuals.Color, out Color color)) diff --git a/Content.Client/Atmos/Visualizers/ScrubberVisualizer.cs b/Content.Client/Atmos/Visualizers/ScrubberVisualizer.cs index 7c5906bafc..295633cc35 100644 --- a/Content.Client/Atmos/Visualizers/ScrubberVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/ScrubberVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Atmos.Piping.Unary.Visuals; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Atmos.Visualizers { @@ -18,7 +19,8 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) return; if (!component.TryGetData(ScrubberVisuals.State, out ScrubberState state)) diff --git a/Content.Client/Atmos/Visualizers/VentPumpVisualizer.cs b/Content.Client/Atmos/Visualizers/VentPumpVisualizer.cs index e1d3d51196..15bf0938de 100644 --- a/Content.Client/Atmos/Visualizers/VentPumpVisualizer.cs +++ b/Content.Client/Atmos/Visualizers/VentPumpVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Atmos.Visuals; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Atmos.Visualizers { @@ -17,7 +18,8 @@ namespace Content.Client.Atmos.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) return; if (!component.TryGetData(VentPumpVisuals.State, out VentPumpState state)) diff --git a/Content.Client/Audio/AmbientSoundSystem.cs b/Content.Client/Audio/AmbientSoundSystem.cs index ac19253201..f524b7b020 100644 --- a/Content.Client/Audio/AmbientSoundSystem.cs +++ b/Content.Client/Audio/AmbientSoundSystem.cs @@ -90,17 +90,17 @@ namespace Content.Client.Audio _accumulator -= _cooldown; var player = _playerManager.LocalPlayer?.ControlledEntity; - if (player == null) + if (!EntityManager.TryGetComponent(player, out TransformComponent? playerManager)) { ClearSounds(); return; } - var coordinates = player.Transform.Coordinates; + var coordinates = playerManager.Coordinates; foreach (var (comp, (stream, _)) in _playingSounds.ToArray()) { - if (!comp.Deleted && comp.Enabled && comp.Owner.Transform.Coordinates.TryDistance(EntityManager, coordinates, out var range) && + if (!comp.Deleted && comp.Enabled && EntityManager.GetComponent(comp.Owner).Coordinates.TryDistance(EntityManager, coordinates, out var range) && range <= comp.Range) { continue; @@ -136,11 +136,11 @@ namespace Content.Client.Audio foreach (var entity in _lookup.GetEntitiesInRange(coordinates, _maxAmbientRange, LookupFlags.Approximate | LookupFlags.IncludeAnchored)) { - if (!entity.TryGetComponent(out AmbientSoundComponent? ambientComp) || + if (!EntityManager.TryGetComponent(entity, out AmbientSoundComponent? ambientComp) || _playingSounds.ContainsKey(ambientComp) || !ambientComp.Enabled || // We'll also do this crude distance check because it's what we're doing in the active loop above. - !entity.Transform.Coordinates.TryDistance(EntityManager, coordinates, out var range) || + !EntityManager.GetComponent(entity).Coordinates.TryDistance(EntityManager, coordinates, out var range) || range > ambientComp.Range - RangeBuffer) { continue; diff --git a/Content.Client/Body/UI/BodyScannerBoundUserInterface.cs b/Content.Client/Body/UI/BodyScannerBoundUserInterface.cs index 448f070ce3..247ce80b95 100644 --- a/Content.Client/Body/UI/BodyScannerBoundUserInterface.cs +++ b/Content.Client/Body/UI/BodyScannerBoundUserInterface.cs @@ -3,6 +3,7 @@ using Content.Shared.Body.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Client.Body.UI @@ -14,7 +15,7 @@ namespace Content.Client.Body.UI private BodyScannerDisplay? _display; [ViewVariables] - private IEntity? _entity; + private EntityUid _entity; public BodyScannerBoundUserInterface(ClientUserInterfaceComponent owner, object uiKey) : base(owner, uiKey) { } @@ -35,9 +36,11 @@ namespace Content.Client.Body.UI return; } - if (!Owner.Owner.EntityManager.TryGetEntity(scannerState.Uid, out _entity)) + var entMan = IoCManager.Resolve(); + + if (!entMan.EntityExists(scannerState.Uid)) { - throw new ArgumentException($"Received an invalid entity with id {scannerState.Uid} for body scanner with id {Owner.Owner.Uid} at {Owner.Owner.Transform.MapPosition}"); + throw new ArgumentException($"Received an invalid entity with id {scannerState.Uid} for body scanner with id {Owner.Owner} at {entMan.GetComponent(Owner.Owner).MapPosition}"); } _display?.UpdateDisplay(_entity); diff --git a/Content.Client/Body/UI/BodyScannerDisplay.cs b/Content.Client/Body/UI/BodyScannerDisplay.cs index 497e00708b..852527014e 100644 --- a/Content.Client/Body/UI/BodyScannerDisplay.cs +++ b/Content.Client/Body/UI/BodyScannerDisplay.cs @@ -1,6 +1,5 @@ using System.Linq; using Content.Shared.Body.Components; -using Content.Shared.Body.Part; using Content.Shared.Damage; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; @@ -14,11 +13,9 @@ namespace Content.Client.Body.UI { public sealed class BodyScannerDisplay : SS14Window { - private IEntity? _currentEntity; + private EntityUid _currentEntity; private SharedBodyPartComponent? _currentBodyPart; - private SharedBodyComponent? CurrentBody => _currentEntity?.GetComponentOrNull(); - public BodyScannerDisplay(BodyScannerBoundUserInterface owner) { IoCManager.InjectDependencies(this); @@ -105,12 +102,15 @@ namespace Content.Client.Body.UI private RichTextLabel MechanismInfoLabel { get; } - public void UpdateDisplay(IEntity entity) + public void UpdateDisplay(EntityUid entity) { + if(entity == null) + return; + _currentEntity = entity; BodyPartList.Clear(); - var body = CurrentBody; + var body = IoCManager.Resolve().GetComponentOrNull(_currentEntity); if (body == null) { @@ -125,7 +125,10 @@ namespace Content.Client.Body.UI public void BodyPartOnItemSelected(ItemListSelectedEventArgs args) { - var body = CurrentBody; + if (_currentEntity == null) + return; + + var body = IoCManager.Resolve().GetComponentOrNull(_currentEntity); if (body == null) { @@ -143,10 +146,11 @@ namespace Content.Client.Body.UI private void UpdateBodyPartBox(SharedBodyPartComponent part, string slotName) { - BodyPartLabel.Text = $"{Loc.GetString(slotName)}: {Loc.GetString(part.Owner.Name)}"; + var entMan = IoCManager.Resolve(); + BodyPartLabel.Text = $"{Loc.GetString(slotName)}: {Loc.GetString(entMan.GetComponent(part.Owner).EntityName)}"; // TODO BODY Part damage - if (part.Owner.TryGetComponent(out DamageableComponent? damageable)) + if (entMan.TryGetComponent(part.Owner, out DamageableComponent? damageable)) { BodyPartHealth.Text = Loc.GetString("body-scanner-display-body-part-damage-text",("damage", damageable.TotalDamage)); } diff --git a/Content.Client/Botany/PlantHolderVisualizer.cs b/Content.Client/Botany/PlantHolderVisualizer.cs index 2cd216d7d2..e9be155804 100644 --- a/Content.Client/Botany/PlantHolderVisualizer.cs +++ b/Content.Client/Botany/PlantHolderVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Botany; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Utility; namespace Content.Client.Botany @@ -9,11 +10,11 @@ namespace Content.Client.Botany [UsedImplicitly] public class PlantHolderVisualizer : AppearanceVisualizer { - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapReserveBlank(PlantHolderLayers.Plant); sprite.LayerMapReserveBlank(PlantHolderLayers.HealthLight); @@ -55,7 +56,7 @@ namespace Content.Client.Botany { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (component.TryGetData(PlantHolderVisuals.Plant, out var specifier)) { diff --git a/Content.Client/Buckle/BuckleComponent.cs b/Content.Client/Buckle/BuckleComponent.cs index 2e342aa203..0842d56402 100644 --- a/Content.Client/Buckle/BuckleComponent.cs +++ b/Content.Client/Buckle/BuckleComponent.cs @@ -1,6 +1,7 @@ -using Content.Shared.Buckle.Components; +using Content.Shared.Buckle.Components; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Buckle { @@ -13,7 +14,7 @@ namespace Content.Client.Buckle public override bool Buckled => _buckled; - public override bool TryBuckle(IEntity? user, IEntity to) + public override bool TryBuckle(EntityUid user, EntityUid to) { // TODO: Prediction return false; @@ -29,8 +30,7 @@ namespace Content.Client.Buckle _buckled = buckle.Buckled; LastEntityBuckledTo = buckle.LastEntityBuckledTo; DontCollide = buckle.DontCollide; - - if (!Owner.TryGetComponent(out SpriteComponent? ownerSprite)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out SpriteComponent? ownerSprite)) { return; } diff --git a/Content.Client/Buckle/BuckleVisualizer.cs b/Content.Client/Buckle/BuckleVisualizer.cs index d53dea6bd3..035b6e8aa0 100644 --- a/Content.Client/Buckle/BuckleVisualizer.cs +++ b/Content.Client/Buckle/BuckleVisualizer.cs @@ -5,6 +5,7 @@ using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.Animations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Buckle @@ -30,9 +31,9 @@ namespace Content.Client.Buckle private void SetRotation(AppearanceComponent component, Angle rotation) { - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); - if (!sprite.Owner.TryGetComponent(out AnimationPlayerComponent? animation)) + if (!IoCManager.Resolve().TryGetComponent(sprite.Owner, out AnimationPlayerComponent? animation)) { sprite.Rotation = rotation; return; diff --git a/Content.Client/Cabinet/ItemCabinetVisualizer.cs b/Content.Client/Cabinet/ItemCabinetVisualizer.cs index d3f3d5bc57..79e173665a 100644 --- a/Content.Client/Cabinet/ItemCabinetVisualizer.cs +++ b/Content.Client/Cabinet/ItemCabinetVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Cabinet; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Cabinet @@ -19,7 +20,8 @@ namespace Content.Client.Cabinet { base.OnChangeData(component); - if (component.Owner.TryGetComponent(out var sprite) + var entities = IoCManager.Resolve(); + if (entities.TryGetComponent(component.Owner, out SpriteComponent sprite) && component.TryGetData(ItemCabinetVisuals.IsOpen, out bool isOpen) && component.TryGetData(ItemCabinetVisuals.ContainsItem, out bool contains)) { diff --git a/Content.Client/Camera/CameraRecoilComponent.cs b/Content.Client/Camera/CameraRecoilComponent.cs index 2a1c95c61d..d037fbd602 100644 --- a/Content.Client/Camera/CameraRecoilComponent.cs +++ b/Content.Client/Camera/CameraRecoilComponent.cs @@ -39,7 +39,7 @@ namespace Content.Client.Camera { if (float.IsNaN(recoil.X) || float.IsNaN(recoil.Y)) { - Logger.Error($"CameraRecoilComponent on entity {Owner.Uid} passed a NaN recoil value. Ignoring."); + Logger.Error($"CameraRecoilComponent on entity {Owner} passed a NaN recoil value. Ignoring."); return; } diff --git a/Content.Client/Cargo/CargoConsoleBoundUserInterface.cs b/Content.Client/Cargo/CargoConsoleBoundUserInterface.cs index 4e85b9fe3a..117b54d4c6 100644 --- a/Content.Client/Cargo/CargoConsoleBoundUserInterface.cs +++ b/Content.Client/Cargo/CargoConsoleBoundUserInterface.cs @@ -4,6 +4,7 @@ using Content.Shared.Cargo; using Content.Shared.Cargo.Components; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; using static Content.Shared.Cargo.Components.SharedCargoConsoleComponent; using static Robust.Client.UserInterface.Controls.BaseButton; @@ -49,8 +50,9 @@ namespace Content.Client.Cargo { base.Open(); - if (!Owner.Owner.TryGetComponent(out GalacticMarketComponent? market) || - !Owner.Owner.TryGetComponent(out CargoOrderDatabaseComponent? orders)) return; + var entMan = IoCManager.Resolve(); + if (!entMan.TryGetComponent(Owner.Owner, out GalacticMarketComponent? market) || + !entMan.TryGetComponent(Owner.Owner, out CargoOrderDatabaseComponent? orders)) return; Market = market; Orders = orders; diff --git a/Content.Client/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs b/Content.Client/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs index 77fdf07c00..b12a2339ba 100644 --- a/Content.Client/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs +++ b/Content.Client/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs @@ -50,7 +50,7 @@ namespace Content.Client.CharacterAppearance.Systems { foreach (var (part, _) in body.Parts) { - if (part.Owner.TryGetComponent(out SpriteComponent? partSprite)) + if (EntityManager.TryGetComponent(part.Owner, out SpriteComponent? partSprite)) { partSprite!.Color = component.Appearance.SkinColor; } @@ -107,13 +107,12 @@ namespace Content.Client.CharacterAppearance.Systems // Scaffolding until Body is moved to ECS. private void BodyPartAdded(HumanoidAppearanceBodyPartAddedEvent args) { - if(!EntityManager.TryGetEntity(args.Uid, out var owner)) return; - if (!owner.TryGetComponent(out SpriteComponent? sprite)) + if (!EntityManager.TryGetComponent(args.Uid, out SpriteComponent? sprite)) { return; } - if (!args.Args.Part.Owner.HasComponent()) + if (!EntityManager.HasComponent(args.Args.Part.Owner)) { return; } @@ -131,13 +130,12 @@ namespace Content.Client.CharacterAppearance.Systems private void BodyPartRemoved(HumanoidAppearanceBodyPartRemovedEvent args) { - if(!EntityManager.TryGetEntity(args.Uid, out var owner)) return; - if (!owner.TryGetComponent(out SpriteComponent? sprite)) + if (!EntityManager.TryGetComponent(args.Uid, out SpriteComponent? sprite)) { return; } - if (!args.Args.Part.Owner.HasComponent()) + if (!EntityManager.HasComponent(args.Args.Part.Owner)) { return; } diff --git a/Content.Client/CharacterInfo/Components/CharacterInfoComponent.cs b/Content.Client/CharacterInfo/Components/CharacterInfoComponent.cs index c5e1404a5e..992e3f4daf 100644 --- a/Content.Client/CharacterInfo/Components/CharacterInfoComponent.cs +++ b/Content.Client/CharacterInfo/Components/CharacterInfoComponent.cs @@ -50,12 +50,13 @@ namespace Content.Client.CharacterInfo.Components { case CharacterInfoMessage characterInfoMessage: _control.UpdateUI(characterInfoMessage); - if (Owner.TryGetComponent(out ISpriteComponent? spriteComponent)) + var entityManager = IoCManager.Resolve(); + if (entityManager.TryGetComponent(Owner, out ISpriteComponent? spriteComponent)) { _control.SpriteView.Sprite = spriteComponent; } - _control.NameLabel.Text = Owner.Name; + _control.NameLabel.Text = entityManager.GetComponent(Owner).EntityName; break; } } diff --git a/Content.Client/CharacterInterface/CharacterInterfaceComponent.cs b/Content.Client/CharacterInterface/CharacterInterfaceComponent.cs index f071c03269..ee944c0224 100644 --- a/Content.Client/CharacterInterface/CharacterInterfaceComponent.cs +++ b/Content.Client/CharacterInterface/CharacterInterfaceComponent.cs @@ -42,7 +42,7 @@ namespace Content.Client.CharacterInterface base.Initialize(); //Use all the character ui interfaced components to create the character window - _uiComponents = Owner.GetAllComponents().ToList(); + _uiComponents = IoCManager.Resolve().GetComponents(Owner).ToList(); if (_uiComponents.Count == 0) { return; diff --git a/Content.Client/CharacterInterface/CharacterInterfaceSystem.cs b/Content.Client/CharacterInterface/CharacterInterfaceSystem.cs index 589b97bc3e..fdc533ed56 100644 --- a/Content.Client/CharacterInterface/CharacterInterfaceSystem.cs +++ b/Content.Client/CharacterInterface/CharacterInterfaceSystem.cs @@ -37,8 +37,7 @@ namespace Content.Client.CharacterInterface private void HandleOpenCharacterMenu() { - if (_playerManager.LocalPlayer?.ControlledEntity == null - || !_playerManager.LocalPlayer.ControlledEntity.TryGetComponent(out CharacterInterfaceComponent? characterInterface)) + if (!EntityManager.TryGetComponent(_playerManager.LocalPlayer?.ControlledEntity, out CharacterInterfaceComponent? characterInterface)) { return; } diff --git a/Content.Client/Chat/Managers/ChatManager.cs b/Content.Client/Chat/Managers/ChatManager.cs index 1c26965529..60ea578aa1 100644 --- a/Content.Client/Chat/Managers/ChatManager.cs +++ b/Content.Client/Chat/Managers/ChatManager.cs @@ -231,7 +231,9 @@ namespace Content.Client.Chat.Managers ChatPermissionsUpdated?.Invoke(new ChatPermissionsUpdatedEventArgs {OldSelectableChannels = oldSelectable}); } - public bool IsGhost => _playerManager.LocalPlayer?.ControlledEntity?.HasComponent() ?? false; + public bool IsGhost => _playerManager.LocalPlayer?.ControlledEntity is {} uid && + uid.IsValid() && + _entityManager.HasComponent(uid); public void FrameUpdate(FrameEventArgs delta) { @@ -241,11 +243,11 @@ namespace Content.Client.Chat.Managers return; } - foreach (var (entityUid, queueData) in _queuedSpeechBubbles.ShallowClone()) + foreach (var (entity, queueData) in _queuedSpeechBubbles.ShallowClone()) { - if (!_entityManager.TryGetEntity(entityUid, out var entity)) + if (!_entityManager.EntityExists(entity)) { - _queuedSpeechBubbles.Remove(entityUid); + _queuedSpeechBubbles.Remove(entity); continue; } @@ -257,7 +259,7 @@ namespace Content.Client.Chat.Managers if (queueData.MessageQueue.Count == 0) { - _queuedSpeechBubbles.Remove(entityUid); + _queuedSpeechBubbles.Remove(entity); continue; } @@ -412,7 +414,7 @@ namespace Content.Client.Chat.Managers private void AddSpeechBubble(MsgChatMessage msg, SpeechBubble.SpeechType speechType) { - if (!_entityManager.TryGetEntity(msg.SenderEntity, out var entity)) + if (!_entityManager.EntityExists(msg.SenderEntity)) { Logger.WarningS("chat", "Got local chat message with invalid sender entity: {0}", msg.SenderEntity); return; @@ -422,7 +424,7 @@ namespace Content.Client.Chat.Managers foreach (var message in messages) { - EnqueueSpeechBubble(entity, message, speechType); + EnqueueSpeechBubble(msg.SenderEntity, message, speechType); } } @@ -472,16 +474,16 @@ namespace Content.Client.Chat.Managers return messages; } - private void EnqueueSpeechBubble(IEntity entity, string contents, SpeechBubble.SpeechType speechType) + private void EnqueueSpeechBubble(EntityUid entity, string contents, SpeechBubble.SpeechType speechType) { // Don't enqueue speech bubbles for other maps. TODO: Support multiple viewports/maps? - if (entity.Transform.MapID != _eyeManager.CurrentMap) + if (_entityManager.GetComponent(entity).MapID != _eyeManager.CurrentMap) return; - if (!_queuedSpeechBubbles.TryGetValue(entity.Uid, out var queueData)) + if (!_queuedSpeechBubbles.TryGetValue(entity, out var queueData)) { queueData = new SpeechBubbleQueueData(); - _queuedSpeechBubbles.Add(entity.Uid, queueData); + _queuedSpeechBubbles.Add(entity, queueData); } queueData.MessageQueue.Enqueue(new SpeechBubbleData @@ -491,12 +493,12 @@ namespace Content.Client.Chat.Managers }); } - private void CreateSpeechBubble(IEntity entity, SpeechBubbleData speechData) + private void CreateSpeechBubble(EntityUid entity, SpeechBubbleData speechData) { var bubble = - SpeechBubble.CreateSpeechBubble(speechData.Type, speechData.Message, entity, _eyeManager, this); + SpeechBubble.CreateSpeechBubble(speechData.Type, speechData.Message, entity, _eyeManager, this, _entityManager); - if (_activeSpeechBubbles.TryGetValue(entity.Uid, out var existing)) + if (_activeSpeechBubbles.TryGetValue(entity, out var existing)) { // Push up existing bubbles above the mob's head. foreach (var existingBubble in existing) @@ -507,7 +509,7 @@ namespace Content.Client.Chat.Managers else { existing = new List(); - _activeSpeechBubbles.Add(entity.Uid, existing); + _activeSpeechBubbles.Add(entity, existing); } existing.Add(bubble); diff --git a/Content.Client/Chat/UI/SpeechBubble.cs b/Content.Client/Chat/UI/SpeechBubble.cs index 88816d6817..2d0c8c8ad2 100644 --- a/Content.Client/Chat/UI/SpeechBubble.cs +++ b/Content.Client/Chat/UI/SpeechBubble.cs @@ -5,6 +5,7 @@ using Robust.Client.Graphics; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Timing; @@ -35,8 +36,9 @@ namespace Content.Client.Chat.UI private const float EntityVerticalOffset = 0.5f; private readonly IEyeManager _eyeManager; - private readonly IEntity _senderEntity; + private readonly EntityUid _senderEntity; private readonly IChatManager _chatManager; + private readonly IEntityManager _entityManager; private float _timeLeft = TotalTime; @@ -45,26 +47,27 @@ namespace Content.Client.Chat.UI public float ContentHeight { get; private set; } - public static SpeechBubble CreateSpeechBubble(SpeechType type, string text, IEntity senderEntity, IEyeManager eyeManager, IChatManager chatManager) + public static SpeechBubble CreateSpeechBubble(SpeechType type, string text, EntityUid senderEntity, IEyeManager eyeManager, IChatManager chatManager, IEntityManager entityManager) { switch (type) { case SpeechType.Emote: - return new EmoteSpeechBubble(text, senderEntity, eyeManager, chatManager); + return new EmoteSpeechBubble(text, senderEntity, eyeManager, chatManager, entityManager); case SpeechType.Say: - return new SaySpeechBubble(text, senderEntity, eyeManager, chatManager); + return new SaySpeechBubble(text, senderEntity, eyeManager, chatManager, entityManager); default: throw new ArgumentOutOfRangeException(); } } - public SpeechBubble(string text, IEntity senderEntity, IEyeManager eyeManager, IChatManager chatManager) + public SpeechBubble(string text, EntityUid senderEntity, IEyeManager eyeManager, IChatManager chatManager, IEntityManager entityManager) { _chatManager = chatManager; _senderEntity = senderEntity; _eyeManager = eyeManager; + _entityManager = entityManager; // Use text clipping so new messages don't overlap old ones being pushed up. RectClipContent = true; @@ -98,7 +101,7 @@ namespace Content.Client.Chat.UI _verticalOffsetAchieved = MathHelper.Lerp(_verticalOffsetAchieved, VerticalOffset, 10 * args.DeltaSeconds); } - if (!_senderEntity.Transform.Coordinates.IsValid(_senderEntity.EntityManager)) + if (!_entityManager.GetComponent(_senderEntity).Coordinates.IsValid(_entityManager)) { Modulate = Color.White.WithAlpha(0); return; @@ -115,14 +118,14 @@ namespace Content.Client.Chat.UI Modulate = Color.White; } - if (_senderEntity.Deleted || _timeLeft <= 0) + if (_entityManager.Deleted(_senderEntity) || _timeLeft <= 0) { // Timer spawn to prevent concurrent modification exception. Timer.Spawn(0, Die); return; } - var worldPos = _senderEntity.Transform.WorldPosition; + var worldPos = _entityManager.GetComponent(_senderEntity).WorldPosition; var scale = _eyeManager.MainViewport.GetRenderScale(); var offset = new Vector2(0, EntityVerticalOffset * EyeManager.PixelsPerMeter * scale); var lowerCenter = (_eyeManager.WorldToScreen(worldPos) - offset) / UIScale; @@ -143,7 +146,7 @@ namespace Content.Client.Chat.UI return; } - _chatManager.RemoveSpeechBubble(_senderEntity.Uid, this); + _chatManager.RemoveSpeechBubble(_senderEntity, this); } /// @@ -161,8 +164,8 @@ namespace Content.Client.Chat.UI public class EmoteSpeechBubble : SpeechBubble { - public EmoteSpeechBubble(string text, IEntity senderEntity, IEyeManager eyeManager, IChatManager chatManager) - : base(text, senderEntity, eyeManager, chatManager) + public EmoteSpeechBubble(string text, EntityUid senderEntity, IEyeManager eyeManager, IChatManager chatManager, IEntityManager entityManager) + : base(text, senderEntity, eyeManager, chatManager, entityManager) { } @@ -187,8 +190,8 @@ namespace Content.Client.Chat.UI public class SaySpeechBubble : SpeechBubble { - public SaySpeechBubble(string text, IEntity senderEntity, IEyeManager eyeManager, IChatManager chatManager) - : base(text, senderEntity, eyeManager, chatManager) + public SaySpeechBubble(string text, EntityUid senderEntity, IEyeManager eyeManager, IChatManager chatManager, IEntityManager entityManager) + : base(text, senderEntity, eyeManager, chatManager, entityManager) { } diff --git a/Content.Client/Chemistry/Visualizers/FoamVisualizer.cs b/Content.Client/Chemistry/Visualizers/FoamVisualizer.cs index 99a2dd3d80..2cb7a4bef5 100644 --- a/Content.Client/Chemistry/Visualizers/FoamVisualizer.cs +++ b/Content.Client/Chemistry/Visualizers/FoamVisualizer.cs @@ -4,6 +4,7 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -36,11 +37,12 @@ namespace Content.Client.Chemistry.Visualizers { base.OnChangeData(component); + var entities = IoCManager.Resolve(); if (component.TryGetData(FoamVisuals.State, out var state)) { if (state) { - if (component.Owner.TryGetComponent(out AnimationPlayerComponent? animPlayer)) + if (entities.TryGetComponent(component.Owner, out AnimationPlayerComponent? animPlayer)) { if (!animPlayer.HasRunningAnimation(AnimationKey)) animPlayer.Play(_foamDissolve, AnimationKey); @@ -50,7 +52,7 @@ namespace Content.Client.Chemistry.Visualizers if (component.TryGetData(FoamVisuals.Color, out var color)) { - if (component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + if (entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { sprite.Color = color; } diff --git a/Content.Client/Chemistry/Visualizers/SmokeVisualizer.cs b/Content.Client/Chemistry/Visualizers/SmokeVisualizer.cs index 89c2d2fd18..666afaa4f6 100644 --- a/Content.Client/Chemistry/Visualizers/SmokeVisualizer.cs +++ b/Content.Client/Chemistry/Visualizers/SmokeVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Chemistry.Visualizers @@ -13,9 +14,10 @@ namespace Content.Client.Chemistry.Visualizers { base.OnChangeData(component); + var entities = IoCManager.Resolve(); if (component.TryGetData(SmokeVisuals.Color, out var color)) { - if (component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + if (entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { sprite.Color = color; } diff --git a/Content.Client/Chemistry/Visualizers/SolutionContainerVisualizer.cs b/Content.Client/Chemistry/Visualizers/SolutionContainerVisualizer.cs index 1911fe6bae..945aa03c73 100644 --- a/Content.Client/Chemistry/Visualizers/SolutionContainerVisualizer.cs +++ b/Content.Client/Chemistry/Visualizers/SolutionContainerVisualizer.cs @@ -3,6 +3,7 @@ using Content.Shared.Chemistry; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; @@ -25,7 +26,8 @@ namespace Content.Client.Chemistry.Visualizers if (!component.TryGetData(SolutionContainerVisuals.VisualState, out SolutionContainerVisualState state)) return; - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) return; if (!sprite.LayerMapTryGet(_layer, out var fillLayer)) return; var fillPercent = state.FilledVolumePercent; diff --git a/Content.Client/Chemistry/Visualizers/VaporVisualizer.cs b/Content.Client/Chemistry/Visualizers/VaporVisualizer.cs index 83192c5709..c6cd5dc945 100644 --- a/Content.Client/Chemistry/Visualizers/VaporVisualizer.cs +++ b/Content.Client/Chemistry/Visualizers/VaporVisualizer.cs @@ -4,6 +4,7 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -53,7 +54,7 @@ namespace Content.Client.Chemistry.Visualizers { if (!state) return; - var animPlayer = component.Owner.GetComponent(); + var animPlayer = IoCManager.Resolve().GetComponent(component.Owner); if(!animPlayer.HasRunningAnimation(AnimationKey)) animPlayer.Play(VaporFlick, AnimationKey); @@ -61,7 +62,7 @@ namespace Content.Client.Chemistry.Visualizers private void SetColor(AppearanceComponent component, Color color) { - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); sprite.Color = color; } diff --git a/Content.Client/Clickable/ClickableComponent.cs b/Content.Client/Clickable/ClickableComponent.cs index 2037602bf1..aebb464c3f 100644 --- a/Content.Client/Clickable/ClickableComponent.cs +++ b/Content.Client/Clickable/ClickableComponent.cs @@ -7,6 +7,7 @@ using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; +using TerraFX.Interop.Windows; namespace Content.Client.Clickable { @@ -29,14 +30,15 @@ namespace Content.Client.Clickable /// True if the click worked, false otherwise. public bool CheckClick(Vector2 worldPos, out int drawDepth, out uint renderOrder) { - if (!Owner.TryGetComponent(out ISpriteComponent? sprite) || !sprite.Visible) + var entMan = IoCManager.Resolve(); + if (!entMan.TryGetComponent(Owner, out ISpriteComponent? sprite) || !sprite.Visible) { drawDepth = default; renderOrder = default; return false; } - var transform = Owner.Transform; + var transform = entMan.GetComponent(Owner); var localPos = transform.InvWorldMatrix.Transform(worldPos); var spriteMatrix = Matrix3.Invert(sprite.GetLocalMatrix()); diff --git a/Content.Client/Clothing/ClothingComponent.cs b/Content.Client/Clothing/ClothingComponent.cs index 4cd1d1ee46..a75febecd8 100644 --- a/Content.Client/Clothing/ClothingComponent.cs +++ b/Content.Client/Clothing/ClothingComponent.cs @@ -42,7 +42,7 @@ namespace Content.Client.Clothing if (!Owner.TryGetContainer(out IContainer? container)) return; - if (!container.Owner.TryGetComponent(out ClientInventoryComponent? inventory)) + if (!IoCManager.Resolve().TryGetComponent(container.Owner, out ClientInventoryComponent? inventory)) return; if (!inventory.TryFindItemSlots(Owner, out EquipmentSlotDefines.Slots? slots)) return; diff --git a/Content.Client/CombatMode/CombatModeSystem.cs b/Content.Client/CombatMode/CombatModeSystem.cs index 26c27fd538..96a3d7da40 100644 --- a/Content.Client/CombatMode/CombatModeSystem.cs +++ b/Content.Client/CombatMode/CombatModeSystem.cs @@ -33,13 +33,8 @@ namespace Content.Client.CombatMode public bool IsInCombatMode() { - var entity = _playerManager.LocalPlayer?.ControlledEntity; - if (entity == null || !entity.TryGetComponent(out CombatModeComponent? combatMode)) - { - return false; - } - - return combatMode.IsInCombatMode; + return EntityManager.TryGetComponent(_playerManager.LocalPlayer?.ControlledEntity, out CombatModeComponent? combatMode) && + combatMode.IsInCombatMode; } private void OnTargetingZoneChanged(TargetingZone obj) @@ -47,4 +42,8 @@ namespace Content.Client.CombatMode EntityManager.RaisePredictiveEvent(new CombatModeSystemMessages.SetTargetZoneMessage(obj)); } } + + public static class A + { + } } diff --git a/Content.Client/Commands/DebugCommands.cs b/Content.Client/Commands/DebugCommands.cs index 33e44930ed..799db2db84 100644 --- a/Content.Client/Commands/DebugCommands.cs +++ b/Content.Client/Commands/DebugCommands.cs @@ -50,12 +50,12 @@ namespace Content.Client.Commands EntitySystem.Get() .ShowAll = true; - var components = IoCManager.Resolve() - .EntityQuery(true); + var entMan = IoCManager.Resolve(); + var components = entMan.EntityQuery(true); foreach (var component in components) { - if (component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + if (entMan.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { sprite.DrawDepth = (int) DrawDepth.Overlays; } diff --git a/Content.Client/Commands/HideMechanismsCommand.cs b/Content.Client/Commands/HideMechanismsCommand.cs index 282fedeff5..31236b0fbc 100644 --- a/Content.Client/Commands/HideMechanismsCommand.cs +++ b/Content.Client/Commands/HideMechanismsCommand.cs @@ -21,7 +21,7 @@ namespace Content.Client.Commands foreach (var mechanism in mechanisms) { - if (!mechanism.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (!entityManager.TryGetComponent(mechanism.Owner, out SpriteComponent? sprite)) { continue; } diff --git a/Content.Client/Commands/ShowMechanismsCommand.cs b/Content.Client/Commands/ShowMechanismsCommand.cs index b61912a854..168bd61c6c 100644 --- a/Content.Client/Commands/ShowMechanismsCommand.cs +++ b/Content.Client/Commands/ShowMechanismsCommand.cs @@ -23,7 +23,7 @@ namespace Content.Client.Commands foreach (var mechanism in mechanisms) { - if (mechanism.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (entityManager.TryGetComponent(mechanism.Owner, out SpriteComponent? sprite)) { sprite.ContainerOccluded = false; } diff --git a/Content.Client/Computer/ComputerVisualizer.cs b/Content.Client/Computer/ComputerVisualizer.cs index 51485abdc4..d2c65dfd70 100644 --- a/Content.Client/Computer/ComputerVisualizer.cs +++ b/Content.Client/Computer/ComputerVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Computer; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Computer @@ -19,11 +20,11 @@ namespace Content.Client.Computer private string BodyBrokenState = "broken"; private string ScreenBroken = "computer_broken"; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerSetState(Layers.Screen, ScreenState); if (!string.IsNullOrEmpty(KeyboardState)) @@ -37,7 +38,7 @@ namespace Content.Client.Computer { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (!component.TryGetData(ComputerVisuals.Powered, out bool powered)) { diff --git a/Content.Client/Construction/ConstructionPlacementHijack.cs b/Content.Client/Construction/ConstructionPlacementHijack.cs index 93eaed99c1..f6a7f4c624 100644 --- a/Content.Client/Construction/ConstructionPlacementHijack.cs +++ b/Content.Client/Construction/ConstructionPlacementHijack.cs @@ -5,6 +5,7 @@ using Robust.Client.Graphics; using Robust.Client.Placement; using Robust.Client.Utility; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; namespace Content.Client.Construction @@ -35,9 +36,9 @@ namespace Content.Client.Construction } /// - public override bool HijackDeletion(IEntity entity) + public override bool HijackDeletion(EntityUid entity) { - if (entity.TryGetComponent(out ConstructionGhostComponent? ghost)) + if (IoCManager.Resolve().TryGetComponent(entity, out ConstructionGhostComponent? ghost)) { _constructionSystem.ClearGhost(ghost.GhostId); } diff --git a/Content.Client/Construction/ConstructionSystem.cs b/Content.Client/Construction/ConstructionSystem.cs index 6e99f38591..78eac7f829 100644 --- a/Content.Client/Construction/ConstructionSystem.cs +++ b/Content.Client/Construction/ConstructionSystem.cs @@ -17,7 +17,6 @@ using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Prototypes; - namespace Content.Client.Construction { /// @@ -111,7 +110,7 @@ namespace Content.Client.Construction private void HandlePlayerAttached(PlayerAttachSysMessage msg) { - var available = IsCrafingAvailable(msg.AttachedEntity); + var available = IsCraftingAvailable(msg.AttachedEntity); UpdateCraftingAvailability(available); } @@ -131,9 +130,9 @@ namespace Content.Client.Construction CraftingEnabled = available; } - private static bool IsCrafingAvailable(IEntity? entity) + private static bool IsCraftingAvailable(EntityUid? entity) { - if (entity == null) + if (entity == default) return false; // TODO: Decide if entity can craft, using capabilities or something @@ -145,9 +144,7 @@ namespace Content.Client.Construction if (!args.EntityUid.IsValid() || !args.EntityUid.IsClientSide()) return false; - var entity = EntityManager.GetEntity(args.EntityUid); - - if (!entity.TryGetComponent(out var ghostComp)) + if (!EntityManager.TryGetComponent(args.EntityUid, out var ghostComp)) return false; TryStartConstruction(ghostComp.GhostId); @@ -159,10 +156,14 @@ namespace Content.Client.Construction /// public void SpawnGhost(ConstructionPrototype prototype, EntityCoordinates loc, Direction dir) { - var user = _playerManager.LocalPlayer?.ControlledEntity; + if (_playerManager.LocalPlayer?.ControlledEntity is not { } user || + !user.IsValid()) + { + return; + } // This InRangeUnobstructed should probably be replaced with "is there something blocking us in that tile?" - if (user == null || GhostPresent(loc) || !user.InRangeUnobstructed(loc, 20f, ignoreInsideBlocker: prototype.CanBuildInImpassable)) return; + if (GhostPresent(loc) || !user.InRangeUnobstructed(loc, 20f, ignoreInsideBlocker: prototype.CanBuildInImpassable)) return; foreach (var condition in prototype.Conditions) { @@ -171,12 +172,12 @@ namespace Content.Client.Construction } var ghost = EntityManager.SpawnEntity("constructionghost", loc); - var comp = ghost.GetComponent(); + var comp = EntityManager.GetComponent(ghost); comp.Prototype = prototype; comp.GhostId = _nextId++; - ghost.Transform.LocalRotation = dir.ToAngle(); + EntityManager.GetComponent(ghost).LocalRotation = dir.ToAngle(); _ghosts.Add(comp.GhostId, comp); - var sprite = ghost.GetComponent(); + var sprite = EntityManager.GetComponent(ghost); sprite.Color = new Color(48, 255, 48, 128); sprite.AddBlankLayer(0); // There is no way to actually check if this already exists, so we blindly insert a new one sprite.LayerSetSprite(0, prototype.Icon); @@ -191,7 +192,7 @@ namespace Content.Client.Construction { foreach (var ghost in _ghosts) { - if (ghost.Value.Owner.Transform.Coordinates.Equals(loc)) return true; + if (EntityManager.GetComponent(ghost.Value.Owner).Coordinates.Equals(loc)) return true; } return false; @@ -206,7 +207,7 @@ namespace Content.Client.Construction throw new ArgumentException($"Can't start construction for a ghost with no prototype. Ghost id: {ghostId}"); } - var transform = ghost.Owner.Transform; + var transform = EntityManager.GetComponent(ghost.Owner); var msg = new TryStartStructureConstructionMessage(transform.Coordinates, ghost.Prototype.ID, transform.LocalRotation, ghostId); RaiseNetworkEvent(msg); } @@ -226,7 +227,7 @@ namespace Content.Client.Construction { if (_ghosts.TryGetValue(ghostId, out var ghost)) { - ghost.Owner.QueueDelete(); + EntityManager.QueueDeleteEntity(ghost.Owner); _ghosts.Remove(ghostId); } } @@ -238,7 +239,7 @@ namespace Content.Client.Construction { foreach (var (_, ghost) in _ghosts) { - ghost.Owner.QueueDelete(); + EntityManager.QueueDeleteEntity(ghost.Owner); } _ghosts.Clear(); diff --git a/Content.Client/Construction/MachineFrameVisualizer.cs b/Content.Client/Construction/MachineFrameVisualizer.cs index 86a3d9ce17..239d1657ac 100644 --- a/Content.Client/Construction/MachineFrameVisualizer.cs +++ b/Content.Client/Construction/MachineFrameVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Construction { @@ -14,7 +15,7 @@ namespace Content.Client.Construction if (component.TryGetData(MachineFrameVisuals.State, out var data)) { - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); sprite.LayerSetState(0, $"box_{data}"); } diff --git a/Content.Client/ContextMenu/UI/EntityMenuElement.cs b/Content.Client/ContextMenu/UI/EntityMenuElement.cs index 96aa0c2243..824aeafbf4 100644 --- a/Content.Client/ContextMenu/UI/EntityMenuElement.cs +++ b/Content.Client/ContextMenu/UI/EntityMenuElement.cs @@ -1,7 +1,7 @@ -using Content.Client.Stylesheets; using Robust.Client.GameObjects; using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.ContextMenu.UI @@ -10,10 +10,12 @@ namespace Content.Client.ContextMenu.UI { public const string StyleClassEntityMenuCountText = "contextMenuCount"; + [Dependency] private IEntityManager _entityManager = default!; + /// /// The entity that can be accessed by interacting with this element. /// - public IEntity? Entity; + public EntityUid Entity; /// /// How many entities are accessible through this element's sub-menus. @@ -23,11 +25,13 @@ namespace Content.Client.ContextMenu.UI /// public int Count; - public Label CountLabel; - public SpriteView EntityIcon = new SpriteView { OverrideDirection = Direction.South}; + public readonly Label CountLabel; + public readonly SpriteView EntityIcon = new() { OverrideDirection = Direction.South}; - public EntityMenuElement(IEntity? entity = null) : base() + public EntityMenuElement(EntityUid entity = default) { + IoCManager.InjectDependencies(this); + CountLabel = new Label { StyleClasses = { StyleClassEntityMenuCountText } }; Icon.AddChild(new LayoutContainer() { Children = { EntityIcon, CountLabel } }); @@ -36,7 +40,7 @@ namespace Content.Client.ContextMenu.UI LayoutContainer.SetGrowVertical(CountLabel, LayoutContainer.GrowDirection.Begin); Entity = entity; - if (Entity != null) + if (Entity != default) { Count = 1; CountLabel.Visible = false; @@ -47,7 +51,7 @@ namespace Content.Client.ContextMenu.UI protected override void Dispose(bool disposing) { base.Dispose(disposing); - Entity = null; + Entity = default; Count = 0; } @@ -55,17 +59,23 @@ namespace Content.Client.ContextMenu.UI /// Update the icon and text of this element based on the given entity or this element's own entity if none /// is provided. /// - public void UpdateEntity(IEntity? entity = null) + public void UpdateEntity(EntityUid entity = default) { - if (Entity != null && !Entity.Deleted) - entity ??= Entity; + if (Entity != default && _entityManager.EntityExists(Entity) && !entity.Valid) + entity = Entity; - EntityIcon.Sprite = entity?.GetComponentOrNull(); + if (entity == default) + { + Text = string.Empty; + return; + } + + EntityIcon.Sprite = _entityManager.GetComponentOrNull(entity); if (UserInterfaceManager.DebugMonitors.Visible) - Text = $"{entity?.Name} ({entity?.Uid})"; + Text = $"{_entityManager.GetComponent(entity!).EntityName} ({entity})"; else - Text = entity?.Name ?? string.Empty; + Text = _entityManager.GetComponent(entity!).EntityName; } } } diff --git a/Content.Client/ContextMenu/UI/EntityMenuPresenter.cs b/Content.Client/ContextMenu/UI/EntityMenuPresenter.cs index bead833a70..033e23b333 100644 --- a/Content.Client/ContextMenu/UI/EntityMenuPresenter.cs +++ b/Content.Client/ContextMenu/UI/EntityMenuPresenter.cs @@ -19,6 +19,7 @@ using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Timing; + namespace Content.Client.ContextMenu.UI { /// @@ -50,7 +51,7 @@ namespace Content.Client.ContextMenu.UI /// /// This is used remove GUI elements when the entities are deleted. or leave the LOS. /// - public Dictionary Elements = new(); + public Dictionary Elements = new(); public EntityMenuPresenter(VerbSystem verbSystem) : base() { @@ -76,7 +77,7 @@ namespace Content.Client.ContextMenu.UI /// /// Given a list of entities, sort them into groups and them to a new entity menu. /// - public void OpenRootMenu(List entities) + public void OpenRootMenu(List entities) { // close any old menus first. if (RootMenu.Visible) @@ -84,7 +85,7 @@ namespace Content.Client.ContextMenu.UI var entitySpriteStates = GroupEntities(entities); var orderedStates = entitySpriteStates.ToList(); - orderedStates.Sort((x, y) => string.CompareOrdinal(x.First().Prototype?.Name, y.First().Prototype?.Name)); + orderedStates.Sort((x, y) => string.CompareOrdinal(_entityManager.GetComponent(x.First()).EntityPrototype?.Name, _entityManager.GetComponent(y.First()).EntityPrototype?.Name)); Elements.Clear(); AddToUI(orderedStates); @@ -100,8 +101,12 @@ namespace Content.Client.ContextMenu.UI // get an entity associated with this element var entity = entityElement.Entity; - entity ??= GetFirstEntityOrNull(element.SubMenu); - if (entity == null) + if (!entity.Valid) + { + entity = GetFirstEntityOrNull(element.SubMenu); + } + + if (!entity.Valid) return; // open verb menu? @@ -134,7 +139,7 @@ namespace Content.Client.ContextMenu.UI var funcId = _inputManager.NetworkBindMap.KeyFunctionID(func); var message = new FullInputCmdMessage(_gameTiming.CurTick, _gameTiming.TickFraction, funcId, - BoundKeyState.Down, entity.Transform.Coordinates, args.PointerLocation, entity.Uid); + BoundKeyState.Down, _entityManager.GetComponent(entity).Coordinates, args.PointerLocation, entity); var session = _playerManager.LocalPlayer?.Session; if (session != null) @@ -172,9 +177,8 @@ namespace Content.Client.ContextMenu.UI if (!RootMenu.Visible) return; - var player = _playerManager.LocalPlayer?.ControlledEntity; - - if (player == null) + if (_playerManager.LocalPlayer?.ControlledEntity is not { } player || + !player.IsValid()) return; // Do we need to do in-range unOccluded checks? @@ -183,16 +187,16 @@ namespace Content.Client.ContextMenu.UI foreach (var entity in Elements.Keys.ToList()) { - if (entity.Deleted || !ignoreFov && !_examineSystem.CanExamine(player, entity)) + if (_entityManager.Deleted(entity) || !ignoreFov && !_examineSystem.CanExamine(player, entity)) RemoveEntity(entity); } } /// - /// Add menu elements for a list of grouped entities; + /// Add menu elements for a list of grouped entities; /// /// A list of entity groups. Entities are grouped together based on prototype. - private void AddToUI(List> entityGroups) + private void AddToUI(List> entityGroups) { // If there is only a single group. We will just directly list individual entities if (entityGroups.Count == 1) @@ -219,13 +223,13 @@ namespace Content.Client.ContextMenu.UI AddElement(RootMenu, element); Elements.TryAdd(group[0], element); } - + } /// /// Given a group of entities, add a menu element that has a pop-up sub-menu listing group members /// - private void AddGroupToUI(List group) + private void AddGroupToUI(List group) { EntityMenuElement element = new(); ContextMenuPopup subMenu = new(this, element); @@ -244,12 +248,12 @@ namespace Content.Client.ContextMenu.UI /// /// Remove an entity from the entity context menu. /// - private void RemoveEntity(IEntity entity) + private void RemoveEntity(EntityUid entity) { // find the element associated with this entity if (!Elements.TryGetValue(entity, out var element)) { - Logger.Error($"Attempted to remove unknown entity from the entity menu: {entity.Name} ({entity.Uid})"); + Logger.Error($"Attempted to remove unknown entity from the entity menu: {_entityManager.GetComponent(entity).EntityName} ({entity})"); return; } @@ -263,7 +267,7 @@ namespace Content.Client.ContextMenu.UI UpdateElement(e); // if the verb menu is open and targeting this entity, close it. - if (_verbSystem.VerbMenu.CurrentTarget == entity.Uid) + if (_verbSystem.VerbMenu.CurrentTarget == entity) _verbSystem.VerbMenu.Close(); // If this was the last entity, close the entity menu @@ -322,30 +326,30 @@ namespace Content.Client.ContextMenu.UI /// /// Recursively look through a sub-menu and return the first entity. /// - private IEntity? GetFirstEntityOrNull(ContextMenuPopup? menu) + private EntityUid GetFirstEntityOrNull(ContextMenuPopup? menu) { if (menu == null) - return null; + return default; foreach (var element in menu.MenuBody.Children) { if (element is not EntityMenuElement entityElement) continue; - if (entityElement.Entity != null) + if (entityElement.Entity != default) { - if (!entityElement.Entity.Deleted) + if (!_entityManager.Deleted(entityElement.Entity)) return entityElement.Entity; continue; } // if the element has no entity, its a group of entities with another attached sub-menu. var entity = GetFirstEntityOrNull(entityElement.SubMenu); - if (entity != null) + if (entity != default) return entity; } - return null; + return default; } public override void OpenSubMenu(ContextMenuElement element) diff --git a/Content.Client/ContextMenu/UI/EntityMenuPresenterGrouping.cs b/Content.Client/ContextMenu/UI/EntityMenuPresenterGrouping.cs index ba958693bb..71e1b8fdfa 100644 --- a/Content.Client/ContextMenu/UI/EntityMenuPresenterGrouping.cs +++ b/Content.Client/ContextMenu/UI/EntityMenuPresenterGrouping.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.ContextMenu.UI { @@ -16,29 +17,29 @@ namespace Content.Client.ContextMenu.UI GroupingContextMenuType = obj; } - private List> GroupEntities(IEnumerable entities, int depth = 0) + private List> GroupEntities(IEnumerable entities, int depth = 0) { if (GroupingContextMenuType == 0) { - var newEntities = entities.GroupBy(e => e.Name + (e.Prototype?.ID ?? string.Empty)).ToList(); + var newEntities = entities.GroupBy(e => _entityManager.GetComponent(e).EntityName + (_entityManager.GetComponent(e).EntityPrototype?.ID ?? string.Empty)).ToList(); return newEntities.Select(grp => grp.ToList()).ToList(); } else { - var newEntities = entities.GroupBy(e => e, new PrototypeAndStatesContextMenuComparer(depth)).ToList(); + var newEntities = entities.GroupBy(e => e, new PrototypeAndStatesContextMenuComparer(depth, _entityManager)).ToList(); return newEntities.Select(grp => grp.ToList()).ToList(); } } - private sealed class PrototypeAndStatesContextMenuComparer : IEqualityComparer + private sealed class PrototypeAndStatesContextMenuComparer : IEqualityComparer { - private static readonly List> EqualsList = new() + private static readonly List> EqualsList = new() { - (a, b) => a.Prototype!.ID == b.Prototype!.ID, - (a, b) => + (a, b, entMan) => entMan.GetComponent(a).EntityPrototype!.ID == entMan.GetComponent(b).EntityPrototype!.ID, + (a, b, entMan) => { - a.TryGetComponent(out var spriteA); - b.TryGetComponent(out var spriteB); + entMan.TryGetComponent(a, out var spriteA); + entMan.TryGetComponent(b, out var spriteB); if (spriteA == null || spriteB == null) return spriteA == spriteB; @@ -49,13 +50,13 @@ namespace Content.Client.ContextMenu.UI return xStates.OrderBy(t => t).SequenceEqual(yStates.OrderBy(t => t)); }, }; - private static readonly List> GetHashCodeList = new() + private static readonly List> GetHashCodeList = new() { - e => EqualityComparer.Default.GetHashCode(e.Prototype!.ID), - e => + (e, entMan) => EqualityComparer.Default.GetHashCode(entMan.GetComponent(e).EntityPrototype!.ID), + (e, entMan) => { var hash = 0; - foreach (var element in e.GetComponent().AllLayers.Where(obj => obj.Visible).Select(s => s.RsiState.Name)) + foreach (var element in entMan.GetComponent(e).AllLayers.Where(obj => obj.Visible).Select(s => s.RsiState.Name)) { hash ^= EqualityComparer.Default.GetHashCode(element!); } @@ -66,24 +67,28 @@ namespace Content.Client.ContextMenu.UI private static int Count => EqualsList.Count - 1; private readonly int _depth; - public PrototypeAndStatesContextMenuComparer(int step = 0) + private readonly IEntityManager _entMan; + public PrototypeAndStatesContextMenuComparer(int step = 0, IEntityManager? entMan = null) { + IoCManager.Resolve(ref entMan); + _depth = step > Count ? Count : step; + _entMan = entMan; } - public bool Equals(IEntity? x, IEntity? y) + public bool Equals(EntityUid x, EntityUid y) { - if (x == null) + if (x == default) { - return y == null; + return y == default; } - return y != null && EqualsList[_depth](x, y); + return y != default && EqualsList[_depth](x, y, _entMan); } - public int GetHashCode(IEntity e) + public int GetHashCode(EntityUid e) { - return GetHashCodeList[_depth](e); + return GetHashCodeList[_depth](e, _entMan); } } } diff --git a/Content.Client/Conveyor/Visualizers/ConveyorVisualizer.cs b/Content.Client/Conveyor/Visualizers/ConveyorVisualizer.cs index 6f025b6395..5a40c18de5 100644 --- a/Content.Client/Conveyor/Visualizers/ConveyorVisualizer.cs +++ b/Content.Client/Conveyor/Visualizers/ConveyorVisualizer.cs @@ -1,8 +1,9 @@ -using System; +using System; using Content.Shared.Conveyor; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Conveyor.Visualizers @@ -21,7 +22,8 @@ namespace Content.Client.Conveyor.Visualizers private void ChangeState(AppearanceComponent appearance) { - if (!appearance.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(appearance.Owner, out ISpriteComponent? sprite)) { return; } @@ -40,11 +42,11 @@ namespace Content.Client.Conveyor.Visualizers } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - - var appearance = entity.EnsureComponent(); + var entities = IoCManager.Resolve(); + var appearance = entities.EnsureComponent(entity); ChangeState(appearance); } diff --git a/Content.Client/Conveyor/Visualizers/TwoWayLeverVisualizer.cs b/Content.Client/Conveyor/Visualizers/TwoWayLeverVisualizer.cs index bea07cbcc6..6608578501 100644 --- a/Content.Client/Conveyor/Visualizers/TwoWayLeverVisualizer.cs +++ b/Content.Client/Conveyor/Visualizers/TwoWayLeverVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.MachineLinking; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Conveyor.Visualizers @@ -20,7 +21,8 @@ namespace Content.Client.Conveyor.Visualizers private void ChangeState(AppearanceComponent appearance) { - if (!appearance.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(appearance.Owner, out ISpriteComponent? sprite)) { return; } @@ -38,11 +40,12 @@ namespace Content.Client.Conveyor.Visualizers sprite.LayerSetState(0, texture); } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var appearance = entity.EnsureComponent(); + var entities = IoCManager.Resolve(); + var appearance = entities.EnsureComponent(entity); ChangeState(appearance); } diff --git a/Content.Client/Cuffs/Components/HandcuffComponent.cs b/Content.Client/Cuffs/Components/HandcuffComponent.cs index 9be4196aea..a5351aa864 100644 --- a/Content.Client/Cuffs/Components/HandcuffComponent.cs +++ b/Content.Client/Cuffs/Components/HandcuffComponent.cs @@ -2,6 +2,7 @@ using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Cuffs.Components { @@ -21,7 +22,7 @@ namespace Content.Client.Cuffs.Components return; } - if (Owner.TryGetComponent(out var sprite)) + if (IoCManager.Resolve().TryGetComponent(Owner, out var sprite)) { sprite.LayerSetState(0, new RSI.StateId(state.IconState)); // TODO: safety check to see if RSI contains the state? } diff --git a/Content.Client/Damage/DamageVisualizer.cs b/Content.Client/Damage/DamageVisualizer.cs index d5d4728172..8ac706777b 100644 --- a/Content.Client/Damage/DamageVisualizer.cs +++ b/Content.Client/Damage/DamageVisualizer.cs @@ -37,8 +37,8 @@ namespace Content.Client.Damage /// public class DamageVisualizer : AppearanceVisualizer { - [Dependency] IPrototypeManager _prototypeManager = default!; - [Dependency] IEntityManager _entityManager = default!; + [Dependency] private readonly IPrototypeManager _prototypeManager = default!; + [Dependency] private readonly IEntityManager _entityManager = default!; private const string _name = "DamageVisualizer"; /// @@ -195,7 +195,7 @@ namespace Content.Client.Damage public readonly string? Color; } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); @@ -207,7 +207,7 @@ namespace Content.Client.Damage InitializeVisualizer(entity, damageData); } - private void VerifyVisualizerSetup(IEntity entity, DamageVisualizerDataComponent damageData) + private void VerifyVisualizerSetup(EntityUid entity, DamageVisualizerDataComponent damageData) { if (_thresholds.Count < 1) { @@ -289,11 +289,11 @@ namespace Content.Client.Damage } } - private void InitializeVisualizer(IEntity entity, DamageVisualizerDataComponent damageData) + private void InitializeVisualizer(EntityUid entity, DamageVisualizerDataComponent damageData) { - if (!entity.TryGetComponent(out SpriteComponent? spriteComponent) - || !entity.TryGetComponent(out var damageComponent) - || !entity.HasComponent()) + if (!_entityManager.TryGetComponent(entity, out SpriteComponent? spriteComponent) + || !_entityManager.TryGetComponent(entity, out var damageComponent) + || !_entityManager.HasComponent(entity)) return; _thresholds.Add(FixedPoint2.Zero); @@ -504,7 +504,8 @@ namespace Content.Client.Damage public override void OnChangeData(AppearanceComponent component) { - if (!component.Owner.TryGetComponent(out var damageData)) + var entities = _entityManager; + if (!entities.TryGetComponent(component.Owner, out DamageVisualizerDataComponent damageData)) return; if (!damageData.Valid) @@ -525,8 +526,9 @@ namespace Content.Client.Damage private void HandleDamage(AppearanceComponent component, DamageVisualizerDataComponent damageData) { - if (!component.Owner.TryGetComponent(out var spriteComponent) - || !component.Owner.TryGetComponent(out var damageComponent)) + var entities = _entityManager; + if (!entities.TryGetComponent(component.Owner, out SpriteComponent spriteComponent) + || !entities.TryGetComponent(component.Owner, out DamageableComponent damageComponent)) return; if (_targetLayers != null && _damageOverlayGroups != null) diff --git a/Content.Client/Disposal/Systems/DisposalUnitSystem.cs b/Content.Client/Disposal/Systems/DisposalUnitSystem.cs index 84b55bff5a..6c649888c1 100644 --- a/Content.Client/Disposal/Systems/DisposalUnitSystem.cs +++ b/Content.Client/Disposal/Systems/DisposalUnitSystem.cs @@ -3,6 +3,8 @@ using Content.Client.Disposal.Components; using Content.Client.Disposal.UI; using Content.Shared.Disposal; using Robust.Client.GameObjects; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Disposal.Systems { @@ -38,7 +40,7 @@ namespace Content.Client.Disposal.Systems { if (component.Deleted) return true; - if (!component.Owner.TryGetComponent(out ClientUserInterfaceComponent? userInterface)) return true; + if (!EntityManager.TryGetComponent(component.Owner, out ClientUserInterfaceComponent? userInterface)) return true; var state = component.UiState; if (state == null) return true; diff --git a/Content.Client/Disposal/UI/DisposalUnitBoundUserInterface.cs b/Content.Client/Disposal/UI/DisposalUnitBoundUserInterface.cs index 1168d77a57..10eb990421 100644 --- a/Content.Client/Disposal/UI/DisposalUnitBoundUserInterface.cs +++ b/Content.Client/Disposal/UI/DisposalUnitBoundUserInterface.cs @@ -3,6 +3,7 @@ using Content.Client.Disposal.Systems; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.Disposal.Components.SharedDisposalUnitComponent; namespace Content.Client.Disposal.UI @@ -52,7 +53,7 @@ namespace Content.Client.Disposal.UI Window?.UpdateState(cast); // Kinda icky but we just want client to handle its own lerping and not flood bandwidth for it. - if (!Owner.Owner.TryGetComponent(out DisposalUnitComponent? component)) return; + if (!IoCManager.Resolve().TryGetComponent(Owner.Owner, out DisposalUnitComponent? component)) return; component.UiState = cast; EntitySystem.Get().UpdateActive(component, true); diff --git a/Content.Client/Disposal/Visualizers/DisposalUnitVisualizer.cs b/Content.Client/Disposal/Visualizers/DisposalUnitVisualizer.cs index 59e3d282d7..1e3a60f5b5 100644 --- a/Content.Client/Disposal/Visualizers/DisposalUnitVisualizer.cs +++ b/Content.Client/Disposal/Visualizers/DisposalUnitVisualizer.cs @@ -4,6 +4,7 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using static Content.Shared.Disposal.Components.SharedDisposalUnitComponent; @@ -69,7 +70,8 @@ namespace Content.Client.Disposal.Visualizers return; } - if (!appearance.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(appearance.Owner, out ISpriteComponent? sprite)) { return; } @@ -88,7 +90,7 @@ namespace Content.Client.Disposal.Visualizers case VisualState.Flushing: sprite.LayerSetState(DisposalUnitVisualLayers.Base, _stateAnchored); - var animPlayer = appearance.Owner.GetComponent(); + var animPlayer = entities.GetComponent(appearance.Owner); if (!animPlayer.HasRunningAnimation(AnimationKey)) { @@ -143,12 +145,12 @@ namespace Content.Client.Disposal.Visualizers } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - - entity.EnsureComponent(); - var appearance = entity.EnsureComponent(); + var entities = IoCManager.Resolve(); + entities.EnsureComponent(entity); + var appearance = entities.EnsureComponent(entity); ChangeState(appearance); } diff --git a/Content.Client/Disposal/Visualizers/DisposalVisualizer.cs b/Content.Client/Disposal/Visualizers/DisposalVisualizer.cs index fe774d945e..98b9a33eea 100644 --- a/Content.Client/Disposal/Visualizers/DisposalVisualizer.cs +++ b/Content.Client/Disposal/Visualizers/DisposalVisualizer.cs @@ -4,6 +4,7 @@ using Content.Shared.SubFloor; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Disposal.Visualizers @@ -22,7 +23,8 @@ namespace Content.Client.Disposal.Visualizers private void ChangeState(AppearanceComponent appearance) { - if (!appearance.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(appearance.Owner, out ISpriteComponent? sprite)) { return; } @@ -46,17 +48,17 @@ namespace Content.Client.Disposal.Visualizers { appearance.Owner.EnsureComponent(); } - else if (appearance.Owner.HasComponent()) + else if (entities.HasComponent(appearance.Owner)) { - appearance.Owner.RemoveComponent(); + entities.RemoveComponent(appearance.Owner); } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - - var appearance = entity.EnsureComponent(); + var entityManager = IoCManager.Resolve(); + var appearance = entityManager.EnsureComponent(entity); ChangeState(appearance); } diff --git a/Content.Client/DoAfter/DoAfterSystem.cs b/Content.Client/DoAfter/DoAfterSystem.cs index 5f03cae7bf..7f0be712bd 100644 --- a/Content.Client/DoAfter/DoAfterSystem.cs +++ b/Content.Client/DoAfter/DoAfterSystem.cs @@ -31,7 +31,7 @@ namespace Content.Client.DoAfter /// public const float ExcessTime = 0.5f; - private IEntity? _attachedEntity; + private EntityUid? _attachedEntity; public override void Initialize() { @@ -51,7 +51,7 @@ namespace Content.Client.DoAfter var currentTime = _gameTiming.CurTime; // Can't see any I guess? - if (_attachedEntity == null || _attachedEntity.Deleted) + if (_attachedEntity is not {Valid: true} entity || Deleted(entity)) return; var viewbox = _eyeManager.GetWorldViewport().Enlarged(2.0f); @@ -59,23 +59,23 @@ namespace Content.Client.DoAfter foreach (var comp in EntityManager.EntityQuery(true)) { var doAfters = comp.DoAfters.ToList(); - var compPos = comp.Owner.Transform.WorldPosition; + var compPos = EntityManager.GetComponent(comp.Owner).WorldPosition; if (doAfters.Count == 0 || - comp.Owner.Transform.MapID != _attachedEntity.Transform.MapID || + EntityManager.GetComponent(comp.Owner).MapID != EntityManager.GetComponent(entity).MapID || !viewbox.Contains(compPos)) { comp.Disable(); continue; } - var range = (compPos - _attachedEntity.Transform.WorldPosition).Length + + var range = (compPos - EntityManager.GetComponent(entity).WorldPosition).Length + 0.01f; if (comp.Owner != _attachedEntity && !ExamineSystemShared.InRangeUnOccluded( - _attachedEntity.Transform.MapPosition, - comp.Owner.Transform.MapPosition, range, + EntityManager.GetComponent(entity).MapPosition, + EntityManager.GetComponent(comp.Owner).MapPosition, range, entity => entity == comp.Owner || entity == _attachedEntity)) { comp.Disable(); @@ -84,7 +84,7 @@ namespace Content.Client.DoAfter comp.Enable(); - var userGrid = comp.Owner.Transform.Coordinates; + var userGrid = EntityManager.GetComponent(comp.Owner).Coordinates; // Check cancellations / finishes foreach (var (id, doAfter) in doAfters) @@ -116,8 +116,8 @@ namespace Content.Client.DoAfter if (doAfter.BreakOnTargetMove) { - if (EntityManager.TryGetEntity(doAfter.TargetUid, out var targetEntity) && - !targetEntity.Transform.Coordinates.InRange(EntityManager, doAfter.TargetGrid, + if (EntityManager.EntityExists(doAfter.TargetUid) && + !EntityManager.GetComponent(doAfter.TargetUid).Coordinates.InRange(EntityManager, doAfter.TargetGrid, doAfter.MovementThreshold)) { comp.Cancel(id, currentTime); diff --git a/Content.Client/DoAfter/UI/DoAfterGui.cs b/Content.Client/DoAfter/UI/DoAfterGui.cs index 2e6a5076c9..a7973adc61 100644 --- a/Content.Client/DoAfter/UI/DoAfterGui.cs +++ b/Content.Client/DoAfter/UI/DoAfterGui.cs @@ -27,7 +27,7 @@ namespace Content.Client.DoAfter.UI // We'll store cancellations for a little bit just so we can flash the graphic to indicate it's cancelled private readonly Dictionary _cancelledDoAfters = new(); - public IEntity? AttachedEntity { get; set; } + public EntityUid AttachedEntity { get; set; } private ScreenCoordinates _playerPosition; public DoAfterGui() @@ -146,8 +146,8 @@ namespace Content.Client.DoAfter.UI { base.FrameUpdate(args); - if (AttachedEntity?.IsValid() != true || - !AttachedEntity.TryGetComponent(out DoAfterComponent? doAfterComponent)) + if (!AttachedEntity.IsValid() || + !_entityManager.TryGetComponent(AttachedEntity, out DoAfterComponent? doAfterComponent)) { Visible = false; return; @@ -160,8 +160,9 @@ namespace Content.Client.DoAfter.UI return; } - if (_eyeManager.CurrentMap != AttachedEntity.Transform.MapID || - !AttachedEntity.Transform.Coordinates.IsValid(_entityManager)) + var transform = _entityManager.GetComponent(AttachedEntity); + + if (_eyeManager.CurrentMap != transform.MapID || !transform.Coordinates.IsValid(_entityManager)) { Visible = false; return; @@ -211,7 +212,7 @@ namespace Content.Client.DoAfter.UI RemoveDoAfter(id); } - var screenCoordinates = _eyeManager.CoordinatesToScreen(AttachedEntity.Transform.Coordinates); + var screenCoordinates = _eyeManager.CoordinatesToScreen(transform.Coordinates); _playerPosition = new ScreenCoordinates(screenCoordinates.Position / UIScale, screenCoordinates.Window); LayoutContainer.SetPosition(this, new Vector2(_playerPosition.X - Width / 2, _playerPosition.Y - Height - 30.0f)); } diff --git a/Content.Client/Doors/AirlockVisualizer.cs b/Content.Client/Doors/AirlockVisualizer.cs index 4802a3f3d0..1ff5311f05 100644 --- a/Content.Client/Doors/AirlockVisualizer.cs +++ b/Content.Client/Doors/AirlockVisualizer.cs @@ -1,12 +1,11 @@ using System; using Content.Client.Wires.Visualizers; -using Content.Shared.Audio; using Content.Shared.Doors; -using Content.Shared.Sound; using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -15,6 +14,8 @@ namespace Content.Client.Doors [UsedImplicitly] public class AirlockVisualizer : AppearanceVisualizer, ISerializationHooks { + [Dependency] private readonly IEntityManager _entMan = default!; + private const string AnimationKey = "airlock_animation"; [DataField("animationTime")] @@ -49,6 +50,8 @@ namespace Content.Client.Doors void ISerializationHooks.AfterDeserialization() { + IoCManager.InjectDependencies(this); + CloseAnimation = new Animation {Length = TimeSpan.FromSeconds(_delay)}; { var flick = new AnimationTrackSpriteFlick(); @@ -109,11 +112,11 @@ namespace Content.Client.Doors } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { - if (!entity.HasComponent()) + if (!_entMan.HasComponent(entity)) { - entity.AddComponent(); + _entMan.AddComponent(entity); } } @@ -121,8 +124,8 @@ namespace Content.Client.Doors { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); - var animPlayer = component.Owner.GetComponent(); + var sprite = _entMan.GetComponent(component.Owner); + var animPlayer = _entMan.GetComponent(component.Owner); if (!component.TryGetData(DoorVisuals.VisualState, out DoorVisualState state)) { state = DoorVisualState.Closed; diff --git a/Content.Client/Doors/ClientDoorComponent.cs b/Content.Client/Doors/ClientDoorComponent.cs index 37201e4a66..0ae261e51b 100644 --- a/Content.Client/Doors/ClientDoorComponent.cs +++ b/Content.Client/Doors/ClientDoorComponent.cs @@ -2,6 +2,7 @@ using System; using Content.Shared.Doors; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom; using DrawDepthTag = Robust.Shared.GameObjects.DrawDepth; @@ -38,7 +39,7 @@ namespace Content.Client.Doors base.State = value; - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new DoorStateChangedEvent(State), false); + IoCManager.Resolve().EventBus.RaiseLocalEvent(Owner, new DoorStateChangedEvent(State), false); } } diff --git a/Content.Client/DragDrop/DragDropSystem.cs b/Content.Client/DragDrop/DragDropSystem.cs index f65a4d3c44..3ebef14401 100644 --- a/Content.Client/DragDrop/DragDropSystem.cs +++ b/Content.Client/DragDrop/DragDropSystem.cs @@ -54,9 +54,9 @@ namespace Content.Client.DragDrop // entity performing the drag action - private IEntity? _dragger; + private EntityUid _dragger; private readonly List _draggables = new(); - private IEntity? _dragShadow; + private EntityUid _dragShadow; // time since mouse down over the dragged entity private float _mouseDownTime; @@ -68,7 +68,7 @@ namespace Content.Client.DragDrop // can ignore any events sent to this system private bool _isReplaying; - private DragDropHelper _dragDropHelper = default!; + private DragDropHelper _dragDropHelper = default!; private ShaderInstance? _dropTargetInRangeShader; private ShaderInstance? _dropTargetOutOfRangeShader; @@ -77,7 +77,7 @@ namespace Content.Client.DragDrop public override void Initialize() { - _dragDropHelper = new DragDropHelper(OnBeginDrag, OnContinueDrag, OnEndDrag); + _dragDropHelper = new DragDropHelper(OnBeginDrag, OnContinueDrag, OnEndDrag); _dropTargetInRangeShader = _prototypeManager.Index(ShaderDropTargetInRange).Instance(); _dropTargetOutOfRangeShader = _prototypeManager.Index(ShaderDropTargetOutOfRange).Instance(); @@ -118,33 +118,32 @@ namespace Content.Client.DragDrop private bool OnUseMouseDown(in PointerInputCmdHandler.PointerInputCmdArgs args) { - if (args.Session?.AttachedEntity == null) + if (args.Session?.AttachedEntity is not {Valid: true} dragger) { return false; } - var dragger = args.Session.AttachedEntity; // cancel any current dragging if there is one (shouldn't be because they would've had to have lifted // the mouse, canceling the drag, but just being cautious) _dragDropHelper.EndDrag(); // possibly initiating a drag // check if the clicked entity is draggable - if (!EntityManager.TryGetEntity(args.EntityUid, out var entity)) + if (!EntityManager.EntityExists(args.EntityUid)) { return false; } // check if the entity is reachable - if (!_interactionSystem.InRangeUnobstructed(dragger, entity)) + if (!_interactionSystem.InRangeUnobstructed(dragger, args.EntityUid)) { return false; } var canDrag = false; - foreach (var draggable in entity.GetAllComponents()) + foreach (var draggable in EntityManager.GetComponents(args.EntityUid)) { - var dragEventArgs = new StartDragDropEvent(dragger, entity); + var dragEventArgs = new StartDragDropEvent(dragger, args.EntityUid); if (!draggable.CanStartDrag(dragEventArgs)) { @@ -161,7 +160,7 @@ namespace Content.Client.DragDrop } // wait to initiate a drag - _dragDropHelper.MouseDown(entity); + _dragDropHelper.MouseDown(args.EntityUid); _dragger = dragger; _mouseDownTime = 0; @@ -176,19 +175,19 @@ namespace Content.Client.DragDrop private bool OnBeginDrag() { - if (_dragDropHelper.Dragged == null || _dragDropHelper.Dragged.Deleted) + if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged)) { // something happened to the clicked entity or we moved the mouse off the target so // we shouldn't replay the original click return false; } - if (_dragDropHelper.Dragged.TryGetComponent(out var draggedSprite)) + if (EntityManager.TryGetComponent(_dragDropHelper.Dragged, out var draggedSprite)) { // pop up drag shadow under mouse var mousePos = _eyeManager.ScreenToMap(_dragDropHelper.MouseScreenPosition); _dragShadow = EntityManager.SpawnEntity("dragshadow", mousePos); - var dragSprite = _dragShadow.GetComponent(); + var dragSprite = EntityManager.GetComponent(_dragShadow); dragSprite.CopyFrom(draggedSprite); dragSprite.RenderOrder = EntityManager.CurrentTick.Value; dragSprite.Color = dragSprite.Color.WithAlpha(0.7f); @@ -196,7 +195,7 @@ namespace Content.Client.DragDrop dragSprite.DrawDepth = (int) DrawDepth.Overlays; if (!dragSprite.NoRotation) { - _dragShadow.Transform.WorldRotation = _dragDropHelper.Dragged.Transform.WorldRotation; + EntityManager.GetComponent(_dragShadow).WorldRotation = EntityManager.GetComponent(_dragDropHelper.Dragged).WorldRotation; } HighlightTargets(); @@ -207,13 +206,13 @@ namespace Content.Client.DragDrop } Logger.Warning("Unable to display drag shadow for {0} because it" + - " has no sprite component.", _dragDropHelper.Dragged.Name); + " has no sprite component.", EntityManager.GetComponent(_dragDropHelper.Dragged).EntityName); return false; } private bool OnContinueDrag(float frameTime) { - if (_dragDropHelper.Dragged == null || _dragDropHelper.Dragged.Deleted) + if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged)) { return false; } @@ -221,7 +220,7 @@ namespace Content.Client.DragDrop DebugTools.AssertNotNull(_dragger); // still in range of the thing we are dragging? - if (!_interactionSystem.InRangeUnobstructed(_dragger!, _dragDropHelper.Dragged)) + if (!_interactionSystem.InRangeUnobstructed(_dragger, _dragDropHelper.Dragged)) { return false; } @@ -230,10 +229,10 @@ namespace Content.Client.DragDrop var mousePos = _eyeManager.ScreenToMap(_dragDropHelper.MouseScreenPosition); // TODO: would use MapPosition instead if it had a setter, but it has no setter. // is that intentional, or should we add a setter for Transform.MapPosition? - if (_dragShadow == null) + if (_dragShadow == default) return false; - _dragShadow.Transform.WorldPosition = mousePos.Position; + EntityManager.GetComponent(_dragShadow).WorldPosition = mousePos.Position; _targetRecheckTime += frameTime; if (_targetRecheckTime > TargetRecheckInterval) @@ -248,22 +247,22 @@ namespace Content.Client.DragDrop private void OnEndDrag() { RemoveHighlights(); - if (_dragShadow != null) + if (_dragShadow != default) { EntityManager.DeleteEntity(_dragShadow); } EntityManager.EventBus.RaiseEvent(EventSource.Local, new OutlineToggleMessage(true)); - _dragShadow = null; + _dragShadow = default; _draggables.Clear(); - _dragger = null; + _dragger = default; _mouseDownTime = 0; _savedMouseDown = null; } private bool OnUseMouseUp(in PointerInputCmdHandler.PointerInputCmdArgs args) { - if (_dragDropHelper.IsDragging == false || _dragDropHelper.Dragged == null) + if (_dragDropHelper.IsDragging == false || _dragDropHelper.Dragged == default) { // haven't started the drag yet, quick mouseup, definitely treat it as a normal click by // replaying the original cmd @@ -287,7 +286,7 @@ namespace Content.Client.DragDrop return false; } - if (_dragger == null) + if (_dragger == default) { _dragDropHelper.EndDrag(); return false; @@ -295,7 +294,7 @@ namespace Content.Client.DragDrop // now when ending the drag, we will not replay the click because // by this time we've determined the input was actually a drag attempt - var range = (args.Coordinates.ToMapPos(EntityManager) - _dragger.Transform.MapPosition.Position).Length + 0.01f; + var range = (args.Coordinates.ToMapPos(EntityManager) - EntityManager.GetComponent(_dragger).MapPosition.Position).Length + 0.01f; // tell the server we are dropping if we are over a valid drop target in range. // We don't use args.EntityUid here because drag interactions generally should // work even if there's something "on top" of the drop target @@ -330,8 +329,8 @@ namespace Content.Client.DragDrop if (!draggable.CanDrop(dropArgs)) continue; // tell the server about the drop attempt - RaiseNetworkEvent(new DragDropRequestEvent(args.Coordinates, _dragDropHelper.Dragged!.Uid, - entity.Uid)); + RaiseNetworkEvent(new DragDropRequestEvent(args.Coordinates, _dragDropHelper.Dragged, + entity)); draggable.Drop(dropArgs); @@ -340,9 +339,11 @@ namespace Content.Client.DragDrop } } - if (outOfRange) + if (outOfRange && + _playerManager.LocalPlayer?.ControlledEntity is { } player && + player.IsValid()) { - _playerManager.LocalPlayer?.ControlledEntity?.PopupMessage(Loc.GetString("drag-drop-system-out-of-range-text")); + player.PopupMessage(Loc.GetString("drag-drop-system-out-of-range-text")); } _dragDropHelper.EndDrag(); @@ -351,10 +352,8 @@ namespace Content.Client.DragDrop private void HighlightTargets() { - if (_dragDropHelper.Dragged == null || - _dragDropHelper.Dragged.Deleted || - _dragShadow == null || - _dragShadow.Deleted) + if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged) || + _dragShadow == default || Deleted(_dragShadow)) { Logger.Warning("Programming error. Can't highlight drag and drop targets, not currently " + "dragging anything or dragged entity / shadow was deleted."); @@ -374,12 +373,12 @@ namespace Content.Client.DragDrop var pvsEntities = IoCManager.Resolve().GetEntitiesIntersecting(_eyeManager.CurrentMap, bounds, LookupFlags.Approximate | LookupFlags.IncludeAnchored); foreach (var pvsEntity in pvsEntities) { - if (!pvsEntity.TryGetComponent(out ISpriteComponent? inRangeSprite) || + if (!EntityManager.TryGetComponent(pvsEntity, out ISpriteComponent? inRangeSprite) || !inRangeSprite.Visible || pvsEntity == _dragDropHelper.Dragged) continue; // check if it's able to be dropped on by current dragged entity - var dropArgs = new DragDropEvent(_dragger!, pvsEntity.Transform.Coordinates, _dragDropHelper.Dragged, pvsEntity); + var dropArgs = new DragDropEvent(_dragger, EntityManager.GetComponent(pvsEntity).Coordinates, _dragDropHelper.Dragged, pvsEntity); var valid = ValidDragDrop(dropArgs); if (valid == null) continue; @@ -415,14 +414,14 @@ namespace Content.Client.DragDrop /// null if the target doesn't support IDragDropOn private bool? ValidDragDrop(DragDropEvent eventArgs) { - if (!_actionBlockerSystem.CanInteract(eventArgs.User.Uid)) + if (!_actionBlockerSystem.CanInteract(eventArgs.User)) { return false; } bool? valid = null; - foreach (var comp in eventArgs.Target.GetAllComponents()) + foreach (var comp in EntityManager.GetComponents(eventArgs.Target)) { if (!comp.CanDragDropOn(eventArgs)) { @@ -440,7 +439,7 @@ namespace Content.Client.DragDrop // Need at least one IDraggable to return true or else we can't do shit valid = false; - foreach (var comp in eventArgs.User.GetAllComponents()) + foreach (var comp in EntityManager.GetComponents(eventArgs.User)) { if (!comp.CanDrop(eventArgs)) continue; valid = true; diff --git a/Content.Client/Entry/EntryPoint.cs b/Content.Client/Entry/EntryPoint.cs index 7043970921..4db2dea02c 100644 --- a/Content.Client/Entry/EntryPoint.cs +++ b/Content.Client/Entry/EntryPoint.cs @@ -57,6 +57,7 @@ namespace Content.Client.Entry [Dependency] private readonly IEscapeMenuOwner _escapeMenuOwner = default!; [Dependency] private readonly IGameController _gameController = default!; [Dependency] private readonly IStateManager _stateManager = default!; + [Dependency] private readonly IEntityManager _entityManager = default!; public override void Init() { @@ -141,19 +142,21 @@ namespace Content.Client.Entry /// /// Add the character interface master which combines all character interfaces into one window /// - public static void AttachPlayerToEntity(EntityAttachedEventArgs eventArgs) + public void AttachPlayerToEntity(EntityAttachedEventArgs eventArgs) { - eventArgs.NewEntity.AddComponent(); + // TODO This is shitcode. Move this to an entity system, FOR FUCK'S SAKE + _entityManager.AddComponent(eventArgs.NewEntity); } /// /// Remove the character interface master from this entity now that we have detached ourselves from it /// - public static void DetachPlayerFromEntity(EntityDetachedEventArgs eventArgs) + public void DetachPlayerFromEntity(EntityDetachedEventArgs eventArgs) { - if (!eventArgs.OldEntity.Deleted) + // TODO This is shitcode. Move this to an entity system, FOR FUCK'S SAKE + if (!_entityManager.Deleted(eventArgs.OldEntity)) { - eventArgs.OldEntity.RemoveComponent(); + _entityManager.RemoveComponent(eventArgs.OldEntity); } } diff --git a/Content.Client/Examine/ExamineSystem.cs b/Content.Client/Examine/ExamineSystem.cs index a226d0b5a1..d3c3c90eaa 100644 --- a/Content.Client/Examine/ExamineSystem.cs +++ b/Content.Client/Examine/ExamineSystem.cs @@ -10,7 +10,6 @@ using Robust.Client.Graphics; using Robust.Client.Player; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; -using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Input.Binding; using Robust.Shared.IoC; @@ -33,8 +32,8 @@ namespace Content.Client.Examine public const string StyleClassEntityTooltip = "entity-tooltip"; - private IEntity? _examinedEntity; - private IEntity? _playerEntity; + private EntityUid _examinedEntity; + private EntityUid _playerEntity; private Popup? _examineTooltipOpen; private CancellationTokenSource? _requestCancelTokenSource; @@ -51,8 +50,8 @@ namespace Content.Client.Examine public override void Update(float frameTime) { - if (_examineTooltipOpen == null || !_examineTooltipOpen.Visible) return; - if (_examinedEntity == null || _playerEntity == null) return; + if (_examineTooltipOpen is not {Visible: true}) return; + if (!_examinedEntity.Valid || !_playerEntity.Valid) return; if (!CanExamine(_playerEntity, _examinedEntity)) CloseTooltip(); @@ -64,7 +63,7 @@ namespace Content.Client.Examine base.Shutdown(); } - public override bool CanExamine(IEntity examiner, MapCoordinates target, Ignored? predicate = null) + public override bool CanExamine(EntityUid examiner, MapCoordinates target, Ignored? predicate = null) { var b = _eyeManager.GetWorldViewbounds(); if (!b.Contains(target.Position)) @@ -73,16 +72,16 @@ namespace Content.Client.Examine return base.CanExamine(examiner, target, predicate); } - private bool HandleExamine(ICommonSession? session, EntityCoordinates coords, EntityUid uid) + private bool HandleExamine(ICommonSession? session, EntityCoordinates coords, EntityUid entity) { - if (!uid.IsValid() || !EntityManager.TryGetEntity(uid, out var entity)) + if (!entity.IsValid() || !EntityManager.EntityExists(entity)) { return false; } - _playerEntity = _playerManager.LocalPlayer?.ControlledEntity; + _playerEntity = _playerManager.LocalPlayer?.ControlledEntity ?? default; - if (_playerEntity == null || !CanExamine(_playerEntity, entity)) + if (_playerEntity == default || !CanExamine(_playerEntity, entity)) { return false; } @@ -104,7 +103,7 @@ namespace Content.Client.Examine args.Verbs.Add(verb); } - public async void DoExamine(IEntity entity) + public async void DoExamine(EntityUid entity) { // Close any examine tooltip that might already be opened CloseTooltip(); @@ -136,14 +135,14 @@ namespace Content.Client.Examine }; vBox.AddChild(hBox); - if (entity.TryGetComponent(out ISpriteComponent? sprite)) + if (EntityManager.TryGetComponent(entity, out ISpriteComponent? sprite)) { hBox.AddChild(new SpriteView { Sprite = sprite, OverrideDirection = Direction.South }); } hBox.AddChild(new Label { - Text = entity.Name, + Text = EntityManager.GetComponent(entity).EntityName, HorizontalExpand = true, }); @@ -153,14 +152,14 @@ namespace Content.Client.Examine _examineTooltipOpen.Open(UIBox2.FromDimensions(popupPos.Position, size)); FormattedMessage message; - if (entity.Uid.IsClientSide()) + if (entity.IsClientSide()) { message = GetExamineText(entity, _playerManager.LocalPlayer?.ControlledEntity); } else { // Ask server for extra examine info. - RaiseNetworkEvent(new ExamineSystemMessages.RequestExamineInfoMessage(entity.Uid)); + RaiseNetworkEvent(new ExamineSystemMessages.RequestExamineInfoMessage(entity)); ExamineSystemMessages.ExamineInfoResponseMessage response; try diff --git a/Content.Client/Explosion/ClusterFlashVisualizer.cs b/Content.Client/Explosion/ClusterFlashVisualizer.cs index 7ca1c02e11..406ddcedc5 100644 --- a/Content.Client/Explosion/ClusterFlashVisualizer.cs +++ b/Content.Client/Explosion/ClusterFlashVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Explosion; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Explosion @@ -17,7 +18,8 @@ namespace Content.Client.Explosion { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out var sprite)) { return; } diff --git a/Content.Client/Extinguisher/FireExtinguisherVisualizer.cs b/Content.Client/Extinguisher/FireExtinguisherVisualizer.cs index ea414509c2..e3f9759342 100644 --- a/Content.Client/Extinguisher/FireExtinguisherVisualizer.cs +++ b/Content.Client/Extinguisher/FireExtinguisherVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Extinguisher; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Extinguisher @@ -26,7 +27,7 @@ namespace Content.Client.Extinguisher private void SetSafety(AppearanceComponent component, bool safety) { - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); sprite.LayerSetState(FireExtinguisherVisualLayers.Base, safety ? _safetyOnState : _safetyOffState); } diff --git a/Content.Client/Flash/FlashSystem.cs b/Content.Client/Flash/FlashSystem.cs index 9ff86debd6..d6644811f5 100644 --- a/Content.Client/Flash/FlashSystem.cs +++ b/Content.Client/Flash/FlashSystem.cs @@ -27,7 +27,7 @@ namespace Content.Client.Flash return; // Yes, this code is awful. I'm just porting it to an entity system so don't blame me. - if (_playerManager.LocalPlayer != null && _playerManager.LocalPlayer.Session.AttachedEntityUid != uid) + if (_playerManager.LocalPlayer != null && _playerManager.LocalPlayer.Session.AttachedEntity != uid) { return; } diff --git a/Content.Client/Fluids/PuddleVisualizer.cs b/Content.Client/Fluids/PuddleVisualizer.cs index f6724e406f..77ac584c69 100644 --- a/Content.Client/Fluids/PuddleVisualizer.cs +++ b/Content.Client/Fluids/PuddleVisualizer.cs @@ -10,7 +10,6 @@ using Robust.Shared.Maths; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; - namespace Content.Client.Fluids { [UsedImplicitly] @@ -21,13 +20,13 @@ namespace Content.Client.Fluids // Whether the underlying solution color should be used [DataField("recolor")] public bool Recolor; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (!entity.TryGetComponent(out SpriteComponent? spriteComponent)) + if (!IoCManager.Resolve().TryGetComponent(entity, out SpriteComponent? spriteComponent)) { - Logger.Warning($"Missing SpriteComponent for PuddleVisualizer on entityUid = {entity.Uid}"); + Logger.Warning($"Missing SpriteComponent for PuddleVisualizer on entityUid = {entity}"); return; } @@ -46,8 +45,9 @@ namespace Content.Client.Fluids { base.OnChangeData(component); + var entities = IoCManager.Resolve(); if (component.TryGetData(PuddleVisuals.VolumeScale, out var volumeScale) && - component.Owner.TryGetComponent(out var spriteComponent)) + entities.TryGetComponent(component.Owner, out var spriteComponent)) { var cappedScale = Math.Min(1.0f, volumeScale * 0.75f +0.25f); UpdateVisual(component, spriteComponent, cappedScale); @@ -69,5 +69,5 @@ namespace Content.Client.Fluids spriteComponent.Color = newColor; } } - -} \ No newline at end of file + +} diff --git a/Content.Client/Ghost/GhostSystem.cs b/Content.Client/Ghost/GhostSystem.cs index 64f59c91cb..57aff0b24c 100644 --- a/Content.Client/Ghost/GhostSystem.cs +++ b/Content.Client/Ghost/GhostSystem.cs @@ -1,10 +1,9 @@ -using Content.Client.Ghost.UI; +using Content.Client.Ghost.UI; using Content.Client.HUD; using Content.Shared.Ghost; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.Player; -using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -36,7 +35,7 @@ namespace Content.Client.Ghost foreach (var ghost in EntityManager.GetAllComponents(typeof(GhostComponent), true)) { - if (ghost.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (EntityManager.TryGetComponent(ghost.Owner, out SpriteComponent? sprite)) { sprite.Visible = value; } @@ -60,7 +59,7 @@ namespace Content.Client.Ghost private void OnGhostInit(EntityUid uid, GhostComponent component, ComponentInit args) { - if (component.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (EntityManager.TryGetComponent(component.Owner, out SpriteComponent? sprite)) { sprite.Visible = GhostVisibility; } @@ -104,7 +103,7 @@ namespace Content.Client.Ghost var entity = _playerManager.LocalPlayer?.ControlledEntity; if (entity == null || - !entity.TryGetComponent(out GhostComponent? ghost)) + !EntityManager.TryGetComponent(entity.Value, out GhostComponent? ghost)) { return; } diff --git a/Content.Client/Gravity/GravityGeneratorVisualizer.cs b/Content.Client/Gravity/GravityGeneratorVisualizer.cs index e9e5c0766e..cc1b9808ad 100644 --- a/Content.Client/Gravity/GravityGeneratorVisualizer.cs +++ b/Content.Client/Gravity/GravityGeneratorVisualizer.cs @@ -4,6 +4,7 @@ using Content.Shared.Gravity; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -37,11 +38,11 @@ namespace Content.Client.Gravity } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (!entity.TryGetComponent(out SpriteComponent? sprite)) + if (!IoCManager.Resolve().TryGetComponent(entity, out SpriteComponent? sprite)) return; sprite.LayerMapReserveBlank(GravityGeneratorVisualLayers.Base); @@ -52,7 +53,7 @@ namespace Content.Client.Gravity { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (component.TryGetData(GravityGeneratorVisuals.State, out GravityGeneratorStatus state)) { diff --git a/Content.Client/Gravity/UI/GravityGeneratorWindow.xaml.cs b/Content.Client/Gravity/UI/GravityGeneratorWindow.xaml.cs index 730b3dc678..d7fb80dcba 100644 --- a/Content.Client/Gravity/UI/GravityGeneratorWindow.xaml.cs +++ b/Content.Client/Gravity/UI/GravityGeneratorWindow.xaml.cs @@ -7,6 +7,7 @@ using Robust.Client.GameObjects; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Client.UserInterface.XAML; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; @@ -33,7 +34,7 @@ namespace Content.Client.Gravity.UI OnButton.OnPressed += _ => _owner.SetPowerSwitch(true); OffButton.OnPressed += _ => _owner.SetPowerSwitch(false); - EntityView.Sprite = component.Owner.GetComponent(); + EntityView.Sprite = IoCManager.Resolve().GetComponent(component.Owner); } public void UpdateState(SharedGravityGeneratorComponent.GeneratorState state) diff --git a/Content.Client/Hands/HandsComponent.cs b/Content.Client/Hands/HandsComponent.cs index 5949b44316..4a81bd6958 100644 --- a/Content.Client/Hands/HandsComponent.cs +++ b/Content.Client/Hands/HandsComponent.cs @@ -1,6 +1,7 @@ using Content.Shared.Hands.Components; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Hands { @@ -37,7 +38,7 @@ namespace Content.Client.Hands public void UpdateHandContainers() { - if (!Owner.TryGetComponent(out var containerMan)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out var containerMan)) return; foreach (var hand in Hands) diff --git a/Content.Client/Hands/HandsGui.xaml.cs b/Content.Client/Hands/HandsGui.xaml.cs index ccb679790a..abe5f35685 100644 --- a/Content.Client/Hands/HandsGui.xaml.cs +++ b/Content.Client/Hands/HandsGui.xaml.cs @@ -100,7 +100,7 @@ namespace Content.Client.Hands // Show blocked overlay if hand is blocked. newButton.Blocked.Visible = - hand.HeldItem != null && hand.HeldItem.HasComponent(); + hand.HeldItem != null && IoCManager.Resolve().HasComponent(hand.HeldItem); } if (TryGetActiveHand(out var activeHand)) @@ -250,7 +250,7 @@ namespace Content.Client.Hands /// The item being held in this hand. /// [ViewVariables] - public IEntity? HeldItem { get; } + public EntityUid HeldItem { get; } /// /// The button in the gui associated with this hand. Assumed to be set by gui shortly after being received from the client HandsComponent. @@ -258,7 +258,7 @@ namespace Content.Client.Hands [ViewVariables] public HandButton HandButton { get; set; } = default!; - public GuiHand(string name, HandLocation handLocation, IEntity? heldItem) + public GuiHand(string name, HandLocation handLocation, EntityUid heldItem) { Name = name; HandLocation = handLocation; diff --git a/Content.Client/Hands/HandsVisualizer.cs b/Content.Client/Hands/HandsVisualizer.cs index 993e1032b5..38704a05d1 100644 --- a/Content.Client/Hands/HandsVisualizer.cs +++ b/Content.Client/Hands/HandsVisualizer.cs @@ -1,24 +1,22 @@ +using System; using Content.Shared.Hands.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.ResourceManagement; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Maths; -using System; -using System.Collections.Generic; namespace Content.Client.Hands { [UsedImplicitly] public class HandsVisualizer : AppearanceVisualizer { - public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out var sprite)) return; if (!component.TryGetData(HandsVisuals.VisualState, out HandsVisualState visualState)) return; foreach (HandLocation location in Enum.GetValues(typeof(HandLocation))) diff --git a/Content.Client/Hands/ShowHandItemOverlay.cs b/Content.Client/Hands/ShowHandItemOverlay.cs index 8515ed9ffe..1c73cbc0a8 100644 --- a/Content.Client/Hands/ShowHandItemOverlay.cs +++ b/Content.Client/Hands/ShowHandItemOverlay.cs @@ -46,7 +46,7 @@ namespace Content.Client.Hands var sys = EntitySystem.Get(); var handEntity = sys.GetActiveHandEntity(); - if (handEntity == null || !_cfg.GetCVar(CCVars.HudHeldItemShow) || !handEntity.HasComponent()) + if (handEntity == default || !_cfg.GetCVar(CCVars.HudHeldItemShow) || !IoCManager.Resolve().HasComponent(handEntity)) return; var screen = args.ScreenHandle; diff --git a/Content.Client/Hands/Systems/HandsSystem.cs b/Content.Client/Hands/Systems/HandsSystem.cs index fc98ea8d1c..c3abe34cb4 100644 --- a/Content.Client/Hands/Systems/HandsSystem.cs +++ b/Content.Client/Hands/Systems/HandsSystem.cs @@ -50,19 +50,19 @@ namespace Content.Client.Hands protected override void HandleContainerModified(EntityUid uid, SharedHandsComponent component, ContainerModifiedMessage args) { - if (uid == _playerManager.LocalPlayer?.ControlledEntity?.Uid) + if (uid == _playerManager.LocalPlayer?.ControlledEntity) GuiStateUpdated?.Invoke(); } private void HandlePickupAnimation(PickupAnimationMessage msg) { - if (!EntityManager.TryGetEntity(msg.EntityUid, out var entity)) + if (!msg.EntityUid.IsValid()) return; if (!_gameTiming.IsFirstTimePredicted) return; - ReusableAnimations.AnimateEntityPickup(entity, msg.InitialPosition, msg.FinalPosition); + ReusableAnimations.AnimateEntityPickup(msg.EntityUid, msg.InitialPosition, msg.FinalPosition, EntityManager); } public HandsGuiState GetGuiState() @@ -77,10 +77,10 @@ namespace Content.Client.Hands return new HandsGuiState(states, hands.ActiveHand); } - public IEntity? GetActiveHandEntity() + public EntityUid GetActiveHandEntity() { if (GetPlayerHandsComponent() is not { ActiveHand: { } active } hands) - return null; + return default; return hands.GetHand(active).HeldEntity; } @@ -89,7 +89,7 @@ namespace Content.Client.Hands { var player = _playerManager.LocalPlayer?.ControlledEntity; - if (player == null || !player.TryGetComponent(out HandsComponent? hands)) + if (player is not {Valid: true} || !EntityManager.TryGetComponent(player.Value, out HandsComponent? hands)) return null; return hands; @@ -106,7 +106,7 @@ namespace Content.Client.Hands var pressedEntity = pressedHand.HeldEntity; var activeEntity = activeHand.HeldEntity; - if (pressedHand == activeHand && activeEntity != null) + if (pressedHand == activeHand && activeEntity != default) { // use item in hand // it will always be attack_self() in my heart. @@ -114,21 +114,21 @@ namespace Content.Client.Hands return; } - if (pressedHand != activeHand && pressedEntity == null) + if (pressedHand != activeHand && pressedEntity == default) { // change active hand RaiseNetworkEvent(new RequestSetHandEvent(handName)); return; } - if (pressedHand != activeHand && pressedEntity != null && activeEntity != null) + if (pressedHand != activeHand && pressedEntity != default && activeEntity != default) { // use active item on held item RaiseNetworkEvent(new ClientInteractUsingInHandMsg(pressedHand.Name)); return; } - if (pressedHand != activeHand && pressedEntity != null && activeEntity == null) + if (pressedHand != activeHand && pressedEntity != default && activeEntity == default) { // use active item on held item RaiseNetworkEvent(new MoveItemFromHandMsg(pressedHand.Name)); diff --git a/Content.Client/HealthOverlay/HealthOverlaySystem.cs b/Content.Client/HealthOverlay/HealthOverlaySystem.cs index 8d43da2692..b04d47f77c 100644 --- a/Content.Client/HealthOverlay/HealthOverlaySystem.cs +++ b/Content.Client/HealthOverlay/HealthOverlaySystem.cs @@ -15,9 +15,10 @@ namespace Content.Client.HealthOverlay public class HealthOverlaySystem : EntitySystem { [Dependency] private readonly IEyeManager _eyeManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; private readonly Dictionary _guis = new(); - private IEntity? _attachedEntity; + private EntityUid? _attachedEntity; private bool _enabled; public bool Enabled @@ -55,7 +56,7 @@ namespace Content.Client.HealthOverlay } _guis.Clear(); - _attachedEntity = null; + _attachedEntity = default; } private void HandlePlayerAttached(PlayerAttachSysMessage message) @@ -72,7 +73,7 @@ namespace Content.Client.HealthOverlay return; } - if (_attachedEntity == null || _attachedEntity.Deleted) + if (_attachedEntity is not {} ent || Deleted(ent)) { return; } @@ -83,25 +84,25 @@ namespace Content.Client.HealthOverlay { var entity = mobState.Owner; - if (_attachedEntity.Transform.MapID != entity.Transform.MapID || - !viewBox.Contains(entity.Transform.WorldPosition)) + if (_entities.GetComponent(ent).MapID != _entities.GetComponent(entity).MapID || + !viewBox.Contains(_entities.GetComponent(entity).WorldPosition)) { - if (_guis.TryGetValue(entity.Uid, out var oldGui)) + if (_guis.TryGetValue(entity, out var oldGui)) { - _guis.Remove(entity.Uid); - oldGui.Dispose(); + _guis.Remove(entity); + oldGui.Dispose(); } continue; } - if (_guis.ContainsKey(entity.Uid)) + if (_guis.ContainsKey(entity)) { continue; } var gui = new HealthOverlayGui(entity); - _guis.Add(entity.Uid, gui); + _guis.Add(entity, gui); } } } diff --git a/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs b/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs index 7f41f8f458..9d81acac07 100644 --- a/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs +++ b/Content.Client/HealthOverlay/UI/HealthOverlayGui.cs @@ -16,8 +16,9 @@ namespace Content.Client.HealthOverlay.UI public class HealthOverlayGui : BoxContainer { [Dependency] private readonly IEyeManager _eyeManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; - public HealthOverlayGui(IEntity entity) + public HealthOverlayGui(EntityUid entity) { IoCManager.InjectDependencies(this); IoCManager.Resolve().StateRoot.AddChild(this); @@ -62,7 +63,7 @@ namespace Content.Client.HealthOverlay.UI public HealthOverlayBar CritBar { get; } - public IEntity Entity { get; } + public EntityUid Entity { get; } public void SetVisibility(bool val) { @@ -72,13 +73,13 @@ namespace Content.Client.HealthOverlay.UI private void MoreFrameUpdate(FrameEventArgs args) { - if (Entity.Deleted) + if (_entities.Deleted(Entity)) { return; } - if (!Entity.TryGetComponent(out MobStateComponent? mobState) || - !Entity.TryGetComponent(out DamageableComponent? damageable)) + if (!_entities.TryGetComponent(Entity, out MobStateComponent? mobState) || + !_entities.TryGetComponent(Entity, out DamageableComponent? damageable)) { CritBar.Visible = false; HealthBar.Visible = false; @@ -138,8 +139,7 @@ namespace Content.Client.HealthOverlay.UI MoreFrameUpdate(args); - if (Entity.Deleted || - _eyeManager.CurrentMap != Entity.Transform.MapID) + if (_entities.Deleted(Entity) || _eyeManager.CurrentMap != _entities.GetComponent(Entity).MapID) { Visible = false; return; @@ -147,7 +147,7 @@ namespace Content.Client.HealthOverlay.UI Visible = true; - var screenCoordinates = _eyeManager.CoordinatesToScreen(Entity.Transform.Coordinates); + var screenCoordinates = _eyeManager.CoordinatesToScreen(_entities.GetComponent(Entity).Coordinates); var playerPosition = UserInterfaceManager.ScreenToUIPosition(screenCoordinates); LayoutContainer.SetPosition(this, new Vector2(playerPosition.X - Width / 2, playerPosition.Y - Height - 30.0f)); } diff --git a/Content.Client/IconSmoothing/IconSmoothComponent.cs b/Content.Client/IconSmoothing/IconSmoothComponent.cs index deb8113c45..d1de5616ad 100644 --- a/Content.Client/IconSmoothing/IconSmoothComponent.cs +++ b/Content.Client/IconSmoothing/IconSmoothComponent.cs @@ -26,6 +26,7 @@ namespace Content.Client.IconSmoothing [RegisterComponent] public class IconSmoothComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IMapManager _mapManager = default!; [DataField("mode")] @@ -63,7 +64,7 @@ namespace Content.Client.IconSmoothing { base.Initialize(); - Sprite = Owner.GetComponent(); + Sprite = _entMan.GetComponent(Owner); } /// @@ -71,12 +72,12 @@ namespace Content.Client.IconSmoothing { base.Startup(); - if (Owner.Transform.Anchored) + if (_entMan.GetComponent(Owner).Anchored) { // ensures lastposition initial value is populated on spawn. Just calling // the hook here would cause a dirty event to fire needlessly UpdateLastPosition(); - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new IconSmoothDirtyEvent(Owner, null, Mode)); + _entMan.EventBus.RaiseEvent(EventSource.Local, new IconSmoothDirtyEvent(Owner, null, Mode)); } if (Sprite != null && Mode == IconSmoothingMode.Corners) @@ -95,9 +96,9 @@ namespace Content.Client.IconSmoothing private void UpdateLastPosition() { - if (_mapManager.TryGetGrid(Owner.Transform.GridID, out var grid)) + if (_mapManager.TryGetGrid(_entMan.GetComponent(Owner).GridID, out var grid)) { - _lastPosition = (Owner.Transform.GridID, grid.TileIndicesFor(Owner.Transform.Coordinates)); + _lastPosition = (_entMan.GetComponent(Owner).GridID, grid.TileIndicesFor(_entMan.GetComponent(Owner).Coordinates)); } else { @@ -109,9 +110,9 @@ namespace Content.Client.IconSmoothing internal virtual void CalculateNewSprite() { - if (!_mapManager.TryGetGrid(Owner.Transform.GridID, out var grid)) + if (!_mapManager.TryGetGrid(_entMan.GetComponent(Owner).GridID, out var grid)) { - Logger.Error($"Failed to calculate IconSmoothComponent sprite in {Owner} because grid {Owner.Transform.GridID} was missing."); + Logger.Error($"Failed to calculate IconSmoothComponent sprite in {Owner} because grid {_entMan.GetComponent(Owner).GridID} was missing."); return; } CalculateNewSprite(grid); @@ -136,14 +137,14 @@ namespace Content.Client.IconSmoothing private void CalculateNewSpriteCardinal(IMapGrid grid) { - if (!Owner.Transform.Anchored || Sprite == null) + if (!_entMan.GetComponent(Owner).Anchored || Sprite == null) { return; } var dirs = CardinalConnectDirs.None; - var position = Owner.Transform.Coordinates; + var position = _entMan.GetComponent(Owner).Coordinates; if (MatchingEntity(grid.GetInDir(position, Direction.North))) dirs |= CardinalConnectDirs.North; if (MatchingEntity(grid.GetInDir(position, Direction.South))) @@ -173,12 +174,12 @@ namespace Content.Client.IconSmoothing protected (CornerFill ne, CornerFill nw, CornerFill sw, CornerFill se) CalculateCornerFill(IMapGrid grid) { - if (!Owner.Transform.Anchored) + if (!_entMan.GetComponent(Owner).Anchored) { return (CornerFill.None, CornerFill.None, CornerFill.None, CornerFill.None); } - var position = Owner.Transform.Coordinates; + var position = _entMan.GetComponent(Owner).Coordinates; var n = MatchingEntity(grid.GetInDir(position, Direction.North)); var ne = MatchingEntity(grid.GetInDir(position, Direction.NorthEast)); var e = MatchingEntity(grid.GetInDir(position, Direction.East)); @@ -240,7 +241,7 @@ namespace Content.Client.IconSmoothing } // Local is fine as we already know it's parented to the grid (due to the way anchoring works). - switch (Owner.Transform.LocalRotation.GetCardinalDir()) + switch (_entMan.GetComponent(Owner).LocalRotation.GetCardinalDir()) { case Direction.North: return (cornerSW, cornerSE, cornerNE, cornerNW); @@ -258,17 +259,17 @@ namespace Content.Client.IconSmoothing { base.Shutdown(); - if (Owner.Transform.Anchored) + if (_entMan.GetComponent(Owner).Anchored) { - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new IconSmoothDirtyEvent(Owner, _lastPosition, Mode)); + _entMan.EventBus.RaiseEvent(EventSource.Local, new IconSmoothDirtyEvent(Owner, _lastPosition, Mode)); } } public void AnchorStateChanged() { - if (Owner.Transform.Anchored) + if (_entMan.GetComponent(Owner).Anchored) { - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new IconSmoothDirtyEvent(Owner, _lastPosition, Mode)); + _entMan.EventBus.RaiseEvent(EventSource.Local, new IconSmoothDirtyEvent(Owner, _lastPosition, Mode)); UpdateLastPosition(); } } @@ -278,7 +279,7 @@ namespace Content.Client.IconSmoothing { foreach (var entity in candidates) { - if (!Owner.EntityManager.TryGetComponent(entity, out IconSmoothComponent? other)) + if (!_entMan.TryGetComponent(entity, out IconSmoothComponent? other)) { continue; } diff --git a/Content.Client/IconSmoothing/IconSmoothSystem.cs b/Content.Client/IconSmoothing/IconSmoothSystem.cs index eefbc01e8a..c38d7c8352 100644 --- a/Content.Client/IconSmoothing/IconSmoothSystem.cs +++ b/Content.Client/IconSmoothing/IconSmoothSystem.cs @@ -51,14 +51,14 @@ namespace Content.Client.IconSmoothing // Yes, we updates ALL smoothing entities surrounding us even if they would never smooth with us. // This is simpler to implement. If you want to optimize it be my guest. var senderEnt = ev.Sender; - if (senderEnt.IsValid() && - _mapManager.TryGetGrid(senderEnt.Transform.GridID, out var grid1) && - senderEnt.TryGetComponent(out IconSmoothComponent? iconSmooth) + if (EntityManager.EntityExists(senderEnt) && + _mapManager.TryGetGrid(EntityManager.GetComponent(senderEnt).GridID, out var grid1) && + EntityManager.TryGetComponent(senderEnt, out IconSmoothComponent? iconSmooth) && iconSmooth.Running) { - var coords = senderEnt.Transform.Coordinates; + var coords = EntityManager.GetComponent(senderEnt).Coordinates; - _dirtyEntities.Enqueue(senderEnt.Uid); + _dirtyEntities.Enqueue(senderEnt); AddValidEntities(grid1.GetInDir(coords, Direction.North)); AddValidEntities(grid1.GetInDir(coords, Direction.South)); AddValidEntities(grid1.GetInDir(coords, Direction.East)); @@ -130,7 +130,7 @@ namespace Content.Client.IconSmoothing /// public sealed class IconSmoothDirtyEvent : EntityEventArgs { - public IconSmoothDirtyEvent(IEntity sender, (GridId grid, Vector2i pos)? lastPosition, IconSmoothingMode mode) + public IconSmoothDirtyEvent(EntityUid sender, (GridId grid, Vector2i pos)? lastPosition, IconSmoothingMode mode) { LastPosition = lastPosition; Mode = mode; @@ -139,6 +139,6 @@ namespace Content.Client.IconSmoothing public (GridId grid, Vector2i pos)? LastPosition { get; } public IconSmoothingMode Mode { get; } - public IEntity Sender { get; } + public EntityUid Sender { get; } } } diff --git a/Content.Client/Instruments/InstrumentSystem.cs b/Content.Client/Instruments/InstrumentSystem.cs index 51419df143..05e2049cf1 100644 --- a/Content.Client/Instruments/InstrumentSystem.cs +++ b/Content.Client/Instruments/InstrumentSystem.cs @@ -319,7 +319,7 @@ namespace Content.Client.Instruments foreach (var instrument in EntityManager.EntityQuery(true)) { if (instrument.DirtyRenderer && instrument.Renderer != null) - UpdateRenderer(instrument.OwnerUid, instrument); + UpdateRenderer(instrument.Owner, instrument); if (!instrument.IsMidiOpen && !instrument.IsInputOpen) continue; @@ -366,7 +366,7 @@ namespace Content.Client.Instruments if (eventCount == 0) continue; - RaiseNetworkEvent(new InstrumentMidiEventEvent(instrument.OwnerUid, events)); + RaiseNetworkEvent(new InstrumentMidiEventEvent(instrument.Owner, events)); instrument.SentWithinASec += eventCount; diff --git a/Content.Client/Instruments/UI/InstrumentBoundUserInterface.cs b/Content.Client/Instruments/UI/InstrumentBoundUserInterface.cs index 67bafc8e43..c94c0c3206 100644 --- a/Content.Client/Instruments/UI/InstrumentBoundUserInterface.cs +++ b/Content.Client/Instruments/UI/InstrumentBoundUserInterface.cs @@ -1,4 +1,6 @@ using Robust.Client.GameObjects; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Client.Instruments.UI @@ -16,7 +18,7 @@ namespace Content.Client.Instruments.UI protected override void Open() { - if (!Owner.Owner.TryGetComponent(out var instrument)) return; + if (!IoCManager.Resolve().TryGetComponent(Owner.Owner, out var instrument)) return; Instrument = instrument; _instrumentMenu = new InstrumentMenu(this); diff --git a/Content.Client/Instruments/UI/InstrumentMenu.xaml.cs b/Content.Client/Instruments/UI/InstrumentMenu.xaml.cs index 3ef9492cd3..afc15ca9d8 100644 --- a/Content.Client/Instruments/UI/InstrumentMenu.xaml.cs +++ b/Content.Client/Instruments/UI/InstrumentMenu.xaml.cs @@ -36,7 +36,7 @@ namespace Content.Client.Instruments.UI if (_owner.Instrument != null) { _owner.Instrument.OnMidiPlaybackEnded += InstrumentOnMidiPlaybackEnded; - Title = _owner.Instrument.Owner.Name; + Title = IoCManager.Resolve().GetComponent(_owner.Instrument.Owner).EntityName; LoopButton.Disabled = !_owner.Instrument.IsMidiOpen; LoopButton.Pressed = _owner.Instrument.LoopMidi; StopButton.Disabled = !_owner.Instrument.IsMidiOpen; @@ -104,7 +104,7 @@ namespace Content.Client.Instruments.UI await Task.WhenAll(Timer.Delay(100), file.CopyToAsync(memStream)); if (_owner.Instrument is not {} instrument - || !EntitySystem.Get().OpenMidi(instrument.OwnerUid, memStream.GetBuffer().AsSpan(0, (int) memStream.Length), instrument)) + || !EntitySystem.Get().OpenMidi(instrument.Owner, memStream.GetBuffer().AsSpan(0, (int) memStream.Length), instrument)) return; MidiPlaybackSetButtonsDisabled(false); @@ -123,10 +123,10 @@ namespace Content.Client.Instruments.UI MidiStopButtonOnPressed(null); if(_owner.Instrument is {} instrument) - instrumentSystem.OpenInput(instrument.OwnerUid, instrument); + instrumentSystem.OpenInput(instrument.Owner, instrument); } else if(_owner.Instrument is {} instrument) - instrumentSystem.CloseInput(instrument.OwnerUid, false, instrument); + instrumentSystem.CloseInput(instrument.Owner, false, instrument); } private bool PlayCheck() @@ -139,7 +139,7 @@ namespace Content.Client.Instruments.UI return false; // If we're a handheld instrument, we might be in a container. Get it just in case. - instrumentEnt.TryGetContainerMan(out var conMan); + instrumentEnt.Value.TryGetContainerMan(out var conMan); var localPlayer = IoCManager.Resolve().LocalPlayer; @@ -151,7 +151,7 @@ namespace Content.Client.Instruments.UI || conMan.Owner != localPlayer.ControlledEntity))) return false; // We check that we're in range unobstructed just in case. - return localPlayer.InRangeUnobstructed(instrumentEnt, + return localPlayer.InRangeUnobstructed(instrumentEnt.Value, predicate: (e) => e == instrumentEnt || e == localPlayer.ControlledEntity); } @@ -162,7 +162,7 @@ namespace Content.Client.Instruments.UI if (_owner.Instrument is not { } instrument) return; - EntitySystem.Get().CloseMidi(instrument.OwnerUid, false, instrument); + EntitySystem.Get().CloseMidi(instrument.Owner, false, instrument); } private void MidiLoopButtonOnOnToggled(ButtonToggledEventArgs obj) @@ -179,14 +179,14 @@ namespace Content.Client.Instruments.UI // Do not seek while still grabbing. if (PlaybackSlider.Grabbed || _owner.Instrument is not {} instrument) return; - EntitySystem.Get().SetPlayerTick(instrument.OwnerUid, (int)Math.Ceiling(PlaybackSlider.Value), instrument); + EntitySystem.Get().SetPlayerTick(instrument.Owner, (int)Math.Ceiling(PlaybackSlider.Value), instrument); } private void PlaybackSliderKeyUp(GUIBoundKeyEventArgs args) { if (args.Function != EngineKeyFunctions.UIClick || _owner.Instrument is not {} instrument) return; - EntitySystem.Get().SetPlayerTick(instrument.OwnerUid, (int)Math.Ceiling(PlaybackSlider.Value), instrument); + EntitySystem.Get().SetPlayerTick(instrument.Owner, (int)Math.Ceiling(PlaybackSlider.Value), instrument); } protected override void FrameUpdate(FrameEventArgs args) diff --git a/Content.Client/Interactable/Components/InteractionOutlineComponent.cs b/Content.Client/Interactable/Components/InteractionOutlineComponent.cs index da3da6a773..17a313e3db 100644 --- a/Content.Client/Interactable/Components/InteractionOutlineComponent.cs +++ b/Content.Client/Interactable/Components/InteractionOutlineComponent.cs @@ -10,6 +10,7 @@ namespace Content.Client.Interactable.Components public class InteractionOutlineComponent : Component { [Dependency] private readonly IPrototypeManager _prototypeManager = default!; + [Dependency] private readonly IEntityManager _entMan = default!; private const float DefaultWidth = 1; private const string ShaderInRange = "SelectionOutlineInrange"; @@ -25,16 +26,16 @@ namespace Content.Client.Interactable.Components { _lastRenderScale = renderScale; _inRange = inInteractionRange; - if (Owner.TryGetComponent(out ISpriteComponent? sprite)) + if (_entMan.TryGetComponent(Owner, out ISpriteComponent? sprite)) { sprite.PostShader = MakeNewShader(inInteractionRange, renderScale); - sprite.RenderOrder = Owner.EntityManager.CurrentTick.Value; + sprite.RenderOrder = _entMan.CurrentTick.Value; } } public void OnMouseLeave() { - if (Owner.TryGetComponent(out ISpriteComponent? sprite)) + if (_entMan.TryGetComponent(Owner, out ISpriteComponent? sprite)) { sprite.PostShader = null; sprite.RenderOrder = 0; @@ -46,7 +47,7 @@ namespace Content.Client.Interactable.Components public void UpdateInRange(bool inInteractionRange, int renderScale) { - if (Owner.TryGetComponent(out ISpriteComponent? sprite) + if (_entMan.TryGetComponent(Owner, out ISpriteComponent? sprite) && (inInteractionRange != _inRange || _lastRenderScale != renderScale)) { _inRange = inInteractionRange; diff --git a/Content.Client/Interactable/InteractionSystem.cs b/Content.Client/Interactable/InteractionSystem.cs index 0103ece58c..2abb966549 100644 --- a/Content.Client/Interactable/InteractionSystem.cs +++ b/Content.Client/Interactable/InteractionSystem.cs @@ -9,13 +9,13 @@ namespace Content.Client.Interactable { public override bool CanAccessViaStorage(EntityUid user, EntityUid target) { - if (!EntityManager.TryGetEntity(target, out var entity)) + if (!EntityManager.EntityExists(target)) return false; - if (!entity.TryGetContainer(out var container)) + if (!target.TryGetContainer(out var container)) return false; - if (!EntityManager.TryGetComponent(container.Owner.Uid, out ClientStorageComponent storage)) + if (!EntityManager.TryGetComponent(container.Owner, out ClientStorageComponent storage)) return false; // we don't check if the user can access the storage entity itself. This should be handed by the UI system. diff --git a/Content.Client/Interactable/UnobstructedExtensions.cs b/Content.Client/Interactable/UnobstructedExtensions.cs index aa3ad83bdf..9d320c276a 100644 --- a/Content.Client/Interactable/UnobstructedExtensions.cs +++ b/Content.Client/Interactable/UnobstructedExtensions.cs @@ -15,14 +15,14 @@ namespace Content.Client.Interactable public static bool InRangeUnobstructed( this LocalPlayer origin, - IEntity other, + EntityUid other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, Ignored? predicate = null, bool ignoreInsideBlocker = false, bool popup = false) { - var otherPosition = other.Transform.MapPosition; + var otherPosition = IoCManager.Resolve().GetComponent(other).MapPosition; return origin.InRangeUnobstructed(otherPosition, range, collisionMask, predicate, ignoreInsideBlocker, popup); @@ -84,7 +84,7 @@ namespace Content.Client.Interactable return false; } - return SharedInteractionSystem.InRangeUnobstructed(originEntity, other, range, collisionMask, predicate, + return SharedInteractionSystem.InRangeUnobstructed(originEntity.Value, other, range, collisionMask, predicate, ignoreInsideBlocker, popup); } } diff --git a/Content.Client/Inventory/ClientInventoryComponent.cs b/Content.Client/Inventory/ClientInventoryComponent.cs index 56062b5255..0c9f0e619f 100644 --- a/Content.Client/Inventory/ClientInventoryComponent.cs +++ b/Content.Client/Inventory/ClientInventoryComponent.cs @@ -3,9 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Client.Clothing; using Content.Shared.CharacterAppearance; -using Content.Shared.Chemistry; using Content.Shared.Inventory; -using Content.Shared.Movement.Components; using Content.Shared.Movement.EntitySystems; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; @@ -24,9 +22,11 @@ namespace Content.Client.Inventory [ComponentReference(typeof(SharedInventoryComponent))] public class ClientInventoryComponent : SharedInventoryComponent { - private readonly Dictionary _slots = new(); + [Dependency] private readonly IEntityManager _entMan = default!; - public IReadOnlyDictionary AllSlots => _slots; + private readonly Dictionary _slots = new(); + + public IReadOnlyDictionary AllSlots => _slots; [ViewVariables] public InventoryInterfaceController InterfaceController { get; private set; } = default!; @@ -78,9 +78,9 @@ namespace Content.Client.Inventory } } - public override bool IsEquipped(IEntity item) + public override bool IsEquipped(EntityUid item) { - return item != null && _slots.Values.Any(e => e == item); + return item != default && _slots.Values.Any(e => e == item); } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) @@ -92,9 +92,9 @@ namespace Content.Client.Inventory var doneSlots = new HashSet(); - foreach (var (slot, entityUid) in state.Entities) + foreach (var (slot, entity) in state.Entities) { - if (!Owner.EntityManager.TryGetEntity(entityUid, out var entity)) + if (!_entMan.EntityExists(entity)) { continue; } @@ -108,9 +108,7 @@ namespace Content.Client.Inventory if (state.HoverEntity != null) { - var (slot, (entityUid, fits)) = state.HoverEntity.Value; - var entity = Owner.EntityManager.GetEntity(entityUid); - + var (slot, (entity, fits)) = state.HoverEntity.Value; InterfaceController?.HoverInSlot(slot, entity, fits); } @@ -123,24 +121,24 @@ namespace Content.Client.Inventory } } - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); } - private void _setSlot(Slots slot, IEntity entity) + private void _setSlot(Slots slot, EntityUid entity) { SetSlotVisuals(slot, entity); InterfaceController?.AddToSlot(slot, entity); } - internal void SetSlotVisuals(Slots slot, IEntity entity) + internal void SetSlotVisuals(Slots slot, EntityUid entity) { if (_sprite == null) { return; } - if (entity.TryGetComponent(out ClothingComponent? clothing)) + if (_entMan.TryGetComponent(entity, out ClothingComponent? clothing)) { var flag = SlotMasks[slot]; var data = clothing.GetEquippedStateInfo(flag, SpeciesId); @@ -230,12 +228,12 @@ namespace Content.Client.Inventory _playerAttached = true; } - public bool TryGetSlot(Slots slot, [NotNullWhen(true)] out IEntity? item) + public bool TryGetSlot(Slots slot, [NotNullWhen(true)] out EntityUid item) { return _slots.TryGetValue(slot, out item); } - public bool TryFindItemSlots(IEntity item, [NotNullWhen(true)] out Slots? slots) + public bool TryFindItemSlots(EntityUid item, [NotNullWhen(true)] out Slots? slots) { slots = null; diff --git a/Content.Client/Inventory/ClientInventorySystem.cs b/Content.Client/Inventory/ClientInventorySystem.cs index d01c5d32eb..6c691803fa 100644 --- a/Content.Client/Inventory/ClientInventorySystem.cs +++ b/Content.Client/Inventory/ClientInventorySystem.cs @@ -1,5 +1,4 @@ using Content.Client.HUD; -using Content.Client.Items.Components; using Content.Shared.Input; using Content.Shared.Inventory; using Content.Shared.Movement.EntitySystems; @@ -36,9 +35,9 @@ namespace Content.Client.Inventory // jesus christ, this is duplicated to server/client, should really just be shared.. private void OnSlipAttemptEvent(EntityUid uid, ClientInventoryComponent component, SlipAttemptEvent args) { - if (component.TryGetSlot(EquipmentSlotDefines.Slots.SHOES, out IEntity? shoes)) + if (component.TryGetSlot(EquipmentSlotDefines.Slots.SHOES, out EntityUid shoes)) { - RaiseLocalEvent(shoes.Uid, args, false); + RaiseLocalEvent(shoes, args, false); } } @@ -46,9 +45,9 @@ namespace Content.Client.Inventory { foreach (var (_, ent) in component.AllSlots) { - if (ent != null) + if (ent != default) { - RaiseLocalEvent(ent.Uid, args, false); + RaiseLocalEvent(ent, args, false); } } } diff --git a/Content.Client/Inventory/HumanInventoryInterfaceController.cs b/Content.Client/Inventory/HumanInventoryInterfaceController.cs index 413f09978b..e1e1b62c34 100644 --- a/Content.Client/Inventory/HumanInventoryInterfaceController.cs +++ b/Content.Client/Inventory/HumanInventoryInterfaceController.cs @@ -3,10 +3,8 @@ using System.Linq; using Content.Client.HUD; using Content.Client.Items.Managers; using Content.Client.Items.UI; -using Content.Shared; using Content.Shared.CCVar; using JetBrains.Annotations; -using Robust.Client.ResourceManagement; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; @@ -15,7 +13,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; -using Robust.Shared.Prototypes; using static Content.Shared.Inventory.EquipmentSlotDefines; using static Robust.Client.UserInterface.Controls.BoxContainer; @@ -155,7 +152,7 @@ namespace Content.Client.Inventory return buttons; } - public override void AddToSlot(Slots slot, IEntity entity) + public override void AddToSlot(Slots slot, EntityUid entity) { base.AddToSlot(slot, entity); @@ -184,7 +181,7 @@ namespace Content.Client.Inventory } } - public override void HoverInSlot(Slots slot, IEntity entity, bool fits) + public override void HoverInSlot(Slots slot, EntityUid entity, bool fits) { base.HoverInSlot(slot, entity, fits); @@ -213,7 +210,7 @@ namespace Content.Client.Inventory private void ClearButton(ItemSlotButton button, Slots slot) { button.OnPressed = (e) => AddToInventory(e, slot); - _itemSlotManager.SetItemSlot(button, null); + _itemSlotManager.SetItemSlot(button, default); } public override void PlayerAttached() diff --git a/Content.Client/Inventory/InventoryInterfaceController.cs b/Content.Client/Inventory/InventoryInterfaceController.cs index 6aea2f466c..16f3efdf8f 100644 --- a/Content.Client/Inventory/InventoryInterfaceController.cs +++ b/Content.Client/Inventory/InventoryInterfaceController.cs @@ -46,11 +46,11 @@ namespace Content.Client.Inventory /// specified slot, if any. Empty if none. public abstract IEnumerable GetItemSlotButtons(EquipmentSlotDefines.Slots slot); - public virtual void AddToSlot(EquipmentSlotDefines.Slots slot, IEntity entity) + public virtual void AddToSlot(EquipmentSlotDefines.Slots slot, EntityUid entity) { } - public virtual void HoverInSlot(EquipmentSlotDefines.Slots slot, IEntity entity, bool fits) + public virtual void HoverInSlot(EquipmentSlotDefines.Slots slot, EntityUid entity, bool fits) { } diff --git a/Content.Client/Inventory/StrippableBoundUserInterface.cs b/Content.Client/Inventory/StrippableBoundUserInterface.cs index 943e3cd16f..dee8e4f03c 100644 --- a/Content.Client/Inventory/StrippableBoundUserInterface.cs +++ b/Content.Client/Inventory/StrippableBoundUserInterface.cs @@ -4,6 +4,7 @@ using Content.Shared.Strip.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.ViewVariables; using static Content.Shared.Inventory.EquipmentSlotDefines; @@ -28,7 +29,7 @@ namespace Content.Client.Inventory { base.Open(); - _strippingMenu = new StrippingMenu($"{Loc.GetString("strippable-bound-user-interface-stripping-menu-title",("ownerName", Owner.Owner.Name))}"); + _strippingMenu = new StrippingMenu($"{Loc.GetString("strippable-bound-user-interface-stripping-menu-title",("ownerName", Name: IoCManager.Resolve().GetComponent(Owner.Owner).EntityName))}"); _strippingMenu.OnClose += Close; _strippingMenu.OpenCentered(); diff --git a/Content.Client/Items/Components/ItemComponent.cs b/Content.Client/Items/Components/ItemComponent.cs index cd552ee288..7c60585abe 100644 --- a/Content.Client/Items/Components/ItemComponent.cs +++ b/Content.Client/Items/Components/ItemComponent.cs @@ -2,6 +2,7 @@ using Content.Client.Hands; using Content.Shared.Item; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Items.Components { @@ -14,7 +15,7 @@ namespace Content.Client.Items.Components if (!Owner.TryGetContainer(out var container)) return; - if (container.Owner.TryGetComponent(out HandsComponent? hands)) + if (IoCManager.Resolve().TryGetComponent(container.Owner, out HandsComponent? hands)) hands.UpdateHandVisualizer(); } } diff --git a/Content.Client/Items/Managers/IItemSlotManager.cs b/Content.Client/Items/Managers/IItemSlotManager.cs index bbebaf55b4..c5533a841a 100644 --- a/Content.Client/Items/Managers/IItemSlotManager.cs +++ b/Content.Client/Items/Managers/IItemSlotManager.cs @@ -7,10 +7,10 @@ namespace Content.Client.Items.Managers { public interface IItemSlotManager { - bool OnButtonPressed(GUIBoundKeyEventArgs args, IEntity? item); - void UpdateCooldown(ItemSlotButton? cooldownTexture, IEntity? entity); - bool SetItemSlot(ItemSlotButton button, IEntity? entity); - void HoverInSlot(ItemSlotButton button, IEntity? entity, bool fits); + bool OnButtonPressed(GUIBoundKeyEventArgs args, EntityUid item); + void UpdateCooldown(ItemSlotButton? cooldownTexture, EntityUid entity); + bool SetItemSlot(ItemSlotButton button, EntityUid entity); + void HoverInSlot(ItemSlotButton button, EntityUid entity, bool fits); event Action? EntityHighlightedUpdated; bool IsHighlighted(EntityUid uid); diff --git a/Content.Client/Items/Managers/ItemSlotManager.cs b/Content.Client/Items/Managers/ItemSlotManager.cs index 5c5aef9bf6..c8a6171225 100644 --- a/Content.Client/Items/Managers/ItemSlotManager.cs +++ b/Content.Client/Items/Managers/ItemSlotManager.cs @@ -9,12 +9,8 @@ using Content.Shared.Hands.Components; using Content.Shared.Input; using Content.Shared.Interaction; using Robust.Client.GameObjects; -using Robust.Client.Graphics; -using Robust.Client.Input; -using Robust.Client.Player; using Robust.Client.UserInterface; using Robust.Shared.GameObjects; -using Robust.Shared.Input; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -32,9 +28,9 @@ namespace Content.Client.Items.Managers public event Action? EntityHighlightedUpdated; - public bool SetItemSlot(ItemSlotButton button, IEntity? entity) + public bool SetItemSlot(ItemSlotButton button, EntityUid entity) { - if (entity == null) + if (entity == default) { button.SpriteView.Sprite = null; button.StorageButton.Visible = false; @@ -42,31 +38,31 @@ namespace Content.Client.Items.Managers else { ISpriteComponent? sprite; - if (entity.TryGetComponent(out HandVirtualItemComponent? virtPull) + if (_entityManager.TryGetComponent(entity, out HandVirtualItemComponent? virtPull) && _entityManager.TryGetComponent(virtPull.BlockingEntity, out ISpriteComponent pulledSprite)) { sprite = pulledSprite; } - else if (!entity.TryGetComponent(out sprite)) + else if (!_entityManager.TryGetComponent(entity, out sprite)) { return false; } button.ClearHover(); button.SpriteView.Sprite = sprite; - button.StorageButton.Visible = entity.HasComponent(); + button.StorageButton.Visible = _entityManager.HasComponent(entity); } - button.Entity = entity?.Uid ?? default; + button.Entity = entity; // im lazy button.UpdateSlotHighlighted(); return true; } - public bool OnButtonPressed(GUIBoundKeyEventArgs args, IEntity? item) + public bool OnButtonPressed(GUIBoundKeyEventArgs args, EntityUid item) { - if (item == null) + if (item == default) return false; if (args.Function == ContentKeyFunctions.ExamineEntity) @@ -80,11 +76,11 @@ namespace Content.Client.Items.Managers } else if (args.Function == ContentKeyFunctions.ActivateItemInWorld) { - _entityManager.EntityNetManager?.SendSystemNetworkMessage(new InteractInventorySlotEvent(item.Uid, altInteract: false)); + _entityManager.EntityNetManager?.SendSystemNetworkMessage(new InteractInventorySlotEvent(item, altInteract: false)); } else if (args.Function == ContentKeyFunctions.AltActivateItemInWorld) { - _entityManager.EntityNetManager?.SendSystemNetworkMessage(new InteractInventorySlotEvent(item.Uid, altInteract: true)); + _entityManager.EntityNetManager?.SendSystemNetworkMessage(new InteractInventorySlotEvent(item, altInteract: true)); } else { @@ -94,7 +90,7 @@ namespace Content.Client.Items.Managers return true; } - public void UpdateCooldown(ItemSlotButton? button, IEntity? entity) + public void UpdateCooldown(ItemSlotButton? button, EntityUid entity) { var cooldownDisplay = button?.CooldownDisplay; @@ -103,9 +99,8 @@ namespace Content.Client.Items.Managers return; } - if (entity == null || - entity.Deleted || - !entity.TryGetComponent(out ItemCooldownComponent? cooldown) || + if (entity == default || _entityManager.Deleted(entity) || + !_entityManager.TryGetComponent(entity, out ItemCooldownComponent? cooldown) || !cooldown.CooldownStart.HasValue || !cooldown.CooldownEnd.HasValue) { @@ -124,23 +119,23 @@ namespace Content.Client.Items.Managers cooldownDisplay.Visible = ratio > -1f; } - public void HoverInSlot(ItemSlotButton button, IEntity? entity, bool fits) + public void HoverInSlot(ItemSlotButton button, EntityUid entity, bool fits) { - if (entity == null || !button.MouseIsHovering) + if (entity == default || !button.MouseIsHovering) { button.ClearHover(); return; } - if (!entity.HasComponent()) + if (!_entityManager.HasComponent(entity)) { return; } // Set green / red overlay at 50% transparency var hoverEntity = _entityManager.SpawnEntity("hoverentity", MapCoordinates.Nullspace); - var hoverSprite = hoverEntity.GetComponent(); - hoverSprite.CopyFrom(entity.GetComponent()); + var hoverSprite = _entityManager.GetComponent(hoverEntity); + hoverSprite.CopyFrom(_entityManager.GetComponent(entity)); hoverSprite.Color = fits ? new Color(0, 255, 0, 127) : new Color(255, 0, 0, 127); button.HoverSpriteView.Sprite = hoverSprite; diff --git a/Content.Client/Items/UI/ItemSlotButton.cs b/Content.Client/Items/UI/ItemSlotButton.cs index 201fa28f5c..499dcc31bf 100644 --- a/Content.Client/Items/UI/ItemSlotButton.cs +++ b/Content.Client/Items/UI/ItemSlotButton.cs @@ -2,6 +2,7 @@ using Content.Client.Cooldown; using Content.Client.Items.Managers; using Content.Client.Stylesheets; +using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; @@ -138,7 +139,12 @@ namespace Content.Client.Items.UI { if (EntityHover) { - HoverSpriteView.Sprite?.Owner.Delete(); + ISpriteComponent? tempQualifier = HoverSpriteView.Sprite; + if (tempQualifier != null) + { + IoCManager.Resolve().DeleteEntity(tempQualifier.Owner); + } + HoverSpriteView.Sprite = null; } } diff --git a/Content.Client/Items/UI/ItemStatusPanel.cs b/Content.Client/Items/UI/ItemStatusPanel.cs index e4d7aa1d41..f0bcb7c8a9 100644 --- a/Content.Client/Items/UI/ItemStatusPanel.cs +++ b/Content.Client/Items/UI/ItemStatusPanel.cs @@ -33,7 +33,7 @@ namespace Content.Client.Items.UI private readonly PanelContainer _panel; [ViewVariables] - private IEntity? _entity; + private EntityUid _entity; public ItemStatusPanel(Texture texture, StyleBox.Margin cutout, StyleBox.Margin flat, Label.AlignMode textAlign) { @@ -130,12 +130,12 @@ namespace Content.Client.Items.UI UpdateItemName(); } - public void Update(IEntity? entity) + public void Update(EntityUid entity) { - if (entity == null) + if (entity == default) { ClearOldStatus(); - _entity = null; + _entity = default; _panel.Visible = false; return; } @@ -153,17 +153,17 @@ namespace Content.Client.Items.UI private void UpdateItemName() { - if (_entity == null) + if (_entity == default) return; - if (_entity.TryGetComponent(out HandVirtualItemComponent? virtualItem) - && _entityManager.TryGetEntity(virtualItem.BlockingEntity, out var blockEnt)) + if (_entityManager.TryGetComponent(_entity, out HandVirtualItemComponent? virtualItem) + && _entityManager.EntityExists(virtualItem.BlockingEntity)) { - _itemNameLabel.Text = blockEnt.Name; + _itemNameLabel.Text = _entityManager.GetComponent(virtualItem.BlockingEntity).EntityName; } else { - _itemNameLabel.Text = _entity.Name; + _itemNameLabel.Text = _entityManager.GetComponent(_entity).EntityName; } } @@ -185,7 +185,7 @@ namespace Content.Client.Items.UI ClearOldStatus(); - foreach (var statusComponent in _entity!.GetAllComponents()) + foreach (var statusComponent in _entityManager.GetComponents(_entity)) { var control = statusComponent.MakeControl(); _statusContents.AddChild(control); @@ -194,7 +194,7 @@ namespace Content.Client.Items.UI } var collectMsg = new ItemStatusCollectMessage(); - _entity.EntityManager.EventBus.RaiseLocalEvent(_entity.Uid, collectMsg); + _entityManager.EventBus.RaiseLocalEvent(_entity, collectMsg); foreach (var control in collectMsg.Controls) { diff --git a/Content.Client/Kitchen/UI/GrinderMenu.xaml.cs b/Content.Client/Kitchen/UI/GrinderMenu.xaml.cs index 5e45ba25a7..816af4797e 100644 --- a/Content.Client/Kitchen/UI/GrinderMenu.xaml.cs +++ b/Content.Client/Kitchen/UI/GrinderMenu.xaml.cs @@ -8,6 +8,7 @@ using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Client.UserInterface.XAML; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Prototypes; @@ -75,7 +76,7 @@ namespace Content.Client.Kitchen.UI BeakerContentBox.EjectButton.Disabled = true; ChamberContentBox.EjectButton.Disabled = true; break; - case SharedReagentGrinderComponent.ReagentGrinderWorkCompleteMessage doneMessage: + case SharedReagentGrinderComponent.ReagentGrinderWorkCompleteMessage: GrindButton.Disabled = false; JuiceButton.Disabled = false; GrindButton.Modulate = Color.White; @@ -92,17 +93,18 @@ namespace Content.Client.Kitchen.UI _chamberVisualContents.Clear(); ChamberContentBox.BoxContents.Clear(); - foreach (var uid in containedSolids) + foreach (var entity in containedSolids) { - if (!_entityManager.TryGetEntity(uid, out var entity)) + if (!_entityManager.EntityExists(entity)) { return; } - var texture = entity.GetComponent().Icon?.Default; - var solidItem = ChamberContentBox.BoxContents.AddItem(entity.Name, texture); + var texture = _entityManager.GetComponent(entity).Icon?.Default; + + var solidItem = ChamberContentBox.BoxContents.AddItem(_entityManager.GetComponent(entity).EntityName, texture); var solidIndex = ChamberContentBox.BoxContents.IndexOf(solidItem); - _chamberVisualContents.Add(solidIndex, uid); + _chamberVisualContents.Add(solidIndex, entity); } //Refresh beaker contents diff --git a/Content.Client/Kitchen/UI/MicrowaveBoundUserInterface.cs b/Content.Client/Kitchen/UI/MicrowaveBoundUserInterface.cs index 500a5da277..a92176faa0 100644 --- a/Content.Client/Kitchen/UI/MicrowaveBoundUserInterface.cs +++ b/Content.Client/Kitchen/UI/MicrowaveBoundUserInterface.cs @@ -108,24 +108,19 @@ namespace Content.Client.Kitchen.UI _solids.Clear(); _menu.IngredientsList.Clear(); - foreach (var t in containedSolids) + foreach (var entity in containedSolids) { - if (!_entityManager.TryGetEntity(t, out var entity)) + if (_entityManager.Deleted(entity)) { return; } - if (entity.Deleted) - { - continue; - } - Texture? texture; - if (entity.TryGetComponent(out IconComponent? iconComponent)) + if (_entityManager.TryGetComponent(entity, out IconComponent? iconComponent)) { texture = iconComponent.Icon?.Default; } - else if (entity.TryGetComponent(out SpriteComponent? spriteComponent)) + else if (_entityManager.TryGetComponent(entity, out SpriteComponent? spriteComponent)) { texture = spriteComponent.Icon?.Default; } @@ -134,9 +129,9 @@ namespace Content.Client.Kitchen.UI continue; } - var solidItem = _menu.IngredientsList.AddItem(entity.Name, texture); + var solidItem = _menu.IngredientsList.AddItem(_entityManager.GetComponent(entity).EntityName, texture); var solidIndex = _menu.IngredientsList.IndexOf(solidItem); - _solids.Add(solidIndex, t); + _solids.Add(solidIndex, entity); } } } diff --git a/Content.Client/Kitchen/Visualizers/MicrowaveVisualizer.cs b/Content.Client/Kitchen/Visualizers/MicrowaveVisualizer.cs index c0a3a68e8c..b720794981 100644 --- a/Content.Client/Kitchen/Visualizers/MicrowaveVisualizer.cs +++ b/Content.Client/Kitchen/Visualizers/MicrowaveVisualizer.cs @@ -5,6 +5,7 @@ using Content.Shared.Power; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; namespace Content.Client.Kitchen.Visualizers @@ -15,9 +16,10 @@ namespace Content.Client.Kitchen.Visualizers public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var entMan = IoCManager.Resolve(); + var sprite = entMan.GetComponent(component.Owner); - var microwaveComponent = component.Owner.GetComponentOrNull(); + var microwaveComponent = entMan.GetComponentOrNull(component.Owner); if (!component.TryGetData(PowerDeviceVisuals.VisualState, out MicrowaveVisualState state)) { diff --git a/Content.Client/Kitchen/Visualizers/ReagentGrinderVisualizer.cs b/Content.Client/Kitchen/Visualizers/ReagentGrinderVisualizer.cs index 7abc3509ca..e799111a6f 100644 --- a/Content.Client/Kitchen/Visualizers/ReagentGrinderVisualizer.cs +++ b/Content.Client/Kitchen/Visualizers/ReagentGrinderVisualizer.cs @@ -1,5 +1,6 @@ using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.Kitchen.Components.SharedReagentGrinderComponent; namespace Content.Client.Kitchen.Visualizers @@ -9,7 +10,7 @@ namespace Content.Client.Kitchen.Visualizers public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); component.TryGetData(ReagentGrinderVisualState.BeakerAttached, out bool hasBeaker); sprite.LayerSetState(0, $"juicer{(hasBeaker ? "1" : "0")}"); } diff --git a/Content.Client/Kudzu/KudzuVisualizer.cs b/Content.Client/Kudzu/KudzuVisualizer.cs index 8c807408b8..297742edc0 100644 --- a/Content.Client/Kudzu/KudzuVisualizer.cs +++ b/Content.Client/Kudzu/KudzuVisualizer.cs @@ -1,6 +1,7 @@ using Content.Shared.Kudzu; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Kudzu; @@ -14,7 +15,8 @@ public class KudzuVisualizer : AppearanceVisualizer { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent? sprite)) { return; } diff --git a/Content.Client/Lathe/UI/LatheBoundUserInterface.cs b/Content.Client/Lathe/UI/LatheBoundUserInterface.cs index 54b21e13d3..ad965c9cb4 100644 --- a/Content.Client/Lathe/UI/LatheBoundUserInterface.cs +++ b/Content.Client/Lathe/UI/LatheBoundUserInterface.cs @@ -13,6 +13,7 @@ namespace Content.Client.Lathe.UI { public class LatheBoundUserInterface : BoundUserInterface { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [ViewVariables] @@ -37,9 +38,9 @@ namespace Content.Client.Lathe.UI { base.Open(); - if (!Owner.Owner.TryGetComponent(out MaterialStorageComponent? storage) - || !Owner.Owner.TryGetComponent(out SharedLatheComponent? lathe) - || !Owner.Owner.TryGetComponent(out SharedLatheDatabaseComponent? database)) return; + if (!_entMan.TryGetComponent(Owner.Owner, out MaterialStorageComponent? storage) + || !_entMan.TryGetComponent(Owner.Owner, out SharedLatheComponent? lathe) + || !_entMan.TryGetComponent(Owner.Owner, out SharedLatheDatabaseComponent? database)) return; Storage = storage; Lathe = lathe; diff --git a/Content.Client/Lathe/Visualizers/AutolatheVisualizer.cs b/Content.Client/Lathe/Visualizers/AutolatheVisualizer.cs index a9ba95597a..7932ef539f 100644 --- a/Content.Client/Lathe/Visualizers/AutolatheVisualizer.cs +++ b/Content.Client/Lathe/Visualizers/AutolatheVisualizer.cs @@ -5,12 +5,15 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Lathe.Visualizers { [UsedImplicitly] public class AutolatheVisualizer : AppearanceVisualizer { + [Dependency] private readonly IEntityManager _entMan = default!; + private const string AnimationKey = "inserting_animation"; private Animation _buildingAnimation; @@ -47,20 +50,19 @@ namespace Content.Client.Lathe.Visualizers return animation; } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { - if (!entity.HasComponent()) - { - entity.AddComponent(); - } + IoCManager.InjectDependencies(this); + + _entMan.EnsureComponent(entity); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); - var animPlayer = component.Owner.GetComponent(); + var sprite = _entMan.GetComponent(component.Owner); + var animPlayer = _entMan.GetComponent(component.Owner); if (!component.TryGetData(PowerDeviceVisuals.VisualState, out LatheVisualState state)) { state = LatheVisualState.Idle; diff --git a/Content.Client/Lathe/Visualizers/ProtolatheVisualizer.cs b/Content.Client/Lathe/Visualizers/ProtolatheVisualizer.cs index ef75bf1683..ccce03886b 100644 --- a/Content.Client/Lathe/Visualizers/ProtolatheVisualizer.cs +++ b/Content.Client/Lathe/Visualizers/ProtolatheVisualizer.cs @@ -5,12 +5,15 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Lathe.Visualizers { [UsedImplicitly] public class ProtolatheVisualizer : AppearanceVisualizer { + [Dependency] private readonly IEntityManager _entMan = default!; + private const string AnimationKey = "inserting_animation"; private Animation _buildingAnimation; @@ -47,20 +50,19 @@ namespace Content.Client.Lathe.Visualizers return animation; } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { - if (!entity.HasComponent()) - { - entity.AddComponent(); - } + IoCManager.InjectDependencies(this); + + _entMan.EnsureComponent(entity); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); - var animPlayer = component.Owner.GetComponent(); + var sprite = _entMan.GetComponent(component.Owner); + var animPlayer = _entMan.GetComponent(component.Owner); if (!component.TryGetData(PowerDeviceVisuals.VisualState, out LatheVisualState state)) { state = LatheVisualState.Idle; diff --git a/Content.Client/Light/Components/LightBehaviourComponent.cs b/Content.Client/Light/Components/LightBehaviourComponent.cs index 6ef0920830..6b594fffa4 100644 --- a/Content.Client/Light/Components/LightBehaviourComponent.cs +++ b/Content.Client/Light/Components/LightBehaviourComponent.cs @@ -26,6 +26,7 @@ namespace Content.Client.Light.Components [ImplicitDataDefinitionForInheritors] public abstract class LightBehaviourAnimationTrack : AnimationTrackProperty { + protected IEntityManager _entMan = default!; protected IRobustRandom _random = default!; [DataField("id")] [ViewVariables] public string ID { get; set; } = string.Empty; @@ -51,14 +52,15 @@ namespace Content.Client.Light.Components [ViewVariables] protected float MaxTime { get; set; } private float _maxTime = default; - private IEntity _parent = default!; + private EntityUid _parent = default!; - public void Initialize(IEntity parent, IRobustRandom random) + public void Initialize(EntityUid parent, IRobustRandom random, IEntityManager entMan) { _random = random; + _entMan = entMan; _parent = parent; - if (Enabled && _parent.TryGetComponent(out PointLightComponent? light)) + if (Enabled && _entMan.TryGetComponent(_parent, out PointLightComponent? light)) { light.Enabled = true; } @@ -68,7 +70,7 @@ namespace Content.Client.Light.Components public void UpdatePlaybackValues(Animation owner) { - if (_parent.TryGetComponent(out PointLightComponent? light)) + if (_entMan.TryGetComponent(_parent, out PointLightComponent? light)) { light.Enabled = true; } @@ -99,7 +101,7 @@ namespace Content.Client.Light.Components throw new InvalidOperationException("Property parameter is null! Check the prototype!"); } - if (_parent.TryGetComponent(out PointLightComponent? light)) + if (_entMan.TryGetComponent(_parent, out PointLightComponent? light)) { AnimationHelper.SetAnimatableProperty(light, Property, value); } @@ -128,7 +130,7 @@ namespace Content.Client.Light.Components if (Property == "Enabled") // special case for boolean { - ApplyProperty(interpolateValue < 0.5f? true : false); + ApplyProperty(interpolateValue < 0.5f); return (-1, playingTime); } @@ -183,7 +185,7 @@ namespace Content.Client.Light.Components if (Property == "Enabled") // special case for boolean { - ApplyProperty(interpolateValue < EndValue? true : false); + ApplyProperty(interpolateValue < EndValue); return (-1, playingTime); } @@ -258,7 +260,7 @@ namespace Content.Client.Light.Components ApplyProperty(InterpolateLinear(_randomValue3, _randomValue4, interpolateValue)); break; case AnimationInterpolationMode.Cubic: - ApplyProperty(InterpolateCubic(_randomValue1!, _randomValue2, _randomValue3, _randomValue4, interpolateValue)); + ApplyProperty(InterpolateCubic(_randomValue1, _randomValue2, _randomValue3, _randomValue4, interpolateValue)); break; default: case AnimationInterpolationMode.Nearest: @@ -340,6 +342,9 @@ namespace Content.Client.Light.Components [RegisterComponent] public class LightBehaviourComponent : SharedLightBehaviourComponent, ISerializationHooks { + [Dependency] private readonly IEntityManager _entMan = default!; + [Dependency] private readonly IRobustRandom _random = default!; + private const string KeyPrefix = nameof(LightBehaviourComponent); public class AnimationContainer @@ -395,7 +400,7 @@ namespace Content.Client.Light.Components // TODO: Do NOT ensure component here. And use eventbus events instead... Owner.EnsureComponent(); - if (Owner.TryGetComponent(out AnimationPlayerComponent? animation)) + if (_entMan.TryGetComponent(Owner, out AnimationPlayerComponent? animation)) { #pragma warning disable 618 animation.AnimationCompleted += OnAnimationCompleted; @@ -404,7 +409,7 @@ namespace Content.Client.Light.Components foreach (var container in _animations) { - container.LightBehaviour.Initialize(Owner, IoCManager.Resolve()); + container.LightBehaviour.Initialize(Owner, _random, _entMan); } // we need to initialize all behaviours before starting any @@ -430,7 +435,7 @@ namespace Content.Client.Light.Components { container.LightBehaviour.UpdatePlaybackValues(container.Animation); - if (Owner.TryGetComponent(out AnimationPlayerComponent? animation)) + if (_entMan.TryGetComponent(Owner, out AnimationPlayerComponent? animation)) { animation.Play(container.Animation, container.FullKey); } @@ -442,7 +447,7 @@ namespace Content.Client.Light.Components /// private void CopyLightSettings() { - if (Owner.TryGetComponent(out PointLightComponent? light)) + if (_entMan.TryGetComponent(Owner, out PointLightComponent? light)) { _originalColor = light.Color; _originalEnabled = light.Enabled; @@ -452,7 +457,7 @@ namespace Content.Client.Light.Components } else { - Logger.Warning($"{Owner.Name} has a {nameof(LightBehaviourComponent)} but it has no {nameof(PointLightComponent)}! Check the prototype!"); + Logger.Warning($"{_entMan.GetComponent(Owner).EntityName} has a {nameof(LightBehaviourComponent)} but it has no {nameof(PointLightComponent)}! Check the prototype!"); } } @@ -463,7 +468,7 @@ namespace Content.Client.Light.Components /// public void StartLightBehaviour(string id = "") { - if (!Owner.TryGetComponent(out AnimationPlayerComponent? animation)) + if (!_entMan.TryGetComponent(Owner, out AnimationPlayerComponent? animation)) { return; } @@ -491,7 +496,7 @@ namespace Content.Client.Light.Components /// Should the light have its original settings applied? public void StopLightBehaviour(string id = "", bool removeBehaviour = false, bool resetToOriginalSettings = false) { - if (!Owner.TryGetComponent(out AnimationPlayerComponent? animation)) + if (!_entMan.TryGetComponent(Owner, out AnimationPlayerComponent? animation)) { return; } @@ -519,7 +524,7 @@ namespace Content.Client.Light.Components _animations.Remove(container); } - if (resetToOriginalSettings && Owner.TryGetComponent(out PointLightComponent? light)) + if (resetToOriginalSettings && _entMan.TryGetComponent(Owner, out PointLightComponent? light)) { light.Color = _originalColor; light.Enabled = _originalEnabled; @@ -546,7 +551,7 @@ namespace Content.Client.Light.Components AnimationTracks = {behaviour} }; - behaviour.Initialize(Owner, IoCManager.Resolve()); + behaviour.Initialize(Owner, _random, _entMan); var container = new AnimationContainer(key, animation, behaviour); _animations.Add(container); diff --git a/Content.Client/Light/RgbLightControllerSystem.cs b/Content.Client/Light/RgbLightControllerSystem.cs index be0b7ab4b0..59fbfe62b9 100644 --- a/Content.Client/Light/RgbLightControllerSystem.cs +++ b/Content.Client/Light/RgbLightControllerSystem.cs @@ -27,7 +27,7 @@ namespace Content.Client.Light public static Color GetCurrentRgbColor(TimeSpan curTime, TimeSpan offset, RgbLightControllerComponent rgb) { return Color.FromHsv(new Vector4( - (float) (((curTime.TotalSeconds - offset.TotalSeconds) / rgb.CycleRate + Math.Abs(rgb.Owner.Uid.GetHashCode() * 0.1)) % 1), + (float) (((curTime.TotalSeconds - offset.TotalSeconds) / rgb.CycleRate + Math.Abs(rgb.Owner.GetHashCode() * 0.1)) % 1), 1.0f, 1.0f, 1.0f diff --git a/Content.Client/Light/Visualizers/EmergencyLightVisualizer.cs b/Content.Client/Light/Visualizers/EmergencyLightVisualizer.cs index f02c3ce7d5..097492eb47 100644 --- a/Content.Client/Light/Visualizers/EmergencyLightVisualizer.cs +++ b/Content.Client/Light/Visualizers/EmergencyLightVisualizer.cs @@ -1,6 +1,7 @@ using Content.Shared.Light.Component; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Light.Visualizers @@ -12,7 +13,8 @@ namespace Content.Client.Light.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent? sprite)) return; if (!component.TryGetData(EmergencyLightVisuals.On, out bool on)) diff --git a/Content.Client/Light/Visualizers/ExpendableLightVisualizer.cs b/Content.Client/Light/Visualizers/ExpendableLightVisualizer.cs index 6c978ae310..7a4fbc58aa 100644 --- a/Content.Client/Light/Visualizers/ExpendableLightVisualizer.cs +++ b/Content.Client/Light/Visualizers/ExpendableLightVisualizer.cs @@ -1,10 +1,10 @@ -using System; -using Content.Client.Light.Components; +using Content.Client.Light.Components; using Content.Shared.Light.Component; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Player; namespace Content.Client.Light.Visualizers @@ -16,9 +16,10 @@ namespace Content.Client.Light.Visualizers { base.OnChangeData(component); + var entities = IoCManager.Resolve(); if (component.TryGetData(ExpendableLightVisuals.Behavior, out string lightBehaviourID)) { - if (component.Owner.TryGetComponent(out var lightBehaviour)) + if (entities.TryGetComponent(component.Owner, out LightBehaviourComponent lightBehaviour)) { lightBehaviour.StopLightBehaviour(); @@ -26,7 +27,7 @@ namespace Content.Client.Light.Visualizers { lightBehaviour.StartLightBehaviour(lightBehaviourID); } - else if (component.Owner.TryGetComponent(out var light)) + else if (entities.TryGetComponent(component.Owner, out PointLightComponent light)) { light.Enabled = false; } @@ -39,7 +40,7 @@ namespace Content.Client.Light.Visualizers } if (component.TryGetData(ExpendableLightVisuals.State, out ExpendableLightState state) - && component.Owner.TryGetComponent(out var expendableLight)) + && entities.TryGetComponent(component.Owner, out ExpendableLightComponent expendableLight)) { switch (state) { diff --git a/Content.Client/Light/Visualizers/LightBulbVisualizer.cs b/Content.Client/Light/Visualizers/LightBulbVisualizer.cs index bfa594f419..9084beb029 100644 --- a/Content.Client/Light/Visualizers/LightBulbVisualizer.cs +++ b/Content.Client/Light/Visualizers/LightBulbVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Light; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Light.Visualizers @@ -13,7 +14,8 @@ namespace Content.Client.Light.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent sprite)) return; // update sprite state diff --git a/Content.Client/Light/Visualizers/PoweredLightVisualizer.cs b/Content.Client/Light/Visualizers/PoweredLightVisualizer.cs index 9b61da8e49..1210cff257 100644 --- a/Content.Client/Light/Visualizers/PoweredLightVisualizer.cs +++ b/Content.Client/Light/Visualizers/PoweredLightVisualizer.cs @@ -7,7 +7,6 @@ using Robust.Client.GameObjects; using Robust.Shared.Animations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Maths; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; @@ -28,7 +27,8 @@ namespace Content.Client.Light.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) return; if (!component.TryGetData(PoweredLightVisuals.BulbState, out PoweredLightState state)) return; switch (state) diff --git a/Content.Client/Lobby/UI/LobbyCharacterPreviewPanel.cs b/Content.Client/Lobby/UI/LobbyCharacterPreviewPanel.cs index 5bc657ae09..db70686e8b 100644 --- a/Content.Client/Lobby/UI/LobbyCharacterPreviewPanel.cs +++ b/Content.Client/Lobby/UI/LobbyCharacterPreviewPanel.cs @@ -22,8 +22,9 @@ namespace Content.Client.Lobby.UI { public class LobbyCharacterPreviewPanel : Control { + private readonly IEntityManager _entMan; private readonly IClientPreferencesManager _preferencesManager; - private IEntity _previewDummy; + private EntityUid _previewDummy; private readonly Label _summaryLabel; private readonly BoxContainer _loaded; private readonly Label _unloaded; @@ -31,6 +32,7 @@ namespace Content.Client.Lobby.UI public LobbyCharacterPreviewPanel(IEntityManager entityManager, IClientPreferencesManager preferencesManager) { + _entMan = entityManager; _preferencesManager = preferencesManager; _previewDummy = entityManager.SpawnEntity("MobHumanDummy", MapCoordinates.Nullspace); @@ -98,15 +100,15 @@ namespace Content.Client.Lobby.UI _preferencesManager.OnServerDataLoaded -= UpdateUI; if (!disposing) return; - _previewDummy.Delete(); - _previewDummy = null!; + _entMan.DeleteEntity(_previewDummy); + _previewDummy = default; } - private static SpriteView MakeSpriteView(IEntity entity, Direction direction) + private SpriteView MakeSpriteView(EntityUid entity, Direction direction) { return new() { - Sprite = entity.GetComponent(), + Sprite = _entMan.GetComponent(entity), OverrideDirection = direction, Scale = (2, 2) }; @@ -130,27 +132,28 @@ namespace Content.Client.Lobby.UI else { _summaryLabel.Text = selectedCharacter.Summary; - EntitySystem.Get().UpdateFromProfile(_previewDummy.Uid, selectedCharacter); + EntitySystem.Get().UpdateFromProfile(_previewDummy, selectedCharacter); GiveDummyJobClothes(_previewDummy, selectedCharacter); } } } - public static void GiveDummyJobClothes(IEntity dummy, HumanoidCharacterProfile profile) + public static void GiveDummyJobClothes(EntityUid dummy, HumanoidCharacterProfile profile) { var protoMan = IoCManager.Resolve(); - var inventory = dummy.GetComponent(); + var entMan = IoCManager.Resolve(); + var inventory = entMan.GetComponent(dummy); var highPriorityJob = profile.JobPriorities.FirstOrDefault(p => p.Value == JobPriority.High).Key; + // ReSharper disable once ConstantNullCoalescingCondition var job = protoMan.Index(highPriorityJob ?? SharedGameTicker.FallbackOverflowJob); inventory.ClearAllSlotVisuals(); if (job.StartingGear != null) { - var entityMan = IoCManager.Resolve(); var gear = protoMan.Index(job.StartingGear); foreach (var slot in AllSlots) @@ -158,9 +161,9 @@ namespace Content.Client.Lobby.UI var itemType = gear.GetGear(slot, profile); if (itemType != string.Empty) { - var item = entityMan.SpawnEntity(itemType, MapCoordinates.Nullspace); + var item = entMan.SpawnEntity(itemType, MapCoordinates.Nullspace); inventory.SetSlotVisuals(slot, item); - item.Delete(); + entMan.DeleteEntity(item); } } } diff --git a/Content.Client/MachineLinking/SignalSwitchVisualizer.cs b/Content.Client/MachineLinking/SignalSwitchVisualizer.cs index fee7370451..616c707371 100644 --- a/Content.Client/MachineLinking/SignalSwitchVisualizer.cs +++ b/Content.Client/MachineLinking/SignalSwitchVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.MachineLinking @@ -12,11 +13,11 @@ namespace Content.Client.MachineLinking [DataField("layer")] private int Layer { get; } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (entity.TryGetComponent(out SpriteComponent? sprite)) + if (IoCManager.Resolve().TryGetComponent(entity, out SpriteComponent? sprite)) { sprite.LayerMapReserveBlank(Layer); } @@ -26,7 +27,8 @@ namespace Content.Client.MachineLinking { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent? sprite)) { return; } diff --git a/Content.Client/Markers/MarkerComponent.cs b/Content.Client/Markers/MarkerComponent.cs index ff75539928..2ac08b3338 100644 --- a/Content.Client/Markers/MarkerComponent.cs +++ b/Content.Client/Markers/MarkerComponent.cs @@ -1,5 +1,6 @@ using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Markers { @@ -19,7 +20,7 @@ namespace Content.Client.Markers { var system = EntitySystem.Get(); - if (Owner.TryGetComponent(out ISpriteComponent? sprite)) + if (IoCManager.Resolve().TryGetComponent(Owner, out ISpriteComponent? sprite)) { sprite.Visible = system.MarkersVisible; } diff --git a/Content.Client/MedicalScanner/MedicalScannerVisualizer.cs b/Content.Client/MedicalScanner/MedicalScannerVisualizer.cs index 3b4786a54a..efa1f6d450 100644 --- a/Content.Client/MedicalScanner/MedicalScannerVisualizer.cs +++ b/Content.Client/MedicalScanner/MedicalScannerVisualizer.cs @@ -2,6 +2,7 @@ using System; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.MedicalScanner.SharedMedicalScannerComponent; using static Content.Shared.MedicalScanner.SharedMedicalScannerComponent.MedicalScannerStatus; @@ -14,7 +15,7 @@ namespace Content.Client.MedicalScanner { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (!component.TryGetData(MedicalScannerVisuals.Status, out MedicalScannerStatus status)) return; sprite.LayerSetState(MedicalScannerVisualLayers.Machine, StatusToMachineStateId(status)); sprite.LayerSetState(MedicalScannerVisualLayers.Terminal, StatusToTerminalStateId(status)); diff --git a/Content.Client/MedicalScanner/UI/MedicalScannerBoundUserInterface.cs b/Content.Client/MedicalScanner/UI/MedicalScannerBoundUserInterface.cs index be5427899f..ef28c43a9e 100644 --- a/Content.Client/MedicalScanner/UI/MedicalScannerBoundUserInterface.cs +++ b/Content.Client/MedicalScanner/UI/MedicalScannerBoundUserInterface.cs @@ -1,6 +1,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.MedicalScanner.SharedMedicalScannerComponent; namespace Content.Client.MedicalScanner.UI @@ -19,7 +20,7 @@ namespace Content.Client.MedicalScanner.UI base.Open(); _window = new MedicalScannerWindow { - Title = Owner.Owner.Name, + Title = IoCManager.Resolve().GetComponent(Owner.Owner).EntityName, }; _window.OnClose += Close; _window.ScanButton.OnPressed += _ => SendMessage(new UiButtonPressedMessage(UiButton.ScanDNA)); diff --git a/Content.Client/MedicalScanner/UI/MedicalScannerWindow.xaml.cs b/Content.Client/MedicalScanner/UI/MedicalScannerWindow.xaml.cs index 5100367f35..485e9b9070 100644 --- a/Content.Client/MedicalScanner/UI/MedicalScannerWindow.xaml.cs +++ b/Content.Client/MedicalScanner/UI/MedicalScannerWindow.xaml.cs @@ -1,17 +1,15 @@ -using System.Text; using System.Collections.Generic; -using System.Linq; -using Robust.Client.UserInterface.Controls; +using System.Text; +using Content.Shared.Damage.Prototypes; +using Content.Shared.FixedPoint; +using Robust.Client.AutoGenerated; using Robust.Client.UserInterface.CustomControls; +using Robust.Client.UserInterface.XAML; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Prototypes; using static Content.Shared.MedicalScanner.SharedMedicalScannerComponent; -using Content.Shared.Damage.Prototypes; -using Content.Shared.FixedPoint; -using Robust.Client.AutoGenerated; -using Robust.Client.UserInterface.XAML; namespace Content.Client.MedicalScanner.UI { @@ -27,9 +25,10 @@ namespace Content.Client.MedicalScanner.UI { var text = new StringBuilder(); + var entities = IoCManager.Resolve(); if (!state.Entity.HasValue || !state.HasDamage() || - !IoCManager.Resolve().TryGetEntity(state.Entity.Value, out var entity)) + !entities.EntityExists(state.Entity.Value)) { Diagnostics.Text = Loc.GetString("medical-scanner-window-no-patient-data-text"); ScanButton.Disabled = true; @@ -37,7 +36,7 @@ namespace Content.Client.MedicalScanner.UI } else { - text.Append($"{Loc.GetString("medical-scanner-window-entity-health-text", ("entityName", entity.Name))}\n"); + text.Append($"{Loc.GetString("medical-scanner-window-entity-health-text", ("entityName", Name: entities.GetComponent(state.Entity.Value).EntityName))}\n"); var totalDamage = state.DamagePerType.Values.Sum(); @@ -46,12 +45,12 @@ namespace Content.Client.MedicalScanner.UI HashSet shownTypes = new(); // Show the total damage and type breakdown for each damage group. - foreach (var (damageGroupID, damageAmount) in state.DamagePerGroup) + foreach (var (damageGroupId, damageAmount) in state.DamagePerGroup) { - text.Append($"\n{Loc.GetString("medical-scanner-window-damage-group-text", ("damageGroup", damageGroupID), ("amount", damageAmount))}"); + text.Append($"\n{Loc.GetString("medical-scanner-window-damage-group-text", ("damageGroup", damageGroupId), ("amount", damageAmount))}"); // Show the damage for each type in that group. - var group = IoCManager.Resolve().Index(damageGroupID); + var group = IoCManager.Resolve().Index(damageGroupId); foreach (var type in group.DamageTypes) { if (state.DamagePerType.TryGetValue(type, out var typeAmount)) diff --git a/Content.Client/Mining/AsteroidRockVisualizer.cs b/Content.Client/Mining/AsteroidRockVisualizer.cs index 1c30d6126c..f9533d9f82 100644 --- a/Content.Client/Mining/AsteroidRockVisualizer.cs +++ b/Content.Client/Mining/AsteroidRockVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Mining @@ -12,18 +13,18 @@ namespace Content.Client.Mining [DataField("layer")] private int Layer { get; } = 0; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - entity.GetComponentOrNull()?.LayerMapReserveBlank(Layer); + IoCManager.Resolve().GetComponentOrNull(entity)?.LayerMapReserveBlank(Layer); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (!IoCManager.Resolve().TryGetComponent(component.Owner, out SpriteComponent? sprite)) { return; } diff --git a/Content.Client/MobState/DamageStateVisualizer.cs b/Content.Client/MobState/DamageStateVisualizer.cs index 8586a9dbcc..afcc822cd1 100644 --- a/Content.Client/MobState/DamageStateVisualizer.cs +++ b/Content.Client/MobState/DamageStateVisualizer.cs @@ -3,6 +3,7 @@ using Content.Shared.MobState; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using DrawDepth = Content.Shared.DrawDepth.DrawDepth; @@ -51,7 +52,7 @@ namespace Content.Client.MobState public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (!component.TryGetData(DamageStateVisuals.State, out DamageState data)) { return; diff --git a/Content.Client/MobState/Overlays/CritOverlay.cs b/Content.Client/MobState/Overlays/CritOverlay.cs index 3813e7e69f..51b3b462ed 100644 --- a/Content.Client/MobState/Overlays/CritOverlay.cs +++ b/Content.Client/MobState/Overlays/CritOverlay.cs @@ -2,6 +2,7 @@ using Content.Shared.MobState.Components; using Robust.Client.Graphics; using Robust.Client.Player; using Robust.Shared.Enums; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Prototypes; @@ -13,6 +14,7 @@ namespace Content.Client.MobState.Overlays [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly IEyeManager _eyeManager = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; public override OverlaySpace Space => OverlaySpace.WorldSpace; private readonly ShaderInstance _gradientCircleShader; @@ -23,15 +25,14 @@ namespace Content.Client.MobState.Overlays _gradientCircleShader = _prototypeManager.Index("GradientCircleMask").Instance(); } - public static bool LocalPlayerHasState(IPlayerManager pm, bool critical, bool dead) { - var playerEntity = pm.LocalPlayer?.ControlledEntity; - - if (playerEntity == null) + public static bool LocalPlayerHasState(IPlayerManager pm, bool critical, bool dead, IEntityManager? entities = null) { + if (pm.LocalPlayer?.ControlledEntity is not {Valid: true} player) { return false; } - if (playerEntity.TryGetComponent(out var mobState)) + IoCManager.Resolve(ref entities); + if (entities.TryGetComponent(player, out var mobState)) { if (critical) if (mobState.IsCritical()) @@ -46,7 +47,7 @@ namespace Content.Client.MobState.Overlays protected override void Draw(in OverlayDrawArgs args) { - if (!LocalPlayerHasState(_playerManager, true, false)) + if (!LocalPlayerHasState(_playerManager, true, false, _entities)) return; var worldHandle = args.WorldHandle; diff --git a/Content.Client/Morgue/Visualizers/BodyBagVisualizer.cs b/Content.Client/Morgue/Visualizers/BodyBagVisualizer.cs index cefa9bea45..1aeff3e8c8 100644 --- a/Content.Client/Morgue/Visualizers/BodyBagVisualizer.cs +++ b/Content.Client/Morgue/Visualizers/BodyBagVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Labels; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Morgue.Visualizers { @@ -12,7 +13,8 @@ namespace Content.Client.Morgue.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { return; } diff --git a/Content.Client/Morgue/Visualizers/CrematoriumVisualizer.cs b/Content.Client/Morgue/Visualizers/CrematoriumVisualizer.cs index a930b71c2e..de39fedbb4 100644 --- a/Content.Client/Morgue/Visualizers/CrematoriumVisualizer.cs +++ b/Content.Client/Morgue/Visualizers/CrematoriumVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Morgue.Visualizers @@ -23,7 +24,11 @@ namespace Content.Client.Morgue.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) + { + return; + } if (component.TryGetData(MorgueVisuals.Open, out bool open)) { diff --git a/Content.Client/Morgue/Visualizers/MorgueVisualizer.cs b/Content.Client/Morgue/Visualizers/MorgueVisualizer.cs index f7df0ce6bb..6f675a1135 100644 --- a/Content.Client/Morgue/Visualizers/MorgueVisualizer.cs +++ b/Content.Client/Morgue/Visualizers/MorgueVisualizer.cs @@ -1,6 +1,7 @@ using Content.Shared.Morgue; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Morgue.Visualizers @@ -23,7 +24,11 @@ namespace Content.Client.Morgue.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) + { + return; + } if (component.TryGetData(MorgueVisuals.Open, out bool open)) { diff --git a/Content.Client/Movement/Components/ClimbableComponent.cs b/Content.Client/Movement/Components/ClimbableComponent.cs index fb74d4fb9b..6d5b4f5161 100644 --- a/Content.Client/Movement/Components/ClimbableComponent.cs +++ b/Content.Client/Movement/Components/ClimbableComponent.cs @@ -17,7 +17,7 @@ namespace Content.Client.Movement.Components var user = eventArgs.User; var target = eventArgs.Target; var dragged = eventArgs.Dragged; - bool Ignored(IEntity entity) => entity == target || entity == user || entity == dragged; + bool Ignored(EntityUid entity) => entity == target || entity == user || entity == dragged; return user.InRangeUnobstructed(target, Range, predicate: Ignored) && user.InRangeUnobstructed(dragged, Range, predicate: Ignored); } diff --git a/Content.Client/NodeContainer/NodeVisualizationOverlay.cs b/Content.Client/NodeContainer/NodeVisualizationOverlay.cs index c782dca838..4d155491c1 100644 --- a/Content.Client/NodeContainer/NodeVisualizationOverlay.cs +++ b/Content.Client/NodeContainer/NodeVisualizationOverlay.cs @@ -5,7 +5,6 @@ using Content.Client.Resources; using Robust.Client.Graphics; using Robust.Client.Input; using Robust.Client.ResourceManagement; -using Robust.Client.UserInterface.CustomControls; using Robust.Shared.Enums; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -78,14 +77,12 @@ namespace Content.Client.NodeContainer var mousePos = _inputManager.MouseScreenPosition.Position; - var entity = _entityManager.GetEntity(node.Entity); - - var gridId = entity.Transform.GridID; + var gridId = _entityManager.GetComponent(node.Entity).GridID; var grid = _mapManager.GetGrid(gridId); - var gridTile = grid.TileIndicesFor(entity.Transform.Coordinates); + var gridTile = grid.TileIndicesFor(_entityManager.GetComponent(node.Entity).Coordinates); var sb = new StringBuilder(); - sb.Append($"entity: {entity}\n"); + sb.Append($"entity: {node.Entity}\n"); sb.Append($"group id: {group.GroupId}\n"); sb.Append($"node: {node.Name}\n"); sb.Append($"type: {node.Type}\n"); @@ -116,13 +113,13 @@ namespace Content.Client.NodeContainer var worldAABB = overlayDrawArgs.WorldAABB; _lookup.FastEntitiesIntersecting(map, ref worldAABB, entity => { - if (!_system.Entities.TryGetValue(entity.Uid, out var nodeData)) + if (!_system.Entities.TryGetValue(entity, out var nodeData)) return; - var gridId = entity.Transform.GridID; + var gridId = _entityManager.GetComponent(entity).GridID; var grid = _mapManager.GetGrid(gridId); var gridDict = _gridIndex.GetOrNew(gridId); - var coords = entity.Transform.Coordinates; + var coords = _entityManager.GetComponent(entity).Coordinates; // TODO: This probably shouldn't be capable of returning NaN... if (float.IsNaN(coords.Position.X) || float.IsNaN(coords.Position.Y)) diff --git a/Content.Client/Nutrition/Components/HungerComponent.cs b/Content.Client/Nutrition/Components/HungerComponent.cs index 3c24528499..5ddf6e2b27 100644 --- a/Content.Client/Nutrition/Components/HungerComponent.cs +++ b/Content.Client/Nutrition/Components/HungerComponent.cs @@ -22,7 +22,7 @@ namespace Content.Client.Nutrition.Components _currentHungerThreshold = hunger.CurrentThreshold; - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); } } } diff --git a/Content.Client/Nutrition/Components/ThirstComponent.cs b/Content.Client/Nutrition/Components/ThirstComponent.cs index 0b1700dc3c..5b1caa099b 100644 --- a/Content.Client/Nutrition/Components/ThirstComponent.cs +++ b/Content.Client/Nutrition/Components/ThirstComponent.cs @@ -22,7 +22,7 @@ namespace Content.Client.Nutrition.Components _currentThirstThreshold = thirst.CurrentThreshold; - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); } } } diff --git a/Content.Client/Nutrition/Visualizers/CreamPiedVisualizer.cs b/Content.Client/Nutrition/Visualizers/CreamPiedVisualizer.cs index 3c509b110f..94d57e07ba 100644 --- a/Content.Client/Nutrition/Visualizers/CreamPiedVisualizer.cs +++ b/Content.Client/Nutrition/Visualizers/CreamPiedVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Nutrition.Visualizers @@ -12,11 +13,11 @@ namespace Content.Client.Nutrition.Visualizers [DataField("state")] private string? _state; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapReserveBlank(CreamPiedVisualLayers.Pie); sprite.LayerSetRSI(CreamPiedVisualLayers.Pie, "Effects/creampie.rsi"); @@ -35,7 +36,7 @@ namespace Content.Client.Nutrition.Visualizers private void SetPied(AppearanceComponent component, bool pied) { - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); sprite.LayerSetVisible(CreamPiedVisualLayers.Pie, pied); sprite.LayerSetState(CreamPiedVisualLayers.Pie, _state); diff --git a/Content.Client/Nutrition/Visualizers/DrinkCanVisualizer.cs b/Content.Client/Nutrition/Visualizers/DrinkCanVisualizer.cs index 94df14440d..f004b5efd5 100644 --- a/Content.Client/Nutrition/Visualizers/DrinkCanVisualizer.cs +++ b/Content.Client/Nutrition/Visualizers/DrinkCanVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Nutrition.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Nutrition.Visualizers @@ -19,7 +20,8 @@ namespace Content.Client.Nutrition.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent sprite)) { return; } diff --git a/Content.Client/PDA/PDAVisualizer.cs b/Content.Client/PDA/PDAVisualizer.cs index 927ad7f041..003dd4f648 100644 --- a/Content.Client/PDA/PDAVisualizer.cs +++ b/Content.Client/PDA/PDAVisualizer.cs @@ -3,6 +3,7 @@ using Content.Shared.PDA; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.PDA @@ -24,10 +25,10 @@ namespace Content.Client.PDA IDLight } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); if (_state != null) { @@ -45,7 +46,7 @@ namespace Content.Client.PDA { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); sprite.LayerSetVisible(PDAVisualLayers.Flashlight, false); if (component.TryGetData(UnpoweredFlashlightVisuals.LightOn, out bool isFlashlightOn)) { diff --git a/Content.Client/Paper/UI/PaperBoundUserInterface.cs b/Content.Client/Paper/UI/PaperBoundUserInterface.cs index 64461658f2..b3803a6e89 100644 --- a/Content.Client/Paper/UI/PaperBoundUserInterface.cs +++ b/Content.Client/Paper/UI/PaperBoundUserInterface.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.Paper.SharedPaperComponent; namespace Content.Client.Paper.UI @@ -20,7 +21,7 @@ namespace Content.Client.Paper.UI base.Open(); _window = new PaperWindow { - Title = Owner.Owner.Name, + Title = IoCManager.Resolve().GetComponent(Owner.Owner).EntityName, }; _window.OnClose += Close; _window.Input.OnTextEntered += Input_OnTextEntered; diff --git a/Content.Client/Parallax/ParallaxGenerator.cs b/Content.Client/Parallax/ParallaxGenerator.cs index ec1b9b8b81..7d77fc2047 100644 --- a/Content.Client/Parallax/ParallaxGenerator.cs +++ b/Content.Client/Parallax/ParallaxGenerator.cs @@ -182,7 +182,7 @@ namespace Content.Client.Parallax // Threshold noiseVal = MathF.Max(0, noiseVal - Threshold); noiseVal *= threshVal; - noiseVal = (float) MathF.Pow(noiseVal, powFactor); + noiseVal = MathF.Pow(noiseVal, powFactor); // Get colors based on noise values. var srcColor = Color.InterpolateBetween(OuterColor, InnerColor, noiseVal) @@ -408,7 +408,7 @@ namespace Content.Client.Parallax // Threshold noiseVal = MathF.Max(0, noiseVal - MaskThreshold); noiseVal *= threshVal; - noiseVal = (float) MathF.Pow(noiseVal, powFactor); + noiseVal = MathF.Pow(noiseVal, powFactor); var randomThresh = random.NextFloat(); if (randomThresh > noiseVal) diff --git a/Content.Client/ParticleAccelerator/ParticleAcceleratorPartVisualizer.cs b/Content.Client/ParticleAccelerator/ParticleAcceleratorPartVisualizer.cs index 3d5fa2c935..9b7a39c45d 100644 --- a/Content.Client/ParticleAccelerator/ParticleAcceleratorPartVisualizer.cs +++ b/Content.Client/ParticleAccelerator/ParticleAcceleratorPartVisualizer.cs @@ -4,6 +4,7 @@ using Content.Shared.Singularity.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -32,10 +33,10 @@ namespace Content.Client.ParticleAccelerator _states.Add(ParticleAcceleratorVisualState.Level3, _baseState + "p3"); } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (!entity.TryGetComponent(out var sprite)) + if (!IoCManager.Resolve().TryGetComponent(entity, out var sprite)) { throw new EntityCreationException("No sprite component found in entity that has ParticleAcceleratorPartVisualizer"); } @@ -49,7 +50,9 @@ namespace Content.Client.ParticleAccelerator public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) return; + + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent sprite)) return; if (!component.TryGetData(ParticleAcceleratorVisuals.VisualState, out ParticleAcceleratorVisualState state)) { state = ParticleAcceleratorVisualState.Unpowered; diff --git a/Content.Client/ParticleAccelerator/UI/ParticleAcceleratorControlMenu.cs b/Content.Client/ParticleAccelerator/UI/ParticleAcceleratorControlMenu.cs index d7c41f53ce..7227c7db70 100644 --- a/Content.Client/ParticleAccelerator/UI/ParticleAcceleratorControlMenu.cs +++ b/Content.Client/ParticleAccelerator/UI/ParticleAcceleratorControlMenu.cs @@ -484,7 +484,7 @@ namespace Content.Client.ParticleAccelerator.UI public void SetPowerState(ParticleAcceleratorUIState state, bool exists) { _base.ShaderOverride = exists ? null : _menu._greyScaleShader; - _base.ModulateSelfOverride = exists ? (Color?) null : new Color(127, 127, 127); + _base.ModulateSelfOverride = exists ? null : new Color(127, 127, 127); if (!state.Enabled || !exists) { diff --git a/Content.Client/Physics/Controllers/MoverController.cs b/Content.Client/Physics/Controllers/MoverController.cs index 1bfcb68930..e9fbeafee1 100644 --- a/Content.Client/Physics/Controllers/MoverController.cs +++ b/Content.Client/Physics/Controllers/MoverController.cs @@ -17,10 +17,12 @@ namespace Content.Client.Physics.Controllers { base.UpdateBeforeSolve(prediction, frameTime); - var player = _playerManager.LocalPlayer?.ControlledEntity; - if (player == null || - !player.TryGetComponent(out IMoverComponent? mover) || - !player.TryGetComponent(out PhysicsComponent? body)) return; + if (_playerManager.LocalPlayer?.ControlledEntity is not {Valid: true} player || + !EntityManager.TryGetComponent(player, out IMoverComponent? mover) || + !EntityManager.TryGetComponent(player, out PhysicsComponent? body)) + { + return; + } // Essentially we only want to set our mob to predicted so every other entity we just interpolate // (i.e. only see what the server has sent us). @@ -30,7 +32,7 @@ namespace Content.Client.Physics.Controllers // We set joints to predicted given these can affect how our mob moves. // I would only recommend disabling this if you make pulling not use joints anymore (someday maybe?) - if (player.TryGetComponent(out JointComponent? jointComponent)) + if (EntityManager.TryGetComponent(player, out JointComponent? jointComponent)) { foreach (var joint in jointComponent.GetJoints) { @@ -40,10 +42,9 @@ namespace Content.Client.Physics.Controllers } // If we're being pulled then we won't predict anything and will receive server lerps so it looks way smoother. - if (player.TryGetComponent(out SharedPullableComponent? pullableComp)) + if (EntityManager.TryGetComponent(player, out SharedPullableComponent? pullableComp)) { - var puller = pullableComp.Puller; - if (puller != null && puller.TryGetComponent(out var pullerBody)) + if (pullableComp.Puller is {Valid: true} puller && EntityManager.TryGetComponent(puller, out var pullerBody)) { pullerBody.Predict = false; body.Predict = false; @@ -51,20 +52,18 @@ namespace Content.Client.Physics.Controllers } // If we're pulling a mob then make sure that isn't predicted so it doesn't fuck our velocity up. - if (player.TryGetComponent(out SharedPullerComponent? pullerComp)) + if (EntityManager.TryGetComponent(player, out SharedPullerComponent? pullerComp)) { - var pulling = pullerComp.Pulling; - - if (pulling != null && - pulling.HasComponent() && - pulling.TryGetComponent(out PhysicsComponent? pullingBody)) + if (pullerComp.Pulling is {Valid: true} pulling && + EntityManager.HasComponent(pulling) && + EntityManager.TryGetComponent(pulling, out PhysicsComponent? pullingBody)) { pullingBody.Predict = false; } } // Server-side should just be handled on its own so we'll just do this shizznit - if (player.TryGetComponent(out IMobMoverComponent? mobMover)) + if (EntityManager.TryGetComponent(player, out IMobMoverComponent? mobMover)) { HandleMobMovement(mover, body, mobMover); return; diff --git a/Content.Client/Pinpointer/PinpointerVisualizer.cs b/Content.Client/Pinpointer/PinpointerVisualizer.cs index 6cf214f5e1..6975c414e4 100644 --- a/Content.Client/Pinpointer/PinpointerVisualizer.cs +++ b/Content.Client/Pinpointer/PinpointerVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Pinpointer; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Pinpointer @@ -13,7 +14,8 @@ namespace Content.Client.Pinpointer { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent sprite)) return; // check if pinpointer screen is active diff --git a/Content.Client/PneumaticCannon/PneumaticCannonVisualizer.cs b/Content.Client/PneumaticCannon/PneumaticCannonVisualizer.cs index b88d04f227..04ecd55dbe 100644 --- a/Content.Client/PneumaticCannon/PneumaticCannonVisualizer.cs +++ b/Content.Client/PneumaticCannon/PneumaticCannonVisualizer.cs @@ -1,6 +1,7 @@ using Content.Shared.PneumaticCannon; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.PneumaticCannon { @@ -10,7 +11,8 @@ namespace Content.Client.PneumaticCannon { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent sprite)) return; if (component.TryGetData(PneumaticCannonVisuals.Tank, out bool tank)) diff --git a/Content.Client/Pointing/Components/PointingArrowComponent.cs b/Content.Client/Pointing/Components/PointingArrowComponent.cs index 4be2892b38..187f9a19a8 100644 --- a/Content.Client/Pointing/Components/PointingArrowComponent.cs +++ b/Content.Client/Pointing/Components/PointingArrowComponent.cs @@ -1,6 +1,7 @@ using Content.Shared.Pointing.Components; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using DrawDepth = Content.Shared.DrawDepth.DrawDepth; namespace Content.Client.Pointing.Components @@ -12,7 +13,7 @@ namespace Content.Client.Pointing.Components { base.Startup(); - if (Owner.TryGetComponent(out SpriteComponent? sprite)) + if (IoCManager.Resolve().TryGetComponent(Owner, out SpriteComponent? sprite)) { sprite.DrawDepth = (int) DrawDepth.Overlays; } diff --git a/Content.Client/Pointing/Components/RoguePointingArrowComponent.cs b/Content.Client/Pointing/Components/RoguePointingArrowComponent.cs index 976505c7ad..9d06ae585f 100644 --- a/Content.Client/Pointing/Components/RoguePointingArrowComponent.cs +++ b/Content.Client/Pointing/Components/RoguePointingArrowComponent.cs @@ -1,6 +1,7 @@ using Content.Shared.Pointing.Components; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using DrawDepth = Content.Shared.DrawDepth.DrawDepth; namespace Content.Client.Pointing.Components @@ -12,7 +13,7 @@ namespace Content.Client.Pointing.Components { base.Startup(); - if (Owner.TryGetComponent(out SpriteComponent? sprite)) + if (IoCManager.Resolve().TryGetComponent(Owner, out SpriteComponent? sprite)) { sprite.DrawDepth = (int) DrawDepth.Overlays; } diff --git a/Content.Client/Pointing/RoguePointingArrowVisualizer.cs b/Content.Client/Pointing/RoguePointingArrowVisualizer.cs index 2f675d49fb..9c313bed3d 100644 --- a/Content.Client/Pointing/RoguePointingArrowVisualizer.cs +++ b/Content.Client/Pointing/RoguePointingArrowVisualizer.cs @@ -5,6 +5,7 @@ using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.Animations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Pointing @@ -24,9 +25,9 @@ namespace Content.Client.Pointing private void SetRotation(AppearanceComponent component, Angle rotation) { - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); - if (!sprite.Owner.TryGetComponent(out AnimationPlayerComponent? animation)) + if (!IoCManager.Resolve().TryGetComponent(sprite.Owner, out AnimationPlayerComponent? animation)) { sprite.Rotation = rotation; return; diff --git a/Content.Client/Popups/PopupSystem.cs b/Content.Client/Popups/PopupSystem.cs index 5352fd9278..eb4e447917 100644 --- a/Content.Client/Popups/PopupSystem.cs +++ b/Content.Client/Popups/PopupSystem.cs @@ -4,7 +4,6 @@ using Content.Client.Stylesheets; using Content.Shared.GameTicking; using Content.Shared.Popups; using Robust.Client.Graphics; -using Robust.Client.Player; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects; @@ -52,9 +51,9 @@ namespace Content.Client.Popups PopupMessage(message, _eyeManager.CoordinatesToScreen(transform.Coordinates)); } - public void PopupMessage(string message, ScreenCoordinates coordinates, IEntity? entity = null) + public void PopupMessage(string message, ScreenCoordinates coordinates, EntityUid entity = default) { - var label = new PopupLabel(_eyeManager) + var label = new PopupLabel(_eyeManager, EntityManager) { Entity = entity, Text = message, @@ -143,14 +142,16 @@ namespace Content.Client.Popups private class PopupLabel : Label { private readonly IEyeManager _eyeManager; + private readonly IEntityManager _entityManager; public float TimeLeft { get; private set; } public Vector2 InitialPos { get; set; } - public IEntity? Entity { get; set; } + public EntityUid Entity { get; set; } - public PopupLabel(IEyeManager eyeManager) + public PopupLabel(IEyeManager eyeManager, IEntityManager entityManager) { _eyeManager = eyeManager; + _entityManager = entityManager; ShadowOffsetXOverride = 1; ShadowOffsetYOverride = 1; FontColorShadowOverride = Color.Black; @@ -160,9 +161,9 @@ namespace Content.Client.Popups { TimeLeft += eventArgs.DeltaSeconds; - var position = Entity == null + var position = Entity == default ? InitialPos - : (_eyeManager.CoordinatesToScreen(Entity.Transform.Coordinates).Position / UIScale) - DesiredSize / 2; + : (_eyeManager.CoordinatesToScreen(_entityManager.GetComponent(Entity).Coordinates).Position / UIScale) - DesiredSize / 2; LayoutContainer.SetPosition(this, position - (0, 20 * (TimeLeft * TimeLeft + TimeLeft))); diff --git a/Content.Client/Power/APC/ApcVisualizer.cs b/Content.Client/Power/APC/ApcVisualizer.cs index 85ed0e5d25..b2f57624ff 100644 --- a/Content.Client/Power/APC/ApcVisualizer.cs +++ b/Content.Client/Power/APC/ApcVisualizer.cs @@ -2,17 +2,18 @@ using Content.Shared.APC; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Power.APC { public class ApcVisualizer : AppearanceVisualizer { [UsedImplicitly] - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapSet(Layers.ChargeState, sprite.AddLayerState("apco3-0")); sprite.LayerSetShader(Layers.ChargeState, "unshaded"); @@ -34,7 +35,7 @@ namespace Content.Client.Power.APC { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (component.TryGetData(ApcVisuals.ChargeState, out var state)) { switch (state) diff --git a/Content.Client/Power/SMES/SmesVisualizer.cs b/Content.Client/Power/SMES/SmesVisualizer.cs index 11fcbd41d5..09b8df501e 100644 --- a/Content.Client/Power/SMES/SmesVisualizer.cs +++ b/Content.Client/Power/SMES/SmesVisualizer.cs @@ -3,17 +3,18 @@ using Content.Shared.SMES; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Power.SMES { [UsedImplicitly] public class SmesVisualizer : AppearanceVisualizer { - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerMapSet(Layers.Input, sprite.AddLayerState("smes-oc0")); sprite.LayerSetShader(Layers.Input, "unshaded"); @@ -28,7 +29,7 @@ namespace Content.Client.Power.SMES { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (!component.TryGetData(SmesVisuals.LastChargeLevel, out var level) || level == 0) { sprite.LayerSetVisible(Layers.Charge, false); diff --git a/Content.Client/Power/Visualizers/CableVisualizer.cs b/Content.Client/Power/Visualizers/CableVisualizer.cs index 7d151d1c6d..ad614428fc 100644 --- a/Content.Client/Power/Visualizers/CableVisualizer.cs +++ b/Content.Client/Power/Visualizers/CableVisualizer.cs @@ -1,6 +1,7 @@ using Content.Shared.Wires; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Power @@ -15,7 +16,8 @@ namespace Content.Client.Power { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent? sprite)) return; if (!component.TryGetData(WireVisVisuals.ConnectedMask, out WireVisDirFlags mask)) diff --git a/Content.Client/Power/Visualizers/PowerDeviceVisualizer.cs b/Content.Client/Power/Visualizers/PowerDeviceVisualizer.cs index e8aed1b15d..dd3c525128 100644 --- a/Content.Client/Power/Visualizers/PowerDeviceVisualizer.cs +++ b/Content.Client/Power/Visualizers/PowerDeviceVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Power; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Power { @@ -12,7 +13,7 @@ namespace Content.Client.Power { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); var powered = component.TryGetData(PowerDeviceVisuals.Powered, out bool poweredVar) && poweredVar; sprite.LayerSetVisible(PowerDeviceVisualLayers.Powered, powered); } diff --git a/Content.Client/PowerCell/PowerCellVisualizer.cs b/Content.Client/PowerCell/PowerCellVisualizer.cs index 29052155f8..4d58a23ca1 100644 --- a/Content.Client/PowerCell/PowerCellVisualizer.cs +++ b/Content.Client/PowerCell/PowerCellVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.PowerCell; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.PowerCell @@ -12,11 +13,11 @@ namespace Content.Client.PowerCell [DataField("prefix")] private string? _prefix; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); if (_prefix != null) { @@ -29,7 +30,7 @@ namespace Content.Client.PowerCell { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (component.TryGetData(PowerCellVisuals.ChargeLevel, out byte level)) { var adjustedLevel = level * 25; diff --git a/Content.Client/PowerCell/PowerChargerVisualizer.cs b/Content.Client/PowerCell/PowerChargerVisualizer.cs index a6bd92a4e1..f86e4b8c9d 100644 --- a/Content.Client/PowerCell/PowerChargerVisualizer.cs +++ b/Content.Client/PowerCell/PowerChargerVisualizer.cs @@ -2,17 +2,18 @@ using Content.Shared.Power; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.PowerCell { [UsedImplicitly] public class PowerChargerVisualizer : AppearanceVisualizer { - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); // Base item sprite.LayerMapSet(Layers.Base, sprite.AddLayerState("empty")); @@ -26,7 +27,7 @@ namespace Content.Client.PowerCell { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); // Update base item if (component.TryGetData(CellVisual.Occupied, out bool occupied)) diff --git a/Content.Client/Preferences/UI/CharacterSetupGui.xaml.cs b/Content.Client/Preferences/UI/CharacterSetupGui.xaml.cs index f8ff373a54..d2b8060ddb 100644 --- a/Content.Client/Preferences/UI/CharacterSetupGui.xaml.cs +++ b/Content.Client/Preferences/UI/CharacterSetupGui.xaml.cs @@ -1,9 +1,7 @@ using System.Linq; using Content.Client.Info; using Content.Client.Lobby.UI; -using Content.Client.Parallax; using Content.Client.Resources; -using Content.Client.Stylesheets; using Content.Shared.CharacterAppearance.Systems; using Content.Shared.Preferences; using Content.Shared.Roles; @@ -138,7 +136,7 @@ namespace Content.Client.Preferences.UI private class CharacterPickerButton : ContainerButton { - private IEntity _previewDummy; + private EntityUid _previewDummy; public CharacterPickerButton( IEntityManager entityManager, @@ -151,7 +149,7 @@ namespace Content.Client.Preferences.UI Group = group; _previewDummy = entityManager.SpawnEntity("MobHumanDummy", MapCoordinates.Nullspace); - EntitySystem.Get().UpdateFromProfile(_previewDummy.Uid, profile); + EntitySystem.Get().UpdateFromProfile(_previewDummy, profile); var humanoid = profile as HumanoidCharacterProfile; if (humanoid != null) { @@ -165,7 +163,7 @@ namespace Content.Client.Preferences.UI var view = new SpriteView { - Sprite = _previewDummy.GetComponent(), + Sprite = entityManager.GetComponent(_previewDummy), Scale = (2, 2), OverrideDirection = Direction.South }; @@ -218,8 +216,8 @@ namespace Content.Client.Preferences.UI if (!disposing) return; - _previewDummy.Delete(); - _previewDummy = null!; + IoCManager.Resolve().DeleteEntity((EntityUid) _previewDummy); + _previewDummy = default; } } } diff --git a/Content.Client/Preferences/UI/HumanoidProfileEditor.xaml.cs b/Content.Client/Preferences/UI/HumanoidProfileEditor.xaml.cs index 6b91912867..6e3f38cecb 100644 --- a/Content.Client/Preferences/UI/HumanoidProfileEditor.xaml.cs +++ b/Content.Client/Preferences/UI/HumanoidProfileEditor.xaml.cs @@ -21,7 +21,6 @@ using Robust.Shared.Enums; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Prototypes; @@ -76,7 +75,7 @@ namespace Content.Client.Preferences.UI private readonly List _antagPreferences; - private readonly IEntity _previewDummy; + private readonly EntityUid _previewDummy; private Control _previewSpriteControl => CSpriteViewFront; private Control _previewSpriteSideControl => CSpriteViewSide; private readonly SpriteView _previewSprite; @@ -438,7 +437,7 @@ namespace Content.Client.Preferences.UI #region Preview _previewDummy = entityManager.SpawnEntity("MobHumanDummy", MapCoordinates.Nullspace); - var sprite = _previewDummy.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(_previewDummy); // Front _previewSprite = new SpriteView @@ -482,7 +481,7 @@ namespace Content.Client.Preferences.UI if (!disposing) return; - _previewDummy.Delete(); + IoCManager.Resolve().DeleteEntity((EntityUid) _previewDummy); _preferencesManager.OnServerDataLoaded -= LoadServerData; } @@ -660,7 +659,7 @@ namespace Content.Client.Preferences.UI if (Profile is null) return; - EntitySystem.Get().UpdateFromProfile(_previewDummy.Uid, Profile); + EntitySystem.Get().UpdateFromProfile(_previewDummy, Profile); LobbyCharacterPreviewPanel.GiveDummyJobClothes(_previewDummy, Profile); } diff --git a/Content.Client/Recycling/RecyclerVisualizer.cs b/Content.Client/Recycling/RecyclerVisualizer.cs index 5d584582d8..0111100f0b 100644 --- a/Content.Client/Recycling/RecyclerVisualizer.cs +++ b/Content.Client/Recycling/RecyclerVisualizer.cs @@ -3,6 +3,7 @@ using Content.Shared.Recycling; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Recycling @@ -16,12 +17,13 @@ namespace Content.Client.Recycling [DataField("state_off")] private string _stateOff = "grinder-o0"; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (!entity.TryGetComponent(out ISpriteComponent? sprite) || - !entity.TryGetComponent(out AppearanceComponent? appearance)) + var entMan = IoCManager.Resolve(); + if (!entMan.TryGetComponent(entity, out ISpriteComponent? sprite) || + !entMan.TryGetComponent(entity, out AppearanceComponent? appearance)) { return; } @@ -33,7 +35,8 @@ namespace Content.Client.Recycling { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { return; } diff --git a/Content.Client/Research/UI/ResearchConsoleBoundUserInterface.cs b/Content.Client/Research/UI/ResearchConsoleBoundUserInterface.cs index 0fcd499e40..8703825d65 100644 --- a/Content.Client/Research/UI/ResearchConsoleBoundUserInterface.cs +++ b/Content.Client/Research/UI/ResearchConsoleBoundUserInterface.cs @@ -2,6 +2,7 @@ using Content.Shared.Research.Prototypes; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.Research.Components.SharedResearchConsoleComponent; namespace Content.Client.Research.UI @@ -23,7 +24,7 @@ namespace Content.Client.Research.UI { base.Open(); - if (!Owner.Owner.TryGetComponent(out _technologyDatabase)) return; + if (!IoCManager.Resolve().TryGetComponent(Owner.Owner, out _technologyDatabase)) return; _consoleMenu = new ResearchConsoleMenu(this); diff --git a/Content.Client/Rotation/RotationVisualizer.cs b/Content.Client/Rotation/RotationVisualizer.cs index 05e5a852de..2021c5b76a 100644 --- a/Content.Client/Rotation/RotationVisualizer.cs +++ b/Content.Client/Rotation/RotationVisualizer.cs @@ -5,6 +5,7 @@ using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.Animations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Rotation @@ -32,9 +33,10 @@ namespace Content.Client.Rotation private void SetRotation(AppearanceComponent component, Angle rotation) { - var sprite = component.Owner.GetComponent(); + var entMan = IoCManager.Resolve(); + var sprite = entMan.GetComponent(component.Owner); - if (!sprite.Owner.TryGetComponent(out AnimationPlayerComponent? animation)) + if (!entMan.TryGetComponent(sprite.Owner, out AnimationPlayerComponent? animation)) { sprite.Rotation = rotation; return; diff --git a/Content.Client/Security/DeployableBarrierVisualizer.cs b/Content.Client/Security/DeployableBarrierVisualizer.cs index 9b0799f0d7..4b88189a50 100644 --- a/Content.Client/Security/DeployableBarrierVisualizer.cs +++ b/Content.Client/Security/DeployableBarrierVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Security; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Security { @@ -12,7 +13,8 @@ namespace Content.Client.Security { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent? sprite)) return; if (!component.TryGetData(DeployableBarrierVisuals.State, out DeployableBarrierState state)) diff --git a/Content.Client/Shuttles/ThrusterVisualizer.cs b/Content.Client/Shuttles/ThrusterVisualizer.cs index 904035539b..5f7712450a 100644 --- a/Content.Client/Shuttles/ThrusterVisualizer.cs +++ b/Content.Client/Shuttles/ThrusterVisualizer.cs @@ -1,6 +1,7 @@ using Content.Shared.Shuttles.Components; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Shuttles { @@ -10,7 +11,8 @@ namespace Content.Client.Shuttles { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? spriteComponent)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent? spriteComponent)) return; component.TryGetData(ThrusterVisualState.State, out bool state); diff --git a/Content.Client/Singularity/Components/ContainmentFieldComponent.cs b/Content.Client/Singularity/Components/ContainmentFieldComponent.cs index ea6afc64ef..2bae3934ab 100644 --- a/Content.Client/Singularity/Components/ContainmentFieldComponent.cs +++ b/Content.Client/Singularity/Components/ContainmentFieldComponent.cs @@ -1,6 +1,7 @@ using Content.Shared.Singularity.Components; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; namespace Content.Client.Singularity.Components @@ -17,7 +18,7 @@ namespace Content.Client.Singularity.Components { base.Initialize(); - if (!Owner.TryGetComponent(out _spriteComponent)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out _spriteComponent)) { Logger.Error($"{nameof(ContainmentFieldComponent)} created without {nameof(SpriteComponent)}"); } diff --git a/Content.Client/Singularity/SingularityOverlay.cs b/Content.Client/Singularity/SingularityOverlay.cs index 020dfb93c9..9157e859a1 100644 --- a/Content.Client/Singularity/SingularityOverlay.cs +++ b/Content.Client/Singularity/SingularityOverlay.cs @@ -43,7 +43,7 @@ namespace Content.Client.Singularity var viewportWB = _eyeManager.GetWorldViewport(); // Has to be correctly handled because of the way intensity/falloff transform works so just do it. _shader?.SetParameter("renderScale", args.Viewport.RenderScale); - foreach (SingularityShaderInstance instance in _singularities.Values) + foreach (var instance in _singularities.Values) { // To be clear, this needs to use "inside-viewport" pixels. // In other words, specifically NOT IViewportControl.WorldToScreen (which uses outer coordinates). @@ -78,31 +78,31 @@ namespace Content.Client.Singularity { var singuloEntity = distortion.Owner; - if (!_singularities.Keys.Contains(singuloEntity.Uid) && SinguloQualifies(singuloEntity, currentEyeLoc)) + if (!_singularities.Keys.Contains(singuloEntity) && SinguloQualifies(singuloEntity, currentEyeLoc)) { - _singularities.Add(singuloEntity.Uid, new SingularityShaderInstance(singuloEntity.Transform.MapPosition.Position, distortion.Intensity, distortion.Falloff)); + _singularities.Add(singuloEntity, new SingularityShaderInstance(_entityManager.GetComponent(singuloEntity).MapPosition.Position, distortion.Intensity, distortion.Falloff)); } } var activeShaderIds = _singularities.Keys; - foreach (var activeSinguloUid in activeShaderIds) //Remove all singulos that are added and no longer qualify + foreach (var activeSingulo in activeShaderIds) //Remove all singulos that are added and no longer qualify { - if (_entityManager.TryGetEntity(activeSinguloUid, out var singuloEntity)) + if (_entityManager.EntityExists(activeSingulo)) { - if (!SinguloQualifies(singuloEntity, currentEyeLoc)) + if (!SinguloQualifies(activeSingulo, currentEyeLoc)) { - _singularities.Remove(activeSinguloUid); + _singularities.Remove(activeSingulo); } else { - if (!singuloEntity.TryGetComponent(out var distortion)) + if (!_entityManager.TryGetComponent(activeSingulo, out var distortion)) { - _singularities.Remove(activeSinguloUid); + _singularities.Remove(activeSingulo); } else { - var shaderInstance = _singularities[activeSinguloUid]; - shaderInstance.CurrentMapCoords = singuloEntity.Transform.MapPosition.Position; + var shaderInstance = _singularities[activeSingulo]; + shaderInstance.CurrentMapCoords = _entityManager.GetComponent(activeSingulo).MapPosition.Position; shaderInstance.Intensity = distortion.Intensity; shaderInstance.Falloff = distortion.Falloff; } @@ -111,15 +111,15 @@ namespace Content.Client.Singularity } else { - _singularities.Remove(activeSinguloUid); + _singularities.Remove(activeSingulo); } } } - private bool SinguloQualifies(IEntity singuloEntity, MapCoordinates currentEyeLoc) + private bool SinguloQualifies(EntityUid singuloEntity, MapCoordinates currentEyeLoc) { - return singuloEntity.Transform.MapID == currentEyeLoc.MapId && singuloEntity.Transform.Coordinates.InRange(_entityManager, EntityCoordinates.FromMap(_entityManager, singuloEntity.Transform.ParentUid, currentEyeLoc), MaxDist); + return _entityManager.GetComponent(singuloEntity).MapID == currentEyeLoc.MapId && _entityManager.GetComponent(singuloEntity).Coordinates.InRange(_entityManager, EntityCoordinates.FromMap(_entityManager, _entityManager.GetComponent(singuloEntity).ParentUid, currentEyeLoc), MaxDist); } private sealed class SingularityShaderInstance diff --git a/Content.Client/Singularity/Visualizers/EmitterVisualizer.cs b/Content.Client/Singularity/Visualizers/EmitterVisualizer.cs index 5bc71fee3f..58c877bcfb 100644 --- a/Content.Client/Singularity/Visualizers/EmitterVisualizer.cs +++ b/Content.Client/Singularity/Visualizers/EmitterVisualizer.cs @@ -4,6 +4,7 @@ using Content.Shared.Storage; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Singularity.Visualizers { @@ -17,7 +18,8 @@ namespace Content.Client.Singularity.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { return; } diff --git a/Content.Client/Singularity/Visualizers/RadiationCollectorVisualizer.cs b/Content.Client/Singularity/Visualizers/RadiationCollectorVisualizer.cs index 459ab2e7a7..b07424139c 100644 --- a/Content.Client/Singularity/Visualizers/RadiationCollectorVisualizer.cs +++ b/Content.Client/Singularity/Visualizers/RadiationCollectorVisualizer.cs @@ -4,6 +4,7 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; namespace Content.Client.Singularity.Visualizers @@ -43,20 +44,18 @@ namespace Content.Client.Singularity.Visualizers } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { - if (!entity.HasComponent()) - { - entity.AddComponent(); - } + IoCManager.Resolve().EnsureComponent(entity); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out var sprite)) return; - if (!component.Owner.TryGetComponent(out var animPlayer)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent sprite)) return; + if (!entities.TryGetComponent(component.Owner, out AnimationPlayerComponent animPlayer)) return; if (!component.TryGetData(RadiationCollectorVisuals.VisualState, out RadiationCollectorVisualState state)) { state = RadiationCollectorVisualState.Deactive; diff --git a/Content.Client/Singularity/Visualizers/SingularityVisualizer.cs b/Content.Client/Singularity/Visualizers/SingularityVisualizer.cs index 769c433ed6..19bec6d582 100644 --- a/Content.Client/Singularity/Visualizers/SingularityVisualizer.cs +++ b/Content.Client/Singularity/Visualizers/SingularityVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -13,18 +14,18 @@ namespace Content.Client.Singularity.Visualizers [DataField("layer")] private int Layer { get; } = 0; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - entity.GetComponentOrNull()?.LayerMapReserveBlank(Layer); + IoCManager.Resolve().GetComponentOrNull(entity)?.LayerMapReserveBlank(Layer); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (!IoCManager.Resolve().TryGetComponent(component.Owner, out SpriteComponent? sprite)) { return; } diff --git a/Content.Client/Smoking/BurnStateVisualizer.cs b/Content.Client/Smoking/BurnStateVisualizer.cs index f144eb5b02..71469bab90 100644 --- a/Content.Client/Smoking/BurnStateVisualizer.cs +++ b/Content.Client/Smoking/BurnStateVisualizer.cs @@ -3,6 +3,7 @@ using Content.Shared.Smoking; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Smoking @@ -24,8 +25,6 @@ namespace Content.Client.Smoking [DataField("unlitPrefix")] private string _unlitPrefix = "unlit"; - - public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); @@ -38,9 +37,10 @@ namespace Content.Client.Smoking private void SetState(AppearanceComponent component, SmokableState burnState) { - var clothing = component.Owner.GetComponentOrNull(); + var entities = IoCManager.Resolve(); + var clothing = entities.GetComponentOrNull(component.Owner); - if (component.Owner.TryGetComponent(out var sprite)) + if (entities.TryGetComponent(component.Owner, out ISpriteComponent sprite)) { switch (burnState) { diff --git a/Content.Client/Spawners/ClientEntitySpawnerComponent.cs b/Content.Client/Spawners/ClientEntitySpawnerComponent.cs index bb17ab1700..0c4b5848f4 100644 --- a/Content.Client/Spawners/ClientEntitySpawnerComponent.cs +++ b/Content.Client/Spawners/ClientEntitySpawnerComponent.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Spawners @@ -10,11 +11,13 @@ namespace Content.Client.Spawners [RegisterComponent] public class ClientEntitySpawnerComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "ClientEntitySpawner"; [DataField("prototypes")] private List _prototypes = new() { "HVDummyWire" }; - private readonly List _entity = new(); + private readonly List _entity = new(); protected override void Initialize() { @@ -32,7 +35,7 @@ namespace Content.Client.Spawners { foreach (var proto in _prototypes) { - var entity = Owner.EntityManager.SpawnEntity(proto, Owner.Transform.Coordinates); + var entity = _entMan.SpawnEntity(proto, _entMan.GetComponent(Owner).Coordinates); _entity.Add(entity); } } @@ -41,7 +44,7 @@ namespace Content.Client.Spawners { foreach (var entity in _entity) { - Owner.EntityManager.DeleteEntity(entity); + _entMan.DeleteEntity(entity); } } } diff --git a/Content.Client/Stack/StackVisualizer.cs b/Content.Client/Stack/StackVisualizer.cs index 092e81f5bd..5980d5d52a 100644 --- a/Content.Client/Stack/StackVisualizer.cs +++ b/Content.Client/Stack/StackVisualizer.cs @@ -5,6 +5,7 @@ using Content.Shared.Stacks; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -77,13 +78,13 @@ namespace Content.Client.Stack [DataField("sprite")] private ResourcePath? _spritePath; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); if (_isComposite && _spriteLayers.Count > 0 - && entity.TryGetComponent(out var spriteComponent)) + && IoCManager.Resolve().TryGetComponent(entity, out var spriteComponent)) { var spritePath = _spritePath ?? spriteComponent.BaseRSI!.Path!; @@ -100,7 +101,8 @@ namespace Content.Client.Stack { base.OnChangeData(component); - if (component.Owner.TryGetComponent(out var spriteComponent)) + var entities = IoCManager.Resolve(); + if (entities.TryGetComponent(component.Owner, out ISpriteComponent spriteComponent)) { if (_isComposite) { diff --git a/Content.Client/StationEvents/RadiationPulseOverlay.cs b/Content.Client/StationEvents/RadiationPulseOverlay.cs index 6bef4d2dd6..a4f8f0ad15 100644 --- a/Content.Client/StationEvents/RadiationPulseOverlay.cs +++ b/Content.Client/StationEvents/RadiationPulseOverlay.cs @@ -4,11 +4,11 @@ using System.Linq; using Robust.Client.Graphics; using Robust.Shared.Enums; using Robust.Shared.GameObjects; -using Robust.Shared.Timing; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Prototypes; +using Robust.Shared.Timing; namespace Content.Client.StationEvents { @@ -86,14 +86,14 @@ namespace Content.Client.StationEvents { var pulseEntity = pulse.Owner; - if (!_pulses.Keys.Contains(pulseEntity.Uid) && PulseQualifies(pulseEntity, currentEyeLoc)) + if (!_pulses.Keys.Contains(pulseEntity) && PulseQualifies(pulseEntity, currentEyeLoc)) { _pulses.Add( - pulseEntity.Uid, + pulseEntity, ( _baseShader.Duplicate(), new RadiationShaderInstance( - pulseEntity.Transform.MapPosition.Position, + _entityManager.GetComponent(pulseEntity).MapPosition.Position, pulse.Range, pulse.StartTime, pulse.EndTime @@ -104,26 +104,26 @@ namespace Content.Client.StationEvents } var activeShaderIds = _pulses.Keys; - foreach (var activePulseUid in activeShaderIds) //Remove all pulses that are added and no longer qualify + foreach (var pulseEntity in activeShaderIds) //Remove all pulses that are added and no longer qualify { - if (_entityManager.TryGetEntity(activePulseUid, out var pulseEntity) && + if (_entityManager.EntityExists(pulseEntity) && PulseQualifies(pulseEntity, currentEyeLoc) && - pulseEntity.TryGetComponent(out var pulse)) + _entityManager.TryGetComponent(pulseEntity, out var pulse)) { - var shaderInstance = _pulses[activePulseUid]; - shaderInstance.instance.CurrentMapCoords = pulseEntity.Transform.MapPosition.Position; + var shaderInstance = _pulses[pulseEntity]; + shaderInstance.instance.CurrentMapCoords = _entityManager.GetComponent(pulseEntity).MapPosition.Position; shaderInstance.instance.Range = pulse.Range; } else { - _pulses[activePulseUid].shd.Dispose(); - _pulses.Remove(activePulseUid); + _pulses[pulseEntity].shd.Dispose(); + _pulses.Remove(pulseEntity); } } } - private bool PulseQualifies(IEntity pulseEntity, MapCoordinates currentEyeLoc) + private bool PulseQualifies(EntityUid pulseEntity, MapCoordinates currentEyeLoc) { - return pulseEntity.Transform.MapID == currentEyeLoc.MapId && pulseEntity.Transform.Coordinates.InRange(_entityManager, EntityCoordinates.FromMap(_entityManager, pulseEntity.Transform.ParentUid, currentEyeLoc), MaxDist); + return _entityManager.GetComponent(pulseEntity).MapID == currentEyeLoc.MapId && _entityManager.GetComponent(pulseEntity).Coordinates.InRange(_entityManager, EntityCoordinates.FromMap(_entityManager, _entityManager.GetComponent(pulseEntity).ParentUid, currentEyeLoc), MaxDist); } private sealed record RadiationShaderInstance(Vector2 CurrentMapCoords, float Range, TimeSpan Start, TimeSpan End) diff --git a/Content.Client/Storage/ClientStorageComponent.cs b/Content.Client/Storage/ClientStorageComponent.cs index a74836279d..b86239c568 100644 --- a/Content.Client/Storage/ClientStorageComponent.cs +++ b/Content.Client/Storage/ClientStorageComponent.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using System.Linq; using Content.Client.Animations; using Content.Client.Hands; -using Content.Client.Items.Managers; using Content.Client.Items.Components; +using Content.Client.Items.Managers; using Content.Client.UserInterface.Controls; using Content.Shared.DragDrop; using Content.Shared.Storage; @@ -22,6 +22,7 @@ using Robust.Shared.Maths; using Robust.Shared.Network; using Robust.Shared.Players; using static Robust.Client.UserInterface.Control; +using static Robust.Client.UserInterface.Controls.BaseButton; using static Robust.Client.UserInterface.Controls.BoxContainer; namespace Content.Client.Storage @@ -33,20 +34,25 @@ namespace Content.Client.Storage public class ClientStorageComponent : SharedStorageComponent, IDraggable { [Dependency] private readonly IItemSlotManager _itemSlotManager = default!; + [Dependency] private readonly IPlayerManager _playerManager = default!; + [Dependency] private readonly IEntityManager _entityManager = default!; - private List _storedEntities = new(); + private List _storedEntities = new(); private int StorageSizeUsed; private int StorageCapacityMax; private StorageWindow? _window; public bool UIOpen => _window?.IsOpen ?? false; - public override IReadOnlyList StoredEntities => _storedEntities; + public override IReadOnlyList StoredEntities => _storedEntities; protected override void OnAdd() { base.OnAdd(); - _window = new StorageWindow(this) {Title = Owner.Name}; + _window = new StorageWindow(this, _playerManager, _entityManager) + { + Title = _entityManager.GetComponent(Owner).EntityName + }; _window.EntityList.GenerateItem += GenerateButton; _window.EntityList.ItemPressed += Interact; } @@ -66,9 +72,7 @@ namespace Content.Client.Storage return; } - _storedEntities = state.StoredEntities - .Select(id => Owner.EntityManager.GetEntity(id)) - .ToList(); + _storedEntities = state.StoredEntities.ToList(); } [Obsolete("Component Messages are deprecated, use Entity Events instead.")] @@ -101,7 +105,7 @@ namespace Content.Client.Storage /// private void HandleStorageMessage(StorageHeldItemsMessage storageState) { - _storedEntities = storageState.StoredEntities.Select(id => Owner.EntityManager.GetEntity(id)).ToList(); + _storedEntities = storageState.StoredEntities.ToList(); StorageSizeUsed = storageState.StorageSizeUsed; StorageCapacityMax = storageState.StorageSizeMax; _window?.BuildEntityList(storageState.StoredEntities.ToList()); @@ -115,12 +119,12 @@ namespace Content.Client.Storage { for (var i = 0; msg.StoredEntities.Count > i; i++) { - var entityId = msg.StoredEntities[i]; + var entity = msg.StoredEntities[i]; var initialPosition = msg.EntityPositions[i]; - if (Owner.EntityManager.TryGetEntity(entityId, out var entity)) + if (_entityManager.EntityExists(entity)) { - ReusableAnimations.AnimateEntityPickup(entity, initialPosition, Owner.Transform.LocalPosition); + ReusableAnimations.AnimateEntityPickup(entity, initialPosition, _entityManager.GetComponent(Owner).LocalPosition, _entityManager); } } } @@ -146,23 +150,23 @@ namespace Content.Client.Storage /// /// Function for clicking one of the stored entity buttons in the UI, tells server to remove that entity /// - /// - private void Interact(BaseButton.ButtonEventArgs buttonEventArgs, EntityUid entityUid) + /// + private void Interact(ButtonEventArgs args, EntityUid entity) { - if (buttonEventArgs.Event.Function == EngineKeyFunctions.UIClick) + if (args.Event.Function == EngineKeyFunctions.UIClick) { #pragma warning disable 618 - SendNetworkMessage(new RemoveEntityMessage(entityUid)); + SendNetworkMessage(new RemoveEntityMessage(entity)); #pragma warning restore 618 - buttonEventArgs.Event.Handle(); + args.Event.Handle(); } - else if (Owner.EntityManager.TryGetEntity(entityUid, out var entity)) + else if (_entityManager.EntityExists(entity)) { - _itemSlotManager.OnButtonPressed(buttonEventArgs.Event, entity); + _itemSlotManager.OnButtonPressed(args.Event, entity); } } - public override bool Remove(IEntity entity) + public override bool Remove(EntityUid entity) { if (_storedEntities.Remove(entity)) { @@ -176,13 +180,13 @@ namespace Content.Client.Storage /// /// Button created for each entity that represents that item in the storage UI, with a texture, and name and size label /// - private void GenerateButton(EntityUid entityUid, EntityContainerButton button) + private void GenerateButton(EntityUid entity, EntityContainerButton button) { - if (!Owner.EntityManager.TryGetEntity(entityUid, out var entity)) + if (!_entityManager.EntityExists(entity)) return; - entity.TryGetComponent(out ISpriteComponent? sprite); - entity.TryGetComponent(out ItemComponent? item); + _entityManager.TryGetComponent(entity, out ISpriteComponent? sprite); + _entityManager.TryGetComponent(entity, out ItemComponent? item); button.AddChild(new BoxContainer { @@ -202,7 +206,7 @@ namespace Content.Client.Storage { HorizontalExpand = true, ClipText = true, - Text = entity.Name + Text = _entityManager.GetComponent(entity).EntityName }, new Label { @@ -223,12 +227,12 @@ namespace Content.Client.Storage private Control _vBox; private readonly Label _information; public readonly EntityListDisplay EntityList; - public ClientStorageComponent StorageEntity; + public readonly ClientStorageComponent StorageEntity; private readonly StyleBoxFlat _hoveredBox = new() { BackgroundColor = Color.Black.WithAlpha(0.35f) }; private readonly StyleBoxFlat _unHoveredBox = new() { BackgroundColor = Color.Black.WithAlpha(0.0f) }; - public StorageWindow(ClientStorageComponent storageEntity) + public StorageWindow(ClientStorageComponent storageEntity, IPlayerManager players, IEntityManager entities) { StorageEntity = storageEntity; SetSize = (200, 320); @@ -250,9 +254,9 @@ namespace Content.Client.Storage containerButton.AddChild(innerContainerButton); containerButton.OnPressed += args => { - var controlledEntity = IoCManager.Resolve().LocalPlayer?.ControlledEntity; + var controlledEntity = players.LocalPlayer?.ControlledEntity; - if (controlledEntity?.TryGetComponent(out HandsComponent? hands) ?? false) + if (entities.HasComponent(controlledEntity)) { #pragma warning disable 618 StorageEntity.SendNetworkMessage(new InsertEntityMessage()); @@ -278,12 +282,12 @@ namespace Content.Client.Storage Name = "EntityListContainer", }; _vBox.AddChild(EntityList); - EntityList.OnMouseEntered += args => + EntityList.OnMouseEntered += _ => { innerContainerButton.PanelOverride = _hoveredBox; }; - EntityList.OnMouseExited += args => + EntityList.OnMouseExited += _ => { innerContainerButton.PanelOverride = _unHoveredBox; }; diff --git a/Content.Client/Storage/Visualizers/BagOpenCloseVisualizer.cs b/Content.Client/Storage/Visualizers/BagOpenCloseVisualizer.cs index 363c6cf061..ec0cff6002 100644 --- a/Content.Client/Storage/Visualizers/BagOpenCloseVisualizer.cs +++ b/Content.Client/Storage/Visualizers/BagOpenCloseVisualizer.cs @@ -1,10 +1,8 @@ - -using Content.Shared.Stacks; -using Content.Shared.Storage; -using Content.Shared.Storage.Components; +using Content.Shared.Storage.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -26,12 +24,14 @@ namespace Content.Client.Storage.Visualizers } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); + var entities = IoCManager.Resolve(); + if (_openIcon != null && - entity.TryGetComponent(out var spriteComponent) && + entities.TryGetComponent(entity, out var spriteComponent) && spriteComponent.BaseRSI?.Path != null) { spriteComponent.LayerMapReserveBlank(OpenIcon); @@ -44,22 +44,23 @@ namespace Content.Client.Storage.Visualizers { base.OnChangeData(component); - if (_openIcon != null - && component.Owner.TryGetComponent(out var spriteComponent)) - { - if (component.TryGetData(SharedBagOpenVisuals.BagState, out var bagState)) - { - switch (bagState) - { - case SharedBagState.Open: - spriteComponent.LayerSetVisible(OpenIcon, true); - break; - default: - spriteComponent.LayerSetVisible(OpenIcon, false); - break; - } + var entities = IoCManager.Resolve(); - } + if (_openIcon == null || + !entities.TryGetComponent(component.Owner, out SpriteComponent spriteComponent)) + return; + + if (!component.TryGetData(SharedBagOpenVisuals.BagState, out var bagState)) + return; + + switch (bagState) + { + case SharedBagState.Open: + spriteComponent.LayerSetVisible(OpenIcon, true); + break; + default: + spriteComponent.LayerSetVisible(OpenIcon, false); + break; } } } diff --git a/Content.Client/Storage/Visualizers/MappedItemVisualizer.cs b/Content.Client/Storage/Visualizers/MappedItemVisualizer.cs index d1d3c88714..29eccbec52 100644 --- a/Content.Client/Storage/Visualizers/MappedItemVisualizer.cs +++ b/Content.Client/Storage/Visualizers/MappedItemVisualizer.cs @@ -4,6 +4,7 @@ using Content.Shared.Storage.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -15,11 +16,11 @@ namespace Content.Client.Storage.Visualizers [DataField("sprite")] private ResourcePath? _rsiPath; private List _spriteLayers = new(); - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (entity.TryGetComponent(out var spriteComponent)) + if (IoCManager.Resolve().TryGetComponent(entity, out var spriteComponent)) { _rsiPath ??= spriteComponent.BaseRSI!.Path!; } @@ -29,14 +30,16 @@ namespace Content.Client.Storage.Visualizers public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - if (component.Owner.TryGetComponent(out var spriteComponent)) + + var entities = IoCManager.Resolve(); + if (entities.TryGetComponent(component.Owner, out ISpriteComponent spriteComponent)) { if (_spriteLayers.Count == 0) { InitLayers(spriteComponent, component); } - EnableLayers(spriteComponent, component); + EnableLayers(spriteComponent, component); } } diff --git a/Content.Client/Storage/Visualizers/StorageVisualizer.cs b/Content.Client/Storage/Visualizers/StorageVisualizer.cs index 43a8df5684..cd1a73927e 100644 --- a/Content.Client/Storage/Visualizers/StorageVisualizer.cs +++ b/Content.Client/Storage/Visualizers/StorageVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Storage; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Storage.Visualizers @@ -16,9 +17,9 @@ namespace Content.Client.Storage.Visualizers [DataField("state_closed")] private string? _stateClosed; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { - if (!entity.TryGetComponent(out ISpriteComponent? sprite)) + if (!IoCManager.Resolve().TryGetComponent(entity, out ISpriteComponent? sprite)) { return; } @@ -33,7 +34,8 @@ namespace Content.Client.Storage.Visualizers { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) { return; } diff --git a/Content.Client/SubFloor/SubFloorShowLayerVisualizer.cs b/Content.Client/SubFloor/SubFloorShowLayerVisualizer.cs index e3958a59c8..7052d30ecb 100644 --- a/Content.Client/SubFloor/SubFloorShowLayerVisualizer.cs +++ b/Content.Client/SubFloor/SubFloorShowLayerVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.SubFloor; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.SubFloor { @@ -12,7 +13,8 @@ namespace Content.Client.SubFloor { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out SpriteComponent? sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out SpriteComponent? sprite)) return; if (component.TryGetData(SubFloorVisuals.SubFloor, out bool subfloor)) diff --git a/Content.Client/Suspicion/SuspicionGui.xaml.cs b/Content.Client/Suspicion/SuspicionGui.xaml.cs index 064fcebe2b..3352d64c94 100644 --- a/Content.Client/Suspicion/SuspicionGui.xaml.cs +++ b/Content.Client/Suspicion/SuspicionGui.xaml.cs @@ -65,7 +65,7 @@ namespace Content.Client.Suspicion return false; } - return _playerManager.LocalPlayer.ControlledEntity.TryGetComponent(out suspicion); + return IoCManager.Resolve().TryGetComponent(_playerManager.LocalPlayer.ControlledEntity, out suspicion); } public void UpdateLabel() diff --git a/Content.Client/Suspicion/SuspicionRoleComponent.cs b/Content.Client/Suspicion/SuspicionRoleComponent.cs index 28b62ad913..5bf4116fce 100644 --- a/Content.Client/Suspicion/SuspicionRoleComponent.cs +++ b/Content.Client/Suspicion/SuspicionRoleComponent.cs @@ -72,7 +72,7 @@ namespace Content.Client.Suspicion } _overlayActive = true; - var overlay = new TraitorOverlay(Owner.EntityManager, _resourceCache, _eyeManager); + var overlay = new TraitorOverlay(IoCManager.Resolve(), _resourceCache, _eyeManager); _overlayManager.AddOverlay(overlay); } diff --git a/Content.Client/Suspicion/TraitorOverlay.cs b/Content.Client/Suspicion/TraitorOverlay.cs index 9646a42dfe..1666673da6 100644 --- a/Content.Client/Suspicion/TraitorOverlay.cs +++ b/Content.Client/Suspicion/TraitorOverlay.cs @@ -41,32 +41,34 @@ namespace Content.Client.Suspicion var viewport = _eyeManager.GetWorldViewport(); var ent = _playerManager.LocalPlayer?.ControlledEntity; - if (ent == null || ent.TryGetComponent(out SuspicionRoleComponent? sus) != true) + if (_entityManager.TryGetComponent(ent, out SuspicionRoleComponent? sus) != true) { return; } - foreach (var (_, uid) in sus.Allies) + foreach (var (_, ally) in sus.Allies) { // Otherwise the entity can not exist yet - if (!_entityManager.TryGetEntity(uid, out var ally)) + if (!_entityManager.EntityExists(ally)) { continue; } - if (!ally.TryGetComponent(out IPhysBody? physics)) + if (!_entityManager.TryGetComponent(ally, out IPhysBody? physics)) { continue; } - if (!ExamineSystemShared.InRangeUnOccluded(ent.Transform.MapPosition, ally.Transform.MapPosition, 15, + var entPosition = _entityManager.GetComponent(ent.Value).MapPosition; + var allyPosition = _entityManager.GetComponent(ally).MapPosition; + if (!ExamineSystemShared.InRangeUnOccluded(entPosition, allyPosition, 15, entity => entity == ent || entity == ally)) { continue; } // if not on the same map, continue - if (physics.Owner.Transform.MapID != _eyeManager.CurrentMap || physics.Owner.IsInContainer()) + if (_entityManager.GetComponent(physics.Owner).MapID != _eyeManager.CurrentMap || physics.Owner.IsInContainer()) { continue; } diff --git a/Content.Client/Tabletop/TabletopSystem.cs b/Content.Client/Tabletop/TabletopSystem.cs index 5e9073b907..bf400df408 100644 --- a/Content.Client/Tabletop/TabletopSystem.cs +++ b/Content.Client/Tabletop/TabletopSystem.cs @@ -19,6 +19,7 @@ using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Timing; +using static Robust.Shared.Input.Binding.PointerInputCmdHandler; using DrawDepth = Content.Shared.DrawDepth.DrawDepth; namespace Content.Client.Tabletop @@ -57,7 +58,7 @@ namespace Content.Client.Tabletop return; // If there is no player entity, return - if (_playerManager.LocalPlayer is not { ControlledEntity: { Uid: var playerEntity } }) return; + if (_playerManager.LocalPlayer is not {ControlledEntity: { } playerEntity}) return; if (StunnedOrNoHands(playerEntity)) { @@ -159,7 +160,7 @@ namespace Content.Client.Tabletop _window = null; } - private bool OnUse(in PointerInputCmdHandler.PointerInputCmdArgs args) + private bool OnUse(in PointerInputCmdArgs args) { return args.State switch { @@ -169,13 +170,14 @@ namespace Content.Client.Tabletop }; } - private bool OnMouseDown(in PointerInputCmdHandler.PointerInputCmdArgs args) + private bool OnMouseDown(in PointerInputCmdArgs args) { // Return if no player entity - if (_playerManager.LocalPlayer is not { ControlledEntity: { Uid : var playerEntityUid } }) return false; + if (_playerManager.LocalPlayer is not {ControlledEntity: { } playerEntity}) + return false; // Return if can not see table or stunned/no hands - if (!CanSeeTable(playerEntityUid, _table) || StunnedOrNoHands(playerEntityUid)) + if (!CanSeeTable(playerEntity, _table) || StunnedOrNoHands(playerEntity)) { return false; } @@ -204,7 +206,7 @@ namespace Content.Client.Tabletop return true; } - private bool OnMouseUp(in PointerInputCmdHandler.PointerInputCmdArgs args) + private bool OnMouseUp(in PointerInputCmdArgs args) { StopDragging(); return false; diff --git a/Content.Client/Tabletop/Visualizers/TabletopItemVisualizer.cs b/Content.Client/Tabletop/Visualizers/TabletopItemVisualizer.cs index 1febac6a49..972a24a650 100644 --- a/Content.Client/Tabletop/Visualizers/TabletopItemVisualizer.cs +++ b/Content.Client/Tabletop/Visualizers/TabletopItemVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Tabletop; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Tabletop.Visualizers @@ -11,7 +12,8 @@ namespace Content.Client.Tabletop.Visualizers { public override void OnChangeData(AppearanceComponent appearance) { - if (!appearance.Owner.TryGetComponent(out var sprite)) + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(appearance.Owner, out var sprite)) { return; } diff --git a/Content.Client/Toilet/ToiletVisualizer.cs b/Content.Client/Toilet/ToiletVisualizer.cs index e714b0cbcf..e9096e6c5d 100644 --- a/Content.Client/Toilet/ToiletVisualizer.cs +++ b/Content.Client/Toilet/ToiletVisualizer.cs @@ -1,6 +1,7 @@ using Content.Shared.Toilet; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Toilet { @@ -10,14 +11,13 @@ namespace Content.Client.Toilet { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) return; if (!component.TryGetData(ToiletVisuals.LidOpen, out bool lidOpen)) lidOpen = false; if (!component.TryGetData(ToiletVisuals.SeatUp, out bool seatUp)) seatUp = false; - var state = string.Format("{0}_toilet_{1}", - lidOpen ? "open" : "closed", - seatUp ? "seat_up" : "seat_down"); + var state = $"{(lidOpen ? "open" : "closed")}_toilet_{(seatUp ? "seat_up" : "seat_down")}"; sprite.LayerSetState(0, state); } diff --git a/Content.Client/Trigger/TimerTriggerVisualizer.cs b/Content.Client/Trigger/TimerTriggerVisualizer.cs index 24051d99dc..b3406411e4 100644 --- a/Content.Client/Trigger/TimerTriggerVisualizer.cs +++ b/Content.Client/Trigger/TimerTriggerVisualizer.cs @@ -5,6 +5,7 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -35,18 +36,16 @@ namespace Content.Client.Trigger } } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { - if (!entity.HasComponent()) - { - entity.AddComponent(); - } + IoCManager.Resolve().EnsureComponent(entity); } public override void OnChangeData(AppearanceComponent component) { - var sprite = component.Owner.GetComponent(); - var animPlayer = component.Owner.GetComponent(); + var entMan = IoCManager.Resolve(); + var sprite = entMan.GetComponent(component.Owner); + var animPlayer = entMan.GetComponent(component.Owner); if (!component.TryGetData(TriggerVisuals.VisualState, out TriggerVisualState state)) { state = TriggerVisualState.Unprimed; diff --git a/Content.Client/VendingMachines/UI/VendingMachineVisualizer.cs b/Content.Client/VendingMachines/UI/VendingMachineVisualizer.cs index 54c5906c86..70167300b4 100644 --- a/Content.Client/VendingMachines/UI/VendingMachineVisualizer.cs +++ b/Content.Client/VendingMachines/UI/VendingMachineVisualizer.cs @@ -4,6 +4,7 @@ using JetBrains.Annotations; using Robust.Client.Animations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using static Content.Shared.VendingMachines.SharedVendingMachineComponent; @@ -116,14 +117,11 @@ namespace Content.Client.VendingMachines.UI flick.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame(key, 0f)); } - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - if (!entity.HasComponent()) - { - entity.AddComponent(); - } + IoCManager.Resolve().EnsureComponent(entity); } private void HideLayers(ISpriteComponent spriteComponent) @@ -140,8 +138,9 @@ namespace Content.Client.VendingMachines.UI { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); - var animPlayer = component.Owner.GetComponent(); + var entMan = IoCManager.Resolve(); + var sprite = entMan.GetComponent(component.Owner); + var animPlayer = entMan.GetComponent(component.Owner); if (!component.TryGetData(VendingMachineVisuals.VisualState, out VendingMachineVisualState state)) { state = VendingMachineVisualState.Normal; diff --git a/Content.Client/VendingMachines/VendingMachineBoundUserInterface.cs b/Content.Client/VendingMachines/VendingMachineBoundUserInterface.cs index c2119c39f9..1e91abd42f 100644 --- a/Content.Client/VendingMachines/VendingMachineBoundUserInterface.cs +++ b/Content.Client/VendingMachines/VendingMachineBoundUserInterface.cs @@ -2,6 +2,7 @@ using Content.Shared.VendingMachines; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; using static Content.Shared.VendingMachines.SharedVendingMachineComponent; @@ -22,14 +23,15 @@ namespace Content.Client.VendingMachines { base.Open(); - if (!Owner.Owner.TryGetComponent(out SharedVendingMachineComponent? vendingMachine)) + var entMan = IoCManager.Resolve(); + if (!entMan.TryGetComponent(Owner.Owner, out SharedVendingMachineComponent? vendingMachine)) { return; } VendingMachine = vendingMachine; - _menu = new VendingMachineMenu(this) {Title = Owner.Owner.Name}; + _menu = new VendingMachineMenu(this) {Title = entMan.GetComponent(Owner.Owner).EntityName}; _menu.Populate(VendingMachine.Inventory); _menu.OnClose += Close; diff --git a/Content.Client/Verbs/UI/VerbMenuPresenter.cs b/Content.Client/Verbs/UI/VerbMenuPresenter.cs index 20d4ad9965..0f2afc685b 100644 --- a/Content.Client/Verbs/UI/VerbMenuPresenter.cs +++ b/Content.Client/Verbs/UI/VerbMenuPresenter.cs @@ -32,7 +32,7 @@ namespace Content.Client.Verbs.UI public EntityUid CurrentTarget; public Dictionary> CurrentVerbs = new(); - public VerbMenuPresenter(VerbSystem verbSystem) : base() + public VerbMenuPresenter(VerbSystem verbSystem) { IoCManager.InjectDependencies(this); _verbSystem = verbSystem; @@ -41,18 +41,17 @@ namespace Content.Client.Verbs.UI /// /// Open a verb menu and fill it work verbs applicable to the given target entity. /// - public void OpenVerbMenu(IEntity target) + public void OpenVerbMenu(EntityUid target) { - var user = _playerManager.LocalPlayer?.ControlledEntity; - if (user == null) + if (_playerManager.LocalPlayer?.ControlledEntity is not {Valid: true} user) return; Close(); - CurrentTarget = target.Uid; + CurrentTarget = target; CurrentVerbs = _verbSystem.GetVerbs(target, user, VerbType.All); - - if (!target.Uid.IsClientSide()) + + if (!target.IsClientSide()) { AddElement(RootMenu, new ContextMenuElement(Loc.GetString("verb-system-waiting-on-server-text"))); } diff --git a/Content.Client/Verbs/VerbSystem.cs b/Content.Client/Verbs/VerbSystem.cs index ba948a62fc..51f1a03d75 100644 --- a/Content.Client/Verbs/VerbSystem.cs +++ b/Content.Client/Verbs/VerbSystem.cs @@ -20,8 +20,6 @@ using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; -using Robust.Shared.Maths; -using static Content.Shared.Interaction.SharedInteractionSystem; namespace Content.Client.Verbs { @@ -87,7 +85,7 @@ namespace Content.Client.Verbs /// /// Get all of the entities in an area for displaying on the context menu. /// - public bool TryGetEntityMenuEntities(MapCoordinates targetPos, [NotNullWhen(true)] out List? result) + public bool TryGetEntityMenuEntities(MapCoordinates targetPos, [NotNullWhen(true)] out List? result) { result = null; @@ -107,11 +105,11 @@ namespace Content.Client.Verbs if ((visibility & MenuVisibility.NoFov) == 0) { var entitiesUnderMouse = gameScreenBase.GetEntitiesUnderPosition(targetPos); - Ignored? predicate = e => e == player || entitiesUnderMouse.Contains(e); - if (!_examineSystem.CanExamine(player, targetPos, predicate)) + bool Predicate(EntityUid e) => e == player || entitiesUnderMouse.Contains(e); + if (!_examineSystem.CanExamine(player.Value, targetPos, Predicate)) return false; } - + // Get entities var entities = _entityLookup.GetEntitiesInRange(targetPos.MapId, targetPos.Position, EntityMenuLookupSize) .ToList(); @@ -130,7 +128,7 @@ namespace Content.Client.Verbs { foreach (var entity in entities.ToList()) { - if (!player.IsInSameOrTransparentContainer(entity)) + if (!player.Value.IsInSameOrTransparentContainer(entity)) entities.Remove(entity); } } @@ -140,7 +138,7 @@ namespace Content.Client.Verbs { foreach (var entity in entities.ToList()) { - if (!EntityManager.TryGetComponent(entity.Uid, out ISpriteComponent? spriteComponent) || + if (!EntityManager.TryGetComponent(entity, out ISpriteComponent? spriteComponent) || !spriteComponent.Visible) { entities.Remove(entity); @@ -155,12 +153,12 @@ namespace Content.Client.Verbs // Remove any entities that do not have LOS if ((visibility & MenuVisibility.NoFov) == 0) { - var playerPos = player.Transform.MapPosition; + var playerPos = EntityManager.GetComponent(player.Value).MapPosition; foreach (var entity in entities.ToList()) { if (!ExamineSystemShared.InRangeUnOccluded( playerPos, - entity.Transform.MapPosition, + EntityManager.GetComponent(entity).MapPosition, ExamineSystemShared.ExamineRange, null)) { @@ -180,13 +178,13 @@ namespace Content.Client.Verbs /// Ask the server to send back a list of server-side verbs, and for now return an incomplete list of verbs /// (only those defined locally). /// - public Dictionary> GetVerbs(IEntity target, IEntity user, VerbType verbTypes) + public Dictionary> GetVerbs(EntityUid target, EntityUid user, VerbType verbTypes) { - if (!target.Uid.IsClientSide()) + if (!target.IsClientSide()) { - RaiseNetworkEvent(new RequestServerVerbsEvent(target.Uid, verbTypes)); + RaiseNetworkEvent(new RequestServerVerbsEvent(target, verbTypes)); } - + return GetLocalVerbs(target, user, verbTypes); } @@ -206,7 +204,7 @@ namespace Content.Client.Verbs return; } - var user = _playerManager.LocalPlayer?.ControlledEntityUid; + var user = _playerManager.LocalPlayer?.ControlledEntity; if (user == null) return; diff --git a/Content.Client/Viewport/GameScreenBase.cs b/Content.Client/Viewport/GameScreenBase.cs index fecfe4b493..fffcbed06c 100644 --- a/Content.Client/Viewport/GameScreenBase.cs +++ b/Content.Client/Viewport/GameScreenBase.cs @@ -6,7 +6,6 @@ using Content.Client.ContextMenu.UI; using Content.Client.Interactable; using Content.Client.Interactable.Components; using Content.Client.State; -using Content.Shared; using Content.Shared.CCVar; using Robust.Client.GameObjects; using Robust.Client.Graphics; @@ -44,7 +43,7 @@ namespace Content.Client.Viewport private IEventBus _eventBus => _entityManager.EventBus; - private IEntity? _lastHoveredEntity; + private EntityUid _lastHoveredEntity; private bool _outlineEnabled = true; @@ -84,7 +83,7 @@ namespace Content.Client.Viewport // lead to extremely thick outlines in the other viewports. Fixing this probably requires changing how the // hover outline works, so that it only highlights the entity in a single viewport. - IEntity? entityToClick = null; + EntityUid entityToClick = default; var renderScale = 1; if (UserInterfaceManager.CurrentlyHovered is IViewportControl vp) { @@ -107,7 +106,7 @@ namespace Content.Client.Viewport } var inRange = false; - if (localPlayer.ControlledEntity != null && entityToClick != null) + if (localPlayer.ControlledEntity != default && entityToClick != default) { inRange = localPlayer.InRangeUnobstructed(entityToClick, ignoreInsideBlocker: true); } @@ -115,7 +114,7 @@ namespace Content.Client.Viewport InteractionOutlineComponent? outline; if(!_outlineEnabled || !ConfigurationManager.GetCVar(CCVars.OutlineEnabled)) { - if(entityToClick != null && entityToClick.TryGetComponent(out outline)) + if(entityToClick != default && _entityManager.TryGetComponent(entityToClick, out outline)) { outline.OnMouseLeave(); //Prevent outline remains from persisting post command. } @@ -124,7 +123,7 @@ namespace Content.Client.Viewport if (entityToClick == _lastHoveredEntity) { - if (entityToClick != null && entityToClick.TryGetComponent(out outline)) + if (entityToClick != default && _entityManager.TryGetComponent(entityToClick, out outline)) { outline.UpdateInRange(inRange, renderScale); } @@ -132,42 +131,42 @@ namespace Content.Client.Viewport return; } - if (_lastHoveredEntity != null && !_lastHoveredEntity.Deleted && - _lastHoveredEntity.TryGetComponent(out outline)) + if (_lastHoveredEntity != default && !_entityManager.Deleted(_lastHoveredEntity) && + _entityManager.TryGetComponent(_lastHoveredEntity, out outline)) { outline.OnMouseLeave(); } _lastHoveredEntity = entityToClick; - if (_lastHoveredEntity != null && _lastHoveredEntity.TryGetComponent(out outline)) + if (_lastHoveredEntity != default && _entityManager.TryGetComponent(_lastHoveredEntity, out outline)) { outline.OnMouseEnter(inRange, renderScale); } } - public IEntity? GetEntityUnderPosition(MapCoordinates coordinates) + public EntityUid GetEntityUnderPosition(MapCoordinates coordinates) { var entitiesUnderPosition = GetEntitiesUnderPosition(coordinates); - return entitiesUnderPosition.Count > 0 ? entitiesUnderPosition[0] : null; + return entitiesUnderPosition.Count > 0 ? entitiesUnderPosition[0] : default; } - public IList GetEntitiesUnderPosition(EntityCoordinates coordinates) + public IList GetEntitiesUnderPosition(EntityCoordinates coordinates) { return GetEntitiesUnderPosition(coordinates.ToMap(EntityManager)); } - public IList GetEntitiesUnderPosition(MapCoordinates coordinates) + public IList GetEntitiesUnderPosition(MapCoordinates coordinates) { // Find all the entities intersecting our click var entities = IoCManager.Resolve().GetEntitiesIntersecting(coordinates.MapId, Box2.CenteredAround(coordinates.Position, (1, 1))); // Check the entities against whether or not we can click them - var foundEntities = new List<(IEntity clicked, int drawDepth, uint renderOrder)>(); + var foundEntities = new List<(EntityUid clicked, int drawDepth, uint renderOrder)>(); foreach (var entity in entities) { - if (entity.TryGetComponent(out var component) + if (_entityManager.TryGetComponent(entity, out var component) && !entity.IsInContainer() && component.CheckClick(coordinates.Position, out var drawDepthClicked, out var renderOrder)) { @@ -176,9 +175,9 @@ namespace Content.Client.Viewport } if (foundEntities.Count == 0) - return new List(); + return new List(); - foundEntities.Sort(new ClickableEntityComparer()); + foundEntities.Sort(new ClickableEntityComparer(_entityManager)); // 0 is the top element. foundEntities.Reverse(); return foundEntities.Select(a => a.clicked).ToList(); @@ -193,20 +192,27 @@ namespace Content.Client.Viewport /// state manager to use to get the current game screen /// coordinates to check /// the entities under the position, empty list if none found - public static IList GetEntitiesUnderPosition(IStateManager stateManager, EntityCoordinates coordinates) + public static IList GetEntitiesUnderPosition(IStateManager stateManager, EntityCoordinates coordinates) { if (stateManager.CurrentState is GameScreenBase gameScreenBase) { return gameScreenBase.GetEntitiesUnderPosition(coordinates); } - return ImmutableList.Empty; + return ImmutableList.Empty; } - internal class ClickableEntityComparer : IComparer<(IEntity clicked, int depth, uint renderOrder)> + internal class ClickableEntityComparer : IComparer<(EntityUid clicked, int depth, uint renderOrder)> { - public int Compare((IEntity clicked, int depth, uint renderOrder) x, - (IEntity clicked, int depth, uint renderOrder) y) + private readonly IEntityManager _entities; + + public ClickableEntityComparer(IEntityManager entities) + { + _entities = entities; + } + + public int Compare((EntityUid clicked, int depth, uint renderOrder) x, + (EntityUid clicked, int depth, uint renderOrder) y) { var val = x.depth.CompareTo(y.depth); if (val != 0) @@ -223,15 +229,15 @@ namespace Content.Client.Viewport } */ - var transX = x.clicked.Transform; - var transY = y.clicked.Transform; + var transX = _entities.GetComponent(x.clicked); + var transY = _entities.GetComponent(y.clicked); val = transX.Coordinates.Y.CompareTo(transY.Coordinates.Y); if (val != 0) { return val; } - return x.clicked.Uid.CompareTo(y.clicked.Uid); + return x.clicked.CompareTo(y.clicked); } } @@ -254,7 +260,7 @@ namespace Content.Client.Viewport if (args.Viewport is IViewportControl vp) { var mousePosWorld = vp.ScreenToMap(kArgs.PointerLocation.Position); - entityToClick = GetEntityUnderPosition(mousePosWorld)?.Uid ?? EntityUid.Invalid; + entityToClick = GetEntityUnderPosition(mousePosWorld); coordinates = MapManager.TryFindGridAt(mousePosWorld, out var grid) ? grid.MapToGrid(mousePosWorld) : EntityCoordinates.FromMap(MapManager, mousePosWorld); diff --git a/Content.Client/Visualizer/GenericEnumVisualizer.cs b/Content.Client/Visualizer/GenericEnumVisualizer.cs index 06df062ea8..29181d71da 100644 --- a/Content.Client/Visualizer/GenericEnumVisualizer.cs +++ b/Content.Client/Visualizer/GenericEnumVisualizer.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; @@ -55,7 +55,8 @@ namespace Content.Client.Visualizer { base.OnChangeData(component); - if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(component.Owner, out ISpriteComponent? sprite)) return; if (!component.TryGetData(Key, out object status)) return; if (!States.TryGetValue(status, out var val)) return; sprite.LayerSetState(Layer, val); diff --git a/Content.Client/Wall/Components/LowWallComponent.cs b/Content.Client/Wall/Components/LowWallComponent.cs index 93a009cf12..8c92261847 100644 --- a/Content.Client/Wall/Components/LowWallComponent.cs +++ b/Content.Client/Wall/Components/LowWallComponent.cs @@ -26,6 +26,7 @@ namespace Content.Client.Wall.Components { public override string Name => "LowWall"; + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IMapManager _mapManager = default!; public CornerFill LastCornerNE { get; private set; } @@ -33,7 +34,7 @@ namespace Content.Client.Wall.Components public CornerFill LastCornerSW { get; private set; } public CornerFill LastCornerNW { get; private set; } - [ViewVariables] private IEntity? _overlayEntity; + [ViewVariables] private EntityUid _overlayEntity; [ViewVariables] private ISpriteComponent? _overlaySprite; @@ -42,11 +43,11 @@ namespace Content.Client.Wall.Components { base.Startup(); - _overlayEntity = Owner.EntityManager.SpawnEntity("LowWallOverlay", Owner.Transform.Coordinates); - _overlayEntity.Transform.AttachParent(Owner); - _overlayEntity.Transform.LocalPosition = Vector2.Zero; + _overlayEntity = _entMan.SpawnEntity("LowWallOverlay", _entMan.GetComponent(Owner).Coordinates); + _entMan.GetComponent(_overlayEntity).AttachParent(Owner); + _entMan.GetComponent(_overlayEntity).LocalPosition = Vector2.Zero; - _overlaySprite = _overlayEntity.GetComponent(); + _overlaySprite = _entMan.GetComponent(_overlayEntity); var overState0 = $"{StateBase}over_0"; _overlaySprite.LayerMapSet(OverCornerLayers.SE, _overlaySprite.AddLayerState(overState0)); @@ -63,20 +64,24 @@ namespace Content.Client.Wall.Components { base.Shutdown(); - _overlayEntity?.Delete(); + EntityUid tempQualifier = _overlayEntity; + if (tempQualifier != null) + { + _entMan.DeleteEntity(tempQualifier); + } } internal override void CalculateNewSprite() { base.CalculateNewSprite(); - if (Sprite == null || !Owner.Transform.Anchored || _overlaySprite == null) + if (Sprite == null || !_entMan.GetComponent(Owner).Anchored || _overlaySprite == null) { return; } - var grid = _mapManager.GetGrid(Owner.Transform.GridID); - var coords = Owner.Transform.Coordinates; + var grid = _mapManager.GetGrid(_entMan.GetComponent(Owner).GridID); + var coords = _entMan.GetComponent(Owner).Coordinates; var (n, nl) = MatchingWall(grid.GetInDir(coords, Direction.North)); var (ne, nel) = MatchingWall(grid.GetInDir(coords, Direction.NorthEast)); @@ -204,7 +209,7 @@ namespace Content.Client.Wall.Components foreach (var entity in grid.GetLocal(coords)) { - if (Owner.EntityManager.TryGetComponent(entity, out WindowComponent? window)) + if (_entMan.TryGetComponent(entity, out WindowComponent? window)) { //window.UpdateSprite(); } @@ -216,7 +221,7 @@ namespace Content.Client.Wall.Components { foreach (var entity in candidates) { - if (!Owner.EntityManager.TryGetComponent(entity, out IconSmoothComponent? other)) + if (!_entMan.TryGetComponent(entity, out IconSmoothComponent? other)) { continue; } diff --git a/Content.Client/Wall/ReinforcedWallVisualizer.cs b/Content.Client/Wall/ReinforcedWallVisualizer.cs index ca23401cf4..11810c3889 100644 --- a/Content.Client/Wall/ReinforcedWallVisualizer.cs +++ b/Content.Client/Wall/ReinforcedWallVisualizer.cs @@ -2,6 +2,7 @@ using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Wall { @@ -22,7 +23,8 @@ namespace Content.Client.Wall { var entity = component.Owner; - if (!entity.TryGetComponent(out ISpriteComponent? sprite)) return; + var entities = IoCManager.Resolve(); + if (!entities.TryGetComponent(entity, out ISpriteComponent? sprite)) return; if (stage < 0) { diff --git a/Content.Client/Weapons/Melee/Components/MeleeLungeComponent.cs b/Content.Client/Weapons/Melee/Components/MeleeLungeComponent.cs index cc61d19c3b..d9e91e894b 100644 --- a/Content.Client/Weapons/Melee/Components/MeleeLungeComponent.cs +++ b/Content.Client/Weapons/Melee/Components/MeleeLungeComponent.cs @@ -1,5 +1,6 @@ using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Weapons.Melee.Components @@ -38,14 +39,16 @@ namespace Content.Client.Weapons.Melee.Components offset *= (ResetTime - _time) / ResetTime; } - if (Owner.TryGetComponent(out ISpriteComponent? spriteComponent)) + var entMan = IoCManager.Resolve(); + + if (entMan.TryGetComponent(Owner, out ISpriteComponent? spriteComponent)) { spriteComponent.Offset = offset; } if (deleteSelf) { - Owner.RemoveComponent(); + entMan.RemoveComponent(Owner); } } } diff --git a/Content.Client/Weapons/Melee/Components/MeleeWeaponArcAnimationComponent.cs b/Content.Client/Weapons/Melee/Components/MeleeWeaponArcAnimationComponent.cs index 9f5863458f..1860c0b1a0 100644 --- a/Content.Client/Weapons/Melee/Components/MeleeWeaponArcAnimationComponent.cs +++ b/Content.Client/Weapons/Melee/Components/MeleeWeaponArcAnimationComponent.cs @@ -2,6 +2,7 @@ using Content.Shared.Weapons.Melee; using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.Weapons.Melee.Components @@ -9,6 +10,8 @@ namespace Content.Client.Weapons.Melee.Components [RegisterComponent] public sealed class MeleeWeaponArcAnimationComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "MeleeWeaponArcAnimation"; private MeleeWeaponAnimationPrototype? _meleeWeaponAnimation; @@ -21,16 +24,16 @@ namespace Content.Client.Weapons.Melee.Components { base.Initialize(); - _sprite = Owner.GetComponent(); + _sprite = _entMan.GetComponent(Owner); } - public void SetData(MeleeWeaponAnimationPrototype prototype, Angle baseAngle, IEntity attacker, bool followAttacker = true) + public void SetData(MeleeWeaponAnimationPrototype prototype, Angle baseAngle, EntityUid attacker, bool followAttacker = true) { _meleeWeaponAnimation = prototype; _sprite?.AddLayer(new RSI.StateId(prototype.State)); _baseAngle = baseAngle; if(followAttacker) - Owner.Transform.AttachParent(attacker); + _entMan.GetComponent(Owner).AttachParent(attacker); } internal void Update(float frameTime) @@ -50,16 +53,17 @@ namespace Content.Client.Weapons.Melee.Components _sprite.Color = new Color(r, g, b, a); } + var transform = _entMan.GetComponent(Owner); + switch (_meleeWeaponAnimation.ArcType) { case WeaponArcType.Slash: var angle = Angle.FromDegrees(_meleeWeaponAnimation.Width)/2; - Owner.Transform.WorldRotation = - _baseAngle + Angle.Lerp(-angle, angle, (float) (_timer / _meleeWeaponAnimation.Length.TotalSeconds)); + transform.WorldRotation = _baseAngle + Angle.Lerp(-angle, angle, (float) (_timer / _meleeWeaponAnimation.Length.TotalSeconds)); break; case WeaponArcType.Poke: - Owner.Transform.WorldRotation = _baseAngle; + transform.WorldRotation = _baseAngle; if (_sprite != null) { @@ -71,7 +75,7 @@ namespace Content.Client.Weapons.Melee.Components if (_meleeWeaponAnimation.Length.TotalSeconds <= _timer) { - Owner.Delete(); + _entMan.DeleteEntity(Owner); } } } diff --git a/Content.Client/Weapons/Melee/MeleeWeaponSystem.cs b/Content.Client/Weapons/Melee/MeleeWeaponSystem.cs index 3924e12bd6..c697b87926 100644 --- a/Content.Client/Weapons/Melee/MeleeWeaponSystem.cs +++ b/Content.Client/Weapons/Melee/MeleeWeaponSystem.cs @@ -44,28 +44,29 @@ namespace Content.Client.Weapons.Melee return; } - if (!EntityManager.TryGetEntity(msg.Attacker, out var attacker)) + var attacker = msg.Attacker; + if (!EntityManager.EntityExists(msg.Attacker)) { // FIXME: This should never happen. Logger.Error($"Tried to play a weapon arc {msg.ArcPrototype}, but the attacker does not exist. attacker={msg.Attacker}, source={msg.Source}"); return; } - if (!attacker.Deleted) + if (!Deleted(attacker)) { var lunge = attacker.EnsureComponent(); lunge.SetData(msg.Angle); - var entity = EntityManager.SpawnEntity(weaponArc.Prototype, attacker.Transform.Coordinates); - entity.Transform.LocalRotation = msg.Angle; + var entity = EntityManager.SpawnEntity(weaponArc.Prototype, EntityManager.GetComponent(attacker).Coordinates); + EntityManager.GetComponent(entity).LocalRotation = msg.Angle; - var weaponArcAnimation = entity.GetComponent(); + var weaponArcAnimation = EntityManager.GetComponent(entity); weaponArcAnimation.SetData(weaponArc, msg.Angle, attacker, msg.ArcFollowAttacker); // Due to ISpriteComponent limitations, weapons that don't use an RSI won't have this effect. - if (EntityManager.TryGetEntity(msg.Source, out var source) && + if (EntityManager.EntityExists(msg.Source) && msg.TextureEffect && - source.TryGetComponent(out ISpriteComponent? sourceSprite) && + EntityManager.TryGetComponent(msg.Source, out ISpriteComponent? sourceSprite) && sourceSprite.BaseRSI?.Path != null) { var curTime = _gameTiming.CurTime; @@ -73,7 +74,7 @@ namespace Content.Client.Weapons.Melee { EffectSprite = sourceSprite.BaseRSI.Path.ToString(), RsiState = sourceSprite.LayerGetState(0).Name, - Coordinates = attacker.Transform.Coordinates, + Coordinates = EntityManager.GetComponent(attacker).Coordinates, Color = Vector4.Multiply(new Vector4(255, 255, 255, 125), 1.0f), ColorDelta = Vector4.Multiply(new Vector4(0, 0, 0, -10), 1.0f), Velocity = msg.Angle.ToWorldVec(), @@ -86,14 +87,14 @@ namespace Content.Client.Weapons.Melee } } - foreach (var uid in msg.Hits) + foreach (var hit in msg.Hits) { - if (!EntityManager.TryGetEntity(uid, out var hitEntity) || hitEntity.Deleted) + if (!EntityManager.EntityExists(hit)) { continue; } - if (!hitEntity.TryGetComponent(out ISpriteComponent? sprite)) + if (!EntityManager.TryGetComponent(hit, out ISpriteComponent? sprite)) { continue; } @@ -102,7 +103,7 @@ namespace Content.Client.Weapons.Melee var newColor = Color.Red * originalColor; sprite.Color = newColor; - hitEntity.SpawnTimer(100, () => + hit.SpawnTimer(100, () => { // Only reset back to the original color if something else didn't change the color in the mean time. if (sprite.Color == newColor) @@ -115,9 +116,9 @@ namespace Content.Client.Weapons.Melee private void PlayLunge(PlayLungeAnimationMessage msg) { - if (EntityManager.TryGetEntity(msg.Source, out var entity)) + if (EntityManager.EntityExists(msg.Source)) { - entity.EnsureComponent().SetData(msg.Angle); + msg.Source.EnsureComponent().SetData(msg.Angle); } else { diff --git a/Content.Client/Weapons/Ranged/Barrels/Components/ClientBatteryBarrelComponent.cs b/Content.Client/Weapons/Ranged/Barrels/Components/ClientBatteryBarrelComponent.cs index 70e2e5c4c2..4ef5813498 100644 --- a/Content.Client/Weapons/Ranged/Barrels/Components/ClientBatteryBarrelComponent.cs +++ b/Content.Client/Weapons/Ranged/Barrels/Components/ClientBatteryBarrelComponent.cs @@ -38,13 +38,13 @@ namespace Content.Client.Weapons.Ranged.Barrels.Components protected override void Initialize() { base.Initialize(); - EntitySystem.Get().AddItemSlot(OwnerUid, $"{Name}-powercell-container", CellSlot); + EntitySystem.Get().AddItemSlot(Owner, $"{Name}-powercell-container", CellSlot); } protected override void OnRemove() { base.OnRemove(); - EntitySystem.Get().RemoveItemSlot(OwnerUid, CellSlot); + EntitySystem.Get().RemoveItemSlot(Owner, CellSlot); } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) diff --git a/Content.Client/Weapons/Ranged/Barrels/Visualizers/BarrelBoltVisualizer.cs b/Content.Client/Weapons/Ranged/Barrels/Visualizers/BarrelBoltVisualizer.cs index f29a8e4a9d..cce9bbdac8 100644 --- a/Content.Client/Weapons/Ranged/Barrels/Visualizers/BarrelBoltVisualizer.cs +++ b/Content.Client/Weapons/Ranged/Barrels/Visualizers/BarrelBoltVisualizer.cs @@ -2,23 +2,24 @@ using Content.Shared.Weapons.Ranged.Barrels.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Weapons.Ranged.Barrels.Visualizers { [UsedImplicitly] public sealed class BarrelBoltVisualizer : AppearanceVisualizer { - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); sprite.LayerSetState(RangedBarrelVisualLayers.Bolt, "bolt-open"); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (!component.TryGetData(BarrelBoltVisuals.BoltOpen, out bool boltOpen)) { diff --git a/Content.Client/Weapons/Ranged/Barrels/Visualizers/MagVisualizer.cs b/Content.Client/Weapons/Ranged/Barrels/Visualizers/MagVisualizer.cs index 89d1180306..948c1aeff3 100644 --- a/Content.Client/Weapons/Ranged/Barrels/Visualizers/MagVisualizer.cs +++ b/Content.Client/Weapons/Ranged/Barrels/Visualizers/MagVisualizer.cs @@ -3,6 +3,7 @@ using Content.Shared.Weapons.Ranged.Barrels.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Client.Weapons.Ranged.Barrels.Visualizers @@ -18,10 +19,10 @@ namespace Content.Client.Weapons.Ranged.Barrels.Visualizers [DataField("zeroVisible")] private bool _zeroVisible; - public override void InitializeEntity(IEntity entity) + public override void InitializeEntity(EntityUid entity) { base.InitializeEntity(entity); - var sprite = entity.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(entity); if (sprite.LayerMapTryGet(RangedBarrelVisualLayers.Mag, out _)) { @@ -44,7 +45,7 @@ namespace Content.Client.Weapons.Ranged.Barrels.Visualizers // 1.If no mag then hide it OR // 2. If step 0 isn't visible then hide it (mag or unshaded) // 3. Otherwise just do mag / unshaded as is - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); component.TryGetData(MagazineBarrelVisuals.MagLoaded, out _magLoaded); diff --git a/Content.Client/Weapons/Ranged/Barrels/Visualizers/SpentAmmoVisualizer.cs b/Content.Client/Weapons/Ranged/Barrels/Visualizers/SpentAmmoVisualizer.cs index e4beb23ea2..10602a6644 100644 --- a/Content.Client/Weapons/Ranged/Barrels/Visualizers/SpentAmmoVisualizer.cs +++ b/Content.Client/Weapons/Ranged/Barrels/Visualizers/SpentAmmoVisualizer.cs @@ -2,6 +2,7 @@ using Content.Shared.Weapons.Ranged.Barrels.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Client.Weapons.Ranged.Barrels.Visualizers { @@ -11,7 +12,7 @@ namespace Content.Client.Weapons.Ranged.Barrels.Visualizers public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (!component.TryGetData(AmmoVisuals.Spent, out bool spent)) { diff --git a/Content.Client/Weapons/Ranged/RangedWeaponSystem.cs b/Content.Client/Weapons/Ranged/RangedWeaponSystem.cs index 38ffb63802..542ccadaae 100644 --- a/Content.Client/Weapons/Ranged/RangedWeaponSystem.cs +++ b/Content.Client/Weapons/Ranged/RangedWeaponSystem.cs @@ -1,6 +1,5 @@ using System; using Content.Client.CombatMode; -using Content.Client.Hands; using Content.Shared.Hands.Components; using Content.Shared.Weapons.Ranged.Components; using JetBrains.Annotations; @@ -48,12 +47,12 @@ namespace Content.Client.Weapons.Ranged } var entity = _playerManager.LocalPlayer?.ControlledEntity; - if (entity == null || !entity.TryGetComponent(out SharedHandsComponent? hands)) + if (!EntityManager.TryGetComponent(entity, out SharedHandsComponent? hands)) { return; } - if (!hands.TryGetActiveHeldEntity(out var held) || !held.TryGetComponent(out ClientRangedWeaponComponent? weapon)) + if (!hands.TryGetActiveHeldEntity(out var held) || !EntityManager.TryGetComponent(held, out ClientRangedWeaponComponent? weapon)) { _blocked = true; return; diff --git a/Content.Client/Wires/Visualizers/WiresVisualizer.cs b/Content.Client/Wires/Visualizers/WiresVisualizer.cs index 713329abfb..52504a905f 100644 --- a/Content.Client/Wires/Visualizers/WiresVisualizer.cs +++ b/Content.Client/Wires/Visualizers/WiresVisualizer.cs @@ -1,5 +1,6 @@ using Robust.Client.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using static Content.Shared.Wires.SharedWiresComponent; namespace Content.Client.Wires.Visualizers @@ -9,7 +10,7 @@ namespace Content.Client.Wires.Visualizers public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); - var sprite = component.Owner.GetComponent(); + var sprite = IoCManager.Resolve().GetComponent(component.Owner); if (component.TryGetData(WiresVisuals.MaintenancePanelState, out var state)) { sprite.LayerSetVisible(WiresVisualLayers.MaintenancePanel, state); diff --git a/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs b/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs index bb9aef7ecf..e78d501560 100644 --- a/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs +++ b/Content.IntegrationTests/Tests/Administration/Logs/AddTests.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using Content.Server.Administration.Logs; using Content.Server.Database; using Content.Server.GameTicking; -using Content.Shared.Administration.Logs; using Content.Shared.CCVar; using Content.Shared.Database; using NUnit.Framework; @@ -161,7 +160,7 @@ public class AddTests : ContentIntegrationTest await server.WaitPost(() => { var coordinates = GetMainEntityCoordinates(sMaps); - var entity = sEntities.SpawnEntity(null, coordinates).Uid; + var entity = sEntities.SpawnEntity(null, coordinates); if (parallel) { diff --git a/Content.IntegrationTests/Tests/Body/LegTest.cs b/Content.IntegrationTests/Tests/Body/LegTest.cs index 1c4dd56790..b2b484315d 100644 --- a/Content.IntegrationTests/Tests/Body/LegTest.cs +++ b/Content.IntegrationTests/Tests/Body/LegTest.cs @@ -48,8 +48,8 @@ namespace Content.IntegrationTests.Tests.Body var entityManager = IoCManager.Resolve(); var human = entityManager.SpawnEntity("HumanBodyAndAppearanceDummy", new MapCoordinates(Vector2.Zero, mapId)); - Assert.That(human.TryGetComponent(out SharedBodyComponent body)); - Assert.That(human.TryGetComponent(out appearance)); + Assert.That(entityManager.TryGetComponent(human, out SharedBodyComponent body)); + Assert.That(entityManager.TryGetComponent(human, out appearance)); Assert.That(!appearance.TryGetData(RotationVisuals.RotationState, out RotationState _)); diff --git a/Content.IntegrationTests/Tests/Body/LungTest.cs b/Content.IntegrationTests/Tests/Body/LungTest.cs index 4aba535f80..ec1c809f92 100644 --- a/Content.IntegrationTests/Tests/Body/LungTest.cs +++ b/Content.IntegrationTests/Tests/Body/LungTest.cs @@ -66,11 +66,11 @@ namespace Content.IntegrationTests.Tests.Body var bodySys = EntitySystem.Get(); var lungSys = EntitySystem.Get(); - Assert.That(human.TryGetComponent(out SharedBodyComponent body)); + Assert.That(entityManager.TryGetComponent(human, out SharedBodyComponent body)); - var lungs = bodySys.GetComponentsOnMechanisms(human.Uid, body).ToArray(); + var lungs = bodySys.GetComponentsOnMechanisms(human, body).ToArray(); Assert.That(lungs.Count, Is.EqualTo(1)); - Assert.That(human.TryGetComponent(out BloodstreamComponent bloodstream)); + Assert.That(entityManager.TryGetComponent(human, out BloodstreamComponent bloodstream)); var gas = new GasMixture(1); @@ -82,7 +82,7 @@ namespace Content.IntegrationTests.Tests.Body gas.AdjustMoles(Gas.Nitrogen, originalNitrogen); var (lung, _) = lungs[0]; - lungSys.TakeGasFrom(lung.OwnerUid, 1, gas, lung); + lungSys.TakeGasFrom(((IComponent) lung).Owner, 1, gas, lung); var lungOxygen = originalOxygen * breathedPercentage; var lungNitrogen = originalNitrogen * breathedPercentage; @@ -103,7 +103,7 @@ namespace Content.IntegrationTests.Tests.Body Assert.Zero(lungOxygenBeforeExhale); Assert.Zero(lungNitrogenBeforeExhale); - lungSys.PushGasTo(lung.OwnerUid, gas, lung); + lungSys.PushGasTo(((IComponent) lung).Owner, gas, lung); var lungOxygenAfterExhale = lung.Air.GetMoles(Gas.Oxygen); var exhaledOxygen = Math.Abs(lungOxygenBeforeExhale - lungOxygenAfterExhale); @@ -153,7 +153,7 @@ namespace Content.IntegrationTests.Tests.Body MapId mapId; IMapGrid grid = null; RespiratorComponent respirator = null; - IEntity human = null; + EntityUid human = default; var testMapName = "Maps/Test/Breathing/3by3-20oxy-80nit.yml"; @@ -171,8 +171,8 @@ namespace Content.IntegrationTests.Tests.Body var coordinates = new EntityCoordinates(grid.GridEntityId, center); human = entityManager.SpawnEntity("HumanBodyAndBloodstreamDummy", coordinates); - Assert.True(human.HasComponent()); - Assert.True(human.TryGetComponent(out respirator)); + Assert.True(entityManager.HasComponent(human)); + Assert.True(entityManager.TryGetComponent(human, out respirator)); Assert.False(respirator.Suffocating); }); @@ -184,7 +184,7 @@ namespace Content.IntegrationTests.Tests.Body await server.WaitRunTicks(increment); await server.WaitAssertion(() => { - Assert.False(respirator.Suffocating, $"Entity {human.Name} is suffocating on tick {tick}"); + Assert.False(respirator.Suffocating, $"Entity {entityManager.GetComponent(human).EntityName} is suffocating on tick {tick}"); }); } diff --git a/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs b/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs index d978c81965..61326e5be6 100644 --- a/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs +++ b/Content.IntegrationTests/Tests/Buckle/BuckleTest.cs @@ -1,4 +1,3 @@ -using System.Linq; using System.Threading.Tasks; using Content.Server.Buckle.Components; using Content.Server.Hands.Components; @@ -7,10 +6,8 @@ using Content.Shared.ActionBlocker; using Content.Shared.Body.Components; using Content.Shared.Body.Part; using Content.Shared.Buckle.Components; -using Content.Shared.Coordinates; using Content.Shared.Standing; using NUnit.Framework; -using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -58,8 +55,8 @@ namespace Content.IntegrationTests.Tests.Buckle var sOptions = new ServerIntegrationOptions {ExtraPrototypes = Prototypes}; var (_, server) = await StartConnectedServerClientPair(cOptions, sOptions); - IEntity human = null; - IEntity chair = null; + EntityUid human = default; + EntityUid chair = default; BuckleComponent buckle = null; StrapComponent strap = null; @@ -72,23 +69,23 @@ namespace Content.IntegrationTests.Tests.Buckle var standingState = EntitySystem.Get(); var grid = GetMainGrid(mapManager); - var coordinates = grid.GridEntityId.ToCoordinates(); + var coordinates = new EntityCoordinates(grid.GridEntityId, 0, 0); human = entityManager.SpawnEntity(BuckleDummyId, coordinates); chair = entityManager.SpawnEntity(StrapDummyId, coordinates); // Default state, unbuckled - Assert.True(human.TryGetComponent(out buckle)); + Assert.True(entityManager.TryGetComponent(human, out buckle)); Assert.NotNull(buckle); Assert.Null(buckle.BuckledTo); Assert.False(buckle.Buckled); - Assert.True(actionBlocker.CanMove(human.Uid)); - Assert.True(actionBlocker.CanChangeDirection(human.Uid)); - Assert.True(standingState.Down(human.Uid)); - Assert.True(standingState.Stand(human.Uid)); + Assert.True(actionBlocker.CanMove(human)); + Assert.True(actionBlocker.CanChangeDirection(human)); + Assert.True(standingState.Down(human)); + Assert.True(standingState.Stand(human)); // Default state, no buckled entities, strap - Assert.True(chair.TryGetComponent(out strap)); + Assert.True(entityManager.TryGetComponent(chair, out strap)); Assert.NotNull(strap); Assert.IsEmpty(strap.BuckledEntities); Assert.Zero(strap.OccupiedSize); @@ -98,12 +95,11 @@ namespace Content.IntegrationTests.Tests.Buckle Assert.NotNull(buckle.BuckledTo); Assert.True(buckle.Buckled); - var player = IoCManager.Resolve().Sessions.Single(); Assert.True(((BuckleComponentState) buckle.GetComponentState()).Buckled); - Assert.False(actionBlocker.CanMove(human.Uid)); - Assert.False(actionBlocker.CanChangeDirection(human.Uid)); - Assert.False(standingState.Down(human.Uid)); - Assert.That((human.Transform.WorldPosition - chair.Transform.WorldPosition).Length, Is.LessThanOrEqualTo(buckle.BuckleOffset.Length)); + Assert.False(actionBlocker.CanMove(human)); + Assert.False(actionBlocker.CanChangeDirection(human)); + Assert.False(standingState.Down(human)); + Assert.That((entityManager.GetComponent(human).WorldPosition - entityManager.GetComponent(chair).WorldPosition).Length, Is.LessThanOrEqualTo(buckle.BuckleOffset.Length)); // Side effects of buckling for the strap Assert.That(strap.BuckledEntities, Does.Contain(human)); @@ -134,9 +130,9 @@ namespace Content.IntegrationTests.Tests.Buckle Assert.True(buckle.TryUnbuckle(human)); Assert.Null(buckle.BuckledTo); Assert.False(buckle.Buckled); - Assert.True(actionBlocker.CanMove(human.Uid)); - Assert.True(actionBlocker.CanChangeDirection(human.Uid)); - Assert.True(standingState.Down(human.Uid)); + Assert.True(actionBlocker.CanMove(human)); + Assert.True(actionBlocker.CanChangeDirection(human)); + Assert.True(standingState.Down(human)); // Unbuckle, strap Assert.IsEmpty(strap.BuckledEntities); @@ -160,6 +156,7 @@ namespace Content.IntegrationTests.Tests.Buckle await server.WaitAssertion(() => { + var entityManager = IoCManager.Resolve(); var actionBlocker = EntitySystem.Get(); var standingState = EntitySystem.Get(); @@ -171,7 +168,7 @@ namespace Content.IntegrationTests.Tests.Buckle Assert.False(buckle.Buckled); // Move away from the chair - human.Transform.WorldPosition += (1000, 1000); + entityManager.GetComponent(human).WorldPosition += (1000, 1000); // Out of range Assert.False(buckle.TryBuckle(human, chair)); @@ -179,7 +176,7 @@ namespace Content.IntegrationTests.Tests.Buckle Assert.False(buckle.ToggleBuckle(human, chair)); // Move near the chair - human.Transform.WorldPosition = chair.Transform.WorldPosition + (0.5f, 0); + entityManager.GetComponent(human).WorldPosition = entityManager.GetComponent(chair).WorldPosition + (0.5f, 0); // In range Assert.True(buckle.TryBuckle(human, chair)); @@ -192,15 +189,15 @@ namespace Content.IntegrationTests.Tests.Buckle // Force unbuckle Assert.True(buckle.TryUnbuckle(human, true)); Assert.False(buckle.Buckled); - Assert.True(actionBlocker.CanMove(human.Uid)); - Assert.True(actionBlocker.CanChangeDirection(human.Uid)); - Assert.True(standingState.Down(human.Uid)); + Assert.True(actionBlocker.CanMove(human)); + Assert.True(actionBlocker.CanChangeDirection(human)); + Assert.True(standingState.Down(human)); // Re-buckle Assert.True(buckle.TryBuckle(human, chair)); // Move away from the chair - human.Transform.WorldPosition += (1, 0); + entityManager.GetComponent(human).WorldPosition += (1, 0); }); await server.WaitRunTicks(1); @@ -220,7 +217,7 @@ namespace Content.IntegrationTests.Tests.Buckle var options = new ServerContentIntegrationOption {ExtraPrototypes = Prototypes}; var server = StartServer(options); - IEntity human = null; + EntityUid human = default; BuckleComponent buckle = null; HandsComponent hands = null; SharedBodyComponent body = null; @@ -233,16 +230,16 @@ namespace Content.IntegrationTests.Tests.Buckle var entityManager = IoCManager.Resolve(); var grid = GetMainGrid(mapManager); - var coordinates = grid.GridEntityId.ToCoordinates(); + var coordinates = new EntityCoordinates(grid.GridEntityId, 0, 0); human = entityManager.SpawnEntity(BuckleDummyId, coordinates); - IEntity chair = entityManager.SpawnEntity(StrapDummyId, coordinates); + var chair = entityManager.SpawnEntity(StrapDummyId, coordinates); // Component sanity check - Assert.True(human.TryGetComponent(out buckle)); - Assert.True(chair.HasComponent()); - Assert.True(human.TryGetComponent(out hands)); - Assert.True(human.TryGetComponent(out body)); + Assert.True(entityManager.TryGetComponent(human, out buckle)); + Assert.True(entityManager.HasComponent(chair)); + Assert.True(entityManager.TryGetComponent(human, out hands)); + Assert.True(entityManager.TryGetComponent(human, out body)); // Buckle Assert.True(buckle.TryBuckle(human, chair)); @@ -255,7 +252,7 @@ namespace Content.IntegrationTests.Tests.Buckle var akms = entityManager.SpawnEntity(ItemDummyId, coordinates); // Equip items - Assert.True(akms.TryGetComponent(out ItemComponent item)); + Assert.True(entityManager.TryGetComponent(akms, out ItemComponent item)); Assert.True(hands.PutInHand(item)); } }); @@ -308,8 +305,8 @@ namespace Content.IntegrationTests.Tests.Buckle }; var server = StartServer(options); - IEntity human = null; - IEntity chair = null; + EntityUid human = default; + EntityUid chair = default; BuckleComponent buckle = null; await server.WaitAssertion(() => @@ -318,14 +315,14 @@ namespace Content.IntegrationTests.Tests.Buckle var entityManager = IoCManager.Resolve(); var grid = GetMainGrid(mapManager); - var coordinates = grid.GridEntityId.ToCoordinates(); + var coordinates = new EntityCoordinates(grid.GridEntityId, 0, 0); human = entityManager.SpawnEntity(BuckleDummyId, coordinates); chair = entityManager.SpawnEntity(StrapDummyId, coordinates); // Component sanity check - Assert.True(human.TryGetComponent(out buckle)); - Assert.True(chair.HasComponent()); + Assert.True(entityManager.TryGetComponent(human, out buckle)); + Assert.True(entityManager.HasComponent(chair)); // Buckle Assert.True(buckle.TryBuckle(human, chair)); @@ -333,7 +330,7 @@ namespace Content.IntegrationTests.Tests.Buckle Assert.True(buckle.Buckled); // Move the buckled entity away - human.Transform.WorldPosition += (100, 0); + entityManager.GetComponent(human).WorldPosition += (100, 0); }); await WaitUntil(server, () => !buckle.Buckled, 10); @@ -342,8 +339,10 @@ namespace Content.IntegrationTests.Tests.Buckle await server.WaitAssertion(() => { + var entityManager = IoCManager.Resolve(); + // Move the now unbuckled entity back onto the chair - human.Transform.WorldPosition -= (100, 0); + entityManager.GetComponent(human).WorldPosition -= (100, 0); // Buckle Assert.True(buckle.TryBuckle(human, chair)); diff --git a/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs b/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs index e53b9f8fc0..12db1b9870 100644 --- a/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs +++ b/Content.IntegrationTests/Tests/Chemistry/TryAllReactionsTest.cs @@ -43,18 +43,18 @@ namespace Content.IntegrationTests.Tests.Chemistry //since i have no clue how to isolate each loop assert-wise im just gonna throw this one in for good measure Console.WriteLine($"Testing {reactionPrototype.ID}"); - IEntity beaker; + EntityUid beaker; Solution component = null; server.Assert(() => { beaker = entityManager.SpawnEntity("TestSolutionContainer", coordinates); Assert.That(EntitySystem.Get() - .TryGetSolution(beaker.Uid, "beaker", out component)); + .TryGetSolution(beaker, "beaker", out component)); foreach (var (id, reactant) in reactionPrototype.Reactants) { Assert.That(EntitySystem.Get() - .TryAddReagent(beaker.Uid, component, id, reactant.Amount, out var quantity)); + .TryAddReagent(beaker, component, id, reactant.Amount, out var quantity)); Assert.That(reactant.Amount, Is.EqualTo(quantity)); } }); @@ -67,7 +67,7 @@ namespace Content.IntegrationTests.Tests.Chemistry //(i'm sorry) var foundProductsMap = reactionPrototype.Products .Concat(reactionPrototype.Reactants.Where(x => x.Value.Catalyst).ToDictionary(x => x.Key, x => x.Value.Amount)) - .ToDictionary(x => x, x => false); + .ToDictionary(x => x, _ => false); foreach (var reagent in component.Contents) { Assert.That(foundProductsMap.TryFirstOrNull(x => x.Key.Key == reagent.ReagentId && x.Key.Value == reagent.Quantity, out var foundProduct)); diff --git a/Content.IntegrationTests/Tests/ClickableTest.cs b/Content.IntegrationTests/Tests/ClickableTest.cs index 4d24722b49..9f98ccc03f 100644 --- a/Content.IntegrationTests/Tests/ClickableTest.cs +++ b/Content.IntegrationTests/Tests/ClickableTest.cs @@ -7,6 +7,7 @@ using NUnit.Framework; using Robust.Server.GameObjects; using Robust.Shared; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -76,12 +77,12 @@ namespace Content.IntegrationTests.Tests await _server.WaitPost(() => { var gridEnt = mapManager.GetAllGrids().First().GridEntityId; - worldPos = serverEntManager.GetEntity(gridEnt).Transform.WorldPosition; + worldPos = serverEntManager.GetComponent(gridEnt).WorldPosition; var ent = serverEntManager.SpawnEntity(prototype, new EntityCoordinates(gridEnt, 0f, 0f)); - ent.Transform.LocalRotation = angle; - ent.GetComponent().Scale = (scale, scale); - entity = ent.Uid; + serverEntManager.GetComponent(ent).LocalRotation = angle; + serverEntManager.GetComponent(ent).Scale = (scale, scale); + entity = ent; }); // Let client sync up. @@ -91,8 +92,7 @@ namespace Content.IntegrationTests.Tests await _client.WaitPost(() => { - var ent = clientEntManager.GetEntity(entity); - var clickable = ent.GetComponent(); + var clickable = clientEntManager.GetComponent(entity); hit = clickable.CheckClick((clickPosX, clickPosY) + worldPos!.Value, out _, out _); }); diff --git a/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs b/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs index bd72d5f8b4..cb35a38272 100644 --- a/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs +++ b/Content.IntegrationTests/Tests/Commands/RejuvenateTest.cs @@ -48,8 +48,8 @@ namespace Content.IntegrationTests.Tests.Commands var human = entityManager.SpawnEntity("DamageableDummy", MapCoordinates.Nullspace); // Sanity check - Assert.True(human.TryGetComponent(out DamageableComponent damageable)); - Assert.True(human.TryGetComponent(out MobStateComponent mobState)); + Assert.True(IoCManager.Resolve().TryGetComponent(human, out DamageableComponent damageable)); + Assert.True(IoCManager.Resolve().TryGetComponent(human, out MobStateComponent mobState)); mobState.UpdateState(0); Assert.That(mobState.IsAlive, Is.True); Assert.That(mobState.IsCritical, Is.False); @@ -59,7 +59,7 @@ namespace Content.IntegrationTests.Tests.Commands // Kill the entity DamageSpecifier damage = new(prototypeManager.Index("Toxin"), FixedPoint2.New(10000000)); - EntitySystem.Get().TryChangeDamage(human.Uid, damage, true); + EntitySystem.Get().TryChangeDamage(human, damage, true); // Check that it is dead Assert.That(mobState.IsAlive, Is.False); diff --git a/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs b/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs index 9a55c5eaf4..21fa17d50d 100644 --- a/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs +++ b/Content.IntegrationTests/Tests/ContainerOcclusionTest.cs @@ -74,25 +74,27 @@ namespace Content.IntegrationTests.Tests { var (c, s) = await Start(); - EntityUid dummyUid = default; + await c.WaitIdleAsync(); + + var cEntities = c.ResolveDependency(); + + EntityUid dummy = default; s.Post(() => { var pos = new MapCoordinates(Vector2.Zero, new MapId(1)); var ent = IoCManager.Resolve(); var container = ent.SpawnEntity("ContainerOcclusionA", pos); - var dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos); - dummyUid = dummy.Uid; + dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos); - container.GetComponent().Insert(dummy); + ent.GetComponent(container).Insert(dummy); }); await RunTicksSync(c, s, 5); c.Assert(() => { - var dummy = IoCManager.Resolve().GetEntity(dummyUid); - var sprite = dummy.GetComponent(); - var light = dummy.GetComponent(); + var sprite = cEntities.GetComponent(dummy); + var light = cEntities.GetComponent(dummy); Assert.True(sprite.ContainerOccluded); Assert.True(light.ContainerOccluded); }); @@ -105,25 +107,27 @@ namespace Content.IntegrationTests.Tests { var (c, s) = await Start(); - EntityUid dummyUid = default; + await c.WaitIdleAsync(); + + var cEntities = c.ResolveDependency(); + + EntityUid dummy = default; s.Post(() => { var pos = new MapCoordinates(Vector2.Zero, new MapId(1)); var ent = IoCManager.Resolve(); var container = ent.SpawnEntity("ContainerOcclusionB", pos); - var dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos); - dummyUid = dummy.Uid; + dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos); - container.GetComponent().Insert(dummy); + ent.GetComponent(container).Insert(dummy); }); await RunTicksSync(c, s, 5); c.Assert(() => { - var dummy = IoCManager.Resolve().GetEntity(dummyUid); - var sprite = dummy.GetComponent(); - var light = dummy.GetComponent(); + var sprite = cEntities.GetComponent(dummy); + var light = cEntities.GetComponent(dummy); Assert.False(sprite.ContainerOccluded); Assert.False(light.ContainerOccluded); }); @@ -136,27 +140,29 @@ namespace Content.IntegrationTests.Tests { var (c, s) = await Start(); - EntityUid dummyUid = default; + await c.WaitIdleAsync(); + + var cEntities = c.ResolveDependency(); + + EntityUid dummy = default; s.Post(() => { var pos = new MapCoordinates(Vector2.Zero, new MapId(1)); var ent = IoCManager.Resolve(); var containerA = ent.SpawnEntity("ContainerOcclusionA", pos); var containerB = ent.SpawnEntity("ContainerOcclusionB", pos); - var dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos); - dummyUid = dummy.Uid; + dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos); - containerA.GetComponent().Insert(containerB); - containerB.GetComponent().Insert(dummy); + ent.GetComponent(containerA).Insert(containerB); + ent.GetComponent(containerB).Insert(dummy); }); await RunTicksSync(c, s, 5); c.Assert(() => { - var dummy = IoCManager.Resolve().GetEntity(dummyUid); - var sprite = dummy.GetComponent(); - var light = dummy.GetComponent(); + var sprite = cEntities.GetComponent(dummy); + var light = cEntities.GetComponent(dummy); Assert.True(sprite.ContainerOccluded); Assert.True(light.ContainerOccluded); }); diff --git a/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs b/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs index b3a20f9cf2..a254427e41 100644 --- a/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs +++ b/Content.IntegrationTests/Tests/Damageable/DamageableTest.cs @@ -5,6 +5,7 @@ using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -94,7 +95,7 @@ namespace Content.IntegrationTests.Tests.Damageable sEntityManager.EventBus.SubscribeLocalEvent(DamageChangedListener); - IEntity sDamageableEntity = null; + EntityUid sDamageableEntity = default; DamageableComponent sDamageableComponent = null; DamageableSystem sDamageableSystem = null; @@ -118,7 +119,7 @@ namespace Content.IntegrationTests.Tests.Damageable sMapManager.CreateMap(mapId); sDamageableEntity = sEntityManager.SpawnEntity("TestDamageableEntityId", coordinates); - sDamageableComponent = sDamageableEntity.GetComponent(); + sDamageableComponent = IoCManager.Resolve().GetComponent(sDamageableEntity); sDamageableSystem = sEntitySystemManager.GetEntitySystem(); group1 = sPrototypeManager.Index("TestGroup1"); @@ -137,7 +138,7 @@ namespace Content.IntegrationTests.Tests.Damageable await server.WaitAssertion(() => { - var uid = sDamageableEntity.Uid; + var uid = (EntityUid) sDamageableEntity; // Check that the correct types are supported. Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type1.ID), Is.False); diff --git a/Content.IntegrationTests/Tests/DeleteInventoryTest.cs b/Content.IntegrationTests/Tests/DeleteInventoryTest.cs index c29d4bebbf..64e87cd90c 100644 --- a/Content.IntegrationTests/Tests/DeleteInventoryTest.cs +++ b/Content.IntegrationTests/Tests/DeleteInventoryTest.cs @@ -28,17 +28,17 @@ namespace Content.IntegrationTests.Tests var entMgr = IoCManager.Resolve(); var container = entMgr.SpawnEntity(null, MapCoordinates.Nullspace); - var inv = container.AddComponent(); + var inv = entMgr.AddComponent(container); var child = entMgr.SpawnEntity(null, MapCoordinates.Nullspace); - var item = child.AddComponent(); + var item = entMgr.AddComponent(child); item.SlotFlags = SlotFlags.HEAD; // Equip item. Assert.That(inv.Equip(Slots.HEAD, item, false), Is.True); // Delete parent. - container.Delete(); + entMgr.DeleteEntity(container); // Assert that child item was also deleted. Assert.That(item.Deleted, Is.True); diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs index 3b5addc1a1..94bd41862b 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs @@ -5,6 +5,7 @@ using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Prototypes; using static Content.IntegrationTests.Tests.Destructible.DestructibleTestPrototypes; @@ -31,7 +32,7 @@ namespace Content.IntegrationTests.Tests.Destructible var sPrototypeManager = server.ResolveDependency(); var sEntitySystemManager = server.ResolveDependency(); - IEntity sDestructibleEntity = null; + EntityUid sDestructibleEntity = default; DamageableComponent sDamageableComponent = null; TestDestructibleListenerSystem sTestThresholdListenerSystem = null; DamageableSystem sDamageableSystem = null; @@ -42,7 +43,7 @@ namespace Content.IntegrationTests.Tests.Destructible var coordinates = new EntityCoordinates(gridId, 0, 0); sDestructibleEntity = sEntityManager.SpawnEntity(DestructibleDamageGroupEntityId, coordinates); - sDamageableComponent = sDestructibleEntity.GetComponent(); + sDamageableComponent = IoCManager.Resolve().GetComponent(sDestructibleEntity); sTestThresholdListenerSystem = sEntitySystemManager.GetEntitySystem(); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -66,19 +67,19 @@ namespace Content.IntegrationTests.Tests.Destructible DamageSpecifier burnDamage = new(burnDamageGroup, FixedPoint2.New(5)); // Raise brute damage to 5 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bruteDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage, true); // No thresholds reached yet, the earliest one is at 10 damage Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise brute damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bruteDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage, true); // No threshold reached, burn needs to be 10 as well Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise burn damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, burnDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // One threshold reached, brute 10 + burn 10 Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -101,26 +102,26 @@ namespace Content.IntegrationTests.Tests.Destructible sTestThresholdListenerSystem.ThresholdsReached.Clear(); // Raise brute damage to 20 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bruteDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise burn damage to 20 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, burnDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Lower brute damage to 0 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bruteDamage * -10); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * -10); Assert.That(sDamageableComponent.TotalDamage,Is.EqualTo(FixedPoint2.New(20))); // No new thresholds reached, healing should not trigger it Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise brute damage back up to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bruteDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // 10 brute + 10 burn threshold reached, brute was healed and brought back to its threshold amount and slash stayed the same Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -134,13 +135,13 @@ namespace Content.IntegrationTests.Tests.Destructible Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise brute damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bruteDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise burn damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, burnDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // Both classes of damage were healed and then raised again, the threshold should have been reached as triggers once is default false Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -172,13 +173,13 @@ namespace Content.IntegrationTests.Tests.Destructible Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise brute damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bruteDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bruteDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise burn damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, burnDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, burnDamage * 2, true); // No new thresholds reached as triggers once is set to true and it already triggered before Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs index 313e6ad549..401d6a3030 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleDamageTypeTest.cs @@ -30,7 +30,7 @@ namespace Content.IntegrationTests.Tests.Destructible var sMapManager = server.ResolveDependency(); var sEntitySystemManager = server.ResolveDependency(); - IEntity sDestructibleEntity = null; + EntityUid sDestructibleEntity = default; DamageableComponent sDamageableComponent = null; TestDestructibleListenerSystem sTestThresholdListenerSystem = null; DamageableSystem sDamageableSystem = null; @@ -41,7 +41,7 @@ namespace Content.IntegrationTests.Tests.Destructible var coordinates = new EntityCoordinates(gridId, 0, 0); sDestructibleEntity = sEntityManager.SpawnEntity(DestructibleDamageTypeEntityId, coordinates); - sDamageableComponent = sDestructibleEntity.GetComponent(); + sDamageableComponent = IoCManager.Resolve().GetComponent(sDestructibleEntity); sTestThresholdListenerSystem = sEntitySystemManager.GetEntitySystem(); sDamageableSystem = sEntitySystemManager.GetEntitySystem(); }); @@ -62,19 +62,19 @@ namespace Content.IntegrationTests.Tests.Destructible var slashDamage = new DamageSpecifier(slashDamageType,5); // Raise blunt damage to 5 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // No thresholds reached yet, the earliest one is at 10 damage Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise blunt damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // No threshold reached, slash needs to be 10 as well Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise slash damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, slashDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // One threshold reached, blunt 10 + slash 10 Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -97,25 +97,25 @@ namespace Content.IntegrationTests.Tests.Destructible sTestThresholdListenerSystem.ThresholdsReached.Clear(); // Raise blunt damage to 20 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise slash damage to 20 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, slashDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Lower blunt damage to 0 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage * -4, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -4, true); // No new thresholds reached, healing should not trigger it Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise blunt damage back up to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // 10 blunt + 10 slash threshold reached, blunt was healed and brought back to its threshold amount and slash stayed the same Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -123,20 +123,20 @@ namespace Content.IntegrationTests.Tests.Destructible sTestThresholdListenerSystem.ThresholdsReached.Clear(); // Heal both types of damage to 0 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage * -2, true); - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, slashDamage * -4, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * -4, true); // No new thresholds reached, healing should not trigger it Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise blunt damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise slash damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, slashDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // Both types of damage were healed and then raised again, the threshold should have been reached as triggers once is default false Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -162,20 +162,20 @@ namespace Content.IntegrationTests.Tests.Destructible threshold.TriggersOnce = true; // Heal blunt and slash back to 0 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage * -2, true); - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, slashDamage * -2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * -2, true); // No new thresholds reached from healing Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise blunt damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true); // No new thresholds reached Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); // Raise slash damage to 10 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, slashDamage * 2, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true); // No new thresholds reached as triggers once is set to true and it already triggered before Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs index 27c40f87b0..85132fbd56 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleDestructionTest.cs @@ -30,8 +30,7 @@ namespace Content.IntegrationTests.Tests.Destructible var sPrototypeManager = server.ResolveDependency(); var sEntitySystemManager = server.ResolveDependency(); - IEntity sDestructibleEntity = null; - DamageableComponent sDamageableComponent = null; + EntityUid sDestructibleEntity = default; TestDestructibleListenerSystem sTestThresholdListenerSystem = null; await server.WaitPost(() => @@ -40,19 +39,18 @@ namespace Content.IntegrationTests.Tests.Destructible var coordinates = new EntityCoordinates(gridId, 0, 0); sDestructibleEntity = sEntityManager.SpawnEntity(DestructibleDestructionEntityId, coordinates); - sDamageableComponent = sDestructibleEntity.GetComponent(); sTestThresholdListenerSystem = sEntitySystemManager.GetEntitySystem(); }); await server.WaitAssertion(() => { - var coordinates = sDestructibleEntity.Transform.Coordinates; + var coordinates = IoCManager.Resolve().GetComponent(sDestructibleEntity).Coordinates; var bruteDamageGroup = sPrototypeManager.Index("TestBrute"); DamageSpecifier bruteDamage = new(bruteDamageGroup,50); Assert.DoesNotThrow(() => { - EntitySystem.Get().TryChangeDamage(sDestructibleEntity.Uid, bruteDamage, true); + EntitySystem.Get().TryChangeDamage(sDestructibleEntity, bruteDamage, true); }); Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -73,12 +71,12 @@ namespace Content.IntegrationTests.Tests.Destructible foreach (var entity in entitiesInRange) { - if (entity.Prototype == null) + if (sEntityManager.GetComponent(entity).EntityPrototype == null) { continue; } - if (entity.Prototype.Name != SpawnedEntityId) + if (sEntityManager.GetComponent(entity).EntityPrototype?.Name != SpawnedEntityId) { continue; } diff --git a/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs b/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs index 90fb064fd5..547275ff66 100644 --- a/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs +++ b/Content.IntegrationTests/Tests/Destructible/DestructibleThresholdActivationTest.cs @@ -9,6 +9,7 @@ using Content.Shared.Damage.Prototypes; using Content.Shared.FixedPoint; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Prototypes; using static Content.IntegrationTests.Tests.Destructible.DestructibleTestPrototypes; @@ -35,7 +36,7 @@ namespace Content.IntegrationTests.Tests.Destructible var sPrototypeManager = server.ResolveDependency(); var sEntitySystemManager = server.ResolveDependency(); - IEntity sDestructibleEntity = null; ; + EntityUid sDestructibleEntity = default; DamageableComponent sDamageableComponent = null; DestructibleComponent sDestructibleComponent = null; TestDestructibleListenerSystem sTestThresholdListenerSystem = null; @@ -47,8 +48,8 @@ namespace Content.IntegrationTests.Tests.Destructible var coordinates = new EntityCoordinates(gridId, 0, 0); sDestructibleEntity = sEntityManager.SpawnEntity(DestructibleEntityId, coordinates); - sDamageableComponent = sDestructibleEntity.GetComponent(); - sDestructibleComponent = sDestructibleEntity.GetComponent(); + sDamageableComponent = IoCManager.Resolve().GetComponent(sDestructibleEntity); + sDestructibleComponent = IoCManager.Resolve().GetComponent(sDestructibleEntity); sTestThresholdListenerSystem = sEntitySystemManager.GetEntitySystem(); sTestThresholdListenerSystem.ThresholdsReached.Clear(); @@ -67,12 +68,12 @@ namespace Content.IntegrationTests.Tests.Destructible { var bluntDamage = new DamageSpecifier(sPrototypeManager.Index("TestBlunt"), 10); - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // No thresholds reached yet, the earliest one is at 20 damage Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // Only one threshold reached, 20 Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -88,7 +89,7 @@ namespace Content.IntegrationTests.Tests.Destructible sTestThresholdListenerSystem.ThresholdsReached.Clear(); - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage*3, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*3, true); // One threshold reached, 50, since 20 already triggered before and it has not been healed below that amount Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -117,7 +118,7 @@ namespace Content.IntegrationTests.Tests.Destructible sTestThresholdListenerSystem.ThresholdsReached.Clear(); // Damage for 50 again, up to 100 now - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage*5, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*5, true); // No thresholds reached as they weren't healed below the trigger amount Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached); @@ -126,7 +127,7 @@ namespace Content.IntegrationTests.Tests.Destructible sDamageableSystem.SetAllDamage(sDamageableComponent, 0); // Damage for 100, up to 100 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage*10, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*10, true); // Two thresholds reached as damage increased past the previous, 20 and 50 Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(2)); @@ -134,25 +135,25 @@ namespace Content.IntegrationTests.Tests.Destructible sTestThresholdListenerSystem.ThresholdsReached.Clear(); // Heal the entity for 40 damage, down to 60 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage*-4, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*-4, true); // Thresholds don't work backwards Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Damage for 10, up to 70 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // Not enough healing to de-trigger a threshold Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Heal by 30, down to 40 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage*-3, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*-3, true); // Thresholds don't work backwards Assert.That(sTestThresholdListenerSystem.ThresholdsReached, Is.Empty); // Damage up to 50 again - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true); // The 50 threshold should have triggered again, after being healed Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1)); @@ -185,7 +186,7 @@ namespace Content.IntegrationTests.Tests.Destructible sDamageableSystem.SetAllDamage(sDamageableComponent, 0); // Damage up to 50 - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage*5, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*5, true); // Check that the total damage matches Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); @@ -246,7 +247,7 @@ namespace Content.IntegrationTests.Tests.Destructible } // Damage the entity up to 50 damage again - sDamageableSystem.TryChangeDamage(sDestructibleEntity.Uid, bluntDamage*5, true); + sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage*5, true); // Check that the total damage matches Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(50))); diff --git a/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs b/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs index a873978f82..c76392ce85 100644 --- a/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs +++ b/Content.IntegrationTests/Tests/DeviceNetwork/DeviceNetworkTest.cs @@ -64,8 +64,8 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork var deviceNetTestSystem = entityManager.EntitySysManager.GetEntitySystem(); - IEntity device1 = null; - IEntity device2 = null; + EntityUid device1 = default; + EntityUid device2 = default; DeviceNetworkComponent networkComponent1 = null; DeviceNetworkComponent networkComponent2 = null; @@ -82,19 +82,19 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork device1 = entityManager.SpawnEntity("DummyNetworkDevice", MapCoordinates.Nullspace); - Assert.That(device1.TryGetComponent(out networkComponent1), Is.True); + Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); Assert.That(networkComponent1.Open, Is.True); Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); device2 = entityManager.SpawnEntity("DummyNetworkDevice", MapCoordinates.Nullspace); - Assert.That(device2.TryGetComponent(out networkComponent2), Is.True); + Assert.That(entityManager.TryGetComponent(device2, out networkComponent2), Is.True); Assert.That(networkComponent2.Open, Is.True); Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); - deviceNetSystem.QueuePacket(device1.Uid, networkComponent2.Address, networkComponent2.Frequency, payload); + deviceNetSystem.QueuePacket(device1, networkComponent2.Address, networkComponent2.Frequency, payload); }); await server.WaitRunTicks(1); @@ -126,8 +126,8 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork var deviceNetTestSystem = entityManager.EntitySysManager.GetEntitySystem(); - IEntity device1 = null; - IEntity device2 = null; + EntityUid device1 = default; + EntityUid device2 = default; DeviceNetworkComponent networkComponent1 = null; DeviceNetworkComponent networkComponent2 = null; WirelessNetworkComponent wirelessNetworkComponent = null; @@ -145,20 +145,20 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork device1 = entityManager.SpawnEntity("DummyWirelessNetworkDevice", MapCoordinates.Nullspace); - Assert.That(device1.TryGetComponent(out networkComponent1), Is.True); - Assert.That(device1.TryGetComponent(out wirelessNetworkComponent), Is.True); + Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); + Assert.That(entityManager.TryGetComponent(device1, out wirelessNetworkComponent), Is.True); Assert.That(networkComponent1.Open, Is.True); Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); device2 = entityManager.SpawnEntity("DummyWirelessNetworkDevice", new MapCoordinates(new Robust.Shared.Maths.Vector2(0,50), MapId.Nullspace)); - Assert.That(device2.TryGetComponent(out networkComponent2), Is.True); + Assert.That(entityManager.TryGetComponent(device2, out networkComponent2), Is.True); Assert.That(networkComponent2.Open, Is.True); Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); - deviceNetSystem.QueuePacket(device1.Uid, networkComponent2.Address, networkComponent2.Frequency, payload); + deviceNetSystem.QueuePacket(device1, networkComponent2.Address, networkComponent2.Frequency, payload); }); await server.WaitRunTicks(1); @@ -174,7 +174,7 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork wirelessNetworkComponent.Range = 0; - deviceNetSystem.QueuePacket(device1.Uid, networkComponent2.Address, networkComponent2.Frequency, payload); + deviceNetSystem.QueuePacket(device1, networkComponent2.Address, networkComponent2.Frequency, payload); }); await server.WaitRunTicks(1); @@ -208,8 +208,8 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork var deviceNetTestSystem = entityManager.EntitySysManager.GetEntitySystem(); - IEntity device1 = null; - IEntity device2 = null; + EntityUid device1 = default; + EntityUid device2 = default; DeviceNetworkComponent networkComponent1 = null; DeviceNetworkComponent networkComponent2 = null; WiredNetworkComponent wiredNetworkComponent = null; @@ -232,20 +232,20 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork device1 = entityManager.SpawnEntity("DummyWiredNetworkDevice", MapCoordinates.Nullspace); - Assert.That(device1.TryGetComponent(out networkComponent1), Is.True); - Assert.That(device1.TryGetComponent(out wiredNetworkComponent), Is.True); + Assert.That(entityManager.TryGetComponent(device1, out networkComponent1), Is.True); + Assert.That(entityManager.TryGetComponent(device1, out wiredNetworkComponent), Is.True); Assert.That(networkComponent1.Open, Is.True); Assert.That(networkComponent1.Address, Is.Not.EqualTo(string.Empty)); device2 = entityManager.SpawnEntity("DummyWiredNetworkDevice", new MapCoordinates(new Robust.Shared.Maths.Vector2(0, 2), MapId.Nullspace)); - Assert.That(device2.TryGetComponent(out networkComponent2), Is.True); + Assert.That(entityManager.TryGetComponent(device2, out networkComponent2), Is.True); Assert.That(networkComponent2.Open, Is.True); Assert.That(networkComponent2.Address, Is.Not.EqualTo(string.Empty)); Assert.That(networkComponent1.Address, Is.Not.EqualTo(networkComponent2.Address)); - deviceNetSystem.QueuePacket(device1.Uid, networkComponent2.Address, networkComponent2.Frequency, payload); + deviceNetSystem.QueuePacket(device1, networkComponent2.Address, networkComponent2.Frequency, payload); }); await server.WaitRunTicks(1); @@ -256,7 +256,7 @@ namespace Content.IntegrationTests.Tests.DeviceNetwork entityManager.SpawnEntity("CableApcExtension", grid.MapToGrid(new MapCoordinates(new Robust.Shared.Maths.Vector2(0, 1), MapId.Nullspace))); - deviceNetSystem.QueuePacket(device1.Uid, networkComponent2.Address, networkComponent2.Frequency, payload); + deviceNetSystem.QueuePacket(device1, networkComponent2.Address, networkComponent2.Frequency, payload); }); await server.WaitRunTicks(1); diff --git a/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs b/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs index 2aef66cd5c..09d4619d40 100644 --- a/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs +++ b/Content.IntegrationTests/Tests/Disposal/DisposalUnitTest.cs @@ -7,6 +7,7 @@ using Content.Server.Power.Components; using Content.Shared.Disposal; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Reflection; @@ -36,18 +37,18 @@ namespace Content.IntegrationTests.Tests.Disposal } } - private void UnitInsert(DisposalUnitComponent unit, bool result, params IEntity[] entities) + private void UnitInsert(DisposalUnitComponent unit, bool result, params EntityUid[] entities) { var system = EntitySystem.Get(); foreach (var entity in entities) { Assert.That(system.CanInsert(unit, entity), Is.EqualTo(result)); - system.TryInsert(unit.Owner.Uid, entity.Uid, entity.Uid); + system.TryInsert(unit.Owner, entity, entity); } } - private void UnitContains(DisposalUnitComponent unit, bool result, params IEntity[] entities) + private void UnitContains(DisposalUnitComponent unit, bool result, params EntityUid[] entities) { foreach (var entity in entities) { @@ -55,13 +56,13 @@ namespace Content.IntegrationTests.Tests.Disposal } } - private void UnitInsertContains(DisposalUnitComponent unit, bool result, params IEntity[] entities) + private void UnitInsertContains(DisposalUnitComponent unit, bool result, params EntityUid[] entities) { UnitInsert(unit, result, entities); UnitContains(unit, result, entities); } - private void Flush(DisposalUnitComponent unit, bool result, params IEntity[] entities) + private void Flush(DisposalUnitComponent unit, bool result, params EntityUid[] entities) { Assert.That(unit.ContainedEntities, Is.SupersetOf(entities)); Assert.That(entities.Length, Is.EqualTo(unit.ContainedEntities.Count)); @@ -126,10 +127,10 @@ namespace Content.IntegrationTests.Tests.Disposal var server = StartServer(options); await server.WaitIdleAsync(); - IEntity human = default!; - IEntity wrench = default!; - IEntity disposalUnit = default!; - IEntity disposalTrunk = default!; + EntityUid human = default!; + EntityUid wrench = default!; + EntityUid disposalUnit = default!; + EntityUid disposalTrunk = default!; DisposalUnitComponent unit = default!; var mapManager = server.ResolveDependency(); @@ -142,21 +143,22 @@ namespace Content.IntegrationTests.Tests.Disposal human = entityManager.SpawnEntity("HumanDummy", coordinates); wrench = entityManager.SpawnEntity("WrenchDummy", coordinates); disposalUnit = entityManager.SpawnEntity("DisposalUnitDummy", coordinates); - disposalTrunk = entityManager.SpawnEntity("DisposalTrunkDummy", disposalUnit.Transform.MapPosition); + disposalTrunk = entityManager.SpawnEntity("DisposalTrunkDummy", IoCManager.Resolve().GetComponent(disposalUnit).MapPosition); // Test for components existing - Assert.True(disposalUnit.TryGetComponent(out unit!)); - Assert.True(disposalTrunk.HasComponent()); + ref DisposalUnitComponent? comp = ref unit!; + Assert.True(entityManager.TryGetComponent(disposalUnit, out comp)); + Assert.True(entityManager.HasComponent(disposalTrunk)); // Can't insert, unanchored and unpowered - unit.Owner.Transform.Anchored = false; + entityManager.GetComponent(unit.Owner).Anchored = false; UnitInsertContains(unit, false, human, wrench, disposalUnit, disposalTrunk); }); await server.WaitAssertion(() => { // Anchor the disposal unit - unit.Owner.Transform.Anchored = true; + entityManager.GetComponent(unit.Owner).Anchored = true; // No power Assert.False(unit.Powered); @@ -171,7 +173,7 @@ namespace Content.IntegrationTests.Tests.Disposal await server.WaitAssertion(() => { // Move the disposal trunk away - disposalTrunk.Transform.WorldPosition += (1, 0); + entityManager.GetComponent(disposalTrunk).WorldPosition += (1, 0); // Fail to flush with a mob and an item Flush(unit, false, human, wrench); @@ -180,7 +182,7 @@ namespace Content.IntegrationTests.Tests.Disposal await server.WaitAssertion(() => { // Move the disposal trunk back - disposalTrunk.Transform.WorldPosition -= (1, 0); + entityManager.GetComponent(disposalTrunk).WorldPosition -= (1, 0); // Fail to flush with a mob and an item, no power Flush(unit, false, human, wrench); @@ -189,7 +191,7 @@ namespace Content.IntegrationTests.Tests.Disposal await server.WaitAssertion(() => { // Remove power need - Assert.True(disposalUnit.TryGetComponent(out ApcPowerReceiverComponent power)); + Assert.True(entityManager.TryGetComponent(disposalUnit, out ApcPowerReceiverComponent power)); power!.NeedsPower = false; Assert.True(unit.Powered); diff --git a/Content.IntegrationTests/Tests/Doors/AirlockTest.cs b/Content.IntegrationTests/Tests/Doors/AirlockTest.cs index 23689f7c8c..92b1d4c877 100644 --- a/Content.IntegrationTests/Tests/Doors/AirlockTest.cs +++ b/Content.IntegrationTests/Tests/Doors/AirlockTest.cs @@ -4,6 +4,7 @@ using Content.Server.Doors.Components; using Content.Shared.Doors; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Physics; @@ -55,7 +56,7 @@ namespace Content.IntegrationTests.Tests.Doors var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); - IEntity airlock = null; + EntityUid airlock = default; ServerDoorComponent doorComponent = null; server.Assert(() => @@ -64,7 +65,7 @@ namespace Content.IntegrationTests.Tests.Doors airlock = entityManager.SpawnEntity("AirlockDummy", MapCoordinates.Nullspace); - Assert.True(airlock.TryGetComponent(out doorComponent)); + Assert.True(entityManager.TryGetComponent(airlock, out doorComponent)); Assert.That(doorComponent.State, Is.EqualTo(SharedDoorComponent.DoorState.Closed)); }); @@ -96,7 +97,7 @@ namespace Content.IntegrationTests.Tests.Doors { Assert.DoesNotThrow(() => { - airlock.Delete(); + entityManager.DeleteEntity(airlock); }); }); @@ -120,8 +121,8 @@ namespace Content.IntegrationTests.Tests.Doors var entityManager = server.ResolveDependency(); IPhysBody physBody = null; - IEntity physicsDummy = null; - IEntity airlock = null; + EntityUid physicsDummy = default; + EntityUid airlock = default; ServerDoorComponent doorComponent = null; var physicsDummyStartingX = -1; @@ -135,9 +136,9 @@ namespace Content.IntegrationTests.Tests.Doors airlock = entityManager.SpawnEntity("AirlockDummy", new MapCoordinates((0, 0), mapId)); - Assert.True(physicsDummy.TryGetComponent(out physBody)); + Assert.True(entityManager.TryGetComponent(physicsDummy, out physBody)); - Assert.True(airlock.TryGetComponent(out doorComponent)); + Assert.True(entityManager.TryGetComponent(airlock, out doorComponent)); Assert.That(doorComponent.State, Is.EqualTo(SharedDoorComponent.DoorState.Closed)); }); @@ -150,7 +151,7 @@ namespace Content.IntegrationTests.Tests.Doors for (var i = 0; i < 240; i += 10) { // Keep the airlock awake so they collide - server.Post(() => airlock.GetComponent().WakeBody()); + server.Post(() => entityManager.GetComponent(airlock).WakeBody()); await server.WaitRunTicks(10); await server.WaitIdleAsync(); @@ -163,7 +164,7 @@ namespace Content.IntegrationTests.Tests.Doors // Assert.That(physicsDummy.Transform.MapPosition.X, Is.GreaterThan(physicsDummyStartingX)); // Blocked by the airlock - await server.WaitAssertion(() => Assert.That(Math.Abs(physicsDummy.Transform.MapPosition.X - 1) > 0.01f)); + await server.WaitAssertion(() => Assert.That(Math.Abs(entityManager.GetComponent(physicsDummy).MapPosition.X - 1) > 0.01f)); } } } diff --git a/Content.IntegrationTests/Tests/EntityTest.cs b/Content.IntegrationTests/Tests/EntityTest.cs index b05c0b38e1..b948bddc54 100644 --- a/Content.IntegrationTests/Tests/EntityTest.cs +++ b/Content.IntegrationTests/Tests/EntityTest.cs @@ -6,6 +6,7 @@ using Content.Shared.CCVar; using Content.Shared.Coordinates; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -14,7 +15,7 @@ using Robust.Shared.Timing; namespace Content.IntegrationTests.Tests { [TestFixture] - [TestOf(typeof(IEntity))] + [TestOf(typeof(EntityUid))] public class EntityTest : ContentIntegrationTest { [Test] @@ -36,7 +37,7 @@ namespace Content.IntegrationTests.Tests var prototypes = new List(); IMapGrid grid = default; - IEntity testEntity; + EntityUid testEntity; //Build up test environment server.Post(() => @@ -87,8 +88,8 @@ namespace Content.IntegrationTests.Tests Logger.LogS(LogLevel.Debug, "EntityTest", $"Testing: {prototype.ID}"); testEntity = entityMan.SpawnEntity(prototype.ID, testLocation); server.RunTicks(2); - Assert.That(testEntity.Initialized); - entityMan.DeleteEntity(testEntity.Uid); + if(!entityMan.Deleted(testEntity)) + entityMan.DeleteEntity(testEntity); }, "Entity '{0}' threw an exception.", prototype.ID); } @@ -172,11 +173,11 @@ namespace Content.IntegrationTests.Tests var entity = entityManager.SpawnEntity("AllComponentsOneToOneDeleteTestEntity", testLocation); - Assert.That(entity.Initialized); + Assert.That(entityManager.GetComponent(entity).EntityInitialized); // The component may already exist if it is a mandatory component // such as MetaData or Transform - if (entity.HasComponent(type)) + if (entityManager.HasComponent(entity, type)) { continue; } @@ -193,7 +194,7 @@ namespace Content.IntegrationTests.Tests server.RunTicks(2); - entityManager.DeleteEntity(entity.Uid); + entityManager.DeleteEntity(entity); } }); }); @@ -301,14 +302,14 @@ namespace Content.IntegrationTests.Tests var testLocation = grid.ToCoordinates(); var entity = entityManager.SpawnEntity("AllComponentsOneEntityDeleteTestEntity", testLocation); - Assert.That(entity.Initialized); + Assert.That(entityManager.GetComponent(entity).EntityInitialized); foreach (var type in distinct.components) { var component = (Component) componentFactory.GetComponent(type); // If the entity already has this component, if it was ensured or added by another - if (entity.HasComponent(component.GetType())) + if (entityManager.HasComponent(entity, component.GetType())) { continue; } @@ -335,7 +336,7 @@ namespace Content.IntegrationTests.Tests } server.RunTicks(2); - entityManager.DeleteEntity(entity.Uid); + entityManager.DeleteEntity(entity); } }); }); diff --git a/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs b/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs index d0d7995d2d..98a1ec5776 100644 --- a/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs +++ b/Content.IntegrationTests/Tests/Fluids/PuddleTest.cs @@ -7,6 +7,7 @@ using Content.Shared.Coordinates; using Content.Shared.FixedPoint; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Timing; @@ -89,12 +90,12 @@ namespace Content.IntegrationTests.Tests.Fluids var sPauseManager = server.ResolveDependency(); var sTileDefinitionManager = server.ResolveDependency(); var sGameTiming = server.ResolveDependency(); - var sEntityManager = server.ResolveDependency(); + var entityManager = server.ResolveDependency(); MapId sMapId = default; IMapGrid sGrid; GridId sGridId = default; - IEntity sGridEntity = null; + EntityUid sGridEntity = default; EntityCoordinates sCoordinates = default; // Spawn a paused map with one tile to spawn puddles on @@ -104,8 +105,8 @@ namespace Content.IntegrationTests.Tests.Fluids sPauseManager.SetMapPaused(sMapId, true); sGrid = sMapManager.CreateGrid(sMapId); sGridId = sGrid.Index; - sGridEntity = sEntityManager.GetEntity(sGrid.GridEntityId); - sGridEntity.Paused = true; // See https://github.com/space-wizards/RobustToolbox/issues/1444 + sGridEntity = sGrid.GridEntityId; + entityManager.GetComponent(sGridEntity).EntityPaused = true; // See https://github.com/space-wizards/RobustToolbox/issues/1444 var tileDefinition = sTileDefinitionManager["underplating"]; var tile = new Tile(tileDefinition.TileId); @@ -119,15 +120,15 @@ namespace Content.IntegrationTests.Tests.Fluids { Assert.True(sPauseManager.IsGridPaused(sGridId)); Assert.True(sPauseManager.IsMapPaused(sMapId)); - Assert.True(sGridEntity.Paused); }); float evaporateTime = default; PuddleComponent puddle = null; + MetaDataComponent meta = null; EvaporationComponent evaporation; - + var amount = 2; - + var entitySystemManager = server.ResolveDependency(); var spillSystem = entitySystemManager.GetEntitySystem(); @@ -136,15 +137,16 @@ namespace Content.IntegrationTests.Tests.Fluids { var solution = new Solution("Water", FixedPoint2.New(amount)); puddle = spillSystem.SpillAt(solution, sCoordinates, "PuddleSmear"); + meta = entityManager.GetComponent(puddle.Owner); // Check that the puddle was created Assert.NotNull(puddle); - evaporation = puddle.Owner.GetComponent(); + evaporation = entityManager.GetComponent(puddle.Owner); - puddle.Owner.Paused = true; // See https://github.com/space-wizards/RobustToolbox/issues/1445 + meta.EntityPaused = true; // See https://github.com/space-wizards/RobustToolbox/issues/1445 - Assert.True(puddle.Owner.Paused); + Assert.True(meta.EntityPaused); // Check that the puddle is going to evaporate Assert.Positive(evaporation.EvaporateTime); @@ -162,10 +164,10 @@ namespace Content.IntegrationTests.Tests.Fluids // No evaporation due to being paused await server.WaitAssertion(() => { - Assert.True(puddle.Owner.Paused); + Assert.True(meta.EntityPaused); // Check that the puddle still exists - Assert.False(puddle.Owner.Deleted); + Assert.False(meta.EntityDeleted); }); // Unpause the map @@ -176,10 +178,10 @@ namespace Content.IntegrationTests.Tests.Fluids { Assert.False(sPauseManager.IsMapPaused(sMapId)); Assert.False(sPauseManager.IsGridPaused(sGridId)); - Assert.False(puddle.Owner.Paused); + Assert.False(meta.EntityPaused); // Check that the puddle still exists - Assert.False(puddle.Owner.Deleted); + Assert.False(meta.EntityDeleted); }); // Wait enough time for it to evaporate @@ -193,4 +195,4 @@ namespace Content.IntegrationTests.Tests.Fluids }); } } -} \ No newline at end of file +} diff --git a/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs b/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs index ed54c7652b..0826619632 100644 --- a/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs +++ b/Content.IntegrationTests/Tests/GameObjects/Components/ActionBlocking/HandCuffTest.cs @@ -42,10 +42,10 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.ActionBlocking var options = new ServerIntegrationOptions{ExtraPrototypes = Prototypes}; var server = StartServer(options); - IEntity human; - IEntity otherHuman; - IEntity cuffs; - IEntity secondCuffs; + EntityUid human; + EntityUid otherHuman; + EntityUid cuffs; + EntityUid secondCuffs; CuffableComponent cuffed; HandsComponent hands; @@ -63,14 +63,14 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.ActionBlocking cuffs = entityManager.SpawnEntity("HandcuffsDummy", coordinates); secondCuffs = entityManager.SpawnEntity("HandcuffsDummy", coordinates); - human.Transform.WorldPosition = otherHuman.Transform.WorldPosition; + entityManager.GetComponent(human).WorldPosition = entityManager.GetComponent(otherHuman).WorldPosition; // Test for components existing - Assert.True(human.TryGetComponent(out cuffed!), $"Human has no {nameof(CuffableComponent)}"); - Assert.True(human.TryGetComponent(out hands!), $"Human has no {nameof(HandsComponent)}"); - Assert.True(human.TryGetComponent(out SharedBodyComponent? _), $"Human has no {nameof(SharedBodyComponent)}"); - Assert.True(cuffs.TryGetComponent(out HandcuffComponent? _), $"Handcuff has no {nameof(HandcuffComponent)}"); - Assert.True(secondCuffs.TryGetComponent(out HandcuffComponent? _), $"Second handcuffs has no {nameof(HandcuffComponent)}"); + Assert.True(entityManager.TryGetComponent(human, out cuffed), $"Human has no {nameof(CuffableComponent)}"); + Assert.True(entityManager.TryGetComponent(human, out hands), $"Human has no {nameof(HandsComponent)}"); + Assert.True(entityManager.TryGetComponent(human, out SharedBodyComponent? _), $"Human has no {nameof(SharedBodyComponent)}"); + Assert.True(entityManager.TryGetComponent(cuffs, out HandcuffComponent? _), $"Handcuff has no {nameof(HandcuffComponent)}"); + Assert.True(entityManager.TryGetComponent(secondCuffs, out HandcuffComponent? _), $"Second handcuffs has no {nameof(HandcuffComponent)}"); // Test to ensure cuffed players register the handcuffs cuffed.TryAddNewCuffs(human, cuffs); @@ -92,10 +92,10 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.ActionBlocking await server.WaitIdleAsync(); } - private void AddHand(IEntity to) + private void AddHand(EntityUid to) { var host = IoCManager.Resolve(); - host.ExecuteCommand(null, $"addhand {to.Uid}"); + host.ExecuteCommand(null, $"addhand {to}"); } } } diff --git a/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/ActionsComponentTests.cs b/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/ActionsComponentTests.cs index 85da3e7612..8fc33251b6 100644 --- a/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/ActionsComponentTests.cs +++ b/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/ActionsComponentTests.cs @@ -15,6 +15,7 @@ using Robust.Client.UserInterface; using Robust.Server.Player; using Robust.Shared; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Timing; using Robust.Shared.Utility; @@ -65,13 +66,17 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs await server.WaitIdleAsync(); await client.WaitIdleAsync(); + var cEntities = client.ResolveDependency(); + + var sEntities = server.ResolveDependency(); var serverPlayerManager = server.ResolveDependency(); var innateActions = new List(); await server.WaitAssertion(() => { - var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity; - var actionsComponent = playerEnt!.GetComponent(); + var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity.GetValueOrDefault(); + Assert.That(playerEnt, Is.Not.EqualTo(default)); + var actionsComponent = sEntities.GetComponent(playerEnt); // player should begin with their innate actions granted innateActions.AddRange(actionsComponent.InnateActions); @@ -98,7 +103,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs { var local = clientPlayerMgr.LocalPlayer; var controlled = local!.ControlledEntity; - var actionsComponent = controlled!.GetComponent(); + var actionsComponent = cEntities.GetComponent(controlled!.Value); // we should have our innate actions and debug1. foreach (var innateAction in innateActions) @@ -122,14 +127,14 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs if (expectEmpty) { Assert.That(slot.HasAssignment, Is.False); - Assert.That(slot.Item, Is.Null); + Assert.That(slot.Item, Is.EqualTo(default)); Assert.That(slot.Action, Is.Null); Assert.That(slot.ActionEnabled, Is.False); continue; } Assert.That(slot.HasAssignment); // all the actions we gave so far are not tied to an item - Assert.That(slot.Item, Is.Null); + Assert.That(slot.Item, Is.EqualTo(default)); Assert.That(slot.Action, Is.Not.Null); Assert.That(slot.ActionEnabled); var asAction = slot.Action as ActionPrototype; @@ -152,8 +157,9 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs // now revoke the action and check that the client sees it as revoked await server.WaitAssertion(() => { - var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity; - var actionsComponent = playerEnt!.GetComponent(); + var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity.GetValueOrDefault(); + Assert.That(playerEnt, Is.Not.EqualTo(default)); + var actionsComponent = sEntities.GetComponent(playerEnt); actionsComponent.Revoke(ActionType.DebugInstant); }); @@ -164,7 +170,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs { var local = clientPlayerMgr.LocalPlayer; var controlled = local!.ControlledEntity; - var actionsComponent = controlled!.GetComponent(); + var actionsComponent = cEntities.GetComponent(controlled!.Value); // we should have our innate actions, but debug1 should be revoked foreach (var innateAction in innateActions) @@ -188,7 +194,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs var expected = expectedOrder[idx++]; Assert.That(slot.HasAssignment); // all the actions we gave so far are not tied to an item - Assert.That(slot.Item, Is.Null); + Assert.That(slot.Item, Is.EqualTo(default)); Assert.That(slot.Action, Is.Not.Null); var asAction = slot.Action as ActionPrototype; Assert.That(asAction, Is.Not.Null); @@ -206,7 +212,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs else { Assert.That(slot.HasAssignment, Is.False); - Assert.That(slot.Item, Is.Null); + Assert.That(slot.Item, Is.EqualTo(default)); Assert.That(slot.Action, Is.Null); Assert.That(slot.ActionEnabled, Is.False); } @@ -231,6 +237,8 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs await server.WaitIdleAsync(); await client.WaitIdleAsync(); + var clientEntities = client.ResolveDependency(); + var serverPlayerManager = server.ResolveDependency(); var serverEntManager = server.ResolveDependency(); var serverGameTiming = server.ResolveDependency(); @@ -239,18 +247,19 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs ServerActionsComponent serverActionsComponent = null; ClientActionsComponent clientActionsComponent = null; - IEntity serverPlayerEnt = null; - IEntity serverFlashlight = null; + EntityUid serverPlayerEnt = default; + EntityUid serverFlashlight = default; await server.WaitAssertion(() => { - serverPlayerEnt = serverPlayerManager.Sessions.Single().AttachedEntity; - serverActionsComponent = serverPlayerEnt!.GetComponent(); + serverPlayerEnt = serverPlayerManager.Sessions.Single().AttachedEntity.GetValueOrDefault(); + Assert.That(serverPlayerEnt, Is.Not.EqualTo(default)); + serverActionsComponent = serverEntManager.GetComponent(serverPlayerEnt); // spawn and give them an item that has actions serverFlashlight = serverEntManager.SpawnEntity("TestFlashlight", - new EntityCoordinates(serverPlayerEnt.Uid, (0, 0))); - Assert.That(serverFlashlight.TryGetComponent(out var itemActions)); + new EntityCoordinates(serverPlayerEnt, (0, 0))); + Assert.That(serverEntManager.TryGetComponent(serverFlashlight, out var itemActions)); // we expect this only to have a toggle light action initially var actionConfigs = itemActions.ActionConfigs.ToList(); Assert.That(actionConfigs.Count == 1); @@ -259,11 +268,11 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs // grant an extra item action, before pickup, initially disabled itemActions.GrantOrUpdate(ItemActionType.DebugToggle, false); - serverPlayerEnt.GetComponent().PutInHand(serverFlashlight.GetComponent(), false); + serverEntManager.GetComponent(serverPlayerEnt).PutInHand(serverEntManager.GetComponent(serverFlashlight), false); // grant an extra item action, after pickup, with a cooldown itemActions.GrantOrUpdate(ItemActionType.DebugInstant, cooldown: cooldown); - Assert.That(serverActionsComponent.TryGetItemActionStates(serverFlashlight.Uid, out var state)); + Assert.That(serverActionsComponent.TryGetItemActionStates(serverFlashlight, out var state)); // they should have been granted all 3 actions Assert.That(state.Count == 3); Assert.That(state.TryGetValue(ItemActionType.ToggleLight, out var toggleLightState)); @@ -285,7 +294,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs { var local = clientPlayerMgr.LocalPlayer; var controlled = local!.ControlledEntity; - clientActionsComponent = controlled!.GetComponent(); + clientActionsComponent = clientEntities.GetComponent(controlled!.Value); var lightEntry = clientActionsComponent.ItemActionStates() .Where(entry => entry.Value.ContainsKey(ItemActionType.ToggleLight)) @@ -317,7 +326,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs // server should see the action toggled on await server.WaitAssertion(() => { - Assert.That(serverActionsComponent.ItemActionStates().TryGetValue(serverFlashlight.Uid, out var lightStates)); + Assert.That(serverActionsComponent.ItemActionStates().TryGetValue(serverFlashlight, out var lightStates)); Assert.That(lightStates.TryGetValue(ItemActionType.ToggleLight, out var lightState)); Assert.That(lightState, Is.EqualTo(new ActionState(true, toggledOn: true))); }); @@ -333,9 +342,9 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs await server.WaitAssertion(() => { // drop the item, and the item actions should go away - serverPlayerEnt.GetComponent() - .TryDropEntity(serverFlashlight, serverPlayerEnt.Transform.Coordinates, false); - Assert.That(serverActionsComponent.ItemActionStates().ContainsKey(serverFlashlight.Uid), Is.False); + serverEntManager.GetComponent(serverPlayerEnt) + .TryDropEntity(serverFlashlight, serverEntManager.GetComponent(serverPlayerEnt).Coordinates, false); + Assert.That(serverActionsComponent.ItemActionStates().ContainsKey(serverFlashlight), Is.False); }); await server.WaitRunTicks(5); @@ -351,8 +360,8 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs { // pick the item up again, the states should be back to what they were when dropped, // as the states "stick" with the item - serverPlayerEnt.GetComponent().PutInHand(serverFlashlight.GetComponent(), false); - Assert.That(serverActionsComponent.ItemActionStates().TryGetValue(serverFlashlight.Uid, out var lightStates)); + serverEntManager.GetComponent(serverPlayerEnt).PutInHand(serverEntManager.GetComponent(serverFlashlight), false); + Assert.That(serverActionsComponent.ItemActionStates().TryGetValue(serverFlashlight, out var lightStates)); Assert.That(lightStates.TryGetValue(ItemActionType.ToggleLight, out var lightState)); Assert.That(lightState.Equals(new ActionState(true, toggledOn: true))); Assert.That(lightStates.TryGetValue(ItemActionType.DebugInstant, out var debugInstantState)); diff --git a/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs b/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs index d5e42d1aff..e454fb179b 100644 --- a/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs +++ b/Content.IntegrationTests/Tests/GameObjects/Components/Mobs/AlertsComponentTests.cs @@ -7,6 +7,8 @@ using Content.Shared.Alert; using NUnit.Framework; using Robust.Client.UserInterface; using Robust.Server.Player; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs { @@ -27,9 +29,9 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs await server.WaitAssertion(() => { - var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity; - Assert.NotNull(playerEnt); - var alertsComponent = playerEnt.GetComponent(); + var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity.GetValueOrDefault(); + Assert.That(playerEnt != default); + var alertsComponent = IoCManager.Resolve().GetComponent(playerEnt); Assert.NotNull(alertsComponent); // show 2 alerts @@ -49,7 +51,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs Assert.NotNull(local); var controlled = local.ControlledEntity; Assert.NotNull(controlled); - var alertsComponent = controlled.GetComponent(); + var alertsComponent = IoCManager.Resolve().GetComponent(controlled.Value); Assert.NotNull(alertsComponent); // find the alertsui @@ -67,9 +69,9 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs await server.WaitAssertion(() => { - var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity; - Assert.NotNull(playerEnt); - var alertsComponent = playerEnt.GetComponent(); + var playerEnt = serverPlayerManager.Sessions.Single().AttachedEntity.GetValueOrDefault(); + Assert.That(playerEnt, Is.Not.EqualTo(default)); + var alertsComponent = IoCManager.Resolve().GetComponent(playerEnt); Assert.NotNull(alertsComponent); alertsComponent.ClearAlert(AlertType.Debug1); @@ -84,7 +86,7 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Mobs Assert.NotNull(local); var controlled = local.ControlledEntity; Assert.NotNull(controlled); - var alertsComponent = controlled.GetComponent(); + var alertsComponent = IoCManager.Resolve().GetComponent(controlled.Value); Assert.NotNull(alertsComponent); // find the alertsui diff --git a/Content.IntegrationTests/Tests/GameObjects/Components/Movement/ClimbUnitTest.cs b/Content.IntegrationTests/Tests/GameObjects/Components/Movement/ClimbUnitTest.cs index f1fad255fa..d70703b6bc 100644 --- a/Content.IntegrationTests/Tests/GameObjects/Components/Movement/ClimbUnitTest.cs +++ b/Content.IntegrationTests/Tests/GameObjects/Components/Movement/ClimbUnitTest.cs @@ -37,8 +37,8 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Movement var options = new ServerIntegrationOptions{ExtraPrototypes = Prototypes}; var server = StartServer(options); - IEntity human; - IEntity table; + EntityUid human; + EntityUid table; ClimbingComponent climbing; server.Assert(() => @@ -54,18 +54,17 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.Movement // Test for climb components existing // Players and tables should have these in their prototypes. - Assert.That(human.TryGetComponent(out climbing!), "Human has no climbing"); - Assert.That(table.TryGetComponent(out ClimbableComponent? _), "Table has no climbable"); + Assert.That(entityManager.TryGetComponent(human, out climbing), "Human has no climbing"); + Assert.That(entityManager.TryGetComponent(table, out ClimbableComponent? _), "Table has no climbable"); // Now let's make the player enter a climbing transitioning state. climbing.IsClimbing = true; - climbing.TryMoveTo(human.Transform.WorldPosition, table.Transform.WorldPosition); - var body = human.GetComponent(); + climbing.TryMoveTo(entityManager.GetComponent(human).WorldPosition, entityManager.GetComponent(table).WorldPosition); + var body = entityManager.GetComponent(human); // TODO: Check it's climbing // Force the player out of climb state. It should immediately remove the ClimbController. climbing.IsClimbing = false; - }); await server.WaitIdleAsync(); diff --git a/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs b/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs index dc27712f31..862c30d6fe 100644 --- a/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs +++ b/Content.IntegrationTests/Tests/Gravity/WeightlessStatusTests.cs @@ -1,11 +1,11 @@ using System.Threading.Tasks; using Content.Server.Gravity; using Content.Server.Gravity.EntitySystems; -using Content.Shared.Acts; using Content.Shared.Alert; using Content.Shared.Coordinates; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; namespace Content.IntegrationTests.Tests.Gravity @@ -43,7 +43,7 @@ namespace Content.IntegrationTests.Tests.Gravity var mapManager = server.ResolveDependency(); var entityManager = server.ResolveDependency(); - IEntity human = null; + EntityUid human = default; SharedAlertsComponent alerts = null; await server.WaitAssertion(() => @@ -52,7 +52,7 @@ namespace Content.IntegrationTests.Tests.Gravity var coordinates = grid.ToCoordinates(); human = entityManager.SpawnEntity("HumanDummy", coordinates); - Assert.True(human.TryGetComponent(out alerts)); + Assert.True(entityManager.TryGetComponent(human, out alerts)); }); // Let WeightlessSystem and GravitySystem tick @@ -63,7 +63,7 @@ namespace Content.IntegrationTests.Tests.Gravity // No gravity without a gravity generator Assert.True(alerts.IsShowingAlert(AlertType.Weightless)); - entityManager.SpawnEntity("GravityGeneratorDummy", human.Transform.Coordinates); + entityManager.SpawnEntity("GravityGeneratorDummy", entityManager.GetComponent(human).Coordinates); }); // Let WeightlessSystem and GravitySystem tick diff --git a/Content.IntegrationTests/Tests/GravityGridTest.cs b/Content.IntegrationTests/Tests/GravityGridTest.cs index d1e2a9c9c2..e9319200fc 100644 --- a/Content.IntegrationTests/Tests/GravityGridTest.cs +++ b/Content.IntegrationTests/Tests/GravityGridTest.cs @@ -33,7 +33,10 @@ namespace Content.IntegrationTests.Tests var options = new ServerIntegrationOptions{ExtraPrototypes = Prototypes}; var server = StartServer(options); - IEntity generator = null; + await server.WaitIdleAsync(); + + EntityUid generator = default; + var entityMan = server.ResolveDependency(); IMapGrid grid1 = null; IMapGrid grid2 = null; @@ -47,30 +50,27 @@ namespace Content.IntegrationTests.Tests grid1 = mapMan.CreateGrid(mapId); grid2 = mapMan.CreateGrid(mapId); - var entityMan = IoCManager.Resolve(); - generator = entityMan.SpawnEntity("GravityGeneratorDummy", grid2.ToCoordinates()); - Assert.That(generator.HasComponent()); - Assert.That(generator.HasComponent()); + Assert.That(entityMan.HasComponent(generator)); + Assert.That(entityMan.HasComponent(generator)); - var powerComponent = generator.GetComponent(); + var powerComponent = entityMan.GetComponent(generator); powerComponent.NeedsPower = false; }); server.RunTicks(1); server.Assert(() => { - var generatorComponent = generator.GetComponent(); - var powerComponent = generator.GetComponent(); + var generatorComponent = entityMan.GetComponent(generator); + var powerComponent = entityMan.GetComponent(generator); Assert.That(generatorComponent.GravityActive, Is.True); - var entityMan = IoCManager.Resolve(); - var grid1Entity = entityMan.GetEntity(grid1.GridEntityId); - var grid2Entity = entityMan.GetEntity(grid2.GridEntityId); + var grid1Entity = grid1.GridEntityId; + var grid2Entity = grid2.GridEntityId; - Assert.That(!grid1Entity.GetComponent().Enabled); - Assert.That(grid2Entity.GetComponent().Enabled); + Assert.That(!entityMan.GetComponent(grid1Entity).Enabled); + Assert.That(entityMan.GetComponent(grid2Entity).Enabled); // Re-enable needs power so it turns off again. // Charge rate is ridiculously high so it finishes in one tick. @@ -79,14 +79,13 @@ namespace Content.IntegrationTests.Tests server.RunTicks(1); server.Assert(() => { - var generatorComponent = generator.GetComponent(); + var generatorComponent = entityMan.GetComponent(generator); Assert.That(generatorComponent.GravityActive, Is.False); - var entityMan = IoCManager.Resolve(); - var grid2Entity = entityMan.GetEntity(grid2.GridEntityId); + var grid2Entity = grid2.GridEntityId; - Assert.That(grid2Entity.GetComponent().Enabled, Is.False); + Assert.That(entityMan.GetComponent(grid2Entity).Enabled, Is.False); }); await server.WaitIdleAsync(); diff --git a/Content.IntegrationTests/Tests/GridTileLookupTest.cs b/Content.IntegrationTests/Tests/GridTileLookupTest.cs index da9c90f947..38d0f125be 100644 --- a/Content.IntegrationTests/Tests/GridTileLookupTest.cs +++ b/Content.IntegrationTests/Tests/GridTileLookupTest.cs @@ -32,7 +32,7 @@ namespace Content.IntegrationTests.Tests server.Assert(() => { - List entities; + List entities; var mapOne = mapManager.CreateMap(); var gridOne = mapManager.CreateGrid(mapOne); diff --git a/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs b/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs index ce62679255..98dfd08c07 100644 --- a/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs +++ b/Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs @@ -61,10 +61,10 @@ namespace Content.IntegrationTests.Tests var options = new ServerIntegrationOptions{ExtraPrototypes = Prototypes}; var server = StartServer(options); - IEntity human = null; - IEntity uniform = null; - IEntity idCard = null; - IEntity pocketItem = null; + EntityUid human = default; + EntityUid uniform = default; + EntityUid idCard = default; + EntityUid pocketItem = default; InventoryComponent inventory = null; server.Assert(() => @@ -81,7 +81,7 @@ namespace Content.IntegrationTests.Tests pocketItem = entityMan.SpawnEntity("FlashlightDummy", MapCoordinates.Nullspace); var tooBigItem = entityMan.SpawnEntity("ToolboxDummy", MapCoordinates.Nullspace); - inventory = human.GetComponent(); + inventory = entityMan.GetComponent(human); Assert.That(inventory.CanEquip(Slots.INNERCLOTHING, uniform)); @@ -121,9 +121,9 @@ namespace Content.IntegrationTests.Tests await server.WaitIdleAsync(); } - private static bool IsDescendant(IEntity descendant, IEntity parent) + private static bool IsDescendant(EntityUid descendant, EntityUid parent) { - var tmpParent = descendant.Transform.Parent; + var tmpParent = IoCManager.Resolve().GetComponent(descendant).Parent; while (tmpParent != null) { if (tmpParent.Owner == parent) diff --git a/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs b/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs index ee1e5cc6f2..50f8b25c2d 100644 --- a/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs +++ b/Content.IntegrationTests/Tests/Interaction/Click/InteractionSystemTests.cs @@ -49,7 +49,7 @@ namespace Content.IntegrationTests.Tests.Interaction.Click await server.WaitIdleAsync(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); var mapManager = server.ResolveDependency(); var mapId = MapId.Nullspace; @@ -61,16 +61,16 @@ namespace Content.IntegrationTests.Tests.Interaction.Click }); await server.WaitIdleAsync(); - IEntity user = null; - IEntity target = null; - IEntity item = null; + EntityUid user = default; + EntityUid target = default; + EntityUid item = default; server.Assert(() => { - user = entityManager.SpawnEntity(null, coords); + user = sEntities.SpawnEntity(null, coords); user.EnsureComponent().AddHand("hand", HandLocation.Left); - target = entityManager.SpawnEntity(null, coords); - item = entityManager.SpawnEntity(null, coords); + target = sEntities.SpawnEntity(null, coords); + item = sEntities.SpawnEntity(null, coords); item.EnsureComponent(); }); @@ -85,20 +85,20 @@ namespace Content.IntegrationTests.Tests.Interaction.Click var interactHand = false; server.Assert(() => { - testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target.Uid)); attack = true; }; + testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; }; testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; - interactionSystem.DoAttack(user, target.Transform.Coordinates, false, target.Uid); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.DoAttack(user, sEntities.GetComponent(target).Coordinates, false, target); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(attack); Assert.That(interactUsing, Is.False); Assert.That(interactHand); - Assert.That(user.TryGetComponent(out var hands)); - Assert.That(hands.PutInHand(item.GetComponent())); + Assert.That(sEntities.TryGetComponent(user, out var hands)); + Assert.That(hands.PutInHand(sEntities.GetComponent(item))); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(interactUsing); }); @@ -119,7 +119,7 @@ namespace Content.IntegrationTests.Tests.Interaction.Click await server.WaitIdleAsync(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); var mapManager = server.ResolveDependency(); var mapId = MapId.Nullspace; @@ -131,19 +131,19 @@ namespace Content.IntegrationTests.Tests.Interaction.Click }); await server.WaitIdleAsync(); - IEntity user = null; - IEntity target = null; - IEntity item = null; - IEntity wall = null; + EntityUid user = default; + EntityUid target = default; + EntityUid item = default; + EntityUid wall = default; server.Assert(() => { - user = entityManager.SpawnEntity(null, coords); + user = sEntities.SpawnEntity(null, coords); user.EnsureComponent().AddHand("hand", HandLocation.Left); - target = entityManager.SpawnEntity(null, new MapCoordinates((1.9f, 0), mapId)); - item = entityManager.SpawnEntity(null, coords); + target = sEntities.SpawnEntity(null, new MapCoordinates((1.9f, 0), mapId)); + item = sEntities.SpawnEntity(null, coords); item.EnsureComponent(); - wall = entityManager.SpawnEntity("DummyDebugWall", new MapCoordinates((1, 0), user.Transform.MapID)); + wall = sEntities.SpawnEntity("DummyDebugWall", new MapCoordinates((1, 0), sEntities.GetComponent(user).MapID)); }); await server.WaitRunTicks(1); @@ -157,20 +157,20 @@ namespace Content.IntegrationTests.Tests.Interaction.Click var interactHand = false; server.Assert(() => { - testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target.Uid)); attack = true; }; + testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; }; testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; - interactionSystem.DoAttack(user, target.Transform.Coordinates, false, target.Uid); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.DoAttack(user, sEntities.GetComponent(target).Coordinates, false, target); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(attack, Is.False); Assert.That(interactUsing, Is.False); Assert.That(interactHand, Is.False); - Assert.That(user.TryGetComponent(out var hands)); - Assert.That(hands.PutInHand(item.GetComponent())); + Assert.That(sEntities.TryGetComponent(user, out var hands)); + Assert.That(hands.PutInHand(sEntities.GetComponent(item))); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(interactUsing, Is.False); }); @@ -190,7 +190,7 @@ namespace Content.IntegrationTests.Tests.Interaction.Click await server.WaitIdleAsync(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); var mapManager = server.ResolveDependency(); var mapId = MapId.Nullspace; @@ -202,16 +202,16 @@ namespace Content.IntegrationTests.Tests.Interaction.Click }); await server.WaitIdleAsync(); - IEntity user = null; - IEntity target = null; - IEntity item = null; + EntityUid user = default; + EntityUid target = default; + EntityUid item = default; server.Assert(() => { - user = entityManager.SpawnEntity(null, coords); + user = sEntities.SpawnEntity(null, coords); user.EnsureComponent().AddHand("hand", HandLocation.Left); - target = entityManager.SpawnEntity(null, new MapCoordinates((InteractionSystem.InteractionRange - 0.1f, 0), mapId)); - item = entityManager.SpawnEntity(null, coords); + target = sEntities.SpawnEntity(null, new MapCoordinates((InteractionSystem.InteractionRange - 0.1f, 0), mapId)); + item = sEntities.SpawnEntity(null, coords); item.EnsureComponent(); }); @@ -226,20 +226,20 @@ namespace Content.IntegrationTests.Tests.Interaction.Click var interactHand = false; server.Assert(() => { - testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target.Uid)); attack = true; }; + testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; }; testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; - interactionSystem.DoAttack(user, target.Transform.Coordinates, false, target.Uid); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.DoAttack(user, sEntities.GetComponent(target).Coordinates, false, target); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(attack); Assert.That(interactUsing, Is.False); Assert.That(interactHand); - Assert.That(user.TryGetComponent(out var hands)); - Assert.That(hands.PutInHand(item.GetComponent())); + Assert.That(sEntities.TryGetComponent(user, out var hands)); + Assert.That(hands.PutInHand(sEntities.GetComponent(item))); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(interactUsing); }); @@ -260,7 +260,7 @@ namespace Content.IntegrationTests.Tests.Interaction.Click await server.WaitIdleAsync(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); var mapManager = server.ResolveDependency(); var mapId = MapId.Nullspace; @@ -272,16 +272,16 @@ namespace Content.IntegrationTests.Tests.Interaction.Click }); await server.WaitIdleAsync(); - IEntity user = null; - IEntity target = null; - IEntity item = null; + EntityUid user = default; + EntityUid target = default; + EntityUid item = default; server.Assert(() => { - user = entityManager.SpawnEntity(null, coords); + user = sEntities.SpawnEntity(null, coords); user.EnsureComponent().AddHand("hand", HandLocation.Left); - target = entityManager.SpawnEntity(null, new MapCoordinates((InteractionSystem.InteractionRange, 0), mapId)); - item = entityManager.SpawnEntity(null, coords); + target = sEntities.SpawnEntity(null, new MapCoordinates((InteractionSystem.InteractionRange, 0), mapId)); + item = sEntities.SpawnEntity(null, coords); item.EnsureComponent(); }); @@ -296,20 +296,20 @@ namespace Content.IntegrationTests.Tests.Interaction.Click var interactHand = false; server.Assert(() => { - testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target.Uid)); attack = true; }; + testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(target)); attack = true; }; testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactUsing = true; }; testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(target)); interactHand = true; }; - interactionSystem.DoAttack(user, target.Transform.Coordinates, false, target.Uid); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.DoAttack(user, sEntities.GetComponent(target).Coordinates, false, target); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(attack, Is.False); Assert.That(interactUsing, Is.False); Assert.That(interactHand, Is.False); - Assert.That(user.TryGetComponent(out var hands)); - Assert.That(hands.PutInHand(item.GetComponent())); + Assert.That(sEntities.TryGetComponent(user, out var hands)); + Assert.That(hands.PutInHand(sEntities.GetComponent(item))); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(interactUsing, Is.False); }); @@ -330,7 +330,7 @@ namespace Content.IntegrationTests.Tests.Interaction.Click await server.WaitIdleAsync(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); var mapManager = server.ResolveDependency(); var mapId = MapId.Nullspace; @@ -342,21 +342,21 @@ namespace Content.IntegrationTests.Tests.Interaction.Click }); await server.WaitIdleAsync(); - IEntity user = null; - IEntity target = null; - IEntity item = null; - IEntity containerEntity = null; + EntityUid user = default; + EntityUid target = default; + EntityUid item = default; + EntityUid containerEntity = default; IContainer container = null; server.Assert(() => { - user = entityManager.SpawnEntity(null, coords); + user = sEntities.SpawnEntity(null, coords); user.EnsureComponent().AddHand("hand", HandLocation.Left); - target = entityManager.SpawnEntity(null, coords); - item = entityManager.SpawnEntity(null, coords); + target = sEntities.SpawnEntity(null, coords); + item = sEntities.SpawnEntity(null, coords); item.EnsureComponent(); - containerEntity = entityManager.SpawnEntity(null, coords); - container = ContainerHelpers.EnsureContainer(containerEntity, "InteractionTestContainer"); + containerEntity = sEntities.SpawnEntity(null, coords); + container = containerEntity.EnsureContainer("InteractionTestContainer"); }); await server.WaitRunTicks(1); @@ -373,31 +373,31 @@ namespace Content.IntegrationTests.Tests.Interaction.Click server.Assert(() => { Assert.That(container.Insert(user)); - Assert.That(user.Transform.Parent.Owner, Is.EqualTo(containerEntity)); + Assert.That(sEntities.GetComponent(user).Parent.Owner, Is.EqualTo(containerEntity)); - testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity.Uid)); attack = true; }; + testInteractionSystem.AttackEvent = (_, _, ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); attack = true; }; testInteractionSystem.InteractUsingEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactUsing = true; }; testInteractionSystem.InteractHandEvent = (ev) => { Assert.That(ev.Target, Is.EqualTo(containerEntity)); interactHand = true; }; - interactionSystem.DoAttack(user, target.Transform.Coordinates, false, target.Uid); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.DoAttack(user, sEntities.GetComponent(target).Coordinates, false, target); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(attack, Is.False); Assert.That(interactUsing, Is.False); Assert.That(interactHand, Is.False); - interactionSystem.DoAttack(user, containerEntity.Transform.Coordinates, false, containerEntity.Uid); - interactionSystem.UserInteraction(user, containerEntity.Transform.Coordinates, containerEntity.Uid); + interactionSystem.DoAttack(user, sEntities.GetComponent(containerEntity).Coordinates, false, containerEntity); + interactionSystem.UserInteraction(user, sEntities.GetComponent(containerEntity).Coordinates, containerEntity); Assert.That(attack); Assert.That(interactUsing, Is.False); Assert.That(interactHand); - Assert.That(user.TryGetComponent(out var hands)); - Assert.That(hands.PutInHand(item.GetComponent())); + Assert.That(sEntities.TryGetComponent(user, out var hands)); + Assert.That(hands.PutInHand(sEntities.GetComponent(item))); - interactionSystem.UserInteraction(user, target.Transform.Coordinates, target.Uid); + interactionSystem.UserInteraction(user, sEntities.GetComponent(target).Coordinates, target); Assert.That(interactUsing, Is.False); - interactionSystem.UserInteraction(user, containerEntity.Transform.Coordinates, containerEntity.Uid); + interactionSystem.UserInteraction(user, sEntities.GetComponent(containerEntity).Coordinates, containerEntity); Assert.That(interactUsing, Is.True); }); diff --git a/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs b/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs index 1f773108f2..f09b7f2e78 100644 --- a/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs +++ b/Content.IntegrationTests/Tests/Interaction/InRangeUnobstructed.cs @@ -5,6 +5,7 @@ using Content.Shared.Interaction.Helpers; using NUnit.Framework; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; @@ -33,11 +34,11 @@ namespace Content.IntegrationTests.Tests.Interaction await server.WaitIdleAsync(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); var mapManager = server.ResolveDependency(); - IEntity origin = null; - IEntity other = null; + EntityUid origin = default; + EntityUid other = default; IContainer container = null; IComponent component = null; EntityCoordinates entityCoordinates = default; @@ -48,12 +49,12 @@ namespace Content.IntegrationTests.Tests.Interaction var mapId = mapManager.CreateMap(); var coordinates = new MapCoordinates(Vector2.Zero, mapId); - origin = entityManager.SpawnEntity(HumanId, coordinates); - other = entityManager.SpawnEntity(HumanId, coordinates); - container = ContainerHelpers.EnsureContainer(other, "InRangeUnobstructedTestOtherContainer"); - component = other.Transform; - entityCoordinates = other.Transform.Coordinates; - mapCoordinates = other.Transform.MapPosition; + origin = sEntities.SpawnEntity(HumanId, coordinates); + other = sEntities.SpawnEntity(HumanId, coordinates); + container = other.EnsureContainer("InRangeUnobstructedTestOtherContainer"); + component = sEntities.GetComponent(other); + entityCoordinates = sEntities.GetComponent(other).Coordinates; + mapCoordinates = sEntities.GetComponent(other).MapPosition; }); await server.WaitIdleAsync(); @@ -82,7 +83,7 @@ namespace Content.IntegrationTests.Tests.Interaction // Move them slightly apart - origin.Transform.LocalPosition += _interactionRangeDivided15X; + sEntities.GetComponent(origin).LocalPosition += _interactionRangeDivided15X; // Entity <-> Entity Assert.True(origin.InRangeUnobstructed(other)); @@ -106,7 +107,7 @@ namespace Content.IntegrationTests.Tests.Interaction // Move them out of range - origin.Transform.LocalPosition += _interactionRangeDivided15X; + sEntities.GetComponent(origin).LocalPosition += _interactionRangeDivided15X; // Entity <-> Entity Assert.False(origin.InRangeUnobstructed(other)); diff --git a/Content.IntegrationTests/Tests/InventoryHelpersTest.cs b/Content.IntegrationTests/Tests/InventoryHelpersTest.cs index e953f4555d..bc7985020b 100644 --- a/Content.IntegrationTests/Tests/InventoryHelpersTest.cs +++ b/Content.IntegrationTests/Tests/InventoryHelpersTest.cs @@ -49,19 +49,21 @@ namespace Content.IntegrationTests.Tests var options = new ServerIntegrationOptions {ExtraPrototypes = Prototypes}; var server = StartServer(options); - IEntity human = null; + await server.WaitIdleAsync(); + + var sEntities = server.ResolveDependency(); + + EntityUid human = default; InventoryComponent inventory = null; - server.Assert(() => + await server.WaitAssertion(() => { var mapMan = IoCManager.Resolve(); mapMan.CreateNewMapEntity(MapId.Nullspace); - var entityMan = IoCManager.Resolve(); - - human = entityMan.SpawnEntity("InventoryStunnableDummy", MapCoordinates.Nullspace); - inventory = human.GetComponent(); + human = sEntities.SpawnEntity("InventoryStunnableDummy", MapCoordinates.Nullspace); + inventory = sEntities.GetComponent(human); // Can't do the test if this human doesn't have the slots for it. Assert.That(inventory.HasSlot(Slots.INNERCLOTHING)); @@ -71,9 +73,12 @@ namespace Content.IntegrationTests.Tests // Do we actually have the uniform equipped? Assert.That(inventory.TryGetSlotItem(Slots.INNERCLOTHING, out ItemComponent uniform)); - Assert.That(uniform.Owner.Prototype != null && uniform.Owner.Prototype.ID == "InventoryJumpsuitJanitorDummy"); + Assert.That(sEntities.GetComponent(uniform.Owner).EntityPrototype is + { + ID: "InventoryJumpsuitJanitorDummy" + }); - EntitySystem.Get().TryStun(human.Uid, TimeSpan.FromSeconds(1f), true); + EntitySystem.Get().TryStun(human, TimeSpan.FromSeconds(1f), true); // Since the mob is stunned, they can't equip this. Assert.That(inventory.SpawnItemInSlot(Slots.IDCARD, "InventoryIDCardDummy", true), Is.False); @@ -84,10 +89,11 @@ namespace Content.IntegrationTests.Tests // Let's try skipping the interaction check and see if it equips it! Assert.That(inventory.SpawnItemInSlot(Slots.IDCARD, "InventoryIDCardDummy")); Assert.That(inventory.TryGetSlotItem(Slots.IDCARD, out ItemComponent id)); - Assert.That(id.Owner.Prototype != null && id.Owner.Prototype.ID == "InventoryIDCardDummy"); + Assert.That(sEntities.GetComponent(id.Owner).EntityPrototype is + { + ID: "InventoryIDCardDummy" + }); }); - - await server.WaitIdleAsync(); } } } diff --git a/Content.IntegrationTests/Tests/MindEntityDeletionTest.cs b/Content.IntegrationTests/Tests/MindEntityDeletionTest.cs index f63a7d100a..fea9d938f9 100644 --- a/Content.IntegrationTests/Tests/MindEntityDeletionTest.cs +++ b/Content.IntegrationTests/Tests/MindEntityDeletionTest.cs @@ -20,25 +20,25 @@ namespace Content.IntegrationTests.Tests { var (_, server) = await StartConnectedServerDummyTickerClientPair(); - IEntity playerEnt = null; - IEntity visitEnt = null; + var entMan = server.ResolveDependency(); + EntityUid playerEnt = default; + EntityUid visitEnt = default; Mind mind = null; server.Assert(() => { var player = IoCManager.Resolve().ServerSessions.Single(); var mapMan = IoCManager.Resolve(); - var entMgr = IoCManager.Resolve(); mapMan.CreateNewMapEntity(MapId.Nullspace); - playerEnt = entMgr.SpawnEntity(null, MapCoordinates.Nullspace); - visitEnt = entMgr.SpawnEntity(null, MapCoordinates.Nullspace); + playerEnt = entMan.SpawnEntity(null, MapCoordinates.Nullspace); + visitEnt = entMan.SpawnEntity(null, MapCoordinates.Nullspace); mind = new Mind(player.UserId); mind.ChangeOwningPlayer(player.UserId); - mind.TransferTo(playerEnt.Uid); + mind.TransferTo(playerEnt); mind.Visit(visitEnt); Assert.That(player.AttachedEntity, Is.EqualTo(visitEnt)); @@ -49,12 +49,12 @@ namespace Content.IntegrationTests.Tests server.Assert(() => { - visitEnt.Delete(); + entMan.DeleteEntity(visitEnt); - Assert.That(mind.VisitingEntity, Is.Null); + Assert.That(mind.VisitingEntity, Is.EqualTo(default)); // This used to throw so make sure it doesn't. - playerEnt.Delete(); + entMan.DeleteEntity(playerEnt); }); await server.WaitIdleAsync(); @@ -66,23 +66,23 @@ namespace Content.IntegrationTests.Tests // Has to be a non-dummy ticker so we have a proper map. var (_, server) = await StartConnectedServerClientPair(); - IEntity playerEnt = null; + var entMan = server.ResolveDependency(); + EntityUid playerEnt = default; Mind mind = null; server.Assert(() => { var player = IoCManager.Resolve().ServerSessions.Single(); var mapMan = IoCManager.Resolve(); - var entMgr = IoCManager.Resolve(); mapMan.CreateNewMapEntity(MapId.Nullspace); - playerEnt = entMgr.SpawnEntity(null, MapCoordinates.Nullspace); + playerEnt = entMan.SpawnEntity(null, MapCoordinates.Nullspace); mind = new Mind(player.UserId); mind.ChangeOwningPlayer(player.UserId); - mind.TransferTo(playerEnt.Uid); + mind.TransferTo(playerEnt); Assert.That(mind.CurrentEntity, Is.EqualTo(playerEnt)); }); @@ -91,14 +91,14 @@ namespace Content.IntegrationTests.Tests server.Post(() => { - playerEnt.Delete(); + entMan.DeleteEntity(playerEnt); }); server.RunTicks(1); server.Assert(() => { - Assert.That(mind.CurrentEntity.IsValid(), Is.True); + Assert.That(entMan.EntityExists(mind.CurrentEntity!.Value), Is.True); }); await server.WaitIdleAsync(); @@ -110,7 +110,7 @@ namespace Content.IntegrationTests.Tests // Has to be a non-dummy ticker so we have a proper map. var (_, server) = await StartConnectedServerClientPair(); - IEntity playerEnt = null; + EntityUid playerEnt = default; Mind mind = null; MapId map = default; server.Assert(() => @@ -131,7 +131,7 @@ namespace Content.IntegrationTests.Tests mind = new Mind(player.UserId); mind.ChangeOwningPlayer(player.UserId); - mind.TransferTo(playerEnt.Uid); + mind.TransferTo(playerEnt); Assert.That(mind.CurrentEntity, Is.EqualTo(playerEnt)); }); @@ -149,7 +149,7 @@ namespace Content.IntegrationTests.Tests server.Assert(() => { - Assert.That(mind.CurrentEntity.IsValid(), Is.True); + Assert.That(IoCManager.Resolve().EntityExists(mind.CurrentEntity!.Value), Is.True); Assert.That(mind.CurrentEntity, Is.Not.EqualTo(playerEnt)); }); diff --git a/Content.IntegrationTests/Tests/Networking/ConnectTest.cs b/Content.IntegrationTests/Tests/Networking/ConnectTest.cs index 857397e6b3..ced087aa57 100644 --- a/Content.IntegrationTests/Tests/Networking/ConnectTest.cs +++ b/Content.IntegrationTests/Tests/Networking/ConnectTest.cs @@ -55,7 +55,7 @@ namespace Content.IntegrationTests.Tests.Networking var clEntityManager = client.ResolveDependency(); var svEntityManager = server.ResolveDependency(); - var lastSvEntity = svEntityManager.GetEntities().Last().Uid; + var lastSvEntity = svEntityManager.GetEntities().Last(); Assert.That(clEntityManager.GetComponent(lastSvEntity).Coordinates, Is.EqualTo(svEntityManager.GetComponent(lastSvEntity).Coordinates)); diff --git a/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs b/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs index 58a0bd7a5e..9a31a29f44 100644 --- a/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs +++ b/Content.IntegrationTests/Tests/Networking/SimplePredictReconcileTest.cs @@ -12,7 +12,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.GameStates; using Robust.Shared.IoC; using Robust.Shared.Map; -using Robust.Shared.Players; using Robust.Shared.Reflection; using Robust.Shared.Serialization; using Robust.Shared.Timing; @@ -77,7 +76,7 @@ namespace Content.IntegrationTests.Tests.Networking var cGameTiming = client.ResolveDependency(); var cGameStateManager = client.ResolveDependency(); - IEntity serverEnt = default!; + EntityUid serverEnt = default; PredictionTestComponent serverComponent = default!; PredictionTestComponent clientComponent = default!; @@ -92,7 +91,7 @@ namespace Content.IntegrationTests.Tests.Networking var map = sMapManager.CreateMap(); var player = sPlayerManager.ServerSessions.Single(); serverEnt = sEntityManager.SpawnEntity(null, new MapCoordinates((0, 0), map)); - serverComponent = serverEnt.AddComponent(); + serverComponent = IoCManager.Resolve().AddComponent(serverEnt); // Make client "join game" so they receive game state updates. player.JoinGame(); @@ -112,8 +111,7 @@ namespace Content.IntegrationTests.Tests.Networking await client.WaitPost(() => { - clientComponent = cEntityManager.GetEntity(serverEnt.Uid) - .GetComponent(); + clientComponent = cEntityManager.GetComponent(serverEnt); }); Assert.That(clientComponent.Foo, Is.False); @@ -137,7 +135,7 @@ namespace Content.IntegrationTests.Tests.Networking { await client.WaitPost(() => { - cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt.Uid, true)); + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true)); Assert.That(clientComponent.Foo, Is.True); }); @@ -209,7 +207,7 @@ namespace Content.IntegrationTests.Tests.Networking // Send event to server to change flag again, this time to disable it.. await client.WaitPost(() => { - cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt.Uid, false)); + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false)); Assert.That(clientComponent.Foo, Is.False); }); @@ -280,7 +278,7 @@ namespace Content.IntegrationTests.Tests.Networking // Send first event to disable the flag (reminder: it never got accepted by the server). await client.WaitPost(() => { - cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt.Uid, false)); + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false)); Assert.That(clientComponent.Foo, Is.False); }); @@ -308,7 +306,7 @@ namespace Content.IntegrationTests.Tests.Networking // Send another event, to re-enable it. await client.WaitPost(() => { - cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt.Uid, true)); + cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true)); Assert.That(clientComponent.Foo, Is.True); }); @@ -456,8 +454,7 @@ namespace Content.IntegrationTests.Tests.Networking private void HandleMessage(SetFooMessage message, EntitySessionEventArgs args) { - var entity = EntityManager.GetEntity(message.Uid); - var component = entity.GetComponent(); + var component = IoCManager.Resolve().GetComponent(message.Uid); var old = component.Foo; if (Allow) { diff --git a/Content.IntegrationTests/Tests/PDA/PDAExtensionsTests.cs b/Content.IntegrationTests/Tests/PDA/PDAExtensionsTests.cs index 18ba577046..fa3c862397 100644 --- a/Content.IntegrationTests/Tests/PDA/PDAExtensionsTests.cs +++ b/Content.IntegrationTests/Tests/PDA/PDAExtensionsTests.cs @@ -59,9 +59,9 @@ namespace Content.IntegrationTests.Tests.PDA await server.WaitAssertion(() => { - var player = sPlayerManager.Sessions.Single().AttachedEntity; + var player = sPlayerManager.Sessions.Single().AttachedEntity.GetValueOrDefault(); - Assert.NotNull(player); + Assert.That(player != default); // The player spawns with an ID on by default Assert.NotNull(player.GetHeldId()); @@ -69,16 +69,16 @@ namespace Content.IntegrationTests.Tests.PDA Assert.NotNull(id); // Put PDA in hand - var dummyPda = sEntityManager.SpawnEntity(PdaDummy, player.Transform.MapPosition); - var pdaItemComponent = dummyPda.GetComponent(); - player.GetComponent().PutInHand(pdaItemComponent); + var dummyPda = sEntityManager.SpawnEntity(PdaDummy, sEntityManager.GetComponent(player).MapPosition); + var pdaItemComponent = sEntityManager.GetComponent(dummyPda); + sEntityManager.GetComponent(player).PutInHand(pdaItemComponent); - var pdaComponent = dummyPda.GetComponent(); - var pdaIdCard = sEntityManager.SpawnEntity(IdCardDummy, player.Transform.MapPosition); + var pdaComponent = sEntityManager.GetComponent(dummyPda); + var pdaIdCard = sEntityManager.SpawnEntity(IdCardDummy, sEntityManager.GetComponent(player).MapPosition); - var itemSlots = dummyPda.GetComponent(); + var itemSlots = sEntityManager.GetComponent(dummyPda); sEntityManager.EntitySysManager.GetEntitySystem() - .TryInsert(dummyPda.Uid, pdaComponent.IdSlot, pdaIdCard); + .TryInsert(dummyPda, pdaComponent.IdSlot, pdaIdCard); var pdaContainedId = pdaComponent.ContainedID; // The PDA in the hand should be found first @@ -89,11 +89,11 @@ namespace Content.IntegrationTests.Tests.PDA Assert.That(id, Is.EqualTo(pdaContainedId)); // Put ID card in hand - var idDummy = sEntityManager.SpawnEntity(IdCardDummy, player.Transform.MapPosition); - var idItemComponent = idDummy.GetComponent(); - player.GetComponent().PutInHand(idItemComponent); + var idDummy = sEntityManager.SpawnEntity(IdCardDummy, sEntityManager.GetComponent(player).MapPosition); + var idItemComponent = sEntityManager.GetComponent(idDummy); + sEntityManager.GetComponent(player).PutInHand(idItemComponent); - var idCardComponent = idDummy.GetComponent(); + var idCardComponent = sEntityManager.GetComponent(idDummy); // The ID in the hand should be found first Assert.NotNull(player.GetHeldId()); @@ -102,7 +102,7 @@ namespace Content.IntegrationTests.Tests.PDA Assert.That(id, Is.EqualTo(idCardComponent)); // Remove all IDs and PDAs - var inventory = player.GetComponent(); + var inventory = sEntityManager.GetComponent(player); foreach (var slot in inventory.Slots) { @@ -113,13 +113,13 @@ namespace Content.IntegrationTests.Tests.PDA continue; } - if (item.Owner.HasComponent()) + if (sEntityManager.HasComponent(item.Owner)) { inventory.ForceUnequip(slot); } } - var hands = player.GetComponent(); + var hands = sEntityManager.GetComponent(player); hands.Drop(dummyPda, false); hands.Drop(idDummy, false); diff --git a/Content.IntegrationTests/Tests/Power/PowerTest.cs b/Content.IntegrationTests/Tests/Power/PowerTest.cs index 759f61f425..e171b2aca3 100644 --- a/Content.IntegrationTests/Tests/Power/PowerTest.cs +++ b/Content.IntegrationTests/Tests/Power/PowerTest.cs @@ -8,6 +8,7 @@ using Content.Server.Power.Nodes; using Content.Shared.Coordinates; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Timing; @@ -204,9 +205,9 @@ namespace Content.IntegrationTests.Tests.Power var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 1)); var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2)); - supplier = generatorEnt.GetComponent(); - consumer1 = consumerEnt1.GetComponent(); - consumer2 = consumerEnt2.GetComponent(); + supplier = _entityManager.GetComponent(generatorEnt); + consumer1 = _entityManager.GetComponent(consumerEnt1); + consumer2 = _entityManager.GetComponent(consumerEnt2); // Plenty of surplus and tolerance supplier.MaxSupply = loadPower * 4; @@ -258,9 +259,9 @@ namespace Content.IntegrationTests.Tests.Power var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 1)); var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2)); - supplier = generatorEnt.GetComponent(); - consumer1 = consumerEnt1.GetComponent(); - consumer2 = consumerEnt2.GetComponent(); + supplier = _entityManager.GetComponent(generatorEnt); + consumer1 = _entityManager.GetComponent(consumerEnt1); + consumer2 = _entityManager.GetComponent(consumerEnt2); // Too little supply, both consumers should get 33% power. supplier.MaxSupply = loadPower; @@ -305,8 +306,8 @@ namespace Content.IntegrationTests.Tests.Power var generatorEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates()); var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2)); - supplier = generatorEnt.GetComponent(); - consumer = consumerEnt.GetComponent(); + supplier = _entityManager.GetComponent(generatorEnt); + consumer = _entityManager.GetComponent(consumerEnt); // Supply has enough total power but needs to ramp up to match. supplier.MaxSupply = 400; @@ -375,9 +376,9 @@ namespace Content.IntegrationTests.Tests.Power var generatorEnt = _entityManager.SpawnEntity("DischargingBatteryDummy", grid.ToCoordinates()); var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 2)); - netBattery = generatorEnt.GetComponent(); - battery = generatorEnt.GetComponent(); - consumer = consumerEnt.GetComponent(); + netBattery = _entityManager.GetComponent(generatorEnt); + battery = _entityManager.GetComponent(generatorEnt); + consumer = _entityManager.GetComponent(consumerEnt); battery.MaxCharge = startingCharge; battery.CurrentCharge = startingCharge; @@ -453,9 +454,9 @@ namespace Content.IntegrationTests.Tests.Power var generatorEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates()); var batteryEnt = _entityManager.SpawnEntity("ChargingBatteryDummy", grid.ToCoordinates(0, 2)); - supplier = generatorEnt.GetComponent(); - var netBattery = batteryEnt.GetComponent(); - battery = batteryEnt.GetComponent(); + supplier = _entityManager.GetComponent(generatorEnt); + var netBattery = _entityManager.GetComponent(batteryEnt); + battery = _entityManager.GetComponent(batteryEnt); supplier.MaxSupply = 500; supplier.SupplyRampTolerance = 500; @@ -498,16 +499,16 @@ namespace Content.IntegrationTests.Tests.Power } var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1)); - terminal.Transform.LocalRotation = Angle.FromDegrees(180); + _entityManager.GetComponent(terminal).LocalRotation = Angle.FromDegrees(180); var batteryEnt = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2)); var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 0)); var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 3)); - consumer = consumerEnt.GetComponent(); - supplier = supplyEnt.GetComponent(); - netBattery = batteryEnt.GetComponent(); - battery = batteryEnt.GetComponent(); + consumer = _entityManager.GetComponent(consumerEnt); + supplier = _entityManager.GetComponent(supplyEnt); + netBattery = _entityManager.GetComponent(batteryEnt); + battery = _entityManager.GetComponent(batteryEnt); // Consumer needs 1000 W, supplier can only provide 800, battery fills in the remaining 200. consumer.DrawRate = 1000; @@ -566,16 +567,16 @@ namespace Content.IntegrationTests.Tests.Power } var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1)); - terminal.Transform.LocalRotation = Angle.FromDegrees(180); + _entityManager.GetComponent(terminal).LocalRotation = Angle.FromDegrees(180); var batteryEnt = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2)); var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 0)); var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 3)); - consumer = consumerEnt.GetComponent(); - supplier = supplyEnt.GetComponent(); - netBattery = batteryEnt.GetComponent(); - battery = batteryEnt.GetComponent(); + consumer = _entityManager.GetComponent(consumerEnt); + supplier = _entityManager.GetComponent(supplyEnt); + netBattery = _entityManager.GetComponent(batteryEnt); + battery = _entityManager.GetComponent(batteryEnt); // Consumer needs 1000 W, supply and battery can only provide 400 each. // BUT the battery has 50% input efficiency, so 50% of the power of the supply gets lost. @@ -642,7 +643,7 @@ namespace Content.IntegrationTests.Tests.Power _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2)); var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2)); - terminal.Transform.LocalRotation = Angle.FromDegrees(180); + _entityManager.GetComponent(terminal).LocalRotation = Angle.FromDegrees(180); var batteryEnt1 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 1)); var batteryEnt2 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 3)); @@ -650,13 +651,13 @@ namespace Content.IntegrationTests.Tests.Power var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 0)); var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 4)); - consumer1 = consumerEnt1.GetComponent(); - consumer2 = consumerEnt2.GetComponent(); - supplier = supplyEnt.GetComponent(); - var netBattery1 = batteryEnt1.GetComponent(); - var netBattery2 = batteryEnt2.GetComponent(); - var battery1 = batteryEnt1.GetComponent(); - var battery2 = batteryEnt2.GetComponent(); + consumer1 = _entityManager.GetComponent(consumerEnt1); + consumer2 = _entityManager.GetComponent(consumerEnt2); + supplier = _entityManager.GetComponent(supplyEnt); + var netBattery1 = _entityManager.GetComponent(batteryEnt1); + var netBattery2 = _entityManager.GetComponent(batteryEnt2); + var battery1 = _entityManager.GetComponent(batteryEnt1); + var battery2 = _entityManager.GetComponent(batteryEnt2); // There are two loads, 500 W and 1000 W respectively. // The 500 W load is behind a 50% efficient battery, @@ -729,7 +730,7 @@ namespace Content.IntegrationTests.Tests.Power _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2)); var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 2)); - terminal.Transform.LocalRotation = Angle.FromDegrees(180); + _entityManager.GetComponent(terminal).LocalRotation = Angle.FromDegrees(180); var batteryEnt1 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 1)); var batteryEnt2 = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 3)); @@ -737,13 +738,13 @@ namespace Content.IntegrationTests.Tests.Power var consumerEnt1 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 0)); var consumerEnt2 = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 4)); - consumer1 = consumerEnt1.GetComponent(); - consumer2 = consumerEnt2.GetComponent(); - supplier = supplyEnt.GetComponent(); - var netBattery1 = batteryEnt1.GetComponent(); - var netBattery2 = batteryEnt2.GetComponent(); - var battery1 = batteryEnt1.GetComponent(); - var battery2 = batteryEnt2.GetComponent(); + consumer1 = _entityManager.GetComponent(consumerEnt1); + consumer2 = _entityManager.GetComponent(consumerEnt2); + supplier = _entityManager.GetComponent(supplyEnt); + var netBattery1 = _entityManager.GetComponent(batteryEnt1); + var netBattery2 = _entityManager.GetComponent(batteryEnt2); + var battery1 = _entityManager.GetComponent(batteryEnt1); + var battery2 = _entityManager.GetComponent(batteryEnt2); consumer1.DrawRate = 500; consumer2.DrawRate = 1000; @@ -799,16 +800,16 @@ namespace Content.IntegrationTests.Tests.Power } var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1)); - terminal.Transform.LocalRotation = Angle.FromDegrees(180); + _entityManager.GetComponent(terminal).LocalRotation = Angle.FromDegrees(180); var batteryEnt = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2)); var supplyEnt = _entityManager.SpawnEntity("GeneratorDummy", grid.ToCoordinates(0, 0)); var consumerEnt = _entityManager.SpawnEntity("ConsumerDummy", grid.ToCoordinates(0, 3)); - consumer = consumerEnt.GetComponent(); - supplier = supplyEnt.GetComponent(); - netBattery = batteryEnt.GetComponent(); - var battery = batteryEnt.GetComponent(); + consumer = _entityManager.GetComponent(consumerEnt); + supplier = _entityManager.GetComponent(supplyEnt); + netBattery = _entityManager.GetComponent(batteryEnt); + var battery = _entityManager.GetComponent(batteryEnt); // Consumer needs 1000 W, supplier can only provide 800, battery fills in the remaining 200. consumer.DrawRate = 1000; @@ -878,13 +879,13 @@ namespace Content.IntegrationTests.Tests.Power var rightEnt = _entityManager.SpawnEntity("CableHV", grid.ToCoordinates(0, 3)); var terminal = _entityManager.SpawnEntity("CableTerminal", grid.ToCoordinates(0, 1)); - terminal.Transform.LocalRotation = Angle.FromDegrees(180); + _entityManager.GetComponent(terminal).LocalRotation = Angle.FromDegrees(180); var battery = _entityManager.SpawnEntity("FullBatteryDummy", grid.ToCoordinates(0, 2)); - var batteryNodeContainer = battery.GetComponent(); + var batteryNodeContainer = _entityManager.GetComponent(battery); - leftNode = leftEnt.GetComponent().GetNode("power"); - rightNode = rightEnt.GetComponent().GetNode("power"); + leftNode = _entityManager.GetComponent(leftEnt).GetNode("power"); + rightNode = _entityManager.GetComponent(rightEnt).GetNode("power"); batteryInput = batteryNodeContainer.GetNode("input"); batteryOutput = batteryNodeContainer.GetNode("output"); @@ -930,9 +931,9 @@ namespace Content.IntegrationTests.Tests.Power var substationEnt = _entityManager.SpawnEntity("SubstationDummy", grid.ToCoordinates(0, 1)); var apcEnt = _entityManager.SpawnEntity("ApcDummy", grid.ToCoordinates(0, 2)); - var generatorSupplier = generatorEnt.GetComponent(); - substationNetBattery = substationEnt.GetComponent(); - apcBattery = apcEnt.GetComponent(); + var generatorSupplier = _entityManager.GetComponent(generatorEnt); + substationNetBattery = _entityManager.GetComponent(substationEnt); + apcBattery = _entityManager.GetComponent(apcEnt); generatorSupplier.MaxSupply = 1000; generatorSupplier.SupplyRampTolerance = 1000; @@ -972,12 +973,12 @@ namespace Content.IntegrationTests.Tests.Power var apcExtensionEnt = _entityManager.SpawnEntity("CableApcExtension", grid.ToCoordinates(0, 0)); var powerReceiverEnt = _entityManager.SpawnEntity("ApcPowerReceiverDummy", grid.ToCoordinates(0, 2)); - receiver = powerReceiverEnt.GetComponent(); - var battery = apcEnt.GetComponent(); - apcNetBattery = apcEnt.GetComponent(); + receiver = _entityManager.GetComponent(powerReceiverEnt); + var battery = _entityManager.GetComponent(apcEnt); + apcNetBattery = _entityManager.GetComponent(apcEnt); - _extensionCableSystem.SetProviderTransferRange(apcExtensionEnt.Uid, 5); - _extensionCableSystem.SetReceiverReceptionRange(powerReceiverEnt.Uid, 5); + _extensionCableSystem.SetProviderTransferRange(apcExtensionEnt, 5); + _extensionCableSystem.SetReceiverReceptionRange(powerReceiverEnt, 5); battery.MaxCharge = 10000; //arbitrary nonzero amount of charge battery.CurrentCharge = battery.MaxCharge; //fill battery diff --git a/Content.IntegrationTests/Tests/SaveLoadMapTest.cs b/Content.IntegrationTests/Tests/SaveLoadMapTest.cs index 46b7747614..e4d2096ce1 100644 --- a/Content.IntegrationTests/Tests/SaveLoadMapTest.cs +++ b/Content.IntegrationTests/Tests/SaveLoadMapTest.cs @@ -25,7 +25,7 @@ namespace Content.IntegrationTests.Tests await server.WaitIdleAsync(); var mapLoader = server.ResolveDependency(); var mapManager = server.ResolveDependency(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); var resManager = server.ResolveDependency(); server.Post(() => @@ -38,14 +38,14 @@ namespace Content.IntegrationTests.Tests { var mapGrid = mapManager.CreateGrid(mapId); - var mapGridEnt = entityManager.GetEntity(mapGrid.GridEntityId); - mapGridEnt.Transform.WorldPosition = new Vector2(10, 10); + var mapGridEnt = mapGrid.GridEntityId; + sEntities.GetComponent(mapGridEnt).WorldPosition = new Vector2(10, 10); mapGrid.SetTile(new Vector2i(0,0), new Tile(1, 512)); } { var mapGrid = mapManager.CreateGrid(mapId); - var mapGridEnt = entityManager.GetEntity(mapGrid.GridEntityId); - mapGridEnt.Transform.WorldPosition = new Vector2(-8, -8); + var mapGridEnt = mapGrid.GridEntityId; + sEntities.GetComponent(mapGridEnt).WorldPosition = new Vector2(-8, -8); mapGrid.SetTile(new Vector2i(0, 0), new Tile(2, 511)); } diff --git a/Content.IntegrationTests/Tests/ShuttleTest.cs b/Content.IntegrationTests/Tests/ShuttleTest.cs index 1593082791..fc59763bd1 100644 --- a/Content.IntegrationTests/Tests/ShuttleTest.cs +++ b/Content.IntegrationTests/Tests/ShuttleTest.cs @@ -1,6 +1,5 @@ #nullable enable using System.Threading.Tasks; -using Content.Server.Shuttles; using Content.Server.Shuttles.Components; using NUnit.Framework; using Robust.Shared.GameObjects; @@ -20,30 +19,29 @@ namespace Content.IntegrationTests.Tests await server.WaitIdleAsync(); - var entMan = server.ResolveDependency(); var mapMan = server.ResolveDependency(); - IEntity? gridEnt = null; + var sEntities = server.ResolveDependency(); + + EntityUid gridEnt = default; await server.WaitAssertion(() => { var mapId = mapMan.CreateMap(); var grid = mapMan.CreateGrid(mapId); - gridEnt = entMan.GetEntity(grid.GridEntityId); + gridEnt = grid.GridEntityId; - Assert.That(gridEnt.TryGetComponent(out ShuttleComponent? shuttleComponent)); - Assert.That(gridEnt.TryGetComponent(out PhysicsComponent? physicsComponent)); + Assert.That(sEntities.TryGetComponent(gridEnt, out ShuttleComponent? shuttleComponent)); + Assert.That(sEntities.TryGetComponent(gridEnt, out PhysicsComponent? physicsComponent)); Assert.That(physicsComponent!.BodyType, Is.EqualTo(BodyType.Dynamic)); - Assert.That(gridEnt.Transform.LocalPosition, Is.EqualTo(Vector2.Zero)); + Assert.That(sEntities.GetComponent(gridEnt).LocalPosition, Is.EqualTo(Vector2.Zero)); physicsComponent.ApplyLinearImpulse(Vector2.One); }); - // TODO: Should have tests that collision + rendertree + pointlights work on a moved grid but I'll deal with that - // when we get rotations. await server.WaitRunTicks(1); await server.WaitAssertion(() => { - Assert.That(gridEnt?.Transform.LocalPosition, Is.Not.EqualTo(Vector2.Zero)); + Assert.That(sEntities.GetComponent(gridEnt).LocalPosition, Is.Not.EqualTo(Vector2.Zero)); }); } } diff --git a/Content.IntegrationTests/Tests/Tag/TagTest.cs b/Content.IntegrationTests/Tests/Tag/TagTest.cs index 1fe45f374d..db27cad716 100644 --- a/Content.IntegrationTests/Tests/Tag/TagTest.cs +++ b/Content.IntegrationTests/Tests/Tag/TagTest.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Content.Shared.Tag; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Prototypes; @@ -53,14 +54,14 @@ namespace Content.IntegrationTests.Tests.Tag var sEntityManager = server.ResolveDependency(); var sPrototypeManager = server.ResolveDependency(); - IEntity sTagDummy = null!; + EntityUid sTagDummy = default; TagComponent sTagComponent = null!; await server.WaitPost(() => { sMapManager.CreateNewMapEntity(MapId.Nullspace); sTagDummy = sEntityManager.SpawnEntity(TagEntityId, MapCoordinates.Nullspace); - sTagComponent = sTagDummy.GetComponent(); + sTagComponent = IoCManager.Resolve().GetComponent(sTagDummy); }); await server.WaitAssertion(() => diff --git a/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs b/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs index 2fd29238ca..290df1a1d2 100644 --- a/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs +++ b/Content.IntegrationTests/Tests/Utility/EntitySystemExtensionsTest.cs @@ -4,6 +4,7 @@ using Content.Shared.Physics; using Content.Shared.Spawning; using NUnit.Framework; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Physics; @@ -45,8 +46,8 @@ namespace Content.IntegrationTests.Tests.Utility await server.WaitAssertion(() => { var grid = GetMainGrid(sMapManager); - var gridEnt = sEntityManager.GetEntity(grid.GridEntityId); - var gridPos = gridEnt.Transform.WorldPosition; + var gridEnt = grid.GridEntityId; + var gridPos = IoCManager.Resolve().GetComponent(gridEnt).WorldPosition; var entityCoordinates = GetMainEntityCoordinates(sMapManager); // Nothing blocking it, only entity is the grid diff --git a/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs b/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs index c7352d98c4..c8d71f51f0 100644 --- a/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs +++ b/Content.IntegrationTests/Tests/Utility/EntityWhitelistTest.cs @@ -65,18 +65,18 @@ namespace Content.IntegrationTests.Tests.Utility await server.WaitIdleAsync(); var mapManager = server.ResolveDependency(); - var entityManager = server.ResolveDependency(); + var sEntities = server.ResolveDependency(); await server.WaitAssertion(() => { var mapId = GetMainMapId(mapManager); var mapCoordinates = new MapCoordinates(0, 0, mapId); - var validComponent = entityManager.SpawnEntity("ValidComponentDummy", mapCoordinates).Uid; - var validTag = entityManager.SpawnEntity("ValidTagDummy", mapCoordinates).Uid; + var validComponent = sEntities.SpawnEntity("ValidComponentDummy", mapCoordinates); + var validTag = sEntities.SpawnEntity("ValidTagDummy", mapCoordinates); - var invalidComponent = entityManager.SpawnEntity("InvalidComponentDummy", mapCoordinates).Uid; - var invalidTag = entityManager.SpawnEntity("InvalidTagDummy", mapCoordinates).Uid; + var invalidComponent = sEntities.SpawnEntity("InvalidComponentDummy", mapCoordinates); + var invalidTag = sEntities.SpawnEntity("InvalidTagDummy", mapCoordinates); // Test instantiated on its own var whitelistInst = new EntityWhitelist @@ -97,8 +97,8 @@ namespace Content.IntegrationTests.Tests.Utility Assert.That(whitelistInst.IsValid(invalidTag), Is.False); // Test from serialized - var dummy = entityManager.SpawnEntity("WhitelistDummy", mapCoordinates); - var whitelistSer = dummy.GetComponent().Slots.Values.First().Whitelist; + var dummy = sEntities.SpawnEntity("WhitelistDummy", mapCoordinates); + var whitelistSer = sEntities.GetComponent(dummy).Slots.Values.First().Whitelist; Assert.That(whitelistSer, Is.Not.Null); Assert.That(whitelistSer.Components, Is.Not.Null); diff --git a/Content.Server/AI/Commands/AddAiCommand.cs b/Content.Server/AI/Commands/AddAiCommand.cs index 24d4fc38fe..694ee57f62 100644 --- a/Content.Server/AI/Commands/AddAiCommand.cs +++ b/Content.Server/AI/Commands/AddAiCommand.cs @@ -13,6 +13,8 @@ namespace Content.Server.AI.Commands [AdminCommand(AdminFlags.Fun)] public class AddAiCommand : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "addai"; public string Description => "Add an ai component with a given processor to an entity."; public string Help => "Usage: addai ..." @@ -29,25 +31,25 @@ namespace Content.Server.AI.Commands var entId = new EntityUid(int.Parse(args[0])); - if (!IoCManager.Resolve().TryGetEntity(entId, out var ent)) + if (!_entities.EntityExists(entId)) { shell.WriteLine($"Unable to find entity with uid {entId}"); return; } - if (ent.HasComponent()) + if (_entities.HasComponent(entId)) { shell.WriteLine("Entity already has an AI component."); return; } // TODO: IMover refffaaccctttooorrr - if (ent.HasComponent()) + if (_entities.HasComponent(entId)) { - ent.RemoveComponent(); + _entities.RemoveComponent(entId); } - var comp = ent.AddComponent(); + var comp = _entities.AddComponent(entId); var behaviorManager = IoCManager.Resolve(); for (var i = 1; i < args.Length; i++) diff --git a/Content.Server/AI/Components/AiControllerComponent.cs b/Content.Server/AI/Components/AiControllerComponent.cs index 630a006cde..0cf2cf33cf 100644 --- a/Content.Server/AI/Components/AiControllerComponent.cs +++ b/Content.Server/AI/Components/AiControllerComponent.cs @@ -85,7 +85,7 @@ namespace Content.Server.AI.Components { get { - if (Owner.TryGetComponent(out MovementSpeedModifierComponent? component)) + if (IoCManager.Resolve().TryGetComponent(Owner, out MovementSpeedModifierComponent? component)) { return component.CurrentWalkSpeed; } @@ -102,7 +102,7 @@ namespace Content.Server.AI.Components { get { - if (Owner.TryGetComponent(out MovementSpeedModifierComponent? component)) + if (IoCManager.Resolve().TryGetComponent(Owner, out MovementSpeedModifierComponent? component)) { return component.CurrentSprintSpeed; } diff --git a/Content.Server/AI/EntitySystems/AiFactionTagSystem.cs b/Content.Server/AI/EntitySystems/AiFactionTagSystem.cs index c5971584db..3052b5b7dd 100644 --- a/Content.Server/AI/EntitySystems/AiFactionTagSystem.cs +++ b/Content.Server/AI/EntitySystems/AiFactionTagSystem.cs @@ -54,12 +54,12 @@ namespace Content.Server.AI.EntitySystems public Faction GetHostileFactions(Faction faction) => _hostileFactions.TryGetValue(faction, out var hostiles) ? hostiles : Faction.None; - public Faction GetFactions(IEntity entity) => - entity.TryGetComponent(out AiFactionTagComponent? factionTags) + public Faction GetFactions(EntityUid entity) => + EntityManager.TryGetComponent(entity, out AiFactionTagComponent? factionTags) ? factionTags.Factions : Faction.None; - public IEnumerable GetNearbyHostiles(IEntity entity, float range) + public IEnumerable GetNearbyHostiles(EntityUid entity, float range) { var ourFaction = GetFactions(entity); var hostile = GetHostileFactions(ourFaction); @@ -72,9 +72,9 @@ namespace Content.Server.AI.EntitySystems { if ((component.Factions & hostile) == 0) continue; - if (component.Owner.Transform.MapID != entity.Transform.MapID) + if (EntityManager.GetComponent(component.Owner).MapID != EntityManager.GetComponent(entity).MapID) continue; - if (!component.Owner.Transform.MapPosition.InRange(entity.Transform.MapPosition, range)) + if (!EntityManager.GetComponent(component.Owner).MapPosition.InRange(EntityManager.GetComponent(entity).MapPosition, range)) continue; yield return component.Owner; diff --git a/Content.Server/AI/LoadBalancer/AiActionRequestJob.cs b/Content.Server/AI/LoadBalancer/AiActionRequestJob.cs index 7e9ef0cf4e..8594dc5eb7 100644 --- a/Content.Server/AI/LoadBalancer/AiActionRequestJob.cs +++ b/Content.Server/AI/LoadBalancer/AiActionRequestJob.cs @@ -9,6 +9,8 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Utility; using Content.Server.CPUJob.JobQueues; using Content.Shared.AI; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Utility; namespace Content.Server.AI.LoadBalancer @@ -37,7 +39,7 @@ namespace Content.Server.AI.LoadBalancer var entity = _request.Context.GetState().GetValue(); - if (entity == null || !entity.HasComponent()) + if (entity == null || !IoCManager.Resolve().HasComponent(entity)) { return null; } @@ -122,7 +124,7 @@ namespace Content.Server.AI.LoadBalancer DebugTools.AssertNotNull(selfState); FoundAction?.Invoke(new SharedAiDebug.UtilityAiDebugMessage( - selfState!.Uid, + selfState!, DebugTime, cutoff, foundAction.GetType().Name, diff --git a/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs b/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs index 0ebf617e0a..e3411f5ebb 100644 --- a/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs +++ b/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs @@ -9,14 +9,18 @@ namespace Content.Server.AI.Operators.Combat.Melee { public class SwingMeleeWeaponOperator : AiOperator { + [Dependency] private readonly IEntityManager _entMan = default!; + private readonly float _burstTime; private float _elapsedTime; - private readonly IEntity _owner; - private readonly IEntity _target; + private readonly EntityUid _owner; + private readonly EntityUid _target; - public SwingMeleeWeaponOperator(IEntity owner, IEntity target, float burstTime = 1.0f) + public SwingMeleeWeaponOperator(EntityUid owner, EntityUid target, float burstTime = 1.0f) { + IoCManager.InjectDependencies(this); + _owner = owner; _target = target; _burstTime = burstTime; @@ -29,7 +33,7 @@ namespace Content.Server.AI.Operators.Combat.Melee return true; } - if (!_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) + if (!_entMan.TryGetComponent(_owner, out CombatModeComponent? combatModeComponent)) { return false; } @@ -47,7 +51,7 @@ namespace Content.Server.AI.Operators.Combat.Melee if (!base.Shutdown(outcome)) return false; - if (_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) + if (_entMan.TryGetComponent(_owner, out CombatModeComponent? combatModeComponent)) { combatModeComponent.IsInCombatMode = false; } @@ -62,15 +66,15 @@ namespace Content.Server.AI.Operators.Combat.Melee return Outcome.Success; } - if (!_owner.TryGetComponent(out HandsComponent? hands) || hands.GetActiveHand == null) + if (!_entMan.TryGetComponent(_owner, out HandsComponent? hands) || hands.GetActiveHand == null) { return Outcome.Failed; } var meleeWeapon = hands.GetActiveHand.Owner; - meleeWeapon.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent); + _entMan.TryGetComponent(meleeWeapon, out MeleeWeaponComponent? meleeWeaponComponent); - if ((_target.Transform.Coordinates.Position - _owner.Transform.Coordinates.Position).Length > + if ((_entMan.GetComponent(_target).Coordinates.Position - _entMan.GetComponent(_owner).Coordinates.Position).Length > meleeWeaponComponent?.Range) { return Outcome.Failed; @@ -78,7 +82,7 @@ namespace Content.Server.AI.Operators.Combat.Melee var interactionSystem = IoCManager.Resolve().GetEntitySystem(); - interactionSystem.AiUseInteraction(_owner, _target.Transform.Coordinates, _target.Uid); + interactionSystem.AiUseInteraction(_owner, _entMan.GetComponent(_target).Coordinates, _target); _elapsedTime += frameTime; return Outcome.Continuing; } diff --git a/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs b/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs index 0a569afaa9..81d05f7c8d 100644 --- a/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs +++ b/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs @@ -8,15 +8,19 @@ namespace Content.Server.AI.Operators.Combat.Melee { public sealed class UnarmedCombatOperator : AiOperator { + [Dependency] private readonly IEntityManager _entMan = default!; + private readonly float _burstTime; private float _elapsedTime; - private readonly IEntity _owner; - private readonly IEntity _target; + private readonly EntityUid _owner; + private readonly EntityUid _target; private UnarmedCombatComponent? _unarmedCombat; - public UnarmedCombatOperator(IEntity owner, IEntity target, float burstTime = 1.0f) + public UnarmedCombatOperator(EntityUid owner, EntityUid target, float burstTime = 1.0f) { + IoCManager.InjectDependencies(this); + _owner = owner; _target = target; _burstTime = burstTime; @@ -29,7 +33,7 @@ namespace Content.Server.AI.Operators.Combat.Melee return true; } - if (!_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) + if (!_entMan.TryGetComponent(_owner, out CombatModeComponent? combatModeComponent)) { return false; } @@ -39,7 +43,7 @@ namespace Content.Server.AI.Operators.Combat.Melee combatModeComponent.IsInCombatMode = true; } - if (_owner.TryGetComponent(out UnarmedCombatComponent? unarmedCombatComponent)) + if (_entMan.TryGetComponent(_owner, out UnarmedCombatComponent? unarmedCombatComponent)) { _unarmedCombat = unarmedCombatComponent; } @@ -56,7 +60,7 @@ namespace Content.Server.AI.Operators.Combat.Melee if (!base.Shutdown(outcome)) return false; - if (_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) + if (_entMan.TryGetComponent(_owner, out CombatModeComponent? combatModeComponent)) { combatModeComponent.IsInCombatMode = false; } @@ -76,14 +80,14 @@ namespace Content.Server.AI.Operators.Combat.Melee return Outcome.Failed; } - if ((_target.Transform.Coordinates.Position - _owner.Transform.Coordinates.Position).Length > + if ((_entMan.GetComponent(_target).Coordinates.Position - _entMan.GetComponent(_owner).Coordinates.Position).Length > _unarmedCombat.Range) { return Outcome.Failed; } var interactionSystem = IoCManager.Resolve().GetEntitySystem(); - interactionSystem.AiUseInteraction(_owner, _target.Transform.Coordinates, _target.Uid); + interactionSystem.AiUseInteraction(_owner, _entMan.GetComponent(_target).Coordinates, _target); _elapsedTime += frameTime; return Outcome.Continuing; } diff --git a/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs b/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs index 3780cefe9f..5812ba66d7 100644 --- a/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs +++ b/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs @@ -4,6 +4,7 @@ using Content.Server.Storage.Components; using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Operators.Inventory { @@ -13,10 +14,10 @@ namespace Content.Server.AI.Operators.Inventory /// public sealed class CloseLastStorageOperator : AiOperator { - private readonly IEntity _owner; - private IEntity? _target; + private readonly EntityUid _owner; + private EntityUid _target; - public CloseLastStorageOperator(IEntity owner) + public CloseLastStorageOperator(EntityUid owner) { _owner = owner; } @@ -37,7 +38,7 @@ namespace Content.Server.AI.Operators.Inventory _target = blackboard.GetState().GetValue(); - return _target != null; + return _target != default; } public override bool Shutdown(Outcome outcome) @@ -47,18 +48,18 @@ namespace Content.Server.AI.Operators.Inventory var blackboard = UtilityAiHelpers.GetBlackboard(_owner); - blackboard?.GetState().SetValue(null); + blackboard?.GetState().SetValue(default); return true; } public override Outcome Execute(float frameTime) { - if (_target == null || !_owner.InRangeUnobstructed(_target, popup: true)) + if (_target == default || !_owner.InRangeUnobstructed(_target, popup: true)) { return Outcome.Failed; } - if (!_target.TryGetComponent(out EntityStorageComponent? storageComponent) || + if (!IoCManager.Resolve().TryGetComponent(_target, out EntityStorageComponent? storageComponent) || storageComponent.IsWeldedShut) { return Outcome.Failed; diff --git a/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs b/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs index 1808434ed8..952bc6b46b 100644 --- a/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs +++ b/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs @@ -1,13 +1,14 @@ using Content.Server.Hands.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Operators.Inventory { public class DropEntityOperator : AiOperator { - private readonly IEntity _owner; - private readonly IEntity _entity; - public DropEntityOperator(IEntity owner, IEntity entity) + private readonly EntityUid _owner; + private readonly EntityUid _entity; + public DropEntityOperator(EntityUid owner, EntityUid entity) { _owner = owner; _entity = entity; @@ -20,7 +21,7 @@ namespace Content.Server.AI.Operators.Inventory /// public override Outcome Execute(float frameTime) { - if (!_owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!IoCManager.Resolve().TryGetComponent(_owner, out HandsComponent? handsComponent)) { return Outcome.Failed; } diff --git a/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs b/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs index 3ab558d009..81908858f5 100644 --- a/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs +++ b/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs @@ -1,20 +1,21 @@ using Content.Server.Hands.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Operators.Inventory { public class DropHandItemsOperator : AiOperator { - private readonly IEntity _owner; + private readonly EntityUid _owner; - public DropHandItemsOperator(IEntity owner) + public DropHandItemsOperator(EntityUid owner) { _owner = owner; } public override Outcome Execute(float frameTime) { - if (!_owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!IoCManager.Resolve().TryGetComponent(_owner, out HandsComponent? handsComponent)) { return Outcome.Failed; } diff --git a/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs b/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs index e42de80336..e2f3ae82fa 100644 --- a/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs +++ b/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs @@ -1,13 +1,14 @@ using Content.Server.Hands.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Operators.Inventory { public sealed class EquipEntityOperator : AiOperator { - private readonly IEntity _owner; - private readonly IEntity _entity; - public EquipEntityOperator(IEntity owner, IEntity entity) + private readonly EntityUid _owner; + private readonly EntityUid _entity; + public EquipEntityOperator(EntityUid owner, EntityUid entity) { _owner = owner; _entity = entity; @@ -15,7 +16,7 @@ namespace Content.Server.AI.Operators.Inventory public override Outcome Execute(float frameTime) { - if (!_owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!IoCManager.Resolve().TryGetComponent(_owner, out HandsComponent? handsComponent)) { return Outcome.Failed; } diff --git a/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs b/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs index 39f3c5a200..ed353d61d2 100644 --- a/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs +++ b/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs @@ -11,11 +11,15 @@ namespace Content.Server.AI.Operators.Inventory /// public class InteractWithEntityOperator : AiOperator { - private readonly IEntity _owner; - private readonly IEntity _useTarget; + [Dependency] private readonly IEntityManager _entMan = default!; - public InteractWithEntityOperator(IEntity owner, IEntity useTarget) + private readonly EntityUid _owner; + private readonly EntityUid _useTarget; + + public InteractWithEntityOperator(EntityUid owner, EntityUid useTarget) { + IoCManager.InjectDependencies(this); + _owner = owner; _useTarget = useTarget; @@ -23,7 +27,9 @@ namespace Content.Server.AI.Operators.Inventory public override Outcome Execute(float frameTime) { - if (_useTarget.Transform.GridID != _owner.Transform.GridID) + var targetTransform = _entMan.GetComponent(_useTarget); + + if (targetTransform.GridID != _entMan.GetComponent(_owner).GridID) { return Outcome.Failed; } @@ -33,14 +39,14 @@ namespace Content.Server.AI.Operators.Inventory return Outcome.Failed; } - if (_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) + if (_entMan.TryGetComponent(_owner, out CombatModeComponent? combatModeComponent)) { combatModeComponent.IsInCombatMode = false; } // Click on da thing - var interactionSystem = IoCManager.Resolve().GetEntitySystem(); - interactionSystem.AiUseInteraction(_owner, _useTarget.Transform.Coordinates, _useTarget.Uid); + var interactionSystem = EntitySystem.Get(); + interactionSystem.AiUseInteraction(_owner, targetTransform.Coordinates, _useTarget); return Outcome.Success; } diff --git a/Content.Server/AI/Operators/Inventory/OpenStorageOperator.cs b/Content.Server/AI/Operators/Inventory/OpenStorageOperator.cs index 32250ab9b8..fbd207ae7e 100644 --- a/Content.Server/AI/Operators/Inventory/OpenStorageOperator.cs +++ b/Content.Server/AI/Operators/Inventory/OpenStorageOperator.cs @@ -5,6 +5,7 @@ using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Operators.Inventory { @@ -13,10 +14,10 @@ namespace Content.Server.AI.Operators.Inventory /// public sealed class OpenStorageOperator : AiOperator { - private readonly IEntity _owner; - private readonly IEntity _target; + private readonly EntityUid _owner; + private readonly EntityUid _target; - public OpenStorageOperator(IEntity owner, IEntity target) + public OpenStorageOperator(EntityUid owner, EntityUid target) { _owner = owner; _target = target; @@ -34,7 +35,7 @@ namespace Content.Server.AI.Operators.Inventory return Outcome.Failed; } - if (!container.Owner.TryGetComponent(out EntityStorageComponent? storageComponent) || + if (!IoCManager.Resolve().TryGetComponent(container.Owner, out EntityStorageComponent? storageComponent) || storageComponent.IsWeldedShut) { return Outcome.Failed; diff --git a/Content.Server/AI/Operators/Inventory/PickupEntityOperator.cs b/Content.Server/AI/Operators/Inventory/PickupEntityOperator.cs index 7b2e60635a..5def6d3f43 100644 --- a/Content.Server/AI/Operators/Inventory/PickupEntityOperator.cs +++ b/Content.Server/AI/Operators/Inventory/PickupEntityOperator.cs @@ -11,10 +11,10 @@ namespace Content.Server.AI.Operators.Inventory public class PickupEntityOperator : AiOperator { // Input variables - private readonly IEntity _owner; - private readonly IEntity _target; + private readonly EntityUid _owner; + private readonly EntityUid _target; - public PickupEntityOperator(IEntity owner, IEntity target) + public PickupEntityOperator(EntityUid owner, EntityUid target) { _owner = owner; _target = target; @@ -22,15 +22,17 @@ namespace Content.Server.AI.Operators.Inventory public override Outcome Execute(float frameTime) { - if (_target.Deleted || - !_target.HasComponent() || - _target.IsInContainer() || - !_owner.InRangeUnobstructed(_target, popup: true)) + var entMan = IoCManager.Resolve(); + + if (entMan.Deleted(_target) + || !entMan.HasComponent(_target) + || _target.IsInContainer() + || !_owner.InRangeUnobstructed(_target, popup: true)) { return Outcome.Failed; } - if (!_owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!entMan.TryGetComponent(_owner, out HandsComponent? handsComponent)) { return Outcome.Failed; } @@ -56,7 +58,7 @@ namespace Content.Server.AI.Operators.Inventory return Outcome.Failed; } - var interactionSystem = IoCManager.Resolve().GetEntitySystem(); + var interactionSystem = EntitySystem.Get(); interactionSystem.InteractHand(_owner, _target); return Outcome.Success; } diff --git a/Content.Server/AI/Operators/Inventory/UseItemInInventoryOperator.cs b/Content.Server/AI/Operators/Inventory/UseItemInInventoryOperator.cs index fec7a7b7a9..1670277b61 100644 --- a/Content.Server/AI/Operators/Inventory/UseItemInInventoryOperator.cs +++ b/Content.Server/AI/Operators/Inventory/UseItemInInventoryOperator.cs @@ -1,6 +1,7 @@ using Content.Server.Hands.Components; using Content.Server.Items; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Operators.Inventory { @@ -9,10 +10,10 @@ namespace Content.Server.AI.Operators.Inventory /// public class UseItemInInventoryOperator : AiOperator { - private readonly IEntity _owner; - private readonly IEntity _target; + private readonly EntityUid _owner; + private readonly EntityUid _target; - public UseItemInInventoryOperator(IEntity owner, IEntity target) + public UseItemInInventoryOperator(EntityUid owner, EntityUid target) { _owner = owner; _target = target; @@ -20,13 +21,15 @@ namespace Content.Server.AI.Operators.Inventory public override Outcome Execute(float frameTime) { + var entMan = IoCManager.Resolve(); + // TODO: Also have this check storage a la backpack etc. - if (!_owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!entMan.TryGetComponent(_owner, out HandsComponent? handsComponent)) { return Outcome.Failed; } - if (!_target.TryGetComponent(out ItemComponent? itemComponent)) + if (!entMan.TryGetComponent(_target, out ItemComponent? itemComponent)) { return Outcome.Failed; } diff --git a/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs b/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs index 2569ffc04e..8be961e4c5 100644 --- a/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs +++ b/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs @@ -8,9 +8,9 @@ namespace Content.Server.AI.Operators.Movement public sealed class MoveToEntityOperator : AiOperator { // TODO: This and steering need to support InRangeUnobstructed now - private readonly IEntity _owner; + private readonly EntityUid _owner; private EntityTargetSteeringRequest? _request; - private readonly IEntity _target; + private readonly EntityUid _target; // For now we'll just get as close as we can because we're not doing LOS checks to be able to pick up at the max interaction range public float ArrivalDistance { get; } public float PathfindingProximity { get; } @@ -18,8 +18,8 @@ namespace Content.Server.AI.Operators.Movement private readonly bool _requiresInRangeUnobstructed; public MoveToEntityOperator( - IEntity owner, - IEntity target, + EntityUid owner, + EntityUid target, float arrivalDistance = 1.0f, float pathfindingProximity = 1.5f, bool requiresInRangeUnobstructed = false) diff --git a/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs b/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs index de560b50c0..f89005e286 100644 --- a/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs +++ b/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs @@ -8,12 +8,12 @@ namespace Content.Server.AI.Operators.Movement { public sealed class MoveToGridOperator : AiOperator { - private readonly IEntity _owner; + private readonly EntityUid _owner; private GridTargetSteeringRequest? _request; private readonly EntityCoordinates _target; public float DesiredRange { get; set; } - public MoveToGridOperator(IEntity owner, EntityCoordinates target, float desiredRange = 1.5f) + public MoveToGridOperator(EntityUid owner, EntityCoordinates target, float desiredRange = 1.5f) { _owner = owner; _target = target; diff --git a/Content.Server/AI/Operators/Nutrition/UseDrinkInInventoryOperator.cs b/Content.Server/AI/Operators/Nutrition/UseDrinkInInventoryOperator.cs index fac0695046..6c3100b4f8 100644 --- a/Content.Server/AI/Operators/Nutrition/UseDrinkInInventoryOperator.cs +++ b/Content.Server/AI/Operators/Nutrition/UseDrinkInInventoryOperator.cs @@ -11,11 +11,11 @@ namespace Content.Server.AI.Operators.Nutrition { public class UseDrinkInInventoryOperator : AiOperator { - private readonly IEntity _owner; - private readonly IEntity _target; + private readonly EntityUid _owner; + private readonly EntityUid _target; private float _interactionCooldown; - public UseDrinkInInventoryOperator(IEntity owner, IEntity target) + public UseDrinkInInventoryOperator(EntityUid owner, EntityUid target) { _owner = owner; _target = target; @@ -29,10 +29,12 @@ namespace Content.Server.AI.Operators.Nutrition return Outcome.Continuing; } + var entities = IoCManager.Resolve(); + // TODO: Also have this check storage a la backpack etc. - if (_target.Deleted || - !_owner.TryGetComponent(out HandsComponent? handsComponent) || - !_target.TryGetComponent(out ItemComponent? itemComponent)) + if (entities.Deleted(_target) || + !entities.TryGetComponent(_owner, out HandsComponent? handsComponent) || + !entities.TryGetComponent(_target, out ItemComponent? itemComponent)) { return Outcome.Failed; } @@ -43,7 +45,7 @@ namespace Content.Server.AI.Operators.Nutrition { if (handsComponent.GetItem(slot) != itemComponent) continue; handsComponent.ActiveHand = slot; - if (!_target.TryGetComponent(out drinkComponent)) + if (!entities.TryGetComponent(_target, out drinkComponent)) { return Outcome.Failed; } @@ -58,8 +60,8 @@ namespace Content.Server.AI.Operators.Nutrition return Outcome.Failed; } - if (drinkComponent.Deleted || EntitySystem.Get().IsEmpty(drinkComponent.Owner.Uid, drinkComponent) - || _owner.TryGetComponent(out ThirstComponent? thirstComponent) && + if (drinkComponent.Deleted || EntitySystem.Get().IsEmpty(drinkComponent.Owner, drinkComponent) + || entities.TryGetComponent(_owner, out ThirstComponent? thirstComponent) && thirstComponent.CurrentThirst >= thirstComponent.ThirstThresholds[ThirstThreshold.Okay]) { return Outcome.Success; diff --git a/Content.Server/AI/Operators/Nutrition/UseFoodInInventoryOperator.cs b/Content.Server/AI/Operators/Nutrition/UseFoodInInventoryOperator.cs index c92ae7d52e..41c940477e 100644 --- a/Content.Server/AI/Operators/Nutrition/UseFoodInInventoryOperator.cs +++ b/Content.Server/AI/Operators/Nutrition/UseFoodInInventoryOperator.cs @@ -10,11 +10,11 @@ namespace Content.Server.AI.Operators.Nutrition { public class UseFoodInInventoryOperator : AiOperator { - private readonly IEntity _owner; - private readonly IEntity _target; + private readonly EntityUid _owner; + private readonly EntityUid _target; private float _interactionCooldown; - public UseFoodInInventoryOperator(IEntity owner, IEntity target) + public UseFoodInInventoryOperator(EntityUid owner, EntityUid target) { _owner = owner; _target = target; @@ -28,10 +28,12 @@ namespace Content.Server.AI.Operators.Nutrition return Outcome.Continuing; } + var entities = IoCManager.Resolve(); + // TODO: Also have this check storage a la backpack etc. - if (_target.Deleted || - !_owner.TryGetComponent(out HandsComponent? handsComponent) || - !_target.TryGetComponent(out ItemComponent? itemComponent)) + if (entities.Deleted(_target) || + !entities.TryGetComponent(_owner, out HandsComponent? handsComponent) || + !entities.TryGetComponent(_target, out ItemComponent? itemComponent)) { return Outcome.Failed; } @@ -42,7 +44,7 @@ namespace Content.Server.AI.Operators.Nutrition { if (handsComponent.GetItem(slot) != itemComponent) continue; handsComponent.ActiveHand = slot; - if (!_target.TryGetComponent(out foodComponent)) + if (!entities.TryGetComponent(_target, out foodComponent)) { return Outcome.Failed; } @@ -57,9 +59,9 @@ namespace Content.Server.AI.Operators.Nutrition return Outcome.Failed; } - if (_target.Deleted || + if ((!entities.EntityExists(_target) ? EntityLifeStage.Deleted : entities.GetComponent(_target).EntityLifeStage) >= EntityLifeStage.Deleted || foodComponent.UsesRemaining == 0 || - _owner.TryGetComponent(out HungerComponent? hungerComponent) && + entities.TryGetComponent(_owner, out HungerComponent? hungerComponent) && hungerComponent.CurrentHunger >= hungerComponent.HungerThresholds[HungerThreshold.Okay]) { return Outcome.Success; diff --git a/Content.Server/AI/Operators/Sequences/GoPickupEntitySequence.cs b/Content.Server/AI/Operators/Sequences/GoPickupEntitySequence.cs index e7d9471e26..c4f8776956 100644 --- a/Content.Server/AI/Operators/Sequences/GoPickupEntitySequence.cs +++ b/Content.Server/AI/Operators/Sequences/GoPickupEntitySequence.cs @@ -7,7 +7,7 @@ namespace Content.Server.AI.Operators.Sequences { public class GoPickupEntitySequence : SequenceOperator { - public GoPickupEntitySequence(IEntity owner, IEntity target) + public GoPickupEntitySequence(EntityUid owner, EntityUid target) { Sequence = new Queue(new AiOperator[] { @@ -17,4 +17,4 @@ namespace Content.Server.AI.Operators.Sequences }); } } -} \ No newline at end of file +} diff --git a/Content.Server/AI/Pathfinding/Accessible/AiReachableSystem.cs b/Content.Server/AI/Pathfinding/Accessible/AiReachableSystem.cs index 48328e95b8..cfc97c432c 100644 --- a/Content.Server/AI/Pathfinding/Accessible/AiReachableSystem.cs +++ b/Content.Server/AI/Pathfinding/Accessible/AiReachableSystem.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Content.Server.Access.Components; using Content.Server.Access.Systems; using Content.Server.AI.Pathfinding.Pathfinders; using Content.Shared.AI; @@ -171,22 +170,22 @@ namespace Content.Server.AI.Pathfinding.Accessible /// /// /// - public bool CanAccess(IEntity entity, IEntity target, float range = 0.0f) + public bool CanAccess(EntityUid entity, EntityUid target, float range = 0.0f) { // TODO: Handle this gracefully instead of just failing. - if (!target.Transform.GridID.IsValid()) + if (!EntityManager.GetComponent(target).GridID.IsValid()) return false; - var targetTile = _mapManager.GetGrid(target.Transform.GridID).GetTileRef(target.Transform.Coordinates); + var targetTile = _mapManager.GetGrid(EntityManager.GetComponent(target).GridID).GetTileRef(EntityManager.GetComponent(target).Coordinates); var targetNode = _pathfindingSystem.GetNode(targetTile); var collisionMask = 0; - if (entity.TryGetComponent(out IPhysBody? physics)) + if (EntityManager.TryGetComponent(entity, out IPhysBody? physics)) { collisionMask = physics.CollisionMask; } - var access = _accessReader.FindAccessTags(entity.Uid); + var access = _accessReader.FindAccessTags(entity); // We'll do a quick traversable check before going through regions // If we can't access it we'll try to get a valid node in range (this is essentially an early-out) @@ -198,7 +197,7 @@ namespace Content.Server.AI.Pathfinding.Accessible return false; } - var pathfindingArgs = new PathfindingArgs(entity.Uid, access, collisionMask, default, targetTile, range); + var pathfindingArgs = new PathfindingArgs(entity, access, collisionMask, default, targetTile, range); foreach (var node in BFSPathfinder.GetNodesInRange(pathfindingArgs, false)) { targetNode = node; @@ -208,14 +207,14 @@ namespace Content.Server.AI.Pathfinding.Accessible return CanAccess(entity, targetNode); } - public bool CanAccess(IEntity entity, PathfindingNode targetNode) + public bool CanAccess(EntityUid entity, PathfindingNode targetNode) { - if (entity.Transform.GridID != targetNode.TileRef.GridIndex) + if (EntityManager.GetComponent(entity).GridID != targetNode.TileRef.GridIndex) { return false; } - var entityTile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.Coordinates); + var entityTile = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID).GetTileRef(EntityManager.GetComponent(entity).Coordinates); var entityNode = _pathfindingSystem.GetNode(entityTile); var entityRegion = GetRegion(entityNode); var targetRegion = GetRegion(targetNode); @@ -423,14 +422,14 @@ namespace Content.Server.AI.Pathfinding.Accessible /// /// /// - public PathfindingRegion? GetRegion(IEntity entity) + public PathfindingRegion? GetRegion(EntityUid entity) { - if (!entity.Transform.GridID.IsValid()) + if (!EntityManager.GetComponent(entity).GridID.IsValid()) { return null; } - var entityTile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.Coordinates); + var entityTile = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID).GetTileRef(EntityManager.GetComponent(entity).Coordinates); var entityNode = _pathfindingSystem.GetNode(entityTile); return GetRegion(entityNode); } diff --git a/Content.Server/AI/Pathfinding/Accessible/ReachableArgs.cs b/Content.Server/AI/Pathfinding/Accessible/ReachableArgs.cs index b503f124a8..2e001502d6 100644 --- a/Content.Server/AI/Pathfinding/Accessible/ReachableArgs.cs +++ b/Content.Server/AI/Pathfinding/Accessible/ReachableArgs.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Content.Server.Access.Components; using Content.Server.Access.Systems; using Content.Server.AI.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Physics; namespace Content.Server.AI.Pathfinding.Accessible @@ -25,17 +25,18 @@ namespace Content.Server.AI.Pathfinding.Accessible /// /// /// - public static ReachableArgs GetArgs(IEntity entity) + public static ReachableArgs GetArgs(EntityUid entity) { var collisionMask = 0; - if (entity.TryGetComponent(out IPhysBody? physics)) + var entMan = IoCManager.Resolve(); + if (entMan.TryGetComponent(entity, out IPhysBody? physics)) { collisionMask = physics.CollisionMask; } var accessSystem = EntitySystem.Get(); - var access = accessSystem.FindAccessTags(entity.Uid); - var visionRadius = entity.GetComponent().VisionRadius; + var access = accessSystem.FindAccessTags(entity); + var visionRadius = entMan.GetComponent(entity).VisionRadius; return new ReachableArgs(visionRadius, access, collisionMask); } diff --git a/Content.Server/AI/Pathfinding/PathfindingNode.cs b/Content.Server/AI/Pathfinding/PathfindingNode.cs index fb9a3238f6..bbd78cfb8d 100644 --- a/Content.Server/AI/Pathfinding/PathfindingNode.cs +++ b/Content.Server/AI/Pathfinding/PathfindingNode.cs @@ -4,6 +4,7 @@ using System.Linq; using Content.Server.Access.Components; using Content.Server.Doors.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; @@ -22,17 +23,17 @@ namespace Content.Server.AI.Pathfinding /// Whenever there's a change in the collision layers we update the mask as the graph has more reads than writes /// public int BlockedCollisionMask { get; private set; } - private readonly Dictionary _blockedCollidables = new(0); + private readonly Dictionary _blockedCollidables = new(0); - public IReadOnlyDictionary PhysicsLayers => _physicsLayers; - private readonly Dictionary _physicsLayers = new(0); + public IReadOnlyDictionary PhysicsLayers => _physicsLayers; + private readonly Dictionary _physicsLayers = new(0); /// /// The entities on this tile that require access to traverse /// /// We don't store the ICollection, at least for now, as we'd need to replicate the access code here public IReadOnlyCollection AccessReaders => _accessReaders.Values; - private readonly Dictionary _accessReaders = new(0); + private readonly Dictionary _accessReaders = new(0); public PathfindingNode(PathfindingChunk parent, TileRef tileRef) { @@ -41,9 +42,9 @@ namespace Content.Server.AI.Pathfinding GenerateMask(); } - public static bool IsRelevant(IEntity entity, IPhysBody physicsComponent) + public static bool IsRelevant(EntityUid entity, IPhysBody physicsComponent) { - if (entity.Transform.GridID == GridId.Invalid || + if (IoCManager.Resolve().GetComponent(entity).GridID == GridId.Invalid || (PathfindingSystem.TrackedCollisionLayers & physicsComponent.CollisionLayer) == 0) { return false; @@ -257,16 +258,17 @@ namespace Content.Server.AI.Pathfinding /// /// TODO: These 2 methods currently don't account for a bunch of changes (e.g. airlock unpowered, wrenching, etc.) /// TODO: Could probably optimise this slightly more. - public void AddEntity(IEntity entity, IPhysBody physicsComponent) + public void AddEntity(EntityUid entity, IPhysBody physicsComponent) { + var entMan = IoCManager.Resolve(); // If we're a door - if (entity.HasComponent() || entity.HasComponent()) + if (entMan.HasComponent(entity) || entMan.HasComponent(entity)) { // If we need access to traverse this then add to readers, otherwise no point adding it (except for maybe tile costs in future) // TODO: Check for powered I think (also need an event for when it's depowered // AccessReader calls this whenever opening / closing but it can seem to get called multiple times // Which may or may not be intended? - if (entity.TryGetComponent(out AccessReader? accessReader) && !_accessReaders.ContainsKey(entity)) + if (entMan.TryGetComponent(entity, out AccessReader? accessReader) && !_accessReaders.ContainsKey(entity)) { _accessReaders.Add(entity, accessReader); ParentChunk.Dirty(); @@ -293,7 +295,7 @@ namespace Content.Server.AI.Pathfinding /// Will check each category and remove it from the applicable one /// /// - public void RemoveEntity(IEntity entity) + public void RemoveEntity(EntityUid entity) { // There's no guarantee that the entity isn't deleted // 90% of updates are probably entities moving around diff --git a/Content.Server/AI/Pathfinding/PathfindingSystem.cs b/Content.Server/AI/Pathfinding/PathfindingSystem.cs index 213d5e38f0..ba08f2dedb 100644 --- a/Content.Server/AI/Pathfinding/PathfindingSystem.cs +++ b/Content.Server/AI/Pathfinding/PathfindingSystem.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Threading; using Content.Server.Access; -using Content.Server.Access.Components; using Content.Server.Access.Systems; using Content.Server.AI.Pathfinding.Pathfinders; using Content.Server.CPUJob.JobQueues; @@ -46,7 +45,7 @@ namespace Content.Server.AI.Pathfinding private readonly Queue _tileUpdateQueue = new(); // Need to store previously known entity positions for collidables for when they move - private readonly Dictionary _lastKnownPositions = new(); + private readonly Dictionary _lastKnownPositions = new(); public const int TrackedCollisionLayers = (int) (CollisionGroup.Impassable | @@ -85,15 +84,15 @@ namespace Content.Server.AI.Pathfinding foreach (var update in _collidableUpdateQueue) { - if (!EntityManager.TryGetEntity(update.Owner, out var entity)) continue; + if (!EntityManager.EntityExists(update.Owner)) continue; if (update.CanCollide) { - HandleEntityAdd(entity); + HandleEntityAdd(update.Owner); } else { - HandleEntityRemove(entity); + HandleEntityRemove(update.Owner); } totalUpdates++; @@ -182,9 +181,9 @@ namespace Content.Server.AI.Pathfinding /// /// /// - public PathfindingNode GetNode(IEntity entity) + public PathfindingNode GetNode(EntityUid entity) { - var tile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.Coordinates); + var tile = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID).GetTileRef(EntityManager.GetComponent(entity).Coordinates); return GetNode(tile); } @@ -263,18 +262,18 @@ namespace Content.Server.AI.Pathfinding /// /// The node will filter it to the correct category (if possible) /// - private void HandleEntityAdd(IEntity entity) + private void HandleEntityAdd(EntityUid entity) { - if (entity.Deleted || + if (Deleted(entity) || _lastKnownPositions.ContainsKey(entity) || - !entity.TryGetComponent(out IPhysBody? physics) || + !EntityManager.TryGetComponent(entity, out IPhysBody? physics) || !PathfindingNode.IsRelevant(entity, physics)) { return; } - var grid = _mapManager.GetGrid(entity.Transform.GridID); - var tileRef = grid.GetTileRef(entity.Transform.Coordinates); + var grid = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID); + var tileRef = grid.GetTileRef(EntityManager.GetComponent(entity).Coordinates); var chunk = GetChunk(tileRef); var node = chunk.GetNode(tileRef); @@ -282,7 +281,7 @@ namespace Content.Server.AI.Pathfinding _lastKnownPositions.Add(entity, node); } - private void HandleEntityRemove(IEntity entity) + private void HandleEntityRemove(EntityUid entity) { if (!_lastKnownPositions.TryGetValue(entity, out var node)) { @@ -305,8 +304,8 @@ namespace Content.Server.AI.Pathfinding private void HandleEntityMove(MoveEvent moveEvent) { // If we've moved to space or the likes then remove us. - if (moveEvent.Sender.Deleted || - !moveEvent.Sender.TryGetComponent(out IPhysBody? physics) || + if ((!EntityManager.EntityExists(moveEvent.Sender) ? EntityLifeStage.Deleted : EntityManager.GetComponent(moveEvent.Sender).EntityLifeStage) >= EntityLifeStage.Deleted || + !EntityManager.TryGetComponent(moveEvent.Sender, out IPhysBody? physics) || !PathfindingNode.IsRelevant(moveEvent.Sender, physics) || moveEvent.NewPosition.GetGridId(EntityManager) == GridId.Invalid) { @@ -315,9 +314,9 @@ namespace Content.Server.AI.Pathfinding } // Memory leak protection until grid parenting confirmed fix / you REALLY need the performance - var gridBounds = _mapManager.GetGrid(moveEvent.Sender.Transform.GridID).WorldBounds; + var gridBounds = _mapManager.GetGrid(EntityManager.GetComponent(moveEvent.Sender).GridID).WorldBounds; - if (!gridBounds.Contains(moveEvent.Sender.Transform.WorldPosition)) + if (!gridBounds.Contains(EntityManager.GetComponent(moveEvent.Sender).WorldPosition)) { HandleEntityRemove(moveEvent.Sender); return; @@ -361,7 +360,7 @@ namespace Content.Server.AI.Pathfinding // TODO: Need to rethink the pathfinder utils (traversable etc.). Maybe just chuck them all in PathfindingSystem // Otherwise you get the steerer using this and the pathfinders using a different traversable. // Also look at increasing tile cost the more physics entities are on it - public bool CanTraverse(IEntity entity, EntityCoordinates coordinates) + public bool CanTraverse(EntityUid entity, EntityCoordinates coordinates) { var gridId = coordinates.GetGridId(EntityManager); var tile = _mapManager.GetGrid(gridId).GetTileRef(coordinates); @@ -369,15 +368,15 @@ namespace Content.Server.AI.Pathfinding return CanTraverse(entity, node); } - public bool CanTraverse(IEntity entity, PathfindingNode node) + public bool CanTraverse(EntityUid entity, PathfindingNode node) { - if (entity.TryGetComponent(out IPhysBody? physics) && + if (EntityManager.TryGetComponent(entity, out IPhysBody? physics) && (physics.CollisionMask & node.BlockedCollisionMask) != 0) { return false; } - var access = _accessReader.FindAccessTags(entity.Uid); + var access = _accessReader.FindAccessTags(entity); foreach (var reader in node.AccessReaders) { if (!_accessReader.IsAllowed(reader, access)) diff --git a/Content.Server/AI/Steering/AiSteeringSystem.cs b/Content.Server/AI/Steering/AiSteeringSystem.cs index 389b5fcb28..8941d7cc3a 100644 --- a/Content.Server/AI/Steering/AiSteeringSystem.cs +++ b/Content.Server/AI/Steering/AiSteeringSystem.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; -using Content.Server.Access.Components; using Content.Server.Access.Systems; using Content.Server.AI.Components; using Content.Server.AI.Pathfinding; @@ -11,7 +10,6 @@ using Content.Server.AI.Pathfinding.Pathfinders; using Content.Server.CPUJob.JobQueues; using Content.Shared.ActionBlocker; using Content.Shared.Interaction.Helpers; -using Content.Shared.Movement; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -47,43 +45,43 @@ namespace Content.Server.AI.Steering /// private const float InRangeUnobstructedCooldown = 0.25f; - private Dictionary RunningAgents => _agentLists[_listIndex]; + private Dictionary RunningAgents => _agentLists[_listIndex]; // We'll cycle the running list every tick as all we're doing is getting a vector2 for the // agent's steering. Should help a lot given this is the most expensive operator by far. // The AI will keep moving, it's just it'll keep moving in its existing direction. // If we change to 20/30 TPS you might want to change this but for now it's fine - private readonly List> _agentLists = new(AgentListCount); + private readonly List> _agentLists = new(AgentListCount); private const int AgentListCount = 2; private int _listIndex; // Cache nextGrid - private readonly Dictionary _nextGrid = new(); + private readonly Dictionary _nextGrid = new(); /// /// Current live paths for AI /// - private readonly Dictionary> _paths = new(); + private readonly Dictionary> _paths = new(); /// /// Pathfinding request jobs we're waiting on /// - private readonly Dictionary> Job)> _pathfindingRequests = + private readonly Dictionary> Job)> _pathfindingRequests = new(); /// /// Keep track of how long we've been in 1 position and re-path if it's been too long /// - private readonly Dictionary _stuckCounter = new(); + private readonly Dictionary _stuckCounter = new(); /// /// Get a fixed position for the target entity; if they move then re-path /// - private readonly Dictionary _entityTargetPosition = new(); + private readonly Dictionary _entityTargetPosition = new(); // Anti-Stuck // Given the collision avoidance can lead to twitching need to store a reference position and check if we've been near this too long - private readonly Dictionary _stuckPositions = new(); + private readonly Dictionary _stuckPositions = new(); public override void Initialize() { @@ -91,7 +89,7 @@ namespace Content.Server.AI.Steering for (var i = 0; i < AgentListCount; i++) { - _agentLists.Add(new Dictionary()); + _agentLists.Add(new Dictionary()); } } @@ -101,7 +99,7 @@ namespace Content.Server.AI.Steering /// We'll add it to the movement list that has the least number of agents /// /// - public void Register(IEntity entity, IAiSteeringRequest steeringRequest) + public void Register(EntityUid entity, IAiSteeringRequest steeringRequest) { var lowestListCount = 1000; var lowestListIndex = 0; @@ -127,9 +125,9 @@ namespace Content.Server.AI.Steering /// /// /// - public void Unregister(IEntity entity) + public void Unregister(EntityUid entity) { - if (entity.TryGetComponent(out AiControllerComponent? controller)) + if (EntityManager.TryGetComponent(entity, out AiControllerComponent? controller)) { controller.VelocityDir = Vector2.Zero; } @@ -194,7 +192,7 @@ namespace Content.Server.AI.Steering /// /// /// - public bool IsRegistered(IEntity entity) + public bool IsRegistered(EntityUid entity) { foreach (var agentList in _agentLists) { @@ -245,26 +243,26 @@ namespace Content.Server.AI.Steering /// /// /// - private SteeringStatus Steer(IEntity entity, IAiSteeringRequest steeringRequest, float frameTime) + private SteeringStatus Steer(EntityUid entity, IAiSteeringRequest steeringRequest, float frameTime) { // Main optimisation to be done below is the redundant calls and adding more variables - if (entity.Deleted || - !entity.TryGetComponent(out AiControllerComponent? controller) || - !EntitySystem.Get().CanMove(entity.Uid) || - !entity.Transform.GridID.IsValid()) + if (Deleted(entity) || + !EntityManager.TryGetComponent(entity, out AiControllerComponent? controller) || + !EntitySystem.Get().CanMove(entity) || + !EntityManager.GetComponent(entity).GridID.IsValid()) { return SteeringStatus.NoPath; } var entitySteering = steeringRequest as EntityTargetSteeringRequest; - if (entitySteering != null && entitySteering.Target.Deleted) + if (entitySteering != null && (!EntityManager.EntityExists(entitySteering.Target) ? EntityLifeStage.Deleted : EntityManager.GetComponent(entitySteering.Target).EntityLifeStage) >= EntityLifeStage.Deleted) { controller.VelocityDir = Vector2.Zero; return SteeringStatus.NoPath; } - if (_pauseManager.IsGridPaused(entity.Transform.GridID)) + if (_pauseManager.IsGridPaused(EntityManager.GetComponent(entity).GridID)) { controller.VelocityDir = Vector2.Zero; return SteeringStatus.Pending; @@ -272,14 +270,14 @@ namespace Content.Server.AI.Steering // Validation // Check if we can even arrive -> Currently only samegrid movement supported - if (entity.Transform.GridID != steeringRequest.TargetGrid.GetGridId(EntityManager)) + if (EntityManager.GetComponent(entity).GridID != steeringRequest.TargetGrid.GetGridId(EntityManager)) { controller.VelocityDir = Vector2.Zero; return SteeringStatus.NoPath; } // Check if we have arrived - var targetDistance = (entity.Transform.MapPosition.Position - steeringRequest.TargetMap.Position).Length; + var targetDistance = (EntityManager.GetComponent(entity).MapPosition.Position - steeringRequest.TargetMap.Position).Length; steeringRequest.TimeUntilInteractionCheck -= frameTime; if (targetDistance <= steeringRequest.ArrivalDistance && steeringRequest.TimeUntilInteractionCheck <= 0.0f) @@ -348,7 +346,7 @@ namespace Content.Server.AI.Steering return SteeringStatus.Pending; } - var ignoredCollision = new List(); + var ignoredCollision = new List(); // Check if the target entity has moved - If so then re-path // TODO: Patch the path from the target's position back towards us, stopping if it ever intersects the current path // Probably need a separate "PatchPath" job @@ -408,7 +406,7 @@ namespace Content.Server.AI.Steering /// /// /// - private void RequestPath(IEntity entity, IAiSteeringRequest steeringRequest) + private void RequestPath(EntityUid entity, IAiSteeringRequest steeringRequest) { if (_pathfindingRequests.ContainsKey(entity)) { @@ -416,19 +414,19 @@ namespace Content.Server.AI.Steering } var cancelToken = new CancellationTokenSource(); - var gridManager = _mapManager.GetGrid(entity.Transform.GridID); - var startTile = gridManager.GetTileRef(entity.Transform.Coordinates); + var gridManager = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID); + var startTile = gridManager.GetTileRef(EntityManager.GetComponent(entity).Coordinates); var endTile = gridManager.GetTileRef(steeringRequest.TargetGrid); var collisionMask = 0; - if (entity.TryGetComponent(out IPhysBody? physics)) + if (EntityManager.TryGetComponent(entity, out IPhysBody? physics)) { collisionMask = physics.CollisionMask; } - var access = _accessReader.FindAccessTags(entity.Uid); + var access = _accessReader.FindAccessTags(entity); var job = _pathfindingSystem.RequestPath(new PathfindingArgs( - entity.Uid, + entity, access, collisionMask, startTile, @@ -443,11 +441,11 @@ namespace Content.Server.AI.Steering /// /// /// - private void UpdatePath(IEntity entity, Queue path) + private void UpdatePath(EntityUid entity, Queue path) { _pathfindingRequests.Remove(entity); - var entityTile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.Coordinates); + var entityTile = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID).GetTileRef(EntityManager.GetComponent(entity).Coordinates); var tile = path.Dequeue(); var closestDistance = PathfindingHelpers.OctileDistance(entityTile, tile); @@ -474,7 +472,7 @@ namespace Content.Server.AI.Steering /// /// /// - private EntityCoordinates? NextGrid(IEntity entity, IAiSteeringRequest steeringRequest) + private EntityCoordinates? NextGrid(EntityUid entity, IAiSteeringRequest steeringRequest) { // Remove the cached grid if (!_paths.ContainsKey(entity) && _nextGrid.ContainsKey(entity)) @@ -485,7 +483,7 @@ namespace Content.Server.AI.Steering // If no tiles left just move towards the target (if we're close) if (!_paths.ContainsKey(entity) || _paths[entity].Count == 0) { - if ((steeringRequest.TargetGrid.Position - entity.Transform.Coordinates.Position).Length <= 2.0f) + if ((steeringRequest.TargetGrid.Position - EntityManager.GetComponent(entity).Coordinates.Position).Length <= 2.0f) { return steeringRequest.TargetGrid; } @@ -495,7 +493,7 @@ namespace Content.Server.AI.Steering } if (!_nextGrid.TryGetValue(entity, out var nextGrid) || - (nextGrid.Position - entity.Transform.Coordinates.Position).Length <= TileTolerance) + (nextGrid.Position - EntityManager.GetComponent(entity).Coordinates.Position).Length <= TileTolerance) { UpdateGridCache(entity); nextGrid = _nextGrid[entity]; @@ -510,11 +508,11 @@ namespace Content.Server.AI.Steering /// /// /// - private void UpdateGridCache(IEntity entity, bool dequeue = true) + private void UpdateGridCache(EntityUid entity, bool dequeue = true) { if (_paths[entity].Count == 0) return; var nextTile = dequeue ? _paths[entity].Dequeue() : _paths[entity].Peek(); - var nextGrid = _mapManager.GetGrid(entity.Transform.GridID).GridTileToLocal(nextTile.GridIndices); + var nextGrid = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID).GridTileToLocal(nextTile.GridIndices); _nextGrid[entity] = nextGrid; } @@ -522,16 +520,16 @@ namespace Content.Server.AI.Steering /// Check if we've been near our last EntityCoordinates too long and try to fix it /// /// - private void HandleStuck(IEntity entity) + private void HandleStuck(EntityUid entity) { if (!_stuckPositions.TryGetValue(entity, out var stuckPosition)) { - _stuckPositions[entity] = entity.Transform.Coordinates; + _stuckPositions[entity] = EntityManager.GetComponent(entity).Coordinates; _stuckCounter[entity] = 0; return; } - if ((entity.Transform.Coordinates.Position - stuckPosition.Position).Length <= 1.0f) + if ((EntityManager.GetComponent(entity).Coordinates.Position - stuckPosition.Position).Length <= 1.0f) { _stuckCounter.TryGetValue(entity, out var stuckCount); _stuckCounter[entity] = stuckCount + 1; @@ -539,7 +537,7 @@ namespace Content.Server.AI.Steering else { // No longer stuck - _stuckPositions[entity] = entity.Transform.Coordinates; + _stuckPositions[entity] = EntityManager.GetComponent(entity).Coordinates; _stuckCounter[entity] = 0; return; } @@ -562,10 +560,10 @@ namespace Content.Server.AI.Steering /// /// /// - private Vector2 Seek(IEntity entity, EntityCoordinates grid) + private Vector2 Seek(EntityUid entity, EntityCoordinates grid) { // is-even much - var entityPos = entity.Transform.Coordinates; + var entityPos = EntityManager.GetComponent(entity).Coordinates; return entityPos == grid ? Vector2.Zero : (grid.Position - entityPos.Position).Normalized; @@ -578,9 +576,9 @@ namespace Content.Server.AI.Steering /// /// /// - private Vector2 Arrival(IEntity entity, EntityCoordinates grid, float slowingDistance = 1.0f) + private Vector2 Arrival(EntityUid entity, EntityCoordinates grid, float slowingDistance = 1.0f) { - var entityPos = entity.Transform.Coordinates; + var entityPos = EntityManager.GetComponent(entity).Coordinates; DebugTools.Assert(slowingDistance > 0.0f); if (entityPos == grid) { @@ -597,16 +595,16 @@ namespace Content.Server.AI.Steering /// /// /// - private Vector2 Pursuit(IEntity entity, IEntity target) + private Vector2 Pursuit(EntityUid entity, EntityUid target) { - var entityPos = entity.Transform.Coordinates; - var targetPos = target.Transform.Coordinates; + var entityPos = EntityManager.GetComponent(entity).Coordinates; + var targetPos = EntityManager.GetComponent(target).Coordinates; if (entityPos == targetPos) { return Vector2.Zero; } - if (target.TryGetComponent(out IPhysBody? physics)) + if (EntityManager.TryGetComponent(target, out IPhysBody? physics)) { var targetDistance = (targetPos.Position - entityPos.Position); targetPos = targetPos.Offset(physics.LinearVelocity * targetDistance); @@ -622,9 +620,9 @@ namespace Content.Server.AI.Steering /// entity's travel direction /// /// - private Vector2 CollisionAvoidance(IEntity entity, Vector2 direction, ICollection ignoredTargets) + private Vector2 CollisionAvoidance(EntityUid entity, Vector2 direction, ICollection ignoredTargets) { - if (direction == Vector2.Zero || !entity.TryGetComponent(out IPhysBody? physics)) + if (direction == Vector2.Zero || !EntityManager.TryGetComponent(entity, out IPhysBody? physics)) { return Vector2.Zero; } @@ -636,8 +634,8 @@ namespace Content.Server.AI.Steering var avoidanceVector = Vector2.Zero; var checkTiles = new HashSet(); var avoidTiles = new HashSet(); - var entityGridCoords = entity.Transform.Coordinates; - var grid = _mapManager.GetGrid(entity.Transform.GridID); + var entityGridCoords = EntityManager.GetComponent(entity).Coordinates; + var grid = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID); var currentTile = grid.GetTileRef(entityGridCoords); var halfwayTile = grid.GetTileRef(entityGridCoords.Offset(direction / 2)); var nextTile = grid.GetTileRef(entityGridCoords.Offset(direction)); @@ -660,18 +658,18 @@ namespace Content.Server.AI.Steering // err for now we'll just assume the first entity is the center and just add a vector for it //Pathfinding updates are deferred so this may not be done yet. - if (physicsEntity.Deleted) continue; + if (Deleted(physicsEntity)) continue; // if we're moving in the same direction then ignore // So if 2 entities are moving towards each other and both detect a collision they'll both move in the same direction // i.e. towards the right - if (physicsEntity.TryGetComponent(out IPhysBody? otherPhysics) && + if (EntityManager.TryGetComponent(physicsEntity, out IPhysBody? otherPhysics) && Vector2.Dot(otherPhysics.LinearVelocity, direction) > 0) { continue; } - var centerGrid = physicsEntity.Transform.Coordinates; + var centerGrid = EntityManager.GetComponent(physicsEntity).Coordinates; // Check how close we are to center of tile and get the inverse; if we're closer this is stronger var additionalVector = (centerGrid.Position - entityGridCoords.Position); var distance = additionalVector.Length; diff --git a/Content.Server/AI/Steering/EntityTargetSteeringRequest.cs b/Content.Server/AI/Steering/EntityTargetSteeringRequest.cs index 7480ad325c..e4cf246772 100644 --- a/Content.Server/AI/Steering/EntityTargetSteeringRequest.cs +++ b/Content.Server/AI/Steering/EntityTargetSteeringRequest.cs @@ -1,4 +1,5 @@ using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; namespace Content.Server.AI.Steering @@ -6,10 +7,10 @@ namespace Content.Server.AI.Steering public sealed class EntityTargetSteeringRequest : IAiSteeringRequest { public SteeringStatus Status { get; set; } = SteeringStatus.Pending; - public MapCoordinates TargetMap => _target.Transform.MapPosition; - public EntityCoordinates TargetGrid => _target.Transform.Coordinates; - public IEntity Target => _target; - private readonly IEntity _target; + public MapCoordinates TargetMap => IoCManager.Resolve().GetComponent(_target).MapPosition; + public EntityCoordinates TargetGrid => IoCManager.Resolve().GetComponent(_target).Coordinates; + public EntityUid Target => _target; + private readonly EntityUid _target; /// public float ArrivalDistance { get; } @@ -30,7 +31,7 @@ namespace Content.Server.AI.Steering /// public float TimeUntilInteractionCheck { get; set; } - public EntityTargetSteeringRequest(IEntity target, float arrivalDistance, float pathfindingProximity = 0.5f, bool requiresInRangeUnobstructed = false) + public EntityTargetSteeringRequest(EntityUid target, float arrivalDistance, float pathfindingProximity = 0.5f, bool requiresInRangeUnobstructed = false) { _target = target; ArrivalDistance = arrivalDistance; diff --git a/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs b/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs index 2051a1584c..9fcb56e390 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Gloves { public sealed class EquipGloves : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs b/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs index 70cdaaff15..f3c3d7c4dd 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Gloves { public sealed class PickUpGloves : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs b/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs index 3f3a7f664f..9429572ada 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Head { public sealed class EquipHead : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs b/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs index 6a380a115b..d756710afe 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Head { public sealed class PickUpHead : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs index a9bc02db85..fd1b7f2e81 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.OuterClothing { public sealed class EquipOuterClothing : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs index e15440b701..501b8ca7ab 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.OuterClothing { public sealed class PickUpOuterClothing : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs b/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs index d3ce78c7ff..f35416f313 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Shoes { public sealed class EquipShoes : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs b/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs index a1780a5115..49db12a914 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Shoes { public sealed class PickUpShoes : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs index 2a727425ae..3f600d9c6b 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class EquipMelee : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs index 453e793545..0885487bb2 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs @@ -21,13 +21,13 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class MeleeWeaponAttackEntity : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { MoveToEntityOperator moveOperator; var equipped = context.GetState().GetValue(); - if (equipped != null && equipped.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) + if (equipped != default && IoCManager.Resolve().TryGetComponent(equipped, out MeleeWeaponComponent? meleeWeaponComponent)) { moveOperator = new MoveToEntityOperator(Owner, Target, meleeWeaponComponent.Range - 0.01f); } diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs index 272bbbdf2c..c33e420922 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class PickUpMeleeWeapon : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs index 873b2440ee..524e77eb9d 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs @@ -19,12 +19,12 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class UnarmedAttackEntity : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { MoveToEntityOperator moveOperator; - if (Owner.TryGetComponent(out UnarmedCombatComponent? unarmedCombatComponent)) + if (IoCManager.Resolve().TryGetComponent(Owner, out UnarmedCombatComponent? unarmedCombatComponent)) { moveOperator = new MoveToEntityOperator(Owner, Target, unarmedCombatComponent.Range - 0.01f); } diff --git a/Content.Server/AI/Utility/Actions/IAiUtility.cs b/Content.Server/AI/Utility/Actions/IAiUtility.cs index c09989707c..fc7f5bb0b8 100644 --- a/Content.Server/AI/Utility/Actions/IAiUtility.cs +++ b/Content.Server/AI/Utility/Actions/IAiUtility.cs @@ -7,7 +7,7 @@ namespace Content.Server.AI.Utility.Actions /// /// NPC this action is attached to. /// - IEntity Owner { get; set; } + EntityUid Owner { get; set; } /// /// Highest possible score for this action. diff --git a/Content.Server/AI/Utility/Actions/Idle/WanderAndWait.cs b/Content.Server/AI/Utility/Actions/Idle/WanderAndWait.cs index 52d4657094..4422837905 100644 --- a/Content.Server/AI/Utility/Actions/Idle/WanderAndWait.cs +++ b/Content.Server/AI/Utility/Actions/Idle/WanderAndWait.cs @@ -81,7 +81,7 @@ namespace Content.Server.AI.Utility.Actions.Idle var targetNode = robustRandom.Pick(reachableNodes); var mapManager = IoCManager.Resolve(); - var grid = mapManager.GetGrid(Owner.Transform.GridID); + var grid = mapManager.GetGrid(IoCManager.Resolve().GetComponent(Owner).GridID); var targetGrid = grid.GridTileToLocal(targetNode.TileRef.GridIndices); return targetGrid; diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs b/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs index 9f7e7e6ac0..0987af5f08 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Drink { public sealed class PickUpDrink : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs b/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs index 7ef0ee9a02..fe18717229 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Drink { public sealed class UseDrinkInInventory : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs b/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs index 24ede12d18..b4760e884e 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Food { public sealed class PickUpFood : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs b/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs index 2bce14ccfa..6b76794694 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Food { public sealed class UseFoodInInventory : UtilityAction { - public IEntity Target { get; set; } = default!; + public EntityUid Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Test/MoveRightAndLeftTen.cs b/Content.Server/AI/Utility/Actions/Test/MoveRightAndLeftTen.cs index 57ea73172b..0e5955c39b 100644 --- a/Content.Server/AI/Utility/Actions/Test/MoveRightAndLeftTen.cs +++ b/Content.Server/AI/Utility/Actions/Test/MoveRightAndLeftTen.cs @@ -19,8 +19,9 @@ namespace Content.Server.AI.Utility.Actions.Test public override void SetupOperators(Blackboard context) { - var currentPosition = Owner.Transform.Coordinates; - var nextPosition = Owner.Transform.Coordinates.Offset(new Vector2(10.0f, 0.0f)); + var entMan = IoCManager.Resolve(); + var currentPosition = entMan.GetComponent(Owner).Coordinates; + var nextPosition = entMan.GetComponent(Owner).Coordinates.Offset(new Vector2(10.0f, 0.0f)); var originalPosOp = new MoveToGridOperator(Owner, currentPosition, 0.25f); var newPosOp = new MoveToGridOperator(Owner, nextPosition, 0.25f); diff --git a/Content.Server/AI/Utility/Actions/UtilityAction.cs b/Content.Server/AI/Utility/Actions/UtilityAction.cs index fe906ad38e..9d8b48ee27 100644 --- a/Content.Server/AI/Utility/Actions/UtilityAction.cs +++ b/Content.Server/AI/Utility/Actions/UtilityAction.cs @@ -36,7 +36,7 @@ namespace Content.Server.AI.Utility.Actions public const float CombatBonus = 30.0f; public const float DangerBonus = 50.0f; - public IEntity Owner { get; set; } + public EntityUid Owner { get; set; } /// /// All the considerations are multiplied together to get the final score; a consideration of 0.0 means the action is not possible. diff --git a/Content.Server/AI/Utility/AiLogic/UtilityAI.cs b/Content.Server/AI/Utility/AiLogic/UtilityAI.cs index 3e735df191..565c402294 100644 --- a/Content.Server/AI/Utility/AiLogic/UtilityAI.cs +++ b/Content.Server/AI/Utility/AiLogic/UtilityAI.cs @@ -145,7 +145,7 @@ namespace Content.Server.AI.Utility.AiLogic { _planCooldownRemaining = PlanCooldown; _actionCancellation = new CancellationTokenSource(); - _actionRequest = _planner.RequestAction(new AiActionRequest(Owner.Uid, _blackboard, AvailableActions), _actionCancellation); + _actionRequest = _planner.RequestAction(new AiActionRequest(Owner, _blackboard, AvailableActions), _actionCancellation); return; } diff --git a/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs b/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs index 83a7db8947..18ffa4ac79 100644 --- a/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs +++ b/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs @@ -12,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.ActionBlocker { var self = context.GetState().GetValue(); - if (self == null || !EntitySystem.Get().CanMove(self.Uid)) + if (self == null || !EntitySystem.Get().CanMove(self)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs b/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs index 1dd5b9b8e7..2b20a2b3e7 100644 --- a/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs +++ b/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs @@ -3,6 +3,8 @@ using Content.Server.AI.WorldState.States.Clothing; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Clothing { @@ -23,7 +25,7 @@ namespace Content.Server.AI.Utility.Considerations.Clothing foreach (var entity in context.GetState().GetValue()) { - if (!entity.TryGetComponent(out ClothingComponent? clothingComponent)) + if (!IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothingComponent)) { continue; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs index 40877f75eb..07f8990b31 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.Weapon.Melee.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat.Melee { @@ -8,7 +10,9 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee { protected override float GetScore(Blackboard context) { - return context.GetState().GetValue()?.HasComponent() ?? false ? 1.0f : 0.0f; + var entityManager = IoCManager.Resolve(); + var entity = context.GetState().GetValue(); + return entityManager.HasComponent(entity) ? 1.0f : 0.0f; } } } diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/HasMeleeWeaponCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/HasMeleeWeaponCon.cs index 8c62d2d56d..7208b6d533 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/HasMeleeWeaponCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/HasMeleeWeaponCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Weapon.Melee.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat.Melee { @@ -10,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee { foreach (var item in context.GetState().GetValue()) { - if (item.HasComponent()) + if (IoCManager.Resolve().HasComponent(item)) { return 1.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs index 470db45994..6c5c317bed 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States.Combat; using Content.Server.Weapon.Melee.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat.Melee { @@ -10,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) + if (target == null || !IoCManager.Resolve().TryGetComponent(target, out MeleeWeaponComponent? meleeWeaponComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponEquippedCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponEquippedCon.cs index 572f042409..60a383e9cb 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponEquippedCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponEquippedCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Weapon.Melee.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat.Melee { @@ -15,7 +17,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee return 0.0f; } - return equipped.HasComponent() ? 1.0f : 0.0f; + return IoCManager.Resolve().HasComponent(equipped) ? 1.0f : 0.0f; } } } diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs index 1c877e75bc..d84c977509 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States.Combat; using Content.Server.Weapon.Melee.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat.Melee { @@ -10,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) + if (target == null || !IoCManager.Resolve().TryGetComponent(target, out MeleeWeaponComponent? meleeWeaponComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs b/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs index 9196904a72..47f23d0f41 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Shared.Damage; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat { @@ -10,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat { var target = context.GetState().GetValue(); - if (target == null || target.Deleted || !target.TryGetComponent(out DamageableComponent? damageableComponent)) + if (target == null || !IoCManager.Resolve().TryGetComponent(target, out DamageableComponent? damageableComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs b/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs index 7bd4ff2adb..37b3f99552 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Shared.MobState.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat { @@ -10,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out MobStateComponent? mobState)) + if (target == null || !IoCManager.Resolve().TryGetComponent(target, out MobStateComponent? mobState)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs b/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs index 271c1ff929..26622c9723 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Shared.MobState.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Combat { @@ -10,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out MobStateComponent? mobState)) + if (target == null || !IoCManager.Resolve().TryGetComponent(target, out MobStateComponent? mobState)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs b/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs index 234a98c612..ebed8d3c34 100644 --- a/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs +++ b/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs @@ -5,6 +5,7 @@ using Content.Server.Storage.Components; using Content.Shared.Interaction; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Containers { @@ -16,15 +17,16 @@ namespace Content.Server.AI.Utility.Considerations.Containers { protected override float GetScore(Blackboard context) { + var entMan = IoCManager.Resolve(); var target = context.GetState().GetValue(); - if (target == null) + if (!entMan.EntityExists(target)) { return 0.0f; } if (target.TryGetContainer(out var container)) { - if (container.Owner.TryGetComponent(out EntityStorageComponent? storageComponent)) + if (entMan.TryGetComponent(container.Owner, out EntityStorageComponent? storageComponent)) { if (storageComponent.IsWeldedShut && !storageComponent.Open) { diff --git a/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs b/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs index 6f12825434..029775d5f3 100644 --- a/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs +++ b/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs @@ -1,6 +1,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.Hands.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Hands { @@ -10,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Hands { var owner = context.GetState().GetValue(); - if (owner == null || !owner.TryGetComponent(out HandsComponent? handsComponent)) + if (owner == null || !IoCManager.Resolve().TryGetComponent(owner, out HandsComponent? handsComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Inventory/CanPutTargetInInventoryCon.cs b/Content.Server/AI/Utility/Considerations/Inventory/CanPutTargetInInventoryCon.cs index cc7572469e..14ccfbf4d2 100644 --- a/Content.Server/AI/Utility/Considerations/Inventory/CanPutTargetInInventoryCon.cs +++ b/Content.Server/AI/Utility/Considerations/Inventory/CanPutTargetInInventoryCon.cs @@ -3,6 +3,8 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Hands; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Items; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Inventory { @@ -14,7 +16,7 @@ namespace Content.Server.AI.Utility.Considerations.Inventory // If not then check if we have a free hand var target = context.GetState().GetValue(); - if (target == null || !target.HasComponent()) + if (target == null || !IoCManager.Resolve().HasComponent(target)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Inventory/TargetInOurInventoryCon.cs b/Content.Server/AI/Utility/Considerations/Inventory/TargetInOurInventoryCon.cs index 63da53c697..b7fcd97b1c 100644 --- a/Content.Server/AI/Utility/Considerations/Inventory/TargetInOurInventoryCon.cs +++ b/Content.Server/AI/Utility/Considerations/Inventory/TargetInOurInventoryCon.cs @@ -2,6 +2,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Items; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Inventory { @@ -11,7 +13,7 @@ namespace Content.Server.AI.Utility.Considerations.Inventory { var target = context.GetState().GetValue(); - if (target == null || !target.HasComponent()) + if (target == null || !IoCManager.Resolve().HasComponent(target)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs b/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs index e3c912acf5..db4bcc0263 100644 --- a/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs +++ b/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs @@ -1,5 +1,7 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Movement { @@ -8,14 +10,16 @@ namespace Content.Server.AI.Utility.Considerations.Movement protected override float GetScore(Blackboard context) { var self = context.GetState().GetValue(); - var target = context.GetState().GetValue(); - if (target == null || target.Deleted || target.Transform.GridID != self?.Transform.GridID) + var entities = IoCManager.Resolve(); + + if (context.GetState().GetValue() is not {Valid: true} target || entities.Deleted(target) || + entities.GetComponent(target).GridID != entities.GetComponent(self).GridID) { return 0.0f; } // Anything further than 100 tiles gets clamped - return (target.Transform.Coordinates.Position - self.Transform.Coordinates.Position).Length / 100; + return (entities.GetComponent(target).Coordinates.Position - entities.GetComponent(self).Coordinates.Position).Length / 100; } } } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs index 8ef53c8a46..e7a7fbc5ca 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs @@ -3,6 +3,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.Chemistry.EntitySystems; using Content.Server.Nutrition.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Nutrition.Drink { @@ -13,8 +14,8 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Drink var target = context.GetState().GetValue(); if (target == null - || target.Deleted - || !EntitySystem.Get().TryGetSolution(target.Uid, DrinkComponent.DefaultSolutionName, out var drink)) + || IoCManager.Resolve().Deleted(target) + || !EntitySystem.Get().TryGetSolution(target, DrinkComponent.DefaultSolutionName, out var drink)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs index 1a3c97f718..6ea21c75db 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs @@ -2,6 +2,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.Nutrition.Components; using Content.Shared.Nutrition.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Nutrition.Drink { @@ -11,7 +13,7 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Drink { var owner = context.GetState().GetValue(); - if (owner == null || !owner.TryGetComponent(out ThirstComponent? thirst)) + if (owner == null || !IoCManager.Resolve().TryGetComponent(owner, out ThirstComponent? thirst)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs index 3c370a1a32..3341d8a193 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs @@ -3,6 +3,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.Chemistry.EntitySystems; using Content.Server.Nutrition.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Nutrition.Food { @@ -12,8 +13,8 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Food { var target = context.GetState().GetValue(); - if (target == null || target.Deleted || !target.TryGetComponent(out var foodComp) || - !EntitySystem.Get().TryGetSolution(target.Uid, foodComp.SolutionName, out var food)) + if (target == null || !IoCManager.Resolve().TryGetComponent(target, out var foodComp) + || !EntitySystem.Get().TryGetSolution(target, foodComp.SolutionName, out var food)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs index bdc5284094..33cc9dca90 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs @@ -2,6 +2,8 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.Nutrition.Components; using Content.Shared.Nutrition.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Considerations.Nutrition.Food { @@ -12,7 +14,7 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Food { var owner = context.GetState().GetValue(); - if (owner == null || !owner.TryGetComponent(out HungerComponent? hunger)) + if (owner == null || !IoCManager.Resolve().TryGetComponent(owner, out HungerComponent? hunger)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs b/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs index 4e53cdab94..17c41986ae 100644 --- a/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs +++ b/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs @@ -27,7 +27,7 @@ namespace Content.Server.AI.Utility.Considerations.State return 0; } - context.GetStoredState(stateData, out StoredStateData state); + context.GetStoredState(stateData, out StoredStateData state); return state.GetValue() == null ? 1.0f : 0.0f; } } diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs index 139083588f..e570698cc6 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Gloves @@ -37,7 +38,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Gloves foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.GLOVES) != 0) { yield return new EquipGloves {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs index 669fe88dc2..959a4a6d87 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Clothing; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Gloves @@ -35,7 +36,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Gloves foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.GLOVES) != 0) { yield return new PickUpGloves {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs index 23d6af0a6e..62f675ae1c 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Head @@ -36,7 +37,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Head foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.HEAD) != 0) { yield return new EquipHead {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs index b69972cbee..0e1ad0e81c 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Clothing; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Head @@ -35,7 +36,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Head foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.HEAD) != 0) { yield return new PickUpHead {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs index 7dfaf113ac..88fc7d3cf3 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.OuterClothing @@ -37,7 +38,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.OuterClothing foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.OUTERCLOTHING) != 0) { yield return new EquipOuterClothing {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs index 965ccf9a78..3134bd14d3 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Clothing; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.OuterClothing @@ -36,7 +37,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.OuterClothing foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.OUTERCLOTHING) != 0) { yield return new PickUpOuterClothing {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs index a5192d9a8e..85077d611c 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Shoes @@ -37,7 +38,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Shoes foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.SHOES) != 0) { yield return new EquipShoes {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs index 404db0235b..dca91f730d 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs @@ -9,6 +9,7 @@ using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Clothing; using Content.Server.Clothing.Components; using Content.Shared.Inventory; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Shoes @@ -36,7 +37,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Shoes foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent? clothing) && + if (IoCManager.Resolve().TryGetComponent(entity, out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.SHOES) != 0) { yield return new PickUpShoes {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs index f00032693d..ef5ba1d2c2 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs @@ -8,6 +8,7 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Weapon.Melee.Components; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee @@ -33,7 +34,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee foreach (var entity in context.GetState().GetValue()) { - if (!entity.HasComponent()) + if (!IoCManager.Resolve().HasComponent(entity)) { continue; } diff --git a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs index 7b8f7d8144..59d0f9a3d7 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs @@ -31,7 +31,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee public override IEnumerable GetActions(Blackboard context) { var owner = context.GetState().GetValue(); - if (!owner.TryGetComponent(out AiControllerComponent? controller)) + if (!IoCManager.Resolve().TryGetComponent(owner, out AiControllerComponent? controller)) { throw new InvalidOperationException(); } diff --git a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs index 97e88c1536..2d06446922 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs @@ -31,7 +31,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee public override IEnumerable GetActions(Blackboard context) { var owner = context.GetState().GetValue(); - if (!owner.TryGetComponent(out AiControllerComponent? controller)) + if (!IoCManager.Resolve().TryGetComponent(owner, out AiControllerComponent? controller)) { throw new InvalidOperationException(); } diff --git a/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs b/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs index 6c3d79ba6c..8a4278a601 100644 --- a/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs +++ b/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs @@ -12,7 +12,7 @@ namespace Content.Server.AI.Utility.ExpandableActions /// public abstract class ExpandableUtilityAction : IAiUtility { - public IEntity Owner { get; set; } = default!; + public EntityUid Owner { get; set; } = default!; public abstract float Bonus { get; } diff --git a/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseDrinkInInventoryExp.cs b/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseDrinkInInventoryExp.cs index 3abcbbcbbe..4ba283ae27 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseDrinkInInventoryExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseDrinkInInventoryExp.cs @@ -8,6 +8,7 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Nutrition.Components; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Nutrition @@ -31,7 +32,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Nutrition foreach (var entity in context.GetState().GetValue()) { - if (!entity.HasComponent()) + if (!IoCManager.Resolve().HasComponent(entity)) { continue; } diff --git a/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseFoodInInventoryExp.cs b/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseFoodInInventoryExp.cs index 4b2fde45f0..dcba00439a 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseFoodInInventoryExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Nutrition/UseFoodInInventoryExp.cs @@ -8,6 +8,7 @@ using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; using Content.Server.Nutrition.Components; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.ExpandableActions.Nutrition @@ -31,7 +32,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Nutrition foreach (var entity in context.GetState().GetValue()) { - if (!entity.HasComponent()) + if (!IoCManager.Resolve().HasComponent(entity)) { continue; } diff --git a/Content.Server/AI/Utility/UtilityAiHelpers.cs b/Content.Server/AI/Utility/UtilityAiHelpers.cs index a1765b9390..733ad15029 100644 --- a/Content.Server/AI/Utility/UtilityAiHelpers.cs +++ b/Content.Server/AI/Utility/UtilityAiHelpers.cs @@ -2,14 +2,15 @@ using Content.Server.AI.Components; using Content.Server.AI.Utility.AiLogic; using Content.Server.AI.WorldState; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.Utility { public static class UtilityAiHelpers { - public static Blackboard? GetBlackboard(IEntity entity) + public static Blackboard? GetBlackboard(EntityUid entity) { - if (!entity.TryGetComponent(out AiControllerComponent? aiControllerComponent)) + if (!IoCManager.Resolve().TryGetComponent(entity, out AiControllerComponent? aiControllerComponent)) { return null; } diff --git a/Content.Server/AI/Utils/Visibility.cs b/Content.Server/AI/Utils/Visibility.cs index e94fb5e398..772b94d63e 100644 --- a/Content.Server/AI/Utils/Visibility.cs +++ b/Content.Server/AI/Utils/Visibility.cs @@ -1,39 +1,37 @@ using System; using System.Collections.Generic; using System.Linq; -using Content.Server.AI.Components; -using Content.Shared.Physics; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; -using Robust.Shared.Maths; -using Robust.Shared.Physics; -using Robust.Shared.Physics.Broadphase; namespace Content.Server.AI.Utils { public static class Visibility { // Should this be in robust or something? Fark it - public static IEnumerable GetNearestEntities(EntityCoordinates grid, Type component, float range) + public static IEnumerable GetNearestEntities(EntityCoordinates grid, Type component, float range) { + var entMan = IoCManager.Resolve(); var inRange = GetEntitiesInRange(grid, component, range).ToList(); - var sortedInRange = inRange.OrderBy(o => (o.Transform.Coordinates.Position - grid.Position).Length); + var sortedInRange = inRange.OrderBy(o => (entMan.GetComponent(o).Coordinates.Position - grid.Position).Length); return sortedInRange; } - public static IEnumerable GetEntitiesInRange(EntityCoordinates grid, Type component, float range) + public static IEnumerable GetEntitiesInRange(EntityCoordinates grid, Type component, float range) { var entityManager = IoCManager.Resolve(); foreach (var entity in entityManager.GetAllComponents(component).Select(c => c.Owner)) { - if (entity.Transform.Coordinates.GetGridId(entityManager) != grid.GetGridId(entityManager)) + var transform = entityManager.GetComponent(entity); + + if (transform.Coordinates.GetGridId(entityManager) != grid.GetGridId(entityManager)) { continue; } - if ((entity.Transform.Coordinates.Position - grid.Position).Length <= range) + if ((transform.Coordinates.Position - grid.Position).Length <= range) { yield return entity; } diff --git a/Content.Server/AI/WorldState/Blackboard.cs b/Content.Server/AI/WorldState/Blackboard.cs index eb33315fac..83eecd0f83 100644 --- a/Content.Server/AI/WorldState/Blackboard.cs +++ b/Content.Server/AI/WorldState/Blackboard.cs @@ -12,18 +12,18 @@ namespace Content.Server.AI.WorldState { // Some stuff like "My Health" is easy to represent as components but abstract stuff like "How much food is nearby" // is harder. This also allows data to be cached if it's being hit frequently. - + // This also stops you from re-writing the same boilerplate everywhere of stuff like "Do I have OuterClothing on?" private readonly Dictionary _states = new(); private readonly List _planningStates = new(); - public Blackboard(IEntity owner) + public Blackboard(EntityUid owner) { Setup(owner); } - private void Setup(IEntity owner) + private void Setup(EntityUid owner) { var typeFactory = IoCManager.Resolve(); var blackboardManager = IoCManager.Resolve(); diff --git a/Content.Server/AI/WorldState/StateData.cs b/Content.Server/AI/WorldState/StateData.cs index 8563ef57fe..ad55329f53 100644 --- a/Content.Server/AI/WorldState/StateData.cs +++ b/Content.Server/AI/WorldState/StateData.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.WorldState /// public interface IAiState { - void Setup(IEntity owner); + void Setup(EntityUid owner); } public interface IPlanningState @@ -32,9 +32,9 @@ namespace Content.Server.AI.WorldState public abstract class StateData : IAiState { public abstract string Name { get; } - protected IEntity Owner { get; private set; } = default!; + protected EntityUid Owner { get; private set; } = default!; - public void Setup(IEntity owner) + public void Setup(EntityUid owner) { Owner = owner; } @@ -51,11 +51,11 @@ namespace Content.Server.AI.WorldState { // Probably not the best class name but couldn't think of anything better public abstract string Name { get; } - private IEntity? Owner { get; set; } + private EntityUid Owner { get; set; } private T? _value; - public void Setup(IEntity owner) + public void Setup(EntityUid owner) { Owner = owner; } @@ -79,10 +79,10 @@ namespace Content.Server.AI.WorldState public abstract class PlanningStateData : IAiState, IPlanningState { public abstract string Name { get; } - protected IEntity? Owner { get; private set; } + protected EntityUid Owner { get; private set; } protected T? Value; - public void Setup(IEntity owner) + public void Setup(EntityUid owner) { Owner = owner; } @@ -108,7 +108,7 @@ namespace Content.Server.AI.WorldState public abstract class CachedStateData : IAiState, ICachedState { public abstract string Name { get; } - protected IEntity Owner { get; private set; } = default!; + protected EntityUid Owner { get; private set; } = default!; private bool _cached; protected T Value = default!; private TimeSpan _lastCache = TimeSpan.Zero; @@ -117,7 +117,7 @@ namespace Content.Server.AI.WorldState /// protected double CacheTime { get; set; } = 2.0f; - public void Setup(IEntity owner) + public void Setup(EntityUid owner) { Owner = owner; } diff --git a/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs b/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs index c9d642ad04..695dc524a9 100644 --- a/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs +++ b/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs @@ -3,19 +3,20 @@ using Content.Server.Inventory.Components; using Content.Shared.Inventory; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Clothing { [UsedImplicitly] - public sealed class EquippedClothingState : StateData> + public sealed class EquippedClothingState : StateData> { public override string Name => "EquippedClothing"; - public override Dictionary GetValue() + public override Dictionary GetValue() { - var result = new Dictionary(); + var result = new Dictionary(); - if (!Owner.TryGetComponent(out InventoryComponent? inventoryComponent)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out InventoryComponent? inventoryComponent)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs b/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs index 1907c8e019..e4f35c5f8a 100644 --- a/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs +++ b/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs @@ -6,29 +6,30 @@ using Content.Server.Storage.Components; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Clothing { [UsedImplicitly] - public sealed class NearbyClothingState : CachedStateData> + public sealed class NearbyClothingState : CachedStateData> { public override string Name => "NearbyClothing"; - protected override List GetTrueValue() + protected override List GetTrueValue() { - var result = new List(); + var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent? controller)) + var entMan = IoCManager.Resolve(); + if (!entMan.TryGetComponent(Owner, out AiControllerComponent? controller)) { return result; } - foreach (var entity in Visibility - .GetNearestEntities(Owner.Transform.Coordinates, typeof(ClothingComponent), controller.VisionRadius)) + foreach (var entity in Visibility.GetNearestEntities(entMan.GetComponent(Owner).Coordinates, typeof(ClothingComponent), controller.VisionRadius)) { if (entity.TryGetContainer(out var container)) { - if (!container.Owner.HasComponent()) + if (!entMan.HasComponent(container.Owner)) { continue; } diff --git a/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs b/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs index ad817ed313..7e6b1e6024 100644 --- a/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs +++ b/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs @@ -4,25 +4,26 @@ using Content.Server.AI.Utils; using Content.Server.Weapon.Melee.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Combat.Nearby { [UsedImplicitly] - public sealed class NearbyMeleeWeapons : CachedStateData> + public sealed class NearbyMeleeWeapons : CachedStateData> { public override string Name => "NearbyMeleeWeapons"; - protected override List GetTrueValue() + protected override List GetTrueValue() { - var result = new List(); + var result = new List(); + var entMan = IoCManager.Resolve(); - if (!Owner.TryGetComponent(out AiControllerComponent? controller)) + if (!entMan.TryGetComponent(Owner, out AiControllerComponent? controller)) { return result; } - foreach (var entity in Visibility - .GetNearestEntities(Owner.Transform.Coordinates, typeof(MeleeWeaponComponent), controller.VisionRadius)) + foreach (var entity in Visibility.GetNearestEntities(entMan.GetComponent(Owner).Coordinates, typeof(MeleeWeaponComponent), controller.VisionRadius)) { result.Add(entity); } diff --git a/Content.Server/AI/WorldState/States/Combat/WeaponEntityState.cs b/Content.Server/AI/WorldState/States/Combat/WeaponEntityState.cs index 369c7afd02..4ed2c20cc0 100644 --- a/Content.Server/AI/WorldState/States/Combat/WeaponEntityState.cs +++ b/Content.Server/AI/WorldState/States/Combat/WeaponEntityState.cs @@ -4,13 +4,13 @@ using Robust.Shared.GameObjects; namespace Content.Server.AI.WorldState.States.Combat { [UsedImplicitly] - public sealed class WeaponEntityState : PlanningStateData + public sealed class WeaponEntityState : PlanningStateData { // Similar to TargetEntity public override string Name => "WeaponEntity"; public override void Reset() { - Value = null; + Value = default; } } } diff --git a/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs b/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs index d960685999..9b33236cdb 100644 --- a/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs +++ b/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs @@ -1,5 +1,7 @@ using Content.Server.Hands.Components; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Hands { @@ -9,7 +11,7 @@ namespace Content.Server.AI.WorldState.States.Hands public override string Name => "AnyFreeHand"; public override bool GetValue() { - if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out HandsComponent? handsComponent)) { return false; } diff --git a/Content.Server/AI/WorldState/States/Hands/FreeHands.cs b/Content.Server/AI/WorldState/States/Hands/FreeHands.cs index 5214d65ea2..83bada9c2c 100644 --- a/Content.Server/AI/WorldState/States/Hands/FreeHands.cs +++ b/Content.Server/AI/WorldState/States/Hands/FreeHands.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; using Content.Server.Hands.Components; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Hands { @@ -13,7 +15,7 @@ namespace Content.Server.AI.WorldState.States.Hands { var result = new List(); - if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out HandsComponent? handsComponent)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs b/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs index 7651afcbc6..2a0ec7503b 100644 --- a/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs +++ b/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs @@ -2,17 +2,18 @@ using System.Collections.Generic; using Content.Server.Hands.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Hands { [UsedImplicitly] - public class HandItemsState : StateData> + public class HandItemsState : StateData> { public override string Name => "HandItems"; - public override List GetValue() + public override List GetValue() { - var result = new List(); - if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) + var result = new List(); + if (!IoCManager.Resolve().TryGetComponent(Owner, out HandsComponent? handsComponent)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs b/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs index f4615a6e52..fb2c55b130 100644 --- a/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs +++ b/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs @@ -1,6 +1,7 @@ using Content.Server.Hands.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Inventory { @@ -8,18 +9,18 @@ namespace Content.Server.AI.WorldState.States.Inventory /// AKA what's in active hand /// [UsedImplicitly] - public sealed class EquippedEntityState : StateData + public sealed class EquippedEntityState : StateData { public override string Name => "EquippedEntity"; - public override IEntity? GetValue() + public override EntityUid GetValue() { - if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out HandsComponent? handsComponent)) { - return null; + return default; } - return handsComponent.GetActiveHand?.Owner; + return handsComponent.GetActiveHand?.Owner ?? default; } } } diff --git a/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs b/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs index a26863f5a1..0294dfd93a 100644 --- a/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs +++ b/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs @@ -2,21 +2,23 @@ using System.Collections.Generic; using Content.Server.Hands.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Inventory { [UsedImplicitly] - public sealed class EnumerableInventoryState : StateData> + public sealed class EnumerableInventoryState : StateData> { public override string Name => "EnumerableInventory"; - public override IEnumerable GetValue() + public override IEnumerable GetValue() { - if (Owner.TryGetComponent(out HandsComponent? handsComponent)) + var entMan = IoCManager.Resolve(); + if (entMan.TryGetComponent(Owner, out HandsComponent? handsComponent)) { foreach (var item in handsComponent.GetAllHeldItems()) { - if (item.Owner.Deleted) + if (entMan.Deleted(item.Owner)) continue; yield return item.Owner; diff --git a/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs b/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs index 3654ed86d3..9471791287 100644 --- a/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs +++ b/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs @@ -1,5 +1,6 @@ using Content.Server.Storage.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; namespace Content.Server.AI.WorldState.States.Inventory @@ -8,16 +9,16 @@ namespace Content.Server.AI.WorldState.States.Inventory /// If we open a storage locker than it will be stored here /// Useful if we want to close it after /// - public sealed class LastOpenedStorageState : StoredStateData + public sealed class LastOpenedStorageState : StoredStateData { // TODO: IF we chain lockers need to handle it. // Fine for now I guess public override string Name => "LastOpenedStorage"; - public override void SetValue(IEntity? value) + public override void SetValue(EntityUid value) { base.SetValue(value); - if (value != null && !value.HasComponent()) + if (value.Valid && !IoCManager.Resolve().HasComponent(value)) { Logger.Warning("Set LastOpenedStorageState for an entity that doesn't have a storage component"); } diff --git a/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs b/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs index 1c20b224fa..98209d1f96 100644 --- a/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs +++ b/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs @@ -4,24 +4,26 @@ using Content.Server.AI.Utils; using Content.Shared.Body.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Mobs { [UsedImplicitly] - public sealed class NearbyBodiesState : CachedStateData> + public sealed class NearbyBodiesState : CachedStateData> { public override string Name => "NearbyBodies"; - protected override List GetTrueValue() + protected override List GetTrueValue() { - var result = new List(); + var result = new List(); + var entMan = IoCManager.Resolve(); - if (!Owner.TryGetComponent(out AiControllerComponent? controller)) + if (!entMan.TryGetComponent(Owner, out AiControllerComponent? controller)) { return result; } - foreach (var entity in Visibility.GetEntitiesInRange(Owner.Transform.Coordinates, typeof(SharedBodyComponent), controller.VisionRadius)) + foreach (var entity in Visibility.GetEntitiesInRange(entMan.GetComponent(Owner).Coordinates, typeof(SharedBodyComponent), controller.VisionRadius)) { if (entity == Owner) continue; result.Add(entity); diff --git a/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs b/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs index de1a38198f..e3b1c64226 100644 --- a/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs +++ b/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs @@ -1,44 +1,42 @@ using System.Collections.Generic; -using System.Linq; using Content.Server.AI.Components; using Content.Shared.Damage; using JetBrains.Annotations; -using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Map; using Robust.Shared.Player; namespace Content.Server.AI.WorldState.States.Mobs { [UsedImplicitly] - public sealed class NearbyPlayersState : CachedStateData> + public sealed class NearbyPlayersState : CachedStateData> { public override string Name => "NearbyPlayers"; - protected override List GetTrueValue() + protected override List GetTrueValue() { - var result = new List(); + var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent? controller)) + var entMan = IoCManager.Resolve(); + if (!entMan.TryGetComponent(Owner, out AiControllerComponent? controller)) { return result; } var nearbyPlayers = Filter.Empty() - .AddInRange(Owner.Transform.MapPosition, controller.VisionRadius) + .AddInRange(entMan.GetComponent(Owner).MapPosition, controller.VisionRadius) .Recipients; foreach (var player in nearbyPlayers) { - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {Valid: true} playerEntity) { continue; } - if (player.AttachedEntity != Owner && player.AttachedEntity.HasComponent()) + if (player.AttachedEntity != Owner && entMan.HasComponent(playerEntity)) { - result.Add(player.AttachedEntity); + result.Add(playerEntity); } } diff --git a/Content.Server/AI/WorldState/States/Movement/MoveTargetState.cs b/Content.Server/AI/WorldState/States/Movement/MoveTargetState.cs index 0acfa56ceb..48e8172ef3 100644 --- a/Content.Server/AI/WorldState/States/Movement/MoveTargetState.cs +++ b/Content.Server/AI/WorldState/States/Movement/MoveTargetState.cs @@ -4,12 +4,12 @@ using Robust.Shared.GameObjects; namespace Content.Server.AI.WorldState.States.Movement { [UsedImplicitly] - public sealed class MoveTargetState : PlanningStateData + public sealed class MoveTargetState : PlanningStateData { public override string Name => "MoveTarget"; public override void Reset() { - Value = null; + Value = default; } } } diff --git a/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs b/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs index 4f29487228..a9c9da5f74 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs @@ -2,6 +2,8 @@ using System; using Content.Server.Nutrition.Components; using Content.Shared.Nutrition.Components; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Nutrition { @@ -12,7 +14,7 @@ namespace Content.Server.AI.WorldState.States.Nutrition public override bool GetValue() { - if (!Owner.TryGetComponent(out HungerComponent? hungerComponent)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out HungerComponent? hungerComponent)) { return false; } diff --git a/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs b/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs index 6e64775696..1ff8f2d28e 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs @@ -6,29 +6,31 @@ using Content.Server.Storage.Components; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Nutrition { [UsedImplicitly] - public sealed class NearbyDrinkState: CachedStateData> + public sealed class NearbyDrinkState: CachedStateData> { public override string Name => "NearbyDrink"; - protected override List GetTrueValue() + protected override List GetTrueValue() { - var result = new List(); + var result = new List(); + var entMan = IoCManager.Resolve(); - if (!Owner.TryGetComponent(out AiControllerComponent? controller)) + if (!entMan.TryGetComponent(Owner, out AiControllerComponent? controller)) { return result; } foreach (var entity in Visibility - .GetNearestEntities(Owner.Transform.Coordinates, typeof(DrinkComponent), controller.VisionRadius)) + .GetNearestEntities(entMan.GetComponent(Owner).Coordinates, typeof(DrinkComponent), controller.VisionRadius)) { if (entity.TryGetContainer(out var container)) { - if (!container.Owner.HasComponent()) + if (!entMan.HasComponent(container.Owner)) { continue; } diff --git a/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs b/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs index fea5d0e76f..156670cfd4 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs @@ -6,29 +6,31 @@ using Content.Server.Storage.Components; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Nutrition { [UsedImplicitly] - public sealed class NearbyFoodState : CachedStateData> + public sealed class NearbyFoodState : CachedStateData> { public override string Name => "NearbyFood"; - protected override List GetTrueValue() + protected override List GetTrueValue() { - var result = new List(); + var result = new List(); + var entMan = IoCManager.Resolve(); - if (!Owner.TryGetComponent(out AiControllerComponent? controller)) + if (!entMan.TryGetComponent(Owner, out AiControllerComponent? controller)) { return result; } foreach (var entity in Visibility - .GetNearestEntities(Owner.Transform.Coordinates, typeof(FoodComponent), controller.VisionRadius)) + .GetNearestEntities(entMan.GetComponent(Owner).Coordinates, typeof(FoodComponent), controller.VisionRadius)) { if (entity.TryGetContainer(out var container)) { - if (!container.Owner.HasComponent()) + if (!entMan.HasComponent(container.Owner)) { continue; } diff --git a/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs b/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs index e9c120e91a..fc78103085 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs @@ -2,6 +2,8 @@ using System; using Content.Server.Nutrition.Components; using Content.Shared.Nutrition.Components; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.AI.WorldState.States.Nutrition { @@ -12,7 +14,7 @@ namespace Content.Server.AI.WorldState.States.Nutrition public override bool GetValue() { - if (!Owner.TryGetComponent(out ThirstComponent? thirstComponent)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out ThirstComponent? thirstComponent)) { return false; } diff --git a/Content.Server/AI/WorldState/States/SelfState.cs b/Content.Server/AI/WorldState/States/SelfState.cs index dc1ed00ac8..889bad9fc8 100644 --- a/Content.Server/AI/WorldState/States/SelfState.cs +++ b/Content.Server/AI/WorldState/States/SelfState.cs @@ -4,11 +4,11 @@ using Robust.Shared.GameObjects; namespace Content.Server.AI.WorldState.States { [UsedImplicitly] - public sealed class SelfState : StateData + public sealed class SelfState : StateData { public override string Name => "Self"; - public override IEntity GetValue() + public override EntityUid GetValue() { return Owner; } diff --git a/Content.Server/AI/WorldState/States/TargetEntityState.cs b/Content.Server/AI/WorldState/States/TargetEntityState.cs index de5b7edb2d..dea4c554fe 100644 --- a/Content.Server/AI/WorldState/States/TargetEntityState.cs +++ b/Content.Server/AI/WorldState/States/TargetEntityState.cs @@ -7,13 +7,13 @@ namespace Content.Server.AI.WorldState.States /// Could be target item to equip, target to attack, etc. /// [UsedImplicitly] - public sealed class TargetEntityState : PlanningStateData + public sealed class TargetEntityState : PlanningStateData { public override string Name => "TargetEntity"; public override void Reset() { - Value = null; + Value = default; } } } diff --git a/Content.Server/AME/AMENodeGroup.cs b/Content.Server/AME/AMENodeGroup.cs index aedf0d33b5..83bfa2654b 100644 --- a/Content.Server/AME/AMENodeGroup.cs +++ b/Content.Server/AME/AMENodeGroup.cs @@ -27,8 +27,9 @@ namespace Content.Server.AME [ViewVariables] private AMEControllerComponent? _masterController; - [Dependency] - private readonly IRobustRandom _random = default!; + [Dependency] private readonly IRobustRandom _random = default!; + + [Dependency] private readonly IEntityManager _entMan = default!; public AMEControllerComponent? MasterController => _masterController; @@ -46,11 +47,10 @@ namespace Content.Server.AME foreach (var node in groupNodes) { var nodeOwner = node.Owner; - if (nodeOwner.TryGetComponent(out AMEShieldComponent? shield)) + if (_entMan.TryGetComponent(nodeOwner, out AMEShieldComponent? shield)) { - var nodeNeighbors = grid.GetCellsInSquareArea(nodeOwner.Transform.Coordinates, 1) - .Select(sgc => nodeOwner.EntityManager.GetEntity(sgc)) - .Where(entity => entity != nodeOwner && entity.HasComponent()); + var nodeNeighbors = grid.GetCellsInSquareArea(_entMan.GetComponent(nodeOwner).Coordinates, 1) + .Where(entity => entity != nodeOwner && _entMan.HasComponent(entity)); if (nodeNeighbors.Count() >= 8) { @@ -69,7 +69,7 @@ namespace Content.Server.AME foreach (var node in groupNodes) { var nodeOwner = node.Owner; - if (nodeOwner.TryGetComponent(out AMEControllerComponent? controller)) + if (_entMan.TryGetComponent(nodeOwner, out AMEControllerComponent? controller)) { if (_masterController == null) { @@ -177,7 +177,7 @@ namespace Content.Server.AME intensity = Math.Min(intensity, 8); - EntitySystem.Get().SpawnExplosion(epicenter.OwnerUid, intensity / 2, intensity, intensity * 2, intensity * 3); + EntitySystem.Get().SpawnExplosion(epicenter.Owner, intensity / 2, intensity, intensity * 2, intensity * 3); } } } diff --git a/Content.Server/AME/Components/AMEControllerComponent.cs b/Content.Server/AME/Components/AMEControllerComponent.cs index a4656b89f4..7504c4971c 100644 --- a/Content.Server/AME/Components/AMEControllerComponent.cs +++ b/Content.Server/AME/Components/AMEControllerComponent.cs @@ -15,6 +15,7 @@ using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -27,6 +28,8 @@ namespace Content.Server.AME.Components [ComponentReference(typeof(IInteractUsing))] public class AMEControllerComponent : SharedAMEControllerComponent, IActivate, IInteractUsing { + [Dependency] private readonly IEntityManager _entities = default!; + [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(AMEControllerUiKey.Key); private bool _injecting; [ViewVariables] public bool Injecting => _injecting; @@ -37,7 +40,7 @@ namespace Content.Server.AME.Components [DataField("clickSound")] private SoundSpecifier _clickSound = new SoundPathSpecifier("/Audio/Machines/machine_switch.ogg"); [DataField("injectSound")] private SoundSpecifier _injectSound = new SoundPathSpecifier("/Audio/Effects/bang.ogg"); - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; [ViewVariables] private int _stability = 100; @@ -54,9 +57,9 @@ namespace Content.Server.AME.Components UserInterface.OnReceiveMessage += OnUiReceiveMessage; } - Owner.TryGetComponent(out _appearance); + _entities.TryGetComponent(Owner, out _appearance); - Owner.TryGetComponent(out _powerSupplier); + _entities.TryGetComponent(Owner, out _powerSupplier); _injecting = false; InjectionAmount = 2; @@ -91,11 +94,10 @@ namespace Content.Server.AME.Components return; } - var jar = _jarSlot.ContainedEntity; - if (jar is null) + if (_jarSlot.ContainedEntity is not {Valid: true} jar) return; - jar.TryGetComponent(out var fuelJar); + _entities.TryGetComponent(jar, out var fuelJar); if (fuelJar != null && _powerSupplier != null) { var availableInject = fuelJar.FuelAmount >= InjectionAmount ? InjectionAmount : fuelJar.FuelAmount; @@ -119,12 +121,12 @@ namespace Content.Server.AME.Components /// Data relevant to the event such as the actor which triggered it. void IActivate.Activate(ActivateEventArgs args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!_entities.TryGetComponent(args.User, out ActorComponent? actor)) { return; } - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!_entities.TryGetComponent(args.User, out HandsComponent? hands)) { Owner.PopupMessage(args.User, Loc.GetString("ame-controller-component-interact-no-hands-text")); return; @@ -150,14 +152,13 @@ namespace Content.Server.AME.Components private AMEControllerBoundUserInterfaceState GetUserInterfaceState() { - var jar = _jarSlot.ContainedEntity; - if (jar == null) + if (_jarSlot.ContainedEntity is not {Valid: true} jar) { return new AMEControllerBoundUserInterfaceState(Powered, IsMasterController(), false, HasJar, 0, InjectionAmount, GetCoreCount()); } - var jarcomponent = jar.GetComponent(); - return new AMEControllerBoundUserInterfaceState(Powered, IsMasterController(), _injecting, HasJar, jarcomponent.FuelAmount, InjectionAmount, GetCoreCount()); + var jarComponent = _entities.GetComponent(jar); + return new AMEControllerBoundUserInterfaceState(Powered, IsMasterController(), _injecting, HasJar, jarComponent.FuelAmount, InjectionAmount, GetCoreCount()); } /// @@ -165,16 +166,16 @@ namespace Content.Server.AME.Components /// /// The player entity. /// Returns true if the entity can use the controller, and false if it cannot. - private bool PlayerCanUseController(IEntity playerEntity, bool needsPower = true) + private bool PlayerCanUseController(EntityUid playerEntity, bool needsPower = true) { //Need player entity to check if they are still able to use the dispenser - if (playerEntity == null) + if (playerEntity == default) return false; var actionBlocker = EntitySystem.Get(); //Check if player can interact in their current state - if (!actionBlocker.CanInteract(playerEntity.Uid) || !actionBlocker.CanUse(playerEntity.Uid)) + if (!actionBlocker.CanInteract(playerEntity) || !actionBlocker.CanUse(playerEntity)) return false; //Check if device is powered if (needsPower && !Powered) @@ -196,7 +197,7 @@ namespace Content.Server.AME.Components /// A user interface message from the client. private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj) { - if (obj.Session.AttachedEntity == null) + if (obj.Session.AttachedEntity is not {Valid: true} player) { return; } @@ -208,13 +209,13 @@ namespace Content.Server.AME.Components _ => true, }; - if (!PlayerCanUseController(obj.Session.AttachedEntity, needsPower)) + if (!PlayerCanUseController(player, needsPower)) return; switch (msg.Button) { case UiButton.Eject: - TryEject(obj.Session.AttachedEntity); + TryEject(player); break; case UiButton.ToggleInjection: ToggleInjection(); @@ -233,19 +234,18 @@ namespace Content.Server.AME.Components ClickSound(); } - private void TryEject(IEntity user) + private void TryEject(EntityUid user) { if (!HasJar || _injecting) return; - var jar = _jarSlot.ContainedEntity; - if (jar is null) + if (_jarSlot.ContainedEntity is not {Valid: true} jar) return; _jarSlot.Remove(jar); UpdateUserInterface(); - if (!user.TryGetComponent(out var hands) || !jar.TryGetComponent(out var item)) + if (!_entities.TryGetComponent(user, out var hands) || !_entities.TryGetComponent(jar, out var item)) return; if (hands.CanPutInHand(item)) hands.PutInHand(item); @@ -289,7 +289,7 @@ namespace Content.Server.AME.Components private AMENodeGroup? GetAMENodeGroup() { - Owner.TryGetComponent(out NodeContainerComponent? nodeContainer); + _entities.TryGetComponent(Owner, out NodeContainerComponent? nodeContainer); var engineNodeGroup = nodeContainer?.Nodes.Values .Select(node => node.NodeGroup) @@ -335,7 +335,7 @@ namespace Content.Server.AME.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs args) { - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!_entities.TryGetComponent(args.User, out HandsComponent? hands)) { Owner.PopupMessage(args.User, Loc.GetString("ame-controller-component-interact-using-no-hands-text")); return true; @@ -348,7 +348,7 @@ namespace Content.Server.AME.Components } var activeHandEntity = hands.GetActiveHand.Owner; - if (activeHandEntity.TryGetComponent(out var fuelContainer)) + if (_entities.HasComponent(activeHandEntity)) { if (HasJar) { diff --git a/Content.Server/AME/Components/AMEPartComponent.cs b/Content.Server/AME/Components/AMEPartComponent.cs index 75d0445d78..4e33af6e8c 100644 --- a/Content.Server/AME/Components/AMEPartComponent.cs +++ b/Content.Server/AME/Components/AMEPartComponent.cs @@ -35,13 +35,13 @@ namespace Content.Server.AME.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs args) { - if (!args.User.HasComponent()) + if (!_serverEntityManager.HasComponent(args.User)) { Owner.PopupMessage(args.User, Loc.GetString("ame-part-component-interact-using-no-hands")); return false; } - if (!EntitySystem.Get().HasQuality(args.Using.Uid, _qualityNeeded)) + if (!EntitySystem.Get().HasQuality(args.Using, _qualityNeeded)) return false; if (!_mapManager.TryGetGrid(args.ClickLocation.GetGridId(_serverEntityManager), out var mapGrid)) @@ -58,7 +58,7 @@ namespace Content.Server.AME.Components SoundSystem.Play(Filter.Pvs(Owner), _unwrapSound.GetSound(), Owner); - Owner.QueueDelete(); + _serverEntityManager.QueueDeleteEntity(Owner); return true; } diff --git a/Content.Server/AME/Components/AMEShieldComponent.cs b/Content.Server/AME/Components/AMEShieldComponent.cs index 33fd8802d5..1708e0c700 100644 --- a/Content.Server/AME/Components/AMEShieldComponent.cs +++ b/Content.Server/AME/Components/AMEShieldComponent.cs @@ -2,6 +2,7 @@ using Content.Shared.AME; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Server.AME.Components @@ -21,8 +22,9 @@ namespace Content.Server.AME.Components protected override void Initialize() { base.Initialize(); - Owner.TryGetComponent(out _appearance); - Owner.TryGetComponent(out _pointLight); + var entMan = IoCManager.Resolve(); + entMan.TryGetComponent(Owner, out _appearance); + entMan.TryGetComponent(Owner, out _pointLight); } public void SetCore() diff --git a/Content.Server/Access/AccessReaderChangeMessage.cs b/Content.Server/Access/AccessReaderChangeMessage.cs index e9a71e59ac..ff2600a2b1 100644 --- a/Content.Server/Access/AccessReaderChangeMessage.cs +++ b/Content.Server/Access/AccessReaderChangeMessage.cs @@ -4,11 +4,11 @@ namespace Content.Server.Access { public sealed class AccessReaderChangeMessage : EntityEventArgs { - public IEntity Sender { get; } + public EntityUid Sender { get; } public bool Enabled { get; } - public AccessReaderChangeMessage(IEntity entity, bool enabled) + public AccessReaderChangeMessage(EntityUid entity, bool enabled) { Sender = entity; Enabled = enabled; diff --git a/Content.Server/Access/Components/IdCardConsoleComponent.cs b/Content.Server/Access/Components/IdCardConsoleComponent.cs index 0683649d12..e31c97fedb 100644 --- a/Content.Server/Access/Components/IdCardConsoleComponent.cs +++ b/Content.Server/Access/Components/IdCardConsoleComponent.cs @@ -5,7 +5,6 @@ using Content.Server.Power.Components; using Content.Server.UserInterface; using Content.Shared.Access; using Content.Shared.Containers.ItemSlots; -using Content.Shared.Interaction; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -20,9 +19,10 @@ namespace Content.Server.Access.Components public sealed class IdCardConsoleComponent : SharedIdCardConsoleComponent { [Dependency] private readonly IPrototypeManager _prototypeManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(IdCardConsoleUiKey.Key); - [ViewVariables] private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + [ViewVariables] private bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; protected override void Initialize() { @@ -39,7 +39,7 @@ namespace Content.Server.Access.Components private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj) { - if (obj.Session.AttachedEntity == null) + if (obj.Session.AttachedEntity is not {Valid: true} player) { return; } @@ -50,10 +50,10 @@ namespace Content.Server.Access.Components switch (msg.Button) { case UiButton.PrivilegedId: - HandleIdButton(obj.Session.AttachedEntity, PrivilegedIdSlot); + HandleIdButton(player, PrivilegedIdSlot); break; case UiButton.TargetId: - HandleIdButton(obj.Session.AttachedEntity, TargetIdSlot); + HandleIdButton(player, TargetIdSlot); break; } break; @@ -69,14 +69,14 @@ namespace Content.Server.Access.Components /// private bool PrivilegedIdIsAuthorized() { - if (!Owner.TryGetComponent(out AccessReader? reader)) + if (!_entities.TryGetComponent(Owner, out AccessReader? reader)) { return true; } var privilegedIdEntity = PrivilegedIdSlot.Item; var accessSystem = EntitySystem.Get(); - return privilegedIdEntity != null && accessSystem.IsAllowed(reader, privilegedIdEntity.Uid); + return privilegedIdEntity != null && accessSystem.IsAllowed(reader, privilegedIdEntity.Value); } /// @@ -85,13 +85,12 @@ namespace Content.Server.Access.Components /// private void TryWriteToTargetId(string newFullName, string newJobTitle, List newAccessList) { - var targetIdEntity = TargetIdSlot.Item; - if (targetIdEntity == null || !PrivilegedIdIsAuthorized()) + if (TargetIdSlot.Item is not {Valid: true} targetIdEntity || !PrivilegedIdIsAuthorized()) return; var cardSystem = EntitySystem.Get(); - cardSystem.TryChangeFullName(targetIdEntity.Uid, newFullName); - cardSystem.TryChangeJobTitle(targetIdEntity.Uid, newJobTitle); + cardSystem.TryChangeFullName(targetIdEntity, newFullName); + cardSystem.TryChangeJobTitle(targetIdEntity, newJobTitle); if (!newAccessList.TrueForAll(x => _prototypeManager.HasIndex(x))) { @@ -100,27 +99,32 @@ namespace Content.Server.Access.Components } var accessSystem = EntitySystem.Get(); - accessSystem.TrySetTags(targetIdEntity.Uid, newAccessList); + accessSystem.TrySetTags(targetIdEntity, newAccessList); } /// /// Called when one of the insert/remove ID buttons gets pressed. /// - private void HandleIdButton(IEntity user, ItemSlot slot) + private void HandleIdButton(EntityUid user, ItemSlot slot) { if (slot.HasItem) - EntitySystem.Get().TryEjectToHands(OwnerUid, slot, user.Uid); + EntitySystem.Get().TryEjectToHands(Owner, slot, user); else - EntitySystem.Get().TryInsertFromHand(OwnerUid, slot, user.Uid); + EntitySystem.Get().TryInsertFromHand(Owner, slot, user); } public void UpdateUserInterface() { - var targetIdEntity = TargetIdSlot.Item; IdCardConsoleBoundUserInterfaceState newState; // this could be prettier - if (targetIdEntity == null) + if (TargetIdSlot.Item is not {Valid: true} targetIdEntity) { + var privilegedIdName = string.Empty; + if (PrivilegedIdSlot.Item is {Valid: true} item) + { + privilegedIdName = _entities.GetComponent(item).EntityName; + } + newState = new IdCardConsoleBoundUserInterfaceState( PrivilegedIdSlot.HasItem, PrivilegedIdIsAuthorized(), @@ -128,13 +132,16 @@ namespace Content.Server.Access.Components null, null, null, - PrivilegedIdSlot.Item?.Name ?? string.Empty, + privilegedIdName, string.Empty); } else { - var targetIdComponent = targetIdEntity.GetComponent(); - var targetAccessComponent = targetIdEntity.GetComponent(); + var targetIdComponent = _entities.GetComponent(targetIdEntity); + var targetAccessComponent = _entities.GetComponent(targetIdEntity); + var name = string.Empty; + if (PrivilegedIdSlot.Item is {Valid: true} item) + name = _entities.GetComponent(item).EntityName; newState = new IdCardConsoleBoundUserInterfaceState( PrivilegedIdSlot.HasItem, PrivilegedIdIsAuthorized(), @@ -142,8 +149,8 @@ namespace Content.Server.Access.Components targetIdComponent.FullName, targetIdComponent.JobTitle, targetAccessComponent.Tags.ToArray(), - PrivilegedIdSlot.Item?.Name ?? string.Empty, - targetIdEntity.Name); + name, + _entities.GetComponent(targetIdEntity).EntityName); } UserInterface?.SetState(newState); } diff --git a/Content.Server/Access/Systems/AccessReaderSystem.cs b/Content.Server/Access/Systems/AccessReaderSystem.cs index 0e090eca6c..25c81350e5 100644 --- a/Content.Server/Access/Systems/AccessReaderSystem.cs +++ b/Content.Server/Access/Systems/AccessReaderSystem.cs @@ -1,3 +1,7 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; using Content.Server.Access.Components; using Content.Server.Inventory.Components; using Content.Server.Items; @@ -9,10 +13,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Prototypes; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; namespace Content.Server.Access.Systems { @@ -73,7 +73,7 @@ namespace Content.Server.Access.Systems if (EntityManager.TryGetComponent(uid, out SharedHandsComponent? hands)) { if (hands.TryGetActiveHeldEntity(out var heldItem) && - FindAccessTagsItem(heldItem.Uid, out tags)) + FindAccessTagsItem(heldItem, out tags)) { return tags; } @@ -84,7 +84,7 @@ namespace Content.Server.Access.Systems { if (inventoryComponent.HasSlot(EquipmentSlotDefines.Slots.IDCARD) && inventoryComponent.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent? item) && - FindAccessTagsItem(item.Owner.Uid, out tags) + FindAccessTagsItem(item.Owner, out tags) ) { return tags; @@ -106,10 +106,11 @@ namespace Content.Server.Access.Systems return true; } - if (EntityManager.TryGetComponent(uid, out PDAComponent? pda)) + if (EntityManager.TryGetComponent(uid, out PDAComponent? pda) && + pda.ContainedID?.Owner is {Valid: true} id) { - tags = pda?.ContainedID?.Owner?.GetComponent()?.Tags; - return tags != null; + tags = EntityManager.GetComponent(id).Tags; + return true; } tags = null; diff --git a/Content.Server/Access/Systems/IdCardSystem.cs b/Content.Server/Access/Systems/IdCardSystem.cs index e15b7aafe1..3c363206cc 100644 --- a/Content.Server/Access/Systems/IdCardSystem.cs +++ b/Content.Server/Access/Systems/IdCardSystem.cs @@ -8,6 +8,7 @@ using Content.Shared.Inventory; using Robust.Shared.GameObjects; using Robust.Shared.Localization; using System.Diagnostics.CodeAnalysis; +using Robust.Shared.IoC; namespace Content.Server.Access.Systems { @@ -21,7 +22,7 @@ namespace Content.Server.Access.Systems private void OnInit(EntityUid uid, IdCardComponent id, ComponentInit args) { - id.OriginalOwnerName ??= id.Owner.Name; + id.OriginalOwnerName ??= EntityManager.GetComponent(id.Owner).EntityName; UpdateEntityName(uid, id); } @@ -66,19 +67,20 @@ namespace Content.Server.Access.Systems if (string.IsNullOrWhiteSpace(id.FullName) && string.IsNullOrWhiteSpace(id.JobTitle)) { - id.Owner.Name = id.OriginalOwnerName; + EntityManager.GetComponent(id.Owner).EntityName = id.OriginalOwnerName; return; } var jobSuffix = string.IsNullOrWhiteSpace(id.JobTitle) ? string.Empty : $" ({id.JobTitle})"; - id.Owner.Name = string.IsNullOrWhiteSpace(id.FullName) + var val = string.IsNullOrWhiteSpace(id.FullName) ? Loc.GetString("access-id-card-component-owner-name-job-title-text", - ("originalOwnerName", id.OriginalOwnerName), - ("jobSuffix", jobSuffix)) + ("originalOwnerName", id.OriginalOwnerName), + ("jobSuffix", jobSuffix)) : Loc.GetString("access-id-card-component-owner-full-name-job-title-text", - ("fullName", id.FullName), - ("jobSuffix", jobSuffix)); + ("fullName", id.FullName), + ("jobSuffix", jobSuffix)); + EntityManager.GetComponent(id.Owner).EntityName = val; } /// @@ -90,7 +92,7 @@ namespace Content.Server.Access.Systems // check held item? if (EntityManager.TryGetComponent(uid, out SharedHandsComponent? hands) && hands.TryGetActiveHeldEntity(out var heldItem) && - TryGetIdCard(heldItem.Uid, out idCard)) + TryGetIdCard(heldItem, out idCard)) { return true; } @@ -103,7 +105,7 @@ namespace Content.Server.Access.Systems if (EntityManager.TryGetComponent(uid, out InventoryComponent? inventoryComponent) && inventoryComponent.HasSlot(EquipmentSlotDefines.Slots.IDCARD) && inventoryComponent.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent? item) && - TryGetIdCard(item.Owner.Uid, out idCard)) + TryGetIdCard(item.Owner, out idCard)) { return true; } diff --git a/Content.Server/Act/IDisarmedAct.cs b/Content.Server/Act/IDisarmedAct.cs index d32912451d..42571c7c86 100644 --- a/Content.Server/Act/IDisarmedAct.cs +++ b/Content.Server/Act/IDisarmedAct.cs @@ -29,12 +29,12 @@ namespace Content.Server.Act /// /// The entity being disarmed. /// - public IEntity? Target { get; init; } + public EntityUid Target { get; init; } /// /// The entity performing the disarm. /// - public IEntity? Source { get; init; } + public EntityUid Source { get; init; } /// /// Probability for push/knockdown. diff --git a/Content.Server/Act/ISuicideAct.cs b/Content.Server/Act/ISuicideAct.cs index b8e7c3f571..6865e915ea 100644 --- a/Content.Server/Act/ISuicideAct.cs +++ b/Content.Server/Act/ISuicideAct.cs @@ -7,7 +7,7 @@ namespace Content.Server.Act [RequiresExplicitImplementation] public interface ISuicideAct { - public SuicideKind Suicide(IEntity victim, IChatManager chat); + public SuicideKind Suicide(EntityUid victim, IChatManager chat); } public enum SuicideKind diff --git a/Content.Server/Actions/Actions/CombatMode.cs b/Content.Server/Actions/Actions/CombatMode.cs index c00ab41d5d..e072b317a9 100644 --- a/Content.Server/Actions/Actions/CombatMode.cs +++ b/Content.Server/Actions/Actions/CombatMode.cs @@ -2,6 +2,8 @@ using Content.Server.CombatMode; using Content.Shared.Actions.Behaviors; using Content.Shared.Popups; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; @@ -13,7 +15,7 @@ namespace Content.Server.Actions.Actions { public bool DoToggleAction(ToggleActionEventArgs args) { - if (!args.Performer.TryGetComponent(out CombatModeComponent? combatMode)) + if (!IoCManager.Resolve().TryGetComponent(args.Performer, out CombatModeComponent? combatMode)) { return false; } diff --git a/Content.Server/Actions/Actions/DebugTargetEntity.cs b/Content.Server/Actions/Actions/DebugTargetEntity.cs index c16b60e051..d30679e9f9 100644 --- a/Content.Server/Actions/Actions/DebugTargetEntity.cs +++ b/Content.Server/Actions/Actions/DebugTargetEntity.cs @@ -1,6 +1,8 @@ using Content.Server.Popups; using Content.Shared.Actions.Behaviors; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Actions.Actions @@ -11,14 +13,15 @@ namespace Content.Server.Actions.Actions { public void DoTargetEntityAction(TargetEntityItemActionEventArgs args) { - args.Performer.PopupMessageEveryone(args.Item.Name + ": Clicked " + - args.Target.Name); + var entMan = IoCManager.Resolve(); + + args.Performer.PopupMessageEveryone(entMan.GetComponent(args.Item).EntityName + ": Clicked " + + entMan.GetComponent(args.Target).EntityName); } public void DoTargetEntityAction(TargetEntityActionEventArgs args) { - args.Performer.PopupMessageEveryone("Clicked " + - args.Target.Name); + args.Performer.PopupMessageEveryone("Clicked " + IoCManager.Resolve().GetComponent(args.Target).EntityName); } } } diff --git a/Content.Server/Actions/Actions/DebugTargetPoint.cs b/Content.Server/Actions/Actions/DebugTargetPoint.cs index 18496f109a..bcab85d283 100644 --- a/Content.Server/Actions/Actions/DebugTargetPoint.cs +++ b/Content.Server/Actions/Actions/DebugTargetPoint.cs @@ -1,6 +1,8 @@ using Content.Server.Popups; using Content.Shared.Actions.Behaviors; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Actions.Actions @@ -11,7 +13,7 @@ namespace Content.Server.Actions.Actions { public void DoTargetPointAction(TargetPointItemActionEventArgs args) { - args.Performer.PopupMessageEveryone(args.Item.Name + ": Clicked local position " + + args.Performer.PopupMessageEveryone(IoCManager.Resolve().GetComponent(args.Item).EntityName + ": Clicked local position " + args.Target); } diff --git a/Content.Server/Actions/Actions/DebugToggle.cs b/Content.Server/Actions/Actions/DebugToggle.cs index 7b386601df..44370bc023 100644 --- a/Content.Server/Actions/Actions/DebugToggle.cs +++ b/Content.Server/Actions/Actions/DebugToggle.cs @@ -2,6 +2,8 @@ using Content.Shared.Actions.Behaviors; using Content.Shared.Actions.Behaviors.Item; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Actions.Actions @@ -15,13 +17,15 @@ namespace Content.Server.Actions.Actions public bool DoToggleAction(ToggleItemActionEventArgs args) { + var entMan = IoCManager.Resolve(); + if (args.ToggledOn) { - args.Performer.PopupMessageEveryone(args.Item.Name + ": " + MessageOn); + args.Performer.PopupMessageEveryone(entMan.GetComponent(args.Item).EntityName + ": " + MessageOn); } else { - args.Performer.PopupMessageEveryone(args.Item.Name + ": " +MessageOff); + args.Performer.PopupMessageEveryone(entMan.GetComponent(args.Item).EntityName + ": " +MessageOff); } return true; diff --git a/Content.Server/Actions/Actions/DisarmAction.cs b/Content.Server/Actions/Actions/DisarmAction.cs index bc0caf804f..90d0bc94ea 100644 --- a/Content.Server/Actions/Actions/DisarmAction.cs +++ b/Content.Server/Actions/Actions/DisarmAction.cs @@ -1,5 +1,9 @@ +using System; +using System.Linq; using Content.Server.Act; +using Content.Server.Administration.Logs; using Content.Server.Interaction; +using Content.Server.Popups; using Content.Server.Weapon.Melee; using Content.Shared.ActionBlocker; using Content.Shared.Actions; @@ -7,7 +11,9 @@ using Content.Shared.Actions.Behaviors; using Content.Shared.Actions.Components; using Content.Shared.Audio; using Content.Shared.Cooldown; +using Content.Shared.Database; using Content.Shared.Interaction.Helpers; +using Content.Shared.Popups; using Content.Shared.Sound; using JetBrains.Annotations; using Robust.Server.GameObjects; @@ -20,13 +26,6 @@ using Robust.Shared.Player; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; -using System; -using System.Linq; -using Content.Server.Administration.Logs; -using Content.Server.Popups; -using Content.Shared.Administration.Logs; -using Content.Shared.Database; -using Content.Shared.Popups; namespace Content.Server.Actions.Actions { @@ -48,18 +47,19 @@ namespace Content.Server.Actions.Actions public void DoTargetEntityAction(TargetEntityActionEventArgs args) { - var disarmedActs = args.Target.GetAllComponents().ToArray(); + var entMan = IoCManager.Resolve(); + var disarmedActs = entMan.GetComponents(args.Target).ToArray(); if (!args.Performer.InRangeUnobstructed(args.Target)) return; if (disarmedActs.Length == 0) { - if (args.Performer.TryGetComponent(out ActorComponent? actor)) + if (entMan.TryGetComponent(args.Performer, out ActorComponent? actor)) { // Fall back to a normal interaction with the entity var player = actor.PlayerSession; - var coordinates = args.Target.Transform.Coordinates; - var target = args.Target.Uid; + var coordinates = entMan.GetComponent(args.Target).Coordinates; + var target = args.Target; EntitySystem.Get().HandleUseInteraction(player, coordinates, target); return; } @@ -67,13 +67,13 @@ namespace Content.Server.Actions.Actions return; } - if (!args.Performer.TryGetComponent(out var actions)) return; - if (args.Target == args.Performer || !EntitySystem.Get().CanAttack(args.Performer.Uid)) return; + if (!entMan.TryGetComponent(args.Performer, out var actions)) return; + if (args.Target == args.Performer || !EntitySystem.Get().CanAttack(args.Performer)) return; var random = IoCManager.Resolve(); var system = EntitySystem.Get(); - var diff = args.Target.Transform.MapPosition.Position - args.Performer.Transform.MapPosition.Position; + var diff = entMan.GetComponent(args.Target).MapPosition.Position - entMan.GetComponent(args.Performer).MapPosition.Position; var angle = Angle.FromWorldVec(diff); actions.Cooldown(ActionType.Disarm, Cooldowns.SecondsFromNow(_cooldown)); @@ -83,10 +83,10 @@ namespace Content.Server.Actions.Actions SoundSystem.Play(Filter.Pvs(args.Performer), PunchMissSound.GetSound(), args.Performer, AudioHelpers.WithVariation(0.025f)); args.Performer.PopupMessageOtherClients(Loc.GetString("disarm-action-popup-message-other-clients", - ("performerName", args.Performer.Name), - ("targetName", args.Target.Name))); + ("performerName", Name: entMan.GetComponent(args.Performer).EntityName), + ("targetName", Name: entMan.GetComponent(args.Target).EntityName))); args.Performer.PopupMessageCursor(Loc.GetString("disarm-action-popup-message-cursor", - ("targetName", args.Target.Name))); + ("targetName", Name: entMan.GetComponent(args.Target).EntityName))); system.SendLunge(angle, args.Performer); return; } @@ -95,7 +95,7 @@ namespace Content.Server.Actions.Actions var eventArgs = new DisarmedActEvent() { Target = args.Target, Source = args.Performer, PushProbability = _pushProb }; - IoCManager.Resolve().EventBus.RaiseLocalEvent(args.Target.Uid, eventArgs); + entMan.EventBus.RaiseLocalEvent(args.Target, eventArgs); EntitySystem.Get().Add(LogType.DisarmedAction, LogImpact.Low, $"{args.Performer:performer} used disarm on {args.Target:target}"); @@ -113,7 +113,7 @@ namespace Content.Server.Actions.Actions return; } - SoundSystem.Play(Filter.Pvs(args.Performer), DisarmSuccessSound.GetSound(), args.Performer.Transform.Coordinates, AudioHelpers.WithVariation(0.025f)); + SoundSystem.Play(Filter.Pvs(args.Performer), DisarmSuccessSound.GetSound(), entMan.GetComponent(args.Performer).Coordinates, AudioHelpers.WithVariation(0.025f)); } } } diff --git a/Content.Server/Actions/Actions/GhostBoo.cs b/Content.Server/Actions/Actions/GhostBoo.cs index ee6b8260cb..3a563da8ed 100644 --- a/Content.Server/Actions/Actions/GhostBoo.cs +++ b/Content.Server/Actions/Actions/GhostBoo.cs @@ -23,7 +23,9 @@ namespace Content.Server.Actions.Actions public void DoInstantAction(InstantActionEventArgs args) { - if (!args.Performer.TryGetComponent(out var actions)) return; + var entMan = IoCManager.Resolve(); + + if (!entMan.TryGetComponent(args.Performer, out var actions)) return; // find all IGhostBooAffected nearby and do boo on them var ents = IoCManager.Resolve().GetEntitiesInRange(args.Performer, _radius); @@ -32,7 +34,7 @@ namespace Content.Server.Actions.Actions foreach (var ent in ents) { var ghostBoo = new GhostBooEvent(); - ent.EntityManager.EventBus.RaiseLocalEvent(ent.Uid, ghostBoo); + entMan.EventBus.RaiseLocalEvent(ent, ghostBoo); if (ghostBoo.Handled) booCounter++; diff --git a/Content.Server/Actions/Actions/PAIMidi.cs b/Content.Server/Actions/Actions/PAIMidi.cs index 717c8a3f42..942633e920 100644 --- a/Content.Server/Actions/Actions/PAIMidi.cs +++ b/Content.Server/Actions/Actions/PAIMidi.cs @@ -23,8 +23,10 @@ namespace Content.Server.Actions.Actions public void DoInstantAction(InstantActionEventArgs args) { - if (!args.Performer.TryGetComponent(out var serverUi)) return; - if (!args.Performer.TryGetComponent(out var actor)) return; + var entMan = IoCManager.Resolve(); + + if (!entMan.TryGetComponent(args.Performer, out var serverUi)) return; + if (!entMan.TryGetComponent(args.Performer, out var actor)) return; if (!serverUi.TryGetBoundUserInterface(InstrumentUiKey.Key,out var bui)) return; bui.Toggle(actor.PlayerSession); diff --git a/Content.Server/Actions/Actions/ScreamAction.cs b/Content.Server/Actions/Actions/ScreamAction.cs index ee3e6952e8..28a20be608 100644 --- a/Content.Server/Actions/Actions/ScreamAction.cs +++ b/Content.Server/Actions/Actions/ScreamAction.cs @@ -26,6 +26,7 @@ namespace Content.Server.Actions.Actions private const float Volume = 4f; [Dependency] private readonly IRobustRandom _random = default!; + [Dependency] private readonly IEntityManager _entMan = default!; [DataField("male", required: true)] private SoundSpecifier _male = default!; [DataField("female", required: true)] private SoundSpecifier _female = default!; @@ -41,9 +42,9 @@ namespace Content.Server.Actions.Actions public void DoInstantAction(InstantActionEventArgs args) { - if (!EntitySystem.Get().CanSpeak(args.Performer.Uid)) return; - if (!args.Performer.TryGetComponent(out var humanoid)) return; - if (!args.Performer.TryGetComponent(out var actions)) return; + if (!EntitySystem.Get().CanSpeak(args.Performer)) return; + if (!_entMan.TryGetComponent(args.Performer, out var humanoid)) return; + if (!_entMan.TryGetComponent(args.Performer, out var actions)) return; if (_random.Prob(.01f)) { diff --git a/Content.Server/Actions/Commands/CooldownAction.cs b/Content.Server/Actions/Commands/CooldownAction.cs index b4eeca63ea..dfd9cb4f41 100644 --- a/Content.Server/Actions/Commands/CooldownAction.cs +++ b/Content.Server/Actions/Commands/CooldownAction.cs @@ -5,6 +5,7 @@ using Content.Shared.Actions; using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Timing; @@ -20,18 +21,16 @@ namespace Content.Server.Actions.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; - if (player == null) return; - var attachedEntity = player.AttachedEntity; + if (player?.AttachedEntity is not {} attachedEntity) return; if (args.Length > 2) { var target = args[2]; if (!CommandUtils.TryGetAttachedEntityByUsernameOrId(shell, target, player, out attachedEntity)) return; } - if (attachedEntity == null) return; - if (!attachedEntity.TryGetComponent(out ServerActionsComponent? actionsComponent)) + if (!IoCManager.Resolve().TryGetComponent(attachedEntity, out ServerActionsComponent? actionsComponent)) { - shell.WriteLine("user has no actions component"); + shell.WriteError("user has no actions component"); return; } diff --git a/Content.Server/Actions/Commands/GrantAction.cs b/Content.Server/Actions/Commands/GrantAction.cs index b864e904ff..09d8fe4b7d 100644 --- a/Content.Server/Actions/Commands/GrantAction.cs +++ b/Content.Server/Actions/Commands/GrantAction.cs @@ -5,6 +5,7 @@ using Content.Shared.Actions; using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.Actions.Commands @@ -18,16 +19,16 @@ namespace Content.Server.Actions.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; - if (player == null) return; - var attachedEntity = player.AttachedEntity; + if (player?.AttachedEntity == null) return; + var attachedEntity = player.AttachedEntity.Value; if (args.Length > 1) { var target = args[1]; if (!CommandUtils.TryGetAttachedEntityByUsernameOrId(shell, target, player, out attachedEntity)) return; } - if (attachedEntity == null) return; - if (!attachedEntity.TryGetComponent(out ServerActionsComponent? actionsComponent)) + if (attachedEntity == default) return; + if (!IoCManager.Resolve().TryGetComponent(attachedEntity, out ServerActionsComponent? actionsComponent)) { shell.WriteLine("user has no actions component"); return; diff --git a/Content.Server/Actions/Commands/RevokeAction.cs b/Content.Server/Actions/Commands/RevokeAction.cs index 4366c7fca3..39db78d88d 100644 --- a/Content.Server/Actions/Commands/RevokeAction.cs +++ b/Content.Server/Actions/Commands/RevokeAction.cs @@ -5,6 +5,7 @@ using Content.Shared.Actions; using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.Actions.Commands @@ -19,15 +20,15 @@ namespace Content.Server.Actions.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; - if (player == null) return; - var attachedEntity = player.AttachedEntity; + if (player?.AttachedEntity == null) return; + var attachedEntity = player.AttachedEntity.Value; if (args.Length > 1) { var target = args[1]; if (!CommandUtils.TryGetAttachedEntityByUsernameOrId(shell, target, player, out attachedEntity)) return; } - if (attachedEntity == null) return; - if (!attachedEntity.TryGetComponent(out ServerActionsComponent? actionsComponent)) + if (attachedEntity == default) return; + if (!IoCManager.Resolve().TryGetComponent(attachedEntity, out ServerActionsComponent? actionsComponent)) { shell.WriteLine("user has no actions component"); return; diff --git a/Content.Server/Actions/ServerActionsComponent.cs b/Content.Server/Actions/ServerActionsComponent.cs index 145ea23cf6..703e276174 100644 --- a/Content.Server/Actions/ServerActionsComponent.cs +++ b/Content.Server/Actions/ServerActionsComponent.cs @@ -1,12 +1,8 @@ using System; -using Content.Shared.ActionBlocker; using Content.Shared.Actions; using Content.Shared.Actions.Components; using Content.Shared.Actions.Prototypes; -using Content.Shared.Interaction.Events; using Content.Shared.Interaction; -using Robust.Server.GameObjects; -using Robust.Server.GameStates; using Robust.Shared; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; @@ -24,6 +20,7 @@ namespace Content.Server.Actions public sealed class ServerActionsComponent : SharedActionsComponent { [Dependency] private readonly IConfigurationManager _configManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; private float MaxUpdateRange; @@ -55,15 +52,14 @@ namespace Content.Server.Actions throw new ArgumentNullException(nameof(session)); } - var player = session.AttachedEntity; - if (player != Owner) return; + if (session.AttachedEntity is not {Valid: true} player || player != Owner) return; var attempt = ActionAttempt(performActionMessage, session); if (attempt == null) return; if (!attempt.TryGetActionState(this, out var actionState) || !actionState.Enabled) { Logger.DebugS("action", "user {0} attempted to use" + - " action {1} which is not granted to them", player.Name, + " action {1} which is not granted to them", _entities.GetComponent(player).EntityName, attempt); return; } @@ -71,7 +67,7 @@ namespace Content.Server.Actions if (actionState.IsOnCooldown(GameTiming)) { Logger.DebugS("action", "user {0} attempted to use" + - " action {1} which is on cooldown", player.Name, + " action {1} which is on cooldown", _entities.GetComponent(player).EntityName, attempt); return; } @@ -86,7 +82,7 @@ namespace Content.Server.Actions if (toggleMsg.ToggleOn == actionState.ToggledOn) { Logger.DebugS("action", "user {0} attempted to" + - " toggle action {1} to {2}, but it is already toggled {2}", player.Name, + " toggle action {1} to {2}, but it is already toggled {2}", _entities.GetComponent(player).EntityName, attempt.Action.Name, toggleMsg.ToggleOn); return; } @@ -109,17 +105,17 @@ namespace Content.Server.Actions break; case BehaviorType.TargetEntity: if (performActionMessage is not ITargetEntityActionMessage targetEntityMsg) return; - if (!EntityManager.TryGetEntity(targetEntityMsg.Target, out var entity)) + if (!EntityManager.EntityExists(targetEntityMsg.Target)) { Logger.DebugS("action", "user {0} attempted to" + " perform target entity action {1} but could not find entity with " + - "provided uid {2}", player.Name, attempt.Action.Name, + "provided uid {2}", _entities.GetComponent(player).EntityName, attempt.Action.Name, targetEntityMsg.Target); return; } - if (!CheckRangeAndSetFacing(entity.Transform.Coordinates, player)) return; + if (!CheckRangeAndSetFacing(_entities.GetComponent(targetEntityMsg.Target).Coordinates, player)) return; - attempt.DoTargetEntityAction(player, entity); + attempt.DoTargetEntityAction(player, targetEntityMsg.Target); break; case BehaviorType.None: break; @@ -131,48 +127,52 @@ namespace Content.Server.Actions private IActionAttempt? ActionAttempt(BasePerformActionMessage message, ICommonSession session) { IActionAttempt? attempt; + var player = session.AttachedEntity; + switch (message) { case PerformActionMessage performActionMessage: if (!ActionManager.TryGet(performActionMessage.ActionType, out var action)) { Logger.DebugS("action", "user {0} attempted to perform" + - " unrecognized action {1}", session.AttachedEntity, + " unrecognized action {1}", player, performActionMessage.ActionType); return null; } attempt = new ActionAttempt(action); break; case PerformItemActionMessage performItemActionMessage: - if (!ActionManager.TryGet(performItemActionMessage.ActionType, out var itemAction)) + var type = performItemActionMessage.ActionType; + if (!ActionManager.TryGet(type, out var itemAction)) { Logger.DebugS("action", "user {0} attempted to perform" + " unrecognized item action {1}", - session.AttachedEntity, performItemActionMessage.ActionType); + player, type); return null; } - if (!EntityManager.TryGetEntity(performItemActionMessage.Item, out var item)) + var item = performItemActionMessage.Item; + if (!EntityManager.EntityExists(item)) { Logger.DebugS("action", "user {0} attempted to perform" + " item action {1} for unknown item {2}", - session.AttachedEntity, performItemActionMessage.ActionType, performItemActionMessage.Item); + player, type, item); return null; } - if (!item.TryGetComponent(out var actionsComponent)) + if (!_entities.TryGetComponent(item, out var actionsComponent)) { Logger.DebugS("action", "user {0} attempted to perform" + " item action {1} for item {2} which has no ItemActionsComponent", - session.AttachedEntity, performItemActionMessage.ActionType, item); + player, type, item); return null; } - if (actionsComponent.Holder != session.AttachedEntity) + if (actionsComponent.Holder != player) { Logger.DebugS("action", "user {0} attempted to perform" + " item action {1} for item {2} which they are not holding", - session.AttachedEntity, performItemActionMessage.ActionType, item); + player, type, item); return null; } @@ -186,7 +186,7 @@ namespace Content.Server.Actions { Logger.DebugS("action", "user {0} attempted to" + " perform action {1} as a {2} behavior, but this action is actually a" + - " {3} behavior", session.AttachedEntity, attempt, message.BehaviorType, + " {3} behavior", player, attempt, message.BehaviorType, attempt.Action.BehaviorType); return null; } @@ -194,17 +194,17 @@ namespace Content.Server.Actions return attempt; } - private bool CheckRangeAndSetFacing(EntityCoordinates target, IEntity player) + private bool CheckRangeAndSetFacing(EntityCoordinates target, EntityUid player) { // ensure it's within their clickable range var targetWorldPos = target.ToMapPos(EntityManager); - var rangeBox = new Box2(player.Transform.WorldPosition, player.Transform.WorldPosition) + var rangeBox = new Box2(_entities.GetComponent(player).WorldPosition, _entities.GetComponent(player).WorldPosition) .Enlarged(MaxUpdateRange); if (!rangeBox.Contains(targetWorldPos)) { Logger.DebugS("action", "user {0} attempted to" + " perform target action further than allowed range", - player.Name); + _entities.GetComponent(player).EntityName); return false; } diff --git a/Content.Server/Actions/Spells/GiveItemSpell.cs b/Content.Server/Actions/Spells/GiveItemSpell.cs index e87656cbbe..2eec52ec14 100644 --- a/Content.Server/Actions/Spells/GiveItemSpell.cs +++ b/Content.Server/Actions/Spells/GiveItemSpell.cs @@ -34,15 +34,17 @@ namespace Content.Server.Actions.Spells public void DoInstantAction(InstantActionEventArgs args) { + var entMan = IoCManager.Resolve(); + var caster = args.Performer; - if (!caster.TryGetComponent(out HandsComponent? handsComponent)) + if (!entMan.TryGetComponent(caster, out HandsComponent? handsComponent)) { caster.PopupMessage(Loc.GetString("spell-fail-no-hands")); return; } - if (!EntitySystem.Get().CanInteract(caster.Uid)) return; + if (!EntitySystem.Get().CanInteract(caster)) return; // TODO: Nix when we get EntityPrototype serializers if (!IoCManager.Resolve().HasIndex(ItemProto)) @@ -52,12 +54,12 @@ namespace Content.Server.Actions.Spells } // TODO: Look this is shitty and ideally a test would do it - var spawnedProto = caster.EntityManager.SpawnEntity(ItemProto, caster.Transform.MapPosition); + var spawnedProto = entMan.SpawnEntity(ItemProto, entMan.GetComponent(caster).MapPosition); - if (!spawnedProto.TryGetComponent(out ItemComponent? itemComponent)) + if (!entMan.TryGetComponent(spawnedProto, out ItemComponent? itemComponent)) { Logger.Error($"Tried to use {nameof(GiveItemSpell)} but prototype has no {nameof(ItemComponent)}?"); - spawnedProto.Delete(); + entMan.DeleteEntity(spawnedProto); return; } diff --git a/Content.Server/Administration/AdminSystem.cs b/Content.Server/Administration/AdminSystem.cs index a7796b2cbf..d2d234e389 100644 --- a/Content.Server/Administration/AdminSystem.cs +++ b/Content.Server/Administration/AdminSystem.cs @@ -123,11 +123,14 @@ namespace Content.Server.Administration private PlayerInfo GetPlayerInfo(IPlayerSession session) { var name = session.Name; - var username = session.AttachedEntity?.Name ?? string.Empty; - var antag = session.ContentData()?.Mind?.AllRoles.Any(r => r.Antagonist) ?? false; - var uid = session.AttachedEntity?.Uid ?? EntityUid.Invalid; + var username = string.Empty; - return new PlayerInfo(name, username, antag, uid, session.UserId); + if (session.AttachedEntity != null) + username = EntityManager.GetComponent(session.AttachedEntity.Value).EntityName; + + var antag = session.ContentData()?.Mind?.AllRoles.Any(r => r.Antagonist) ?? false; + + return new PlayerInfo(name, username, antag, session.AttachedEntity.GetValueOrDefault(), session.UserId); } } } diff --git a/Content.Server/Administration/AdminVerbSystem.cs b/Content.Server/Administration/AdminVerbSystem.cs index 9c2d6ad9e5..9844983ca5 100644 --- a/Content.Server/Administration/AdminVerbSystem.cs +++ b/Content.Server/Administration/AdminVerbSystem.cs @@ -15,7 +15,6 @@ using Content.Server.Mind.Commands; using Content.Server.Mind.Components; using Content.Server.Players; using Content.Shared.Administration; -using Content.Shared.Administration.Logs; using Content.Shared.Body.Components; using Content.Shared.Database; using Content.Shared.GameTicking; @@ -56,7 +55,7 @@ namespace Content.Server.Administration private void AddDebugVerbs(GetOtherVerbsEvent args) { - if (!args.User.TryGetComponent(out var actor)) + if (!EntityManager.TryGetComponent(args.User, out var actor)) return; var player = actor.PlayerSession; @@ -68,7 +67,7 @@ namespace Content.Server.Administration verb.Text = Loc.GetString("delete-verb-get-data-text"); verb.Category = VerbCategory.Debug; verb.IconTexture = "/Textures/Interface/VerbIcons/delete_transparent.svg.192dpi.png"; - verb.Act = () => args.Target.Delete(); + verb.Act = () => EntityManager.DeleteEntity(args.Target); verb.Impact = LogImpact.Medium; args.Verbs.Add(verb); } @@ -88,8 +87,8 @@ namespace Content.Server.Administration // Control mob verb if (_groupController.CanCommand(player, "controlmob") && args.User != args.Target && - args.User.HasComponent() && - args.Target.TryGetComponent(out var targetMind)) + EntityManager.HasComponent(args.User) && + EntityManager.TryGetComponent(args.Target, out var targetMind)) { Verb verb = new(); verb.Text = Loc.GetString("control-mob-verb-get-data-text"); @@ -97,7 +96,7 @@ namespace Content.Server.Administration // TODO VERB ICON control mob icon verb.Act = () => { - player.ContentData()?.Mind?.TransferTo(args.Target.Uid, ghostCheckOverride: true); + player.ContentData()?.Mind?.TransferTo(args.Target, ghostCheckOverride: true); }; verb.Impact = LogImpact.High; args.Verbs.Add(verb); @@ -106,13 +105,13 @@ namespace Content.Server.Administration // Make Sentient verb if (_groupController.CanCommand(player, "makesentient") && args.User != args.Target && - !args.Target.HasComponent()) + !EntityManager.HasComponent(args.Target)) { Verb verb = new(); verb.Text = Loc.GetString("make-sentient-verb-get-data-text"); verb.Category = VerbCategory.Debug; verb.IconTexture = "/Textures/Interface/VerbIcons/sentient.svg.192dpi.png"; - verb.Act = () => MakeSentientCommand.MakeSentient(args.Target.Uid, EntityManager); + verb.Act = () => MakeSentientCommand.MakeSentient(args.Target, EntityManager); verb.Impact = LogImpact.Medium; args.Verbs.Add(verb); } @@ -125,9 +124,9 @@ namespace Content.Server.Administration verb.Category = VerbCategory.Debug; verb.Act = () => { - var coords = args.Target.Transform.Coordinates; - Timer.Spawn(_gameTiming.TickPeriod, () => _explosions.SpawnExplosion(coords, 0, 1, 2, 1, args.TargetUid), CancellationToken.None); - if (args.Target.TryGetComponent(out SharedBodyComponent? body)) + var coords = EntityManager.GetComponent(args.Target).Coordinates; + Timer.Spawn(_gameTiming.TickPeriod, () => _explosions.SpawnExplosion(coords, 0, 1, 2, 1, args.Target), CancellationToken.None); + if (EntityManager.TryGetComponent(args.Target, out SharedBodyComponent? body)) { body.Gib(); } @@ -138,7 +137,7 @@ namespace Content.Server.Administration // Set clothing verb if (_groupController.CanCommand(player, "setoutfit") && - args.Target.HasComponent()) + EntityManager.HasComponent(args.Target)) { Verb verb = new(); verb.Text = Loc.GetString("set-outfit-verb-get-data-text"); @@ -168,7 +167,7 @@ namespace Content.Server.Administration // Get Disposal tube direction verb if (_groupController.CanCommand(player, "tubeconnections") && - args.Target.TryGetComponent(out var tube)) + EntityManager.TryGetComponent(args.Target, out var tube)) { Verb verb = new(); verb.Text = Loc.GetString("tube-direction-verb-get-data-text"); @@ -180,21 +179,21 @@ namespace Content.Server.Administration // Make ghost role verb if (_groupController.CanCommand(player, "makeghostrole") && - !(args.Target.GetComponentOrNull()?.HasMind ?? false)) + !(EntityManager.GetComponentOrNull(args.Target)?.HasMind ?? false)) { Verb verb = new(); verb.Text = Loc.GetString("make-ghost-role-verb-get-data-text"); verb.Category = VerbCategory.Debug; // TODO VERB ICON add ghost icon // Where is the national park service icon for haunted forests? - verb.Act = () => _ghostRoleSystem.OpenMakeGhostRoleEui(player, args.Target.Uid); + verb.Act = () => _ghostRoleSystem.OpenMakeGhostRoleEui(player, args.Target); verb.Impact = LogImpact.Medium; args.Verbs.Add(verb); } // Configuration verb. Is this even used for anything!? if (_groupController.CanAdminMenu(player) && - args.Target.TryGetComponent(out var config)) + EntityManager.TryGetComponent(args.Target, out var config)) { Verb verb = new(); verb.Text = Loc.GetString("configure-verb-get-data-text"); @@ -206,13 +205,13 @@ namespace Content.Server.Administration // Add verb to open Solution Editor if (_groupController.CanCommand(player, "addreagent") && - args.Target.HasComponent()) + EntityManager.HasComponent(args.Target)) { Verb verb = new(); verb.Text = Loc.GetString("edit-solutions-verb-get-data-text"); verb.Category = VerbCategory.Debug; verb.IconTexture = "/Textures/Interface/VerbIcons/spill.svg.192dpi.png"; - verb.Act = () => OpenEditSolutionsEui(player, args.Target.Uid); + verb.Act = () => OpenEditSolutionsEui(player, args.Target); verb.Impact = LogImpact.Medium; // maybe high depending on WHAT reagents they add... args.Verbs.Add(verb); } diff --git a/Content.Server/Administration/Commands/AGhost.cs b/Content.Server/Administration/Commands/AGhost.cs index fb8a72c6d8..d7252145c7 100644 --- a/Content.Server/Administration/Commands/AGhost.cs +++ b/Content.Server/Administration/Commands/AGhost.cs @@ -13,6 +13,8 @@ namespace Content.Server.Administration.Commands [AdminCommand(AdminFlags.Admin)] public class AGhost : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "aghost"; public string Description => "Makes you an admin ghost."; public string Help => "aghost"; @@ -34,34 +36,35 @@ namespace Content.Server.Administration.Commands return; } - if (mind.VisitingEntity != null && mind.VisitingEntity.HasComponent()) + if (mind.VisitingEntity != default && _entities.HasComponent(mind.VisitingEntity)) { player.ContentData()!.Mind?.UnVisit(); return; } var canReturn = mind.CurrentEntity != null; - var ghost = IoCManager.Resolve() - .SpawnEntity("AdminObserver", player.AttachedEntity?.Transform.Coordinates - ?? EntitySystem.Get().GetObserverSpawnPoint()); + var coordinates = player.AttachedEntity != null + ? _entities.GetComponent(player.AttachedEntity.Value).Coordinates + : EntitySystem.Get().GetObserverSpawnPoint(); + var ghost = _entities.SpawnEntity("AdminObserver", coordinates); if (canReturn) { // TODO: Remove duplication between all this and "GamePreset.OnGhostAttempt()"... if(!string.IsNullOrWhiteSpace(mind.CharacterName)) - ghost.Name = mind.CharacterName; + _entities.GetComponent(ghost).EntityName = mind.CharacterName; else if (!string.IsNullOrWhiteSpace(mind.Session?.Name)) - ghost.Name = mind.Session.Name; + _entities.GetComponent(ghost).EntityName = mind.Session.Name; mind.Visit(ghost); } else { - ghost.Name = player.Name; - mind.TransferTo(ghost.Uid); + _entities.GetComponent(ghost).EntityName = player.Name; + mind.TransferTo(ghost); } - var comp = ghost.GetComponent(); + var comp = _entities.GetComponent(ghost); EntitySystem.Get().SetCanReturnToBody(comp, canReturn); } } diff --git a/Content.Server/Administration/Commands/AddEntityStorageCommand.cs b/Content.Server/Administration/Commands/AddEntityStorageCommand.cs index 85da28ad53..d3385136cd 100644 --- a/Content.Server/Administration/Commands/AddEntityStorageCommand.cs +++ b/Content.Server/Administration/Commands/AddEntityStorageCommand.cs @@ -38,7 +38,7 @@ namespace Content.Server.Administration.Commands if (entityManager.TryGetComponent(storageUid, out var storage)) { - storage.Insert(entityManager.GetEntity(entityUid)); + storage.Insert(entityUid); } else { diff --git a/Content.Server/Administration/Commands/ControlMob.cs b/Content.Server/Administration/Commands/ControlMob.cs index 3c5d70f1e3..6dae68645e 100644 --- a/Content.Server/Administration/Commands/ControlMob.cs +++ b/Content.Server/Administration/Commands/ControlMob.cs @@ -13,14 +13,15 @@ namespace Content.Server.Administration.Commands [AdminCommand(AdminFlags.Admin)] class ControlMob : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "controlmob"; public string Description => Loc.GetString("control-mob-command-description"); public string Help => Loc.GetString("control-mob-command-help-text"); public void Execute(IConsoleShell shell, string argStr, string[] args) { - var player = shell.Player as IPlayerSession; - if (player == null) + if (shell.Player is not IPlayerSession player) { shell.WriteLine("shell-server-cannot"); return; @@ -32,25 +33,21 @@ namespace Content.Server.Administration.Commands return; } - - var entityManager = IoCManager.Resolve(); - if (!int.TryParse(args[0], out var targetId)) { shell.WriteLine(Loc.GetString("shell-argument-must-be-number")); return; } - var eUid = new EntityUid(targetId); + var target = new EntityUid(targetId); - if (!eUid.IsValid() || !entityManager.EntityExists(eUid)) + if (!target.IsValid() || !_entities.EntityExists(target)) { shell.WriteLine(Loc.GetString("shell-invalid-entity-id")); return; } - var target = entityManager.GetEntity(eUid); - if (!target.TryGetComponent(out MindComponent? mindComponent)) + if (!_entities.HasComponent(target)) { shell.WriteLine(Loc.GetString("shell-entity-is-not-mob")); return; @@ -60,7 +57,7 @@ namespace Content.Server.Administration.Commands DebugTools.AssertNotNull(mind); - mind!.TransferTo(target.Uid); + mind!.TransferTo(target); } } } diff --git a/Content.Server/Administration/Commands/DeleteComponent.cs b/Content.Server/Administration/Commands/DeleteComponent.cs index 839ba06863..d848b1312b 100644 --- a/Content.Server/Administration/Commands/DeleteComponent.cs +++ b/Content.Server/Administration/Commands/DeleteComponent.cs @@ -37,7 +37,7 @@ namespace Content.Server.Administration.Commands foreach (var component in components) { - var uid = component.Owner.Uid; + var uid = component.Owner; entityManager.RemoveComponent(uid, component); i++; } diff --git a/Content.Server/Administration/Commands/DeleteEntitiesWithComponent.cs b/Content.Server/Administration/Commands/DeleteEntitiesWithComponent.cs index f2fff25edd..a2324d3810 100644 --- a/Content.Server/Administration/Commands/DeleteEntitiesWithComponent.cs +++ b/Content.Server/Administration/Commands/DeleteEntitiesWithComponent.cs @@ -37,12 +37,12 @@ namespace Content.Server.Administration.Commands var entityManager = IoCManager.Resolve(); var entitiesWithComponents = components.Select(c => entityManager.GetAllComponents(c).Select(x => x.Owner)); - var entitiesWithAllComponents = entitiesWithComponents.Skip(1).Aggregate(new HashSet(entitiesWithComponents.First()), (h, e) => { h.IntersectWith(e); return h; }); + var entitiesWithAllComponents = entitiesWithComponents.Skip(1).Aggregate(new HashSet(entitiesWithComponents.First()), (h, e) => { h.IntersectWith(e); return h; }); var count = 0; foreach (var entity in entitiesWithAllComponents) { - entity.Delete(); + entityManager.DeleteEntity(entity); count += 1; } diff --git a/Content.Server/Administration/Commands/DeleteEntitiesWithId.cs b/Content.Server/Administration/Commands/DeleteEntitiesWithId.cs index f646ce9281..def77308ed 100644 --- a/Content.Server/Administration/Commands/DeleteEntitiesWithId.cs +++ b/Content.Server/Administration/Commands/DeleteEntitiesWithId.cs @@ -1,8 +1,8 @@ +using System.Linq; using Content.Shared.Administration; using Robust.Shared.Console; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using System.Linq; namespace Content.Server.Administration.Commands { @@ -23,12 +23,12 @@ namespace Content.Server.Administration.Commands var id = args[0].ToLower(); var entityManager = IoCManager.Resolve(); - var entities = entityManager.GetEntities().Where(e => e.Prototype?.ID.ToLower() == id); + var entities = entityManager.GetEntities().Where(e => entityManager.GetComponent(e).EntityPrototype?.ID.ToLower() == id); var i = 0; foreach (var entity in entities) { - entity.Delete(); + entityManager.DeleteEntity(entity); i++; } diff --git a/Content.Server/Administration/Commands/DeleteEntityCommand.cs b/Content.Server/Administration/Commands/DeleteEntityCommand.cs index d6e2815f05..1d8aa288ac 100644 --- a/Content.Server/Administration/Commands/DeleteEntityCommand.cs +++ b/Content.Server/Administration/Commands/DeleteEntityCommand.cs @@ -28,13 +28,13 @@ namespace Content.Server.Administration.Commands var entityManager = IoCManager.Resolve(); - if (!entityManager.TryGetEntity(id, out var entity)) + if (!entityManager.EntityExists(id)) { shell.WriteLine($"No entity found with id {id}."); return; } - entity.Delete(); + entityManager.DeleteEntity(id); shell.WriteLine($"Deleted entity with id {id}."); } } diff --git a/Content.Server/Administration/Commands/ExplosionCommand.cs b/Content.Server/Administration/Commands/ExplosionCommand.cs index d9f9c86912..6e94dc4030 100644 --- a/Content.Server/Administration/Commands/ExplosionCommand.cs +++ b/Content.Server/Administration/Commands/ExplosionCommand.cs @@ -3,6 +3,7 @@ using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; namespace Content.Server.Administration.Commands @@ -18,7 +19,7 @@ namespace Content.Server.Administration.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; - if (player?.AttachedEntity == null) + if (player?.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine("You must have an attached entity."); return; @@ -32,8 +33,8 @@ namespace Content.Server.Administration.Commands var lgh = int.Parse(args[4]); var fla = int.Parse(args[5]); - var mapTransform = player.AttachedEntity.Transform.GetMapTransform(); - var coords = new EntityCoordinates(mapTransform.Owner.Uid, x, y); + var mapTransform = IoCManager.Resolve().GetComponent(playerEntity).GetMapTransform(); + var coords = new EntityCoordinates(mapTransform.Owner, x, y); EntitySystem.Get().SpawnExplosion(coords, dev, hvy, lgh, fla); } diff --git a/Content.Server/Administration/Commands/FindEntitiesWithComponents.cs b/Content.Server/Administration/Commands/FindEntitiesWithComponents.cs index b619159294..e6086e72f8 100644 --- a/Content.Server/Administration/Commands/FindEntitiesWithComponents.cs +++ b/Content.Server/Administration/Commands/FindEntitiesWithComponents.cs @@ -47,17 +47,17 @@ namespace Content.Server.Administration.Commands var entityManager = IoCManager.Resolve(); var entityIds = new HashSet(); - var entitiesWithComponents = components.Select(c => entityManager.GetAllComponents(c).Select(x => x.Owner)); - var entitiesWithAllComponents = entitiesWithComponents.Skip(1).Aggregate(new HashSet(entitiesWithComponents.First()), (h, e) => { h.IntersectWith(e); return h; }); + var entitiesWithComponents = components.Select(c => entityManager.GetAllComponents(c).Select(x => x.Owner)).ToArray(); + var entitiesWithAllComponents = entitiesWithComponents.Skip(1).Aggregate(new HashSet(entitiesWithComponents.First()), (h, e) => { h.IntersectWith(e); return h; }); foreach (var entity in entitiesWithAllComponents) { - if (entity.Prototype == null) + if (entityManager.GetComponent(entity).EntityPrototype is not { } prototypeId) { continue; } - entityIds.Add(entity.Prototype.ID); + entityIds.Add(prototypeId.ID); } if (entityIds.Count == 0) diff --git a/Content.Server/Administration/Commands/RejuvenateCommand.cs b/Content.Server/Administration/Commands/RejuvenateCommand.cs index 21b1d2f171..186dc13a5b 100644 --- a/Content.Server/Administration/Commands/RejuvenateCommand.cs +++ b/Content.Server/Administration/Commands/RejuvenateCommand.cs @@ -27,8 +27,7 @@ namespace Content.Server.Administration.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { - var player = shell.Player as IPlayerSession; - if (args.Length < 1 && player != null) //Try to heal the users mob if applicable + if (args.Length < 1 && shell.Player is IPlayerSession player) //Try to heal the users mob if applicable { shell.WriteLine(Loc.GetString("rejuvenate-command-self-heal-message")); if (player.AttachedEntity == null) @@ -36,13 +35,13 @@ namespace Content.Server.Administration.Commands shell.WriteLine(Loc.GetString("rejuvenate-command-no-entity-attached-message")); return; } - PerformRejuvenate(player.AttachedEntity); + PerformRejuvenate(player.AttachedEntity.Value); } var entityManager = IoCManager.Resolve(); foreach (var arg in args) { - if(!EntityUid.TryParse(arg, out var uid) || !entityManager.TryGetEntity(uid, out var entity)) + if (!EntityUid.TryParse(arg, out var entity) || !entityManager.EntityExists(entity)) { shell.WriteLine(Loc.GetString("shell-could-not-find-entity",("entity", arg))); continue; @@ -51,32 +50,34 @@ namespace Content.Server.Administration.Commands } } - public static void PerformRejuvenate(IEntity target) + public static void PerformRejuvenate(EntityUid target) { - target.GetComponentOrNull()?.UpdateState(0); - target.GetComponentOrNull()?.ResetFood(); - target.GetComponentOrNull()?.ResetThirst(); + var targetUid = target; + var entMan = IoCManager.Resolve(); + entMan.GetComponentOrNull(targetUid)?.UpdateState(0); + entMan.GetComponentOrNull(targetUid)?.ResetFood(); + entMan.GetComponentOrNull(targetUid)?.ResetThirst(); - EntitySystem.Get().TryRemoveAllStatusEffects(target.Uid); + EntitySystem.Get().TryRemoveAllStatusEffects(target); - if (target.TryGetComponent(out FlammableComponent? flammable)) + if (entMan.TryGetComponent(target, out FlammableComponent? flammable)) { - EntitySystem.Get().Extinguish(target.Uid, flammable); + EntitySystem.Get().Extinguish(target, flammable); } - if (target.TryGetComponent(out DamageableComponent? damageable)) + if (entMan.TryGetComponent(target, out DamageableComponent? damageable)) { EntitySystem.Get().SetAllDamage(damageable, 0); } - if (target.TryGetComponent(out CreamPiedComponent? creamPied)) + if (entMan.TryGetComponent(target, out CreamPiedComponent? creamPied)) { - EntitySystem.Get().SetCreamPied(target.Uid, creamPied, false); + EntitySystem.Get().SetCreamPied(target, creamPied, false); } - if (target.HasComponent()) + if (entMan.HasComponent(target)) { - target.RemoveComponent(); + entMan.RemoveComponent(target); } } } diff --git a/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs b/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs index fb4cc0698d..bc73bf7c51 100644 --- a/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs +++ b/Content.Server/Administration/Commands/RemoveEntityStorageCommand.cs @@ -36,7 +36,7 @@ namespace Content.Server.Administration.Commands if (entityManager.TryGetComponent(parent, out var storage)) { - storage.Remove(entityManager.GetEntity(entityUid)); + storage.Remove(entityUid); } else { diff --git a/Content.Server/Administration/Commands/RemoveExtraComponents.cs b/Content.Server/Administration/Commands/RemoveExtraComponents.cs index b680ecac06..ae1d31b209 100644 --- a/Content.Server/Administration/Commands/RemoveExtraComponents.cs +++ b/Content.Server/Administration/Commands/RemoveExtraComponents.cs @@ -32,19 +32,20 @@ namespace Content.Server.Administration.Commands foreach (var entity in entityManager.GetEntities()) { - if (checkPrototype && entity.Prototype != prototype || entity.Prototype == null) + var metaData = entityManager.GetComponent(entity); + if (checkPrototype && metaData.EntityPrototype != prototype || metaData.EntityPrototype == null) { continue; } var modified = false; - foreach (var component in entity.GetAllComponents()) + foreach (var component in entityManager.GetComponents(entity)) { - if (entity.Prototype.Components.ContainsKey(component.Name)) + if (metaData.EntityPrototype.Components.ContainsKey(component.Name)) continue; - entityManager.RemoveComponent(entity.Uid, component); + entityManager.RemoveComponent(entity, component); components++; modified = true; diff --git a/Content.Server/Administration/Commands/SetMindCommand.cs b/Content.Server/Administration/Commands/SetMindCommand.cs index 51c856b89e..9fc34085f7 100644 --- a/Content.Server/Administration/Commands/SetMindCommand.cs +++ b/Content.Server/Administration/Commands/SetMindCommand.cs @@ -42,9 +42,7 @@ namespace Content.Server.Administration.Commands return; } - var target = entityManager.GetEntity(eUid); - - if (!target.HasComponent()) + if (!entityManager.HasComponent(eUid)) { shell.WriteLine(Loc.GetString("set-mind-command-target-has-no-mind-message")); return; @@ -69,11 +67,11 @@ namespace Content.Server.Administration.Commands { mind = new Mind.Mind(session.UserId) { - CharacterName = target.Name + CharacterName = entityManager.GetComponent(eUid).EntityName }; mind.ChangeOwningPlayer(session.UserId); } - mind.TransferTo(target.Uid); + mind.TransferTo(eUid); } } } diff --git a/Content.Server/Administration/Commands/SetOutfitCommand.cs b/Content.Server/Administration/Commands/SetOutfitCommand.cs index 6337a9fb05..6bf82f8a95 100644 --- a/Content.Server/Administration/Commands/SetOutfitCommand.cs +++ b/Content.Server/Administration/Commands/SetOutfitCommand.cs @@ -43,17 +43,15 @@ namespace Content.Server.Administration.Commands var entityManager = IoCManager.Resolve(); - var eUid = new EntityUid(entityUid); + var target = new EntityUid(entityUid); - if (!eUid.IsValid() || !entityManager.EntityExists(eUid)) + if (!target.IsValid() || !entityManager.EntityExists(target)) { shell.WriteLine(Loc.GetString("shell-invalid-entity-id")); return; } - var target = entityManager.GetEntity(eUid); - - if (!target.TryGetComponent(out var inventoryComponent)) + if (!entityManager.TryGetComponent(target, out var inventoryComponent)) { shell.WriteLine(Loc.GetString("shell-target-entity-does-not-have-message",("missing", "inventory"))); return; @@ -82,7 +80,7 @@ namespace Content.Server.Administration.Commands HumanoidCharacterProfile? profile = null; // Check if we are setting the outfit of a player to respect the preferences - if (target.TryGetComponent(out var actorComponent)) + if (entityManager.TryGetComponent(target, out var actorComponent)) { var userId = actorComponent.PlayerSession.UserId; var preferencesManager = IoCManager.Resolve(); @@ -98,15 +96,15 @@ namespace Content.Server.Administration.Commands { continue; } - var equipmentEntity = entityManager.SpawnEntity(gearStr, target.Transform.Coordinates); + var equipmentEntity = entityManager.SpawnEntity(gearStr, entityManager.GetComponent(target).Coordinates); if (slot == EquipmentSlotDefines.Slots.IDCARD && - equipmentEntity.TryGetComponent(out var pdaComponent) && + entityManager.TryGetComponent(equipmentEntity, out var pdaComponent) && pdaComponent.ContainedID != null) { - pdaComponent.ContainedID.FullName = target.Name; + pdaComponent.ContainedID.FullName = entityManager.GetComponent(target).EntityName; } - inventoryComponent.Equip(slot, equipmentEntity.GetComponent(), false); + inventoryComponent.Equip(slot, entityManager.GetComponent(equipmentEntity), false); } } } diff --git a/Content.Server/Administration/Commands/WarpCommand.cs b/Content.Server/Administration/Commands/WarpCommand.cs index f37c366782..8a9c8b5291 100644 --- a/Content.Server/Administration/Commands/WarpCommand.cs +++ b/Content.Server/Administration/Commands/WarpCommand.cs @@ -53,19 +53,19 @@ namespace Content.Server.Administration.Commands } else { - if (player.Status != SessionStatus.InGame || player.AttachedEntity == null) + if (player.Status != SessionStatus.InGame || player.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine("You are not in-game!"); return; } var mapManager = IoCManager.Resolve(); - var currentMap = player.AttachedEntity.Transform.MapID; - var currentGrid = player.AttachedEntity.Transform.GridID; + var currentMap = entMan.GetComponent(playerEntity).MapID; + var currentGrid = entMan.GetComponent(playerEntity).GridID; var found = entMan.EntityQuery(true) .Where(p => p.Location == location) - .Select(p => p.Owner.Transform.Coordinates) + .Select(p => entMan.GetComponent(p.Owner).Coordinates) .OrderBy(p => p, Comparer.Create((a, b) => { // Sort so that warp points on the same grid/map are first. @@ -113,8 +113,8 @@ namespace Content.Server.Administration.Commands if (found.GetGridId(entMan) != GridId.Invalid) { - player.AttachedEntity.Transform.Coordinates = found; - if (player.AttachedEntity.TryGetComponent(out IPhysBody? physics)) + entMan.GetComponent(playerEntity).Coordinates = found; + if (entMan.TryGetComponent(playerEntity, out IPhysBody? physics)) { physics.LinearVelocity = Vector2.Zero; } diff --git a/Content.Server/Administration/Logs/AdminLogSystem.Json.cs b/Content.Server/Administration/Logs/AdminLogSystem.Json.cs index ee14ab864f..1c21f167af 100644 --- a/Content.Server/Administration/Logs/AdminLogSystem.Json.cs +++ b/Content.Server/Administration/Logs/AdminLogSystem.Json.cs @@ -57,9 +57,8 @@ public partial class AdminLogSystem EntityUid? entityId = properties[key] switch { EntityUid id => id, - IEntity entity => entity.Uid, - IPlayerSession {AttachedEntityUid: { }} session => session.AttachedEntityUid.Value, - IComponent component => component.OwnerUid, + IPlayerSession {AttachedEntity: {Valid: true}} session => session.AttachedEntity, + IComponent component => component.Owner, _ => null }; diff --git a/Content.Server/Administration/Logs/Converters/EntityConverter.cs b/Content.Server/Administration/Logs/Converters/EntityConverter.cs deleted file mode 100644 index 226d14a97f..0000000000 --- a/Content.Server/Administration/Logs/Converters/EntityConverter.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Text.Json; -using Robust.Server.GameObjects; -using Robust.Shared.GameObjects; -using Robust.Shared.IoC; - -namespace Content.Server.Administration.Logs.Converters; - -[AdminLogConverter] -public class EntityConverter : AdminLogConverter -{ - [Dependency] private readonly IEntityManager _entities = default!; - - public override void Write(Utf8JsonWriter writer, IEntity value, JsonSerializerOptions options) - { - EntityUidConverter.Write(writer, value.Uid, options, _entities); - } -} diff --git a/Content.Server/Administration/Logs/Converters/PlayerSessionConverter.cs b/Content.Server/Administration/Logs/Converters/PlayerSessionConverter.cs index 275dbc617c..5d7c133c78 100644 --- a/Content.Server/Administration/Logs/Converters/PlayerSessionConverter.cs +++ b/Content.Server/Administration/Logs/Converters/PlayerSessionConverter.cs @@ -1,5 +1,7 @@ using System.Text.Json; using Robust.Server.Player; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Administration.Logs.Converters; @@ -10,10 +12,12 @@ public class PlayerSessionConverter : AdminLogConverter { writer.WriteStartObject(); - if (value.Player.AttachedEntity != null) + if (value.Player.AttachedEntity is {Valid: true} playerEntity) { - writer.WriteNumber("id", (int) value.Player.AttachedEntity.Uid); - writer.WriteString("name", value.Player.AttachedEntity.Name); + var entityManager = IoCManager.Resolve(); + + writer.WriteNumber("id", (int) value.Player.AttachedEntity); + writer.WriteString("name", entityManager.GetComponent(playerEntity).EntityName); } writer.WriteString("player", value.Player.UserId.UserId); diff --git a/Content.Server/Administration/UI/SetOutfitEui.cs b/Content.Server/Administration/UI/SetOutfitEui.cs index 4ffa70c942..24e727682c 100644 --- a/Content.Server/Administration/UI/SetOutfitEui.cs +++ b/Content.Server/Administration/UI/SetOutfitEui.cs @@ -12,8 +12,9 @@ namespace Content.Server.Administration.UI public sealed class SetOutfitEui : BaseEui { [Dependency] private readonly IAdminManager _adminManager = default!; - private readonly IEntity _target; - public SetOutfitEui(IEntity entity) + private readonly EntityUid _target; + + public SetOutfitEui(EntityUid entity) { _target = entity; IoCManager.InjectDependencies(this); @@ -31,7 +32,7 @@ namespace Content.Server.Administration.UI { return new SetOutfitEuiState { - TargetEntityId = _target.Uid + TargetEntityId = _target }; } diff --git a/Content.Server/Advertise/AdvertiseSystem.cs b/Content.Server/Advertise/AdvertiseSystem.cs index 1e8c483daa..3ffdc39eb1 100644 --- a/Content.Server/Advertise/AdvertiseSystem.cs +++ b/Content.Server/Advertise/AdvertiseSystem.cs @@ -3,7 +3,6 @@ using Content.Server.Advertisements; using Content.Server.Chat.Managers; using Content.Server.Power.Components; using Content.Server.VendingMachines; -using Content.Shared.Acts; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; @@ -117,7 +116,7 @@ namespace Content.Server.Advertise if (advertise.NextAdvertisementTime > curTime) continue; - SayAdvertisement(advertise.Owner.Uid, true, advertise); + SayAdvertisement(advertise.Owner, true, advertise); } } } diff --git a/Content.Server/Alert/Click/RemoveCuffs.cs b/Content.Server/Alert/Click/RemoveCuffs.cs index 6ef8fd87c4..af55ca2617 100644 --- a/Content.Server/Alert/Click/RemoveCuffs.cs +++ b/Content.Server/Alert/Click/RemoveCuffs.cs @@ -1,6 +1,8 @@ using Content.Server.Cuffs.Components; using Content.Shared.Alert; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Alert.Click @@ -14,7 +16,7 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (args.Player.TryGetComponent(out CuffableComponent? cuffableComponent)) + if (IoCManager.Resolve().TryGetComponent(args.Player, out CuffableComponent? cuffableComponent)) { cuffableComponent.TryUncuff(args.Player); } diff --git a/Content.Server/Alert/Click/ResistFire.cs b/Content.Server/Alert/Click/ResistFire.cs index 94d0e594dc..8a980b1037 100644 --- a/Content.Server/Alert/Click/ResistFire.cs +++ b/Content.Server/Alert/Click/ResistFire.cs @@ -3,6 +3,7 @@ using Content.Server.Atmos.EntitySystems; using Content.Shared.Alert; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Alert.Click @@ -16,9 +17,9 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (args.Player.TryGetComponent(out FlammableComponent? flammable)) + if (IoCManager.Resolve().TryGetComponent(args.Player, out FlammableComponent? flammable)) { - EntitySystem.Get().Resist(args.Player.Uid, flammable); + EntitySystem.Get().Resist(args.Player, flammable); } } } diff --git a/Content.Server/Alert/Click/StopBeingPulled.cs b/Content.Server/Alert/Click/StopBeingPulled.cs index f69fe44661..2d76c98347 100644 --- a/Content.Server/Alert/Click/StopBeingPulled.cs +++ b/Content.Server/Alert/Click/StopBeingPulled.cs @@ -4,6 +4,7 @@ using Content.Shared.Pulling.Components; using Content.Shared.Pulling; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Alert.Click @@ -17,10 +18,10 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (!EntitySystem.Get().CanInteract(args.Player.Uid)) + if (!EntitySystem.Get().CanInteract(args.Player)) return; - if (args.Player.TryGetComponent(out var playerPullable)) + if (IoCManager.Resolve().TryGetComponent(args.Player, out var playerPullable)) { EntitySystem.Get().TryStopPull(playerPullable); } diff --git a/Content.Server/Alert/Click/StopPiloting.cs b/Content.Server/Alert/Click/StopPiloting.cs index 64b6841a70..9b1ccabed7 100644 --- a/Content.Server/Alert/Click/StopPiloting.cs +++ b/Content.Server/Alert/Click/StopPiloting.cs @@ -5,6 +5,7 @@ using Content.Shared.Shuttles; using Content.Shared.Shuttles.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Alert.Click @@ -18,7 +19,7 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (args.Player.TryGetComponent(out PilotComponent? pilotComponent) && + if (IoCManager.Resolve().TryGetComponent(args.Player, out PilotComponent? pilotComponent) && pilotComponent.Console != null) { EntitySystem.Get().RemovePilot(pilotComponent); diff --git a/Content.Server/Alert/Click/StopPulling.cs b/Content.Server/Alert/Click/StopPulling.cs index 1e098733b4..30d3d11cce 100644 --- a/Content.Server/Alert/Click/StopPulling.cs +++ b/Content.Server/Alert/Click/StopPulling.cs @@ -3,6 +3,7 @@ using Content.Shared.Pulling; using Content.Shared.Pulling.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Alert.Click @@ -17,11 +18,10 @@ namespace Content.Server.Alert.Click public void AlertClicked(ClickAlertEventArgs args) { var ps = EntitySystem.Get(); - var playerTargetPullable = ps.GetPulled(args.Player)? - .GetComponentOrNull(); - if (playerTargetPullable != null) + var playerTarget = ps.GetPulled(args.Player); + if (playerTarget != default && IoCManager.Resolve().TryGetComponent(playerTarget, out SharedPullableComponent playerPullable)) { - ps.TryStopPull(playerTargetPullable); + ps.TryStopPull(playerPullable); } } } diff --git a/Content.Server/Alert/Click/Unbuckle.cs b/Content.Server/Alert/Click/Unbuckle.cs index 38ac730bfc..9515320efe 100644 --- a/Content.Server/Alert/Click/Unbuckle.cs +++ b/Content.Server/Alert/Click/Unbuckle.cs @@ -1,6 +1,8 @@ using Content.Server.Buckle.Components; using Content.Shared.Alert; using JetBrains.Annotations; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Alert.Click @@ -14,7 +16,7 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (args.Player.TryGetComponent(out BuckleComponent? buckle)) + if (IoCManager.Resolve().TryGetComponent(args.Player, out BuckleComponent? buckle)) { buckle.TryUnbuckle(args.Player); } diff --git a/Content.Server/Alert/Commands/ClearAlert.cs b/Content.Server/Alert/Commands/ClearAlert.cs index 3ddc04a72d..3348d3bf3b 100644 --- a/Content.Server/Alert/Commands/ClearAlert.cs +++ b/Content.Server/Alert/Commands/ClearAlert.cs @@ -5,6 +5,7 @@ using Content.Shared.Administration; using Content.Shared.Alert; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.Alert.Commands @@ -25,7 +26,7 @@ namespace Content.Server.Alert.Commands return; } - var attachedEntity = player.AttachedEntity; + var attachedEntity = player.AttachedEntity.Value; if (args.Length > 1) { @@ -33,7 +34,7 @@ namespace Content.Server.Alert.Commands if (!CommandUtils.TryGetAttachedEntityByUsernameOrId(shell, target, player, out attachedEntity)) return; } - if (!attachedEntity.TryGetComponent(out ServerAlertsComponent? alertsComponent)) + if (!IoCManager.Resolve().TryGetComponent(attachedEntity, out ServerAlertsComponent? alertsComponent)) { shell.WriteLine("user has no alerts component"); return; diff --git a/Content.Server/Alert/Commands/ShowAlert.cs b/Content.Server/Alert/Commands/ShowAlert.cs index 05cf1397a8..04769bc3d2 100644 --- a/Content.Server/Alert/Commands/ShowAlert.cs +++ b/Content.Server/Alert/Commands/ShowAlert.cs @@ -5,6 +5,7 @@ using Content.Shared.Administration; using Content.Shared.Alert; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.Alert.Commands @@ -19,19 +20,13 @@ namespace Content.Server.Alert.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; - if (player == null) + if (player?.AttachedEntity == null) { - shell.WriteLine("You cannot run this command from the server."); + shell.WriteLine("You cannot run this from the server or without an attached entity."); return; } - var attachedEntity = player.AttachedEntity; - - if (attachedEntity == null) - { - shell.WriteLine("You don't have an entity."); - return; - } + var attachedEntity = player.AttachedEntity.Value; if (args.Length > 2) { @@ -39,7 +34,7 @@ namespace Content.Server.Alert.Commands if (!CommandUtils.TryGetAttachedEntityByUsernameOrId(shell, target, player, out attachedEntity)) return; } - if (!attachedEntity.TryGetComponent(out ServerAlertsComponent? alertsComponent)) + if (!IoCManager.Resolve().TryGetComponent(attachedEntity, out ServerAlertsComponent? alertsComponent)) { shell.WriteLine("user has no alerts component"); return; @@ -58,7 +53,7 @@ namespace Content.Server.Alert.Commands shell.WriteLine("invalid severity " + sevint); return; } - alertsComponent.ShowAlert(alert.AlertType, sevint == -1 ? (short?) null : sevint); + alertsComponent.ShowAlert(alert.AlertType, sevint == -1 ? null : sevint); } } } diff --git a/Content.Server/Alert/ServerAlertsComponent.cs b/Content.Server/Alert/ServerAlertsComponent.cs index f619292635..954838a1ba 100644 --- a/Content.Server/Alert/ServerAlertsComponent.cs +++ b/Content.Server/Alert/ServerAlertsComponent.cs @@ -2,6 +2,7 @@ using Content.Server.Gravity.EntitySystems; using Content.Shared.Alert; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Network; using Robust.Shared.Players; @@ -55,7 +56,7 @@ namespace Content.Server.Alert { case ClickAlertMessage msg: { - var player = session.AttachedEntity; + var player = session.AttachedEntity.GetValueOrDefault(); if (player != Owner) { @@ -66,7 +67,7 @@ namespace Content.Server.Alert { Logger.DebugS("alert", "user {0} attempted to" + " click alert {1} which is not currently showing for them", - player.Name, msg.Type); + IoCManager.Resolve().GetComponent(player).EntityName, msg.Type); break; } diff --git a/Content.Server/Animals/Systems/UdderSystem.cs b/Content.Server/Animals/Systems/UdderSystem.cs index 0d4e362765..6158582a6f 100644 --- a/Content.Server/Animals/Systems/UdderSystem.cs +++ b/Content.Server/Animals/Systems/UdderSystem.cs @@ -1,16 +1,15 @@ -using System; using Content.Server.Animals.Components; +using Content.Server.Chemistry.Components.SolutionManager; +using Content.Server.Chemistry.EntitySystems; +using Content.Server.DoAfter; +using Content.Server.Nutrition.Components; +using Content.Server.Popups; +using Content.Shared.Nutrition.Components; +using Content.Shared.Verbs; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Content.Server.Chemistry.EntitySystems; -using Content.Server.Nutrition.Components; -using Content.Shared.Nutrition.Components; -using Content.Server.Chemistry.Components.SolutionManager; -using Content.Server.DoAfter; using Robust.Shared.Localization; -using Content.Shared.Verbs; using Robust.Shared.Player; -using Content.Server.Popups; namespace Content.Server.Animals.Systems { @@ -42,7 +41,7 @@ namespace Content.Server.Animals.Systems continue; // Actually there is food digestion so no problem with instant reagent generation "OnFeed" - if (udder.Owner.TryGetComponent(out var hunger)) + if (EntityManager.TryGetComponent(udder.Owner, out var hunger)) { hunger.HungerThresholds.TryGetValue(HungerThreshold.Peckish, out var targetThreshold); @@ -51,11 +50,11 @@ namespace Content.Server.Animals.Systems continue; } - if (!_solutionContainerSystem.TryGetSolution(udder.OwnerUid, udder.TargetSolutionName, out var solution)) + if (!_solutionContainerSystem.TryGetSolution(udder.Owner, udder.TargetSolutionName, out var solution)) continue; //TODO: toxins from bloodstream !? - _solutionContainerSystem.TryAddReagent(udder.OwnerUid, solution, udder.ReagentId, udder.QuantityPerUpdate, out var accepted); + _solutionContainerSystem.TryAddReagent(udder.Owner, solution, udder.ReagentId, udder.QuantityPerUpdate, out var accepted); udder.AccumulatedFrameTime = 0; } } @@ -110,8 +109,7 @@ namespace Content.Server.Animals.Systems var split = _solutionContainerSystem.SplitSolution(uid, solution, quantity); _solutionContainerSystem.TryAddSolution(ev.ContainerUid, targetSolution, split); - var container = EntityManager.GetEntity(ev.ContainerUid); - _popupSystem.PopupEntity(Loc.GetString("udder-system-success", ("amount", quantity), ("target", container)), uid, Filter.Entities(ev.UserUid)); + _popupSystem.PopupEntity(Loc.GetString("udder-system-success", ("amount", quantity), ("target", ev.ContainerUid)), uid, Filter.Entities(ev.UserUid)); } private void OnMilkingFailed(EntityUid uid, UdderComponent component, MilkingFailEvent ev) @@ -123,16 +121,18 @@ namespace Content.Server.Animals.Systems { if (args.Using == null || !args.CanInteract || - !args.Using.HasComponent()) + !EntityManager.HasComponent(args.Using.Value)) return; - Verb verb = new(); - verb.Act = () => + Verb verb = new() { - AttemptMilk(uid, args.User.Uid, args.Using.Uid, component); + Act = () => + { + AttemptMilk(uid, args.User, args.Using.Value, component); + }, + Text = Loc.GetString("udder-system-verb-milk"), + Priority = 2 }; - verb.Text = Loc.GetString("udder-system-verb-milk"); - verb.Priority = 2; args.Verbs.Add(verb); } diff --git a/Content.Server/Arcade/Components/BlockGameArcadeComponent.cs b/Content.Server/Arcade/Components/BlockGameArcadeComponent.cs index 23ddb79cde..24139d624b 100644 --- a/Content.Server/Arcade/Components/BlockGameArcadeComponent.cs +++ b/Content.Server/Arcade/Components/BlockGameArcadeComponent.cs @@ -49,10 +49,10 @@ namespace Content.Server.Arcade.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if(!Powered || !eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if(!Powered || !IoCManager.Resolve().TryGetComponent(eventArgs.User, out ActorComponent? actor)) return; - if(!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if(!EntitySystem.Get().CanInteract(eventArgs.User)) return; UserInterface?.Toggle(actor.PlayerSession); @@ -131,7 +131,7 @@ namespace Content.Server.Arcade.Components if (obj.Session != _player) break; // TODO: Should this check if the Owner can interact...? - if (!EntitySystem.Get().CanInteract(OwnerUid)) + if (!EntitySystem.Get().CanInteract(Owner)) { DeactivePlayer(obj.Session); break; @@ -664,11 +664,11 @@ namespace Content.Server.Arcade.Components _running = false; _gameOver = true; - if (_component._player?.AttachedEntity != null) + if (_component._player?.AttachedEntity is {Valid: true} playerEntity) { var blockGameSystem = EntitySystem.Get(); - _highScorePlacement = blockGameSystem.RegisterHighScore(_component._player.AttachedEntity.Name, Points); + _highScorePlacement = blockGameSystem.RegisterHighScore(IoCManager.Resolve().GetComponent(playerEntity).EntityName, Points); SendHighscoreUpdate(); } _component.UserInterface?.SendMessage(new BlockGameMessages.BlockGameGameOverScreenMessage(Points, _highScorePlacement?.LocalPlacement, _highScorePlacement?.GlobalPlacement)); diff --git a/Content.Server/Arcade/Components/SpaceVillainArcadeComponent.cs b/Content.Server/Arcade/Components/SpaceVillainArcadeComponent.cs index b3b82cc276..ab5b1e8a9e 100644 --- a/Content.Server/Arcade/Components/SpaceVillainArcadeComponent.cs +++ b/Content.Server/Arcade/Components/SpaceVillainArcadeComponent.cs @@ -74,10 +74,10 @@ namespace Content.Server.Arcade.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!Powered || !eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!Powered || !IoCManager.Resolve().TryGetComponent(eventArgs.User, out ActorComponent? actor)) return; - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if (!EntitySystem.Get().CanInteract(eventArgs.User)) return; _game ??= new SpaceVillainGame(this); @@ -223,7 +223,7 @@ namespace Content.Server.Arcade.Components public void ProcessWin() { var entityManager = IoCManager.Resolve(); - entityManager.SpawnEntity(_random.Pick(_possibleRewards), Owner.Transform.MapPosition); + entityManager.SpawnEntity(_random.Pick(_possibleRewards), entityManager.GetComponent(Owner).MapPosition); } /// diff --git a/Content.Server/Atmos/Commands/AddAtmosCommand.cs b/Content.Server/Atmos/Commands/AddAtmosCommand.cs index 69c85997f5..be4fc7e35e 100644 --- a/Content.Server/Atmos/Commands/AddAtmosCommand.cs +++ b/Content.Server/Atmos/Commands/AddAtmosCommand.cs @@ -11,6 +11,8 @@ namespace Content.Server.Atmos.Commands [AdminCommand(AdminFlags.Debug)] public class AddAtmosCommand : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "addatmos"; public string Description => "Adds atmos support to a grid."; public string Help => $"{Command} "; @@ -39,21 +41,19 @@ namespace Content.Server.Atmos.Commands return; } - var entMan = IoCManager.Resolve(); - - if (!entMan.TryGetEntity(gridComp.GridEntityId, out var grid)) + if (!_entities.EntityExists(gridComp.GridEntityId)) { shell.WriteLine("Failed to get grid entity."); return; } - if (grid.HasComponent()) + if (_entities.HasComponent(gridComp.GridEntityId)) { shell.WriteLine("Grid already has an atmosphere."); return; } - grid.AddComponent(); + _entities.AddComponent(gridComp.GridEntityId); shell.WriteLine($"Added atmosphere to grid {id}."); } diff --git a/Content.Server/Atmos/Commands/AddUnsimulatedAtmosCommand.cs b/Content.Server/Atmos/Commands/AddUnsimulatedAtmosCommand.cs index 5fb659cc59..b5e4850aaa 100644 --- a/Content.Server/Atmos/Commands/AddUnsimulatedAtmosCommand.cs +++ b/Content.Server/Atmos/Commands/AddUnsimulatedAtmosCommand.cs @@ -41,19 +41,19 @@ namespace Content.Server.Atmos.Commands var entMan = IoCManager.Resolve(); - if (!entMan.TryGetEntity(gridComp.GridEntityId, out var grid)) + if (!entMan.EntityExists(gridComp.GridEntityId)) { shell.WriteLine("Failed to get grid entity."); return; } - if (grid.HasComponent()) + if (entMan.HasComponent(gridComp.GridEntityId)) { shell.WriteLine("Grid already has an atmosphere."); return; } - grid.AddComponent(); + entMan.AddComponent(gridComp.GridEntityId); shell.WriteLine($"Added unsimulated atmosphere to grid {id}."); } diff --git a/Content.Server/Atmos/Commands/DeleteGasCommand.cs b/Content.Server/Atmos/Commands/DeleteGasCommand.cs index a06da56564..0e1adc1e6f 100644 --- a/Content.Server/Atmos/Commands/DeleteGasCommand.cs +++ b/Content.Server/Atmos/Commands/DeleteGasCommand.cs @@ -24,22 +24,25 @@ namespace Content.Server.Atmos.Commands GridId gridId; Gas? gas = null; + var entMan = IoCManager.Resolve(); + switch (args.Length) { case 0: + { if (player == null) { shell.WriteLine("A grid must be specified when the command isn't used by a player."); return; } - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine("You have no entity to get a grid from."); return; } - gridId = player.AttachedEntity.Transform.GridID; + gridId = entMan.GetComponent(playerEntity).GridID; if (gridId == GridId.Invalid) { @@ -48,6 +51,7 @@ namespace Content.Server.Atmos.Commands } break; + } case 1: { if (!int.TryParse(args[0], out var number)) @@ -59,13 +63,13 @@ namespace Content.Server.Atmos.Commands return; } - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine("You have no entity from which to get a grid id."); return; } - gridId = player.AttachedEntity.Transform.GridID; + gridId = entMan.GetComponent(playerEntity).GridID; if (gridId == GridId.Invalid) { diff --git a/Content.Server/Atmos/Components/AtmosPlaqueComponent.cs b/Content.Server/Atmos/Components/AtmosPlaqueComponent.cs index 4709f9712b..087ff837a6 100644 --- a/Content.Server/Atmos/Components/AtmosPlaqueComponent.cs +++ b/Content.Server/Atmos/Components/AtmosPlaqueComponent.cs @@ -10,6 +10,8 @@ namespace Content.Server.Atmos.Components [RegisterComponent] public sealed class AtmosPlaqueComponent : Component, IMapInit { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "AtmosPlaque"; [DataField("plaqueType")] @@ -55,7 +57,9 @@ namespace Content.Server.Atmos.Components return; } - Owner.Description = _type switch + var metaData = _entMan.GetComponent(Owner); + + var val = _type switch { PlaqueType.Zumos => "This plaque commemorates the rise of the Atmos ZUM division. May they carry the torch that the Atmos ZAS, LINDA and FEA divisions left behind.", @@ -69,7 +73,9 @@ namespace Content.Server.Atmos.Components _ => "Uhm", }; - Owner.Name = _type switch + metaData.EntityDescription = val; + + var val1 = _type switch { PlaqueType.Zumos => "ZUM Atmospherics Division plaque", @@ -83,7 +89,9 @@ namespace Content.Server.Atmos.Components _ => "Uhm", }; - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + metaData.EntityName = val1; + + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { var state = _type == PlaqueType.Zumos ? "zumosplaque" : "atmosplaque"; diff --git a/Content.Server/Atmos/Components/BreathToolComponent.cs b/Content.Server/Atmos/Components/BreathToolComponent.cs index d1ebbc483c..326e45ad62 100644 --- a/Content.Server/Atmos/Components/BreathToolComponent.cs +++ b/Content.Server/Atmos/Components/BreathToolComponent.cs @@ -1,6 +1,7 @@ using Content.Server.Body.Components; using Content.Shared.Inventory; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Atmos.Components @@ -11,6 +12,8 @@ namespace Content.Server.Atmos.Components [RegisterComponent] public class BreathToolComponent : Component, IEquipped, IUnequipped { + [Dependency] private readonly IEntityManager _entities = default!; + /// /// Tool is functional only in allowed slots /// @@ -19,7 +22,7 @@ namespace Content.Server.Atmos.Components public override string Name => "BreathMask"; public bool IsFunctional { get; private set; } - public IEntity? ConnectedInternalsEntity { get; private set; } + public EntityUid ConnectedInternalsEntity { get; private set; } protected override void Shutdown() { @@ -32,7 +35,7 @@ namespace Content.Server.Atmos.Components if ((EquipmentSlotDefines.SlotMasks[eventArgs.Slot] & _allowedSlots) != _allowedSlots) return; IsFunctional = true; - if (eventArgs.User.TryGetComponent(out InternalsComponent? internals)) + if (_entities.TryGetComponent(eventArgs.User, out InternalsComponent? internals)) { ConnectedInternalsEntity = eventArgs.User; internals.ConnectBreathTool(Owner); @@ -47,9 +50,9 @@ namespace Content.Server.Atmos.Components public void DisconnectInternals() { var old = ConnectedInternalsEntity; - ConnectedInternalsEntity = null; + ConnectedInternalsEntity = default; - if (old != null && old.TryGetComponent(out var internalsComponent)) + if (old != default && _entities.TryGetComponent(old, out var internalsComponent)) { internalsComponent.DisconnectBreathTool(); } diff --git a/Content.Server/Atmos/Components/GasAnalyzerComponent.cs b/Content.Server/Atmos/Components/GasAnalyzerComponent.cs index d0ff509c2e..03230438e3 100644 --- a/Content.Server/Atmos/Components/GasAnalyzerComponent.cs +++ b/Content.Server/Atmos/Components/GasAnalyzerComponent.cs @@ -10,9 +10,9 @@ using Content.Shared.Popups; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; -using Robust.Shared.Players; using Robust.Shared.ViewVariables; namespace Content.Server.Atmos.Components @@ -20,6 +20,8 @@ namespace Content.Server.Atmos.Components [RegisterComponent] public class GasAnalyzerComponent : SharedGasAnalyzerComponent, IAfterInteract, IDropped, IUse { + [Dependency] private readonly IEntityManager _entities = default!; + private GasAnalyzerDanger _pressureDanger; private float _timeSinceSync; private const float TimeBetweenSyncs = 2f; @@ -39,7 +41,7 @@ namespace Content.Server.Atmos.Components UserInterface.OnClosed += UserInterfaceOnClose; } - Owner.TryGetComponent(out _appearance); + _entities.TryGetComponent(Owner, out _appearance); } public override ComponentState GetComponentState() @@ -122,7 +124,7 @@ namespace Content.Server.Atmos.Components { // Already get the pressure before Dirty(), because we can't get the EntitySystem in that thread or smth var pressure = 0f; - var tile = EntitySystem.Get().GetTileMixture(Owner.Transform.Coordinates); + var tile = EntitySystem.Get().GetTileMixture(_entities.GetComponent(Owner).Coordinates); if (tile != null) { pressure = tile.Pressure; @@ -157,24 +159,24 @@ namespace Content.Server.Atmos.Components // Check if the player is still holding the gas analyzer => if not, don't update foreach (var session in UserInterface.SubscribedSessions) { - if (session.AttachedEntity == null) + if (session.AttachedEntity is not {Valid: true} playerEntity) return; - if (!session.AttachedEntity.TryGetComponent(out HandsComponent? handsComponent)) + if (!_entities.TryGetComponent(playerEntity, out HandsComponent? handsComponent)) return; - var activeHandEntity = handsComponent?.GetActiveHand?.Owner; - if (activeHandEntity == null || !activeHandEntity.TryGetComponent(out GasAnalyzerComponent? gasAnalyzer)) + if (handsComponent?.GetActiveHand?.Owner is not {Valid: true} activeHandEntity || + !_entities.TryGetComponent(activeHandEntity, out GasAnalyzerComponent? gasAnalyzer)) { return; } } - var pos = Owner.Transform.Coordinates; + var pos = _entities.GetComponent(Owner).Coordinates; if (!_checkPlayer && _position.HasValue) { // Check if position is out of range => don't update - if (!_position.Value.InRange(Owner.EntityManager, pos, SharedInteractionSystem.InteractionRange)) + if (!_position.Value.InRange(_entities, pos, SharedInteractionSystem.InteractionRange)) return; pos = _position.Value; @@ -219,22 +221,21 @@ namespace Content.Server.Atmos.Components switch (message) { case GasAnalyzerRefreshMessage msg: - var player = serverMsg.Session.AttachedEntity; - if (player == null) + if (serverMsg.Session.AttachedEntity is not {Valid: true} player) { return; } - if (!player.TryGetComponent(out HandsComponent? handsComponent)) + if (!_entities.TryGetComponent(player, out HandsComponent? handsComponent)) { Owner.PopupMessage(player, Loc.GetString("gas-analyzer-component-player-has-no-hands-message")); return; } - var activeHandEntity = handsComponent.GetActiveHand?.Owner; - if (activeHandEntity == null || !activeHandEntity.TryGetComponent(out GasAnalyzerComponent? gasAnalyzer)) + if (handsComponent.GetActiveHand?.Owner is not {Valid: true} activeHandEntity || + !_entities.TryGetComponent(activeHandEntity, out GasAnalyzerComponent? gasAnalyzer)) { - serverMsg.Session.AttachedEntity?.PopupMessage(Loc.GetString("gas-analyzer-component-need-gas-analyzer-in-hand-message")); + serverMsg.Session.AttachedEntity.Value.PopupMessage(Loc.GetString("gas-analyzer-component-need-gas-analyzer-in-hand-message")); return; } @@ -252,7 +253,7 @@ namespace Content.Server.Atmos.Components return true; } - if (eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { OpenInterface(actor.PlayerSession, eventArgs.ClickLocation); } @@ -264,7 +265,7 @@ namespace Content.Server.Atmos.Components void IDropped.Dropped(DroppedEventArgs eventArgs) { - if (eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { CloseInterface(actor.PlayerSession); } @@ -272,7 +273,7 @@ namespace Content.Server.Atmos.Components bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - if (eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { ToggleInterface(actor.PlayerSession); return true; diff --git a/Content.Server/Atmos/Components/GasTankComponent.cs b/Content.Server/Atmos/Components/GasTankComponent.cs index e9e0f63306..b9d5d1a6b6 100644 --- a/Content.Server/Atmos/Components/GasTankComponent.cs +++ b/Content.Server/Atmos/Components/GasTankComponent.cs @@ -19,6 +19,7 @@ using Robust.Server.Player; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -33,6 +34,8 @@ namespace Content.Server.Atmos.Components public class GasTankComponent : Component, IExamine, IGasMixtureHolder, IUse, IDropped, IActivate #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "GasTank"; private const float MaxExplosionRange = 14f; @@ -154,14 +157,14 @@ namespace Content.Server.Atmos.Components bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) return false; + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return false; OpenInterface(actor.PlayerSession); return true; } void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) return; + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return; OpenInterface(actor.PlayerSession); } @@ -174,7 +177,7 @@ namespace Content.Server.Atmos.Components UpdateUserInterface(); } - public void DisconnectFromInternals(IEntity? owner = null) + public void DisconnectFromInternals(EntityUid? owner = null) { if (!IsConnected) return; IsConnected = false; @@ -189,7 +192,7 @@ namespace Content.Server.Atmos.Components new GasTankBoundUserInterfaceState { TankPressure = Air?.Pressure ?? 0, - OutputPressure = initialUpdate ? OutputPressure : (float?) null, + OutputPressure = initialUpdate ? OutputPressure : null, InternalsConnected = IsConnected, CanConnectInternals = IsFunctional && internals != null }); @@ -215,7 +218,7 @@ namespace Content.Server.Atmos.Components { var user = GetInternalsComponent()?.Owner; - if (user == null || !EntitySystem.Get().CanUse(user.Uid)) + if (user == null || !EntitySystem.Get().CanUse(user.Value)) return; if (IsConnected) @@ -227,12 +230,12 @@ namespace Content.Server.Atmos.Components ConnectToInternals(); } - private InternalsComponent? GetInternalsComponent(IEntity? owner = null) + private InternalsComponent? GetInternalsComponent(EntityUid? owner = null) { - if (Owner.Deleted) return null; - if (owner != null) return owner.GetComponentOrNull(); + if (_entMan.Deleted(Owner)) return null; + if (owner != null) return _entMan.GetComponentOrNull(owner.Value); return Owner.TryGetContainer(out var container) - ? container.Owner.GetComponentOrNull() + ? _entMan.GetComponentOrNull(container.Owner) : null; } @@ -268,9 +271,9 @@ namespace Content.Server.Atmos.Components range = MaxExplosionRange; } - EntitySystem.Get().SpawnExplosion(OwnerUid, (int) (range * 0.25f), (int) (range * 0.5f), (int) (range * 1.5f), 1); + EntitySystem.Get().SpawnExplosion(Owner, (int) (range * 0.25f), (int) (range * 0.5f), (int) (range * 1.5f), 1); - Owner.QueueDelete(); + _entMan.QueueDeleteEntity(Owner); return; } @@ -278,13 +281,13 @@ namespace Content.Server.Atmos.Components { if (_integrity <= 0) { - var environment = atmosphereSystem.GetTileMixture(Owner.Transform.Coordinates, true); + var environment = atmosphereSystem.GetTileMixture(_entMan.GetComponent(Owner).Coordinates, true); if(environment != null) atmosphereSystem.Merge(environment, Air); - SoundSystem.Play(Filter.Pvs(Owner), _ruptureSound.GetSound(), Owner.Transform.Coordinates, AudioHelpers.WithVariation(0.125f)); + SoundSystem.Play(Filter.Pvs(Owner), _ruptureSound.GetSound(), _entMan.GetComponent(Owner).Coordinates, AudioHelpers.WithVariation(0.125f)); - Owner.QueueDelete(); + _entMan.QueueDeleteEntity(Owner); return; } @@ -296,7 +299,7 @@ namespace Content.Server.Atmos.Components { if (_integrity <= 0) { - var environment = atmosphereSystem.GetTileMixture(Owner.Transform.Coordinates, true); + var environment = atmosphereSystem.GetTileMixture(_entMan.GetComponent(Owner).Coordinates, true); if (environment == null) return; @@ -327,7 +330,7 @@ namespace Content.Server.Atmos.Components { public bool DoToggleAction(ToggleItemActionEventArgs args) { - if (!args.Item.TryGetComponent(out var gasTankComponent)) return false; + if (!IoCManager.Resolve().TryGetComponent(args.Item, out var gasTankComponent)) return false; // no change if (gasTankComponent.IsConnected == args.ToggledOn) return false; gasTankComponent.ToggleInternals(); diff --git a/Content.Server/Atmos/Components/MovedByPressureComponent.cs b/Content.Server/Atmos/Components/MovedByPressureComponent.cs index 17c2973d24..0d3d85a5e8 100644 --- a/Content.Server/Atmos/Components/MovedByPressureComponent.cs +++ b/Content.Server/Atmos/Components/MovedByPressureComponent.cs @@ -18,6 +18,7 @@ namespace Content.Server.Atmos.Components public class MovedByPressureComponent : Component { [Dependency] private readonly IRobustRandom _robustRandom = default!; + [Dependency] private readonly IEntityManager _entMan = default!; public override string Name => "MovedByPressure"; @@ -42,12 +43,12 @@ namespace Content.Server.Atmos.Components public void ExperiencePressureDifference(int cycle, float pressureDifference, AtmosDirection direction, float pressureResistanceProbDelta, EntityCoordinates throwTarget) { - if (!Owner.TryGetComponent(out PhysicsComponent? physics)) + if (!_entMan.TryGetComponent(Owner, out PhysicsComponent? physics)) return; // TODO ATMOS stuns? - var transform = physics.Owner.Transform; + var transform = _entMan.GetComponent(physics.Owner); var maxForce = MathF.Sqrt(pressureDifference) * 2.25f; var moveProb = 100f; @@ -61,7 +62,7 @@ namespace Content.Server.Atmos.Components && (maxForce >= (MoveResist * MoveForcePushRatio))) || (physics.BodyType == BodyType.Static && (maxForce >= (MoveResist * MoveForceForcePushRatio)))) { - if (physics.Owner.HasComponent()) + if (_entMan.HasComponent(physics.Owner)) { physics.BodyStatus = BodyStatus.InAir; @@ -72,10 +73,10 @@ namespace Content.Server.Atmos.Components Owner.SpawnTimer(2000, () => { - if (Deleted || !Owner.TryGetComponent(out PhysicsComponent? physicsComponent)) return; + if (Deleted || !_entMan.TryGetComponent(Owner, out PhysicsComponent? physicsComponent)) return; // Uhh if you get race conditions good luck buddy. - if (physicsComponent.Owner.HasComponent()) + if (_entMan.HasComponent(physicsComponent.Owner)) { physicsComponent.BodyStatus = BodyStatus.OnGround; } @@ -111,14 +112,14 @@ namespace Content.Server.Atmos.Components public static class MovedByPressureExtensions { - public static bool IsMovedByPressure(this IEntity entity) + public static bool IsMovedByPressure(this EntityUid entity) { return entity.IsMovedByPressure(out _); } - public static bool IsMovedByPressure(this IEntity entity, [NotNullWhen(true)] out MovedByPressureComponent? moved) + public static bool IsMovedByPressure(this EntityUid entity, [NotNullWhen(true)] out MovedByPressureComponent? moved) { - return entity.TryGetComponent(out moved) && + return IoCManager.Resolve().TryGetComponent(entity, out moved) && moved.Enabled; } } diff --git a/Content.Server/Atmos/EntitySystems/AirtightSystem.cs b/Content.Server/Atmos/EntitySystems/AirtightSystem.cs index 33ad557adc..4a481f0195 100644 --- a/Content.Server/Atmos/EntitySystems/AirtightSystem.cs +++ b/Content.Server/Atmos/EntitySystems/AirtightSystem.cs @@ -27,15 +27,17 @@ namespace Content.Server.Atmos.EntitySystems private void OnAirtightInit(EntityUid uid, AirtightComponent airtight, ComponentInit args) { + var xform = EntityManager.GetComponent(uid); + if (airtight.FixAirBlockedDirectionInitialize) { - var rotateEvent = new RotateEvent(airtight.Owner, Angle.Zero, airtight.Owner.Transform.WorldRotation); + var rotateEvent = new RotateEvent(airtight.Owner, Angle.Zero, xform.WorldRotation); OnAirtightRotated(uid, airtight, ref rotateEvent); } // Adding this component will immediately anchor the entity, because the atmos system // requires airtight entities to be anchored for performance. - airtight.Owner.Transform.Anchored = true; + xform.Anchored = true; UpdatePosition(airtight); } @@ -54,8 +56,10 @@ namespace Content.Server.Atmos.EntitySystems private void OnAirtightPositionChanged(EntityUid uid, AirtightComponent airtight, ref AnchorStateChangedEvent args) { - var gridId = airtight.Owner.Transform.GridID; - var coords = airtight.Owner.Transform.Coordinates; + var xform = EntityManager.GetComponent(uid); + + var gridId = xform.GridID; + var coords = xform.Coordinates; var grid = _mapManager.GetGrid(gridId); var tilePos = grid.TileIndicesFor(coords); @@ -79,16 +83,18 @@ namespace Content.Server.Atmos.EntitySystems { airtight.AirBlocked = airblocked; UpdatePosition(airtight); - RaiseLocalEvent(airtight.OwnerUid, new AirtightChanged(airtight)); + RaiseLocalEvent((airtight).Owner, new AirtightChanged(airtight)); } public void UpdatePosition(AirtightComponent airtight) { - if (!airtight.Owner.Transform.Anchored || !airtight.Owner.Transform.GridID.IsValid()) + var xform = EntityManager.GetComponent(airtight.Owner); + + if (!xform.Anchored || !xform.GridID.IsValid()) return; - var grid = _mapManager.GetGrid(airtight.Owner.Transform.GridID); - airtight.LastPosition = (airtight.Owner.Transform.GridID, grid.TileIndicesFor(airtight.Owner.Transform.Coordinates)); + var grid = _mapManager.GetGrid(xform.GridID); + airtight.LastPosition = (xform.GridID, grid.TileIndicesFor(xform.Coordinates)); InvalidatePosition(airtight.LastPosition.Item1, airtight.LastPosition.Item2, airtight.FixVacuum && !airtight.AirBlocked); } diff --git a/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs b/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs index f952b6e76d..a0841e0b3d 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosDebugOverlaySystem.cs @@ -7,10 +7,10 @@ using JetBrains.Annotations; using Robust.Server.Player; using Robust.Shared.Configuration; using Robust.Shared.Enums; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; -using Robust.Shared.Timing; namespace Content.Server.Atmos.EntitySystems { @@ -131,20 +131,22 @@ namespace Content.Server.Atmos.EntitySystems // Afterwards we reset all the chunk data for the next time we tick. foreach (var session in _playerObservers) { - if (session.AttachedEntity == null) continue; + if (session.AttachedEntity is not {Valid: true} entity) + continue; - var entity = session.AttachedEntity; + var transform = EntityManager.GetComponent(entity); - var worldBounds = Box2.CenteredAround(entity.Transform.WorldPosition, + var worldBounds = Box2.CenteredAround(transform.WorldPosition, new Vector2(LocalViewRange, LocalViewRange)); - foreach (var grid in _mapManager.FindGridsIntersecting(entity.Transform.MapID, worldBounds)) + foreach (var grid in _mapManager.FindGridsIntersecting(transform.MapID, worldBounds)) { - if (!EntityManager.TryGetEntity(grid.GridEntityId, out var gridEnt)) continue; + if (!EntityManager.EntityExists(grid.GridEntityId)) + continue; - if (!gridEnt.TryGetComponent(out var gam)) continue; + if (!EntityManager.TryGetComponent(grid.GridEntityId, out var gam)) continue; - var entityTile = grid.GetTileRef(entity.Transform.Coordinates).GridIndices; + var entityTile = grid.GetTileRef(transform.Coordinates).GridIndices; var baseTile = new Vector2i(entityTile.X - (LocalViewRange / 2), entityTile.Y - (LocalViewRange / 2)); var debugOverlayContent = new AtmosDebugOverlayData[LocalViewRange * LocalViewRange]; diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Grid.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Grid.cs index bb2695edd6..b0eb8ac153 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Grid.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Grid.cs @@ -1315,7 +1315,7 @@ namespace Content.Server.Atmos.EntitySystems public bool AddAtmosDevice(AtmosDeviceComponent atmosDevice) { - var grid = atmosDevice.Owner.Transform.GridID; + var grid = EntityManager.GetComponent(atmosDevice.Owner).GridID; if (!_mapManager.TryGetGrid(grid, out var mapGrid)) return false; @@ -1526,7 +1526,7 @@ namespace Content.Server.Atmos.EntitySystems public bool TryGetMapGrid(GridAtmosphereComponent gridAtmosphere, [NotNullWhen(true)] out IMapGrid? mapGrid) { - if (gridAtmosphere.Owner.TryGetComponent(out IMapGridComponent? mapGridComponent)) + if (EntityManager.TryGetComponent(gridAtmosphere.Owner, out IMapGridComponent? mapGridComponent)) { mapGrid = mapGridComponent.Grid; return true; diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs index 846d0be429..7e33c1a9d1 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.HighPressureDelta.cs @@ -1,10 +1,10 @@ using Content.Server.Atmos.Components; using Content.Shared.Atmos; using Content.Shared.Audio; -using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; @@ -33,7 +33,7 @@ namespace Content.Server.Atmos.EntitySystems foreach (var entity in _gridtileLookupSystem.GetEntitiesIntersecting(tile.GridIndex, tile.GridIndices)) { - if (!entity.TryGetComponent(out IPhysBody? physics) + if (!EntityManager.TryGetComponent(entity, out IPhysBody? physics) || !entity.IsMovedByPressure(out var pressure) || entity.IsInContainer()) continue; @@ -62,7 +62,7 @@ namespace Content.Server.Atmos.EntitySystems if (difference > tile.PressureDifference) { tile.PressureDifference = difference; - tile.PressureDirection = ((Vector2i)(tile.GridIndices - other.GridIndices)).GetDir().ToAtmosDirection(); + tile.PressureDirection = (tile.GridIndices - other.GridIndices).GetDir().ToAtmosDirection(); } } } diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Hotspot.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Hotspot.cs index ae213ddc45..07fdc654e4 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Hotspot.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Hotspot.cs @@ -2,6 +2,7 @@ using Content.Server.Atmos.Components; using Content.Server.Atmos.Reactions; using Content.Shared.Atmos; using Robust.Server.GameObjects; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.Atmos.EntitySystems @@ -143,7 +144,7 @@ namespace Content.Server.Atmos.EntitySystems foreach (var entity in _gridtileLookupSystem.GetEntitiesIntersecting(tile.GridIndex, tile.GridIndices)) { - RaiseLocalEvent(entity.Uid, fireEvent, false); + RaiseLocalEvent(entity, fireEvent, false); } } } diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs index e33fe91a74..eba7619884 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.Processing.cs @@ -314,7 +314,7 @@ namespace Content.Server.Atmos.EntitySystems var number = 0; while (atmosphere.CurrentRunAtmosDevices.TryDequeue(out var device)) { - RaiseLocalEvent(device.Owner.Uid, _updateEvent, false); + RaiseLocalEvent(device.Owner, _updateEvent, false); device.LastProcess = time; if (number++ < LagCheckIterations) continue; diff --git a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs index b977d883e8..f2dbd82d88 100644 --- a/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs +++ b/Content.Server/Atmos/EntitySystems/AtmosphereSystem.cs @@ -75,10 +75,10 @@ namespace Content.Server.Atmos.EntitySystems { foreach (var exposed in EntityManager.EntityQuery()) { - var tile = GetTileMixture(exposed.Owner.Transform.Coordinates); + var tile = GetTileMixture(EntityManager.GetComponent(exposed.Owner).Coordinates); if (tile == null) continue; - var updateEvent = new AtmosExposedUpdateEvent(exposed.Owner.Transform.Coordinates, tile); - RaiseLocalEvent(exposed.Owner.Uid, ref updateEvent); + var updateEvent = new AtmosExposedUpdateEvent(EntityManager.GetComponent(exposed.Owner).Coordinates, tile); + RaiseLocalEvent(exposed.Owner, ref updateEvent); } _exposedTimer -= ExposedUpdateDelay; diff --git a/Content.Server/Atmos/EntitySystems/BarotraumaSystem.cs b/Content.Server/Atmos/EntitySystems/BarotraumaSystem.cs index 89ca5022df..6850458c34 100644 --- a/Content.Server/Atmos/EntitySystems/BarotraumaSystem.cs +++ b/Content.Server/Atmos/EntitySystems/BarotraumaSystem.cs @@ -1,9 +1,7 @@ using System; -using System.Data; using Content.Server.Administration.Logs; using Content.Server.Alert; using Content.Server.Atmos.Components; -using Content.Shared.Administration.Logs; using Content.Shared.Alert; using Content.Shared.Atmos; using Content.Shared.Damage; @@ -86,9 +84,9 @@ namespace Content.Server.Atmos.EntitySystems if (totalDamage >= barotrauma.MaxDamage) continue; - var uid = barotrauma.Owner.Uid; + var uid = barotrauma.Owner; - var status = barotrauma.Owner.GetComponentOrNull(); + var status = EntityManager.GetComponentOrNull(barotrauma.Owner); var pressure = 1f; diff --git a/Content.Server/Atmos/EntitySystems/FlammableSystem.cs b/Content.Server/Atmos/EntitySystems/FlammableSystem.cs index 1cc6a90953..518dae272a 100644 --- a/Content.Server/Atmos/EntitySystems/FlammableSystem.cs +++ b/Content.Server/Atmos/EntitySystems/FlammableSystem.cs @@ -6,7 +6,6 @@ using Content.Server.Atmos.Components; using Content.Server.Stunnable; using Content.Server.Temperature.Systems; using Content.Shared.ActionBlocker; -using Content.Shared.Administration.Logs; using Content.Shared.Alert; using Content.Shared.Atmos; using Content.Shared.Damage; @@ -58,7 +57,7 @@ namespace Content.Server.Atmos.EntitySystems return; var isHotEvent = new IsHotEvent(); - RaiseLocalEvent(args.Used.Uid, isHotEvent, false); + RaiseLocalEvent(args.Used, isHotEvent, false); if (!isHotEvent.IsHot) return; @@ -69,7 +68,7 @@ namespace Content.Server.Atmos.EntitySystems private void OnCollideEvent(EntityUid uid, FlammableComponent flammable, StartCollideEvent args) { - var otherUid = args.OtherFixture.Body.Owner.Uid; + var otherUid = args.OtherFixture.Body.Owner; if (!EntityManager.TryGetComponent(otherUid, out FlammableComponent? otherFlammable)) return; @@ -174,7 +173,7 @@ namespace Content.Server.Atmos.EntitySystems if (!Resolve(uid, ref flammable, ref alerts)) return; - if (!flammable.OnFire || !_actionBlockerSystem.CanInteract(flammable.Owner.Uid) || flammable.Resisting) + if (!flammable.OnFire || !_actionBlockerSystem.CanInteract(flammable.Owner) || flammable.Resisting) return; flammable.Resisting = true; @@ -201,9 +200,9 @@ namespace Content.Server.Atmos.EntitySystems var fireStackDelta = fireStackMod - flammable.FireStacks; if (fireStackDelta > 0) { - AdjustFireStacks(flammable.OwnerUid, fireStackDelta, flammable); + AdjustFireStacks((flammable).Owner, fireStackDelta, flammable); } - Ignite(flammable.OwnerUid, flammable); + Ignite((flammable).Owner, flammable); } _fireEvents.Clear(); @@ -217,7 +216,7 @@ namespace Content.Server.Atmos.EntitySystems // TODO: This needs cleanup to take off the crust from TemperatureComponent and shit. foreach (var (flammable, physics, transform) in EntityManager.EntityQuery()) { - var uid = flammable.Owner.Uid; + var uid = flammable.Owner; // Slowly dry ourselves off if wet. if (flammable.FireStacks < 0) @@ -225,7 +224,7 @@ namespace Content.Server.Atmos.EntitySystems flammable.FireStacks = MathF.Min(0, flammable.FireStacks + 1); } - flammable.Owner.TryGetComponent(out ServerAlertsComponent? status); + EntityManager.TryGetComponent(flammable.Owner, out ServerAlertsComponent? status); if (!flammable.OnFire) { diff --git a/Content.Server/Atmos/EntitySystems/GasTankSystem.cs b/Content.Server/Atmos/EntitySystems/GasTankSystem.cs index 3080367c8a..856d9acfc0 100644 --- a/Content.Server/Atmos/EntitySystems/GasTankSystem.cs +++ b/Content.Server/Atmos/EntitySystems/GasTankSystem.cs @@ -24,7 +24,7 @@ namespace Content.Server.Atmos.EntitySystems private void AddOpenUIVerb(EntityUid uid, GasTankComponent component, GetActivationVerbsEvent args) { - if (!args.CanAccess || !args.User.TryGetComponent(out var actor)) + if (!args.CanAccess || !EntityManager.TryGetComponent(args.User, out var actor)) return; Verb verb = new(); diff --git a/Content.Server/Atmos/EntitySystems/GasTileOverlaySystem.cs b/Content.Server/Atmos/EntitySystems/GasTileOverlaySystem.cs index 90ddea67b7..ac44b578f3 100644 --- a/Content.Server/Atmos/EntitySystems/GasTileOverlaySystem.cs +++ b/Content.Server/Atmos/EntitySystems/GasTileOverlaySystem.cs @@ -19,17 +19,16 @@ using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Timing; // ReSharper disable once RedundantUsingDirective -using Dependency = Robust.Shared.IoC.DependencyAttribute; namespace Content.Server.Atmos.EntitySystems { [UsedImplicitly] internal sealed class GasTileOverlaySystem : SharedGasTileOverlaySystem { - [Dependency] private readonly IGameTiming _gameTiming = default!; - [Dependency] private readonly IPlayerManager _playerManager = default!; - [Dependency] private readonly IMapManager _mapManager = default!; - [Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!; + [Robust.Shared.IoC.Dependency] private readonly IGameTiming _gameTiming = default!; + [Robust.Shared.IoC.Dependency] private readonly IPlayerManager _playerManager = default!; + [Robust.Shared.IoC.Dependency] private readonly IMapManager _mapManager = default!; + [Robust.Shared.IoC.Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!; /// /// The tiles that have had their atmos data updated since last tick @@ -190,24 +189,24 @@ namespace Content.Server.Atmos.EntitySystems /// /// /// - private List GetChunksInRange(IEntity entity) + private List GetChunksInRange(EntityUid entity) { var inRange = new List(); // This is the max in any direction that we can get a chunk (e.g. max 2 chunks away of data). var (maxXDiff, maxYDiff) = ((int) (_updateRange / ChunkSize) + 1, (int) (_updateRange / ChunkSize) + 1); - var worldBounds = Box2.CenteredAround(entity.Transform.WorldPosition, + var worldBounds = Box2.CenteredAround(EntityManager.GetComponent(entity).WorldPosition, new Vector2(_updateRange, _updateRange)); - foreach (var grid in _mapManager.FindGridsIntersecting(entity.Transform.MapID, worldBounds)) + foreach (var grid in _mapManager.FindGridsIntersecting(EntityManager.GetComponent(entity).MapID, worldBounds)) { if (!_overlay.TryGetValue(grid.Index, out var chunks)) { continue; } - var entityTile = grid.GetTileRef(entity.Transform.Coordinates).GridIndices; + var entityTile = grid.GetTileRef(EntityManager.GetComponent(entity).Coordinates).GridIndices; for (var x = -maxXDiff; x <= maxXDiff; x++) { @@ -311,10 +310,10 @@ namespace Content.Server.Atmos.EntitySystems // Afterwards we reset all the chunk data for the next time we tick. foreach (var (session, overlay) in _knownPlayerChunks) { - if (session.AttachedEntity == null) continue; + if (session.AttachedEntity is not {Valid: true} entity) continue; // Get chunks in range and update if we've moved around or the chunks have new overlay data - var chunksInRange = GetChunksInRange(session.AttachedEntity); + var chunksInRange = GetChunksInRange(entity); var knownChunks = overlay.GetKnownChunks(); var chunksToRemove = new List(); var chunksToAdd = new List(); diff --git a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasDualPortVentPumpSystem.cs b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasDualPortVentPumpSystem.cs index 5018ae8203..00ad837a56 100644 --- a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasDualPortVentPumpSystem.cs +++ b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasDualPortVentPumpSystem.cs @@ -28,7 +28,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnGasDualPortVentPumpUpdated(EntityUid uid, GasDualPortVentPumpComponent vent, AtmosDeviceUpdateEvent args) { - var appearance = vent.Owner.GetComponentOrNull(); + var appearance = EntityManager.GetComponentOrNull(vent.Owner); if (vent.Welded) { @@ -45,7 +45,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems return; } - var environment = _atmosphereSystem.GetTileMixture(vent.Owner.Transform.Coordinates, true); + var environment = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(vent.Owner).Coordinates, true); // We're in an air-blocked tile... Do nothing. if (environment == null) diff --git a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPressurePumpSystem.cs b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPressurePumpSystem.cs index ccfead7f73..374d69faed 100644 --- a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPressurePumpSystem.cs +++ b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasPressurePumpSystem.cs @@ -38,7 +38,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnExamined(EntityUid uid, GasPressurePumpComponent pump, ExaminedEvent args) { - if (!pump.Owner.Transform.Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. + if (!EntityManager.GetComponent(pump.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. return; if (Loc.TryGetString("gas-pressure-pump-system-examined", out var str, @@ -50,7 +50,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnPumpUpdated(EntityUid uid, GasPressurePumpComponent pump, AtmosDeviceUpdateEvent args) { - var appearance = pump.Owner.GetComponentOrNull(); + var appearance = EntityManager.GetComponentOrNull(pump.Owner); if (!pump.Enabled || !EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodeContainer) @@ -92,10 +92,10 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnPumpInteractHand(EntityUid uid, GasPressurePumpComponent component, InteractHandEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; - if (component.Owner.Transform.Anchored) + if (EntityManager.GetComponent(component.Owner).Anchored) { _userInterfaceSystem.TryOpen(uid, GasPressurePumpUiKey.Key, actor.PlayerSession); DirtyUI(uid, component); @@ -127,7 +127,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems return; _userInterfaceSystem.TrySetUiState(uid, GasPressurePumpUiKey.Key, - new GasPressurePumpBoundUserInterfaceState(pump.Owner.Name, pump.TargetPressure, pump.Enabled)); + new GasPressurePumpBoundUserInterfaceState(EntityManager.GetComponent(pump.Owner).EntityName, pump.TargetPressure, pump.Enabled)); } } } diff --git a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs index d4d4465d39..5d04f55d01 100644 --- a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs +++ b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasValveSystem.cs @@ -11,6 +11,7 @@ using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; @@ -30,7 +31,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnExamined(EntityUid uid, GasValveComponent valve, ExaminedEvent args) { - if (!valve.Owner.Transform.Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. + if (!EntityManager.GetComponent(valve.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. return; if (Loc.TryGetString("gas-valve-system-examined", out var str, @@ -48,7 +49,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnActivate(EntityUid uid, GasValveComponent component, ActivateInWorldEvent args) { - if (args.User.InRangeUnobstructed(args.Target) && Get().CanInteract(args.User.Uid)) + if (args.User.InRangeUnobstructed(args.Target) && Get().CanInteract(args.User)) { Toggle(uid, component); SoundSystem.Play(Filter.Pvs(component.Owner), component._valveSound.GetSound(), component.Owner, AudioHelpers.WithVariation(0.25f)); diff --git a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasVolumePumpSystem.cs b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasVolumePumpSystem.cs index 527f11e676..b9e64a898d 100644 --- a/Content.Server/Atmos/Piping/Binary/EntitySystems/GasVolumePumpSystem.cs +++ b/Content.Server/Atmos/Piping/Binary/EntitySystems/GasVolumePumpSystem.cs @@ -39,7 +39,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnExamined(EntityUid uid, GasVolumePumpComponent pump, ExaminedEvent args) { - if (!pump.Owner.Transform.Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. + if (!EntityManager.GetComponent(pump.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status. return; if (Loc.TryGetString("gas-volume-pump-system-examined", out var str, @@ -83,7 +83,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems // Some of the gas from the mixture leaks when overclocked. if (pump.Overclocked) { - var tile = _atmosphereSystem.GetTileMixture(pump.Owner.Transform.Coordinates, true); + var tile = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(pump.Owner).Coordinates, true); if (tile != null) { @@ -97,10 +97,10 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems private void OnPumpInteractHand(EntityUid uid, GasVolumePumpComponent component, InteractHandEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; - if (component.Owner.Transform.Anchored) + if (EntityManager.GetComponent(component.Owner).Anchored) { _userInterfaceSystem.TryOpen(uid, GasVolumePumpUiKey.Key, actor.PlayerSession); DirtyUI(uid, component); @@ -132,7 +132,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems return; _userInterfaceSystem.TrySetUiState(uid, GasVolumePumpUiKey.Key, - new GasVolumePumpBoundUserInterfaceState(pump.Owner.Name, pump.TransferRate, pump.Enabled)); + new GasVolumePumpBoundUserInterfaceState(EntityManager.GetComponent(pump.Owner).EntityName, pump.TransferRate, pump.Enabled)); } } } diff --git a/Content.Server/Atmos/Piping/Components/AtmosPipeColorComponent.cs b/Content.Server/Atmos/Piping/Components/AtmosPipeColorComponent.cs index 87439345f5..2057ae2118 100644 --- a/Content.Server/Atmos/Piping/Components/AtmosPipeColorComponent.cs +++ b/Content.Server/Atmos/Piping/Components/AtmosPipeColorComponent.cs @@ -19,7 +19,7 @@ namespace Content.Server.Atmos.Piping.Components public Color ColorVV { get => Color; - set => EntitySystem.Get().SetColor(Owner.Uid, this, value); + set => EntitySystem.Get().SetColor(Owner, this, value); } } } diff --git a/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs b/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs index 1c4e0807e3..2d5bcca41a 100644 --- a/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs +++ b/Content.Server/Atmos/Piping/EntitySystems/AtmosDeviceSystem.cs @@ -32,7 +32,7 @@ namespace Content.Server.Atmos.Piping.EntitySystems private bool CanJoinAtmosphere(AtmosDeviceComponent component) { - return !component.RequireAnchored || component.Owner.Transform.Anchored; + return !component.RequireAnchored || EntityManager.GetComponent(component.Owner).Anchored; } public void JoinAtmosphere(AtmosDeviceComponent component) @@ -59,7 +59,7 @@ namespace Content.Server.Atmos.Piping.EntitySystems component.LastProcess = _gameTiming.CurTime; - RaiseLocalEvent(component.Owner.Uid, new AtmosDeviceEnabledEvent(), false); + RaiseLocalEvent(component.Owner, new AtmosDeviceEnabledEvent(), false); } public void LeaveAtmosphere(AtmosDeviceComponent component) @@ -79,7 +79,7 @@ namespace Content.Server.Atmos.Piping.EntitySystems } component.LastProcess = TimeSpan.Zero; - RaiseLocalEvent(component.Owner.Uid, new AtmosDeviceDisabledEvent(), false); + RaiseLocalEvent(component.Owner, new AtmosDeviceDisabledEvent(), false); } public void RejoinAtmosphere(AtmosDeviceComponent component) @@ -104,7 +104,7 @@ namespace Content.Server.Atmos.Piping.EntitySystems if (!component.RequireAnchored) return; - if(component.Owner.Transform.Anchored) + if(EntityManager.GetComponent(component.Owner).Anchored) JoinAtmosphere(component); else LeaveAtmosphere(component); @@ -127,7 +127,7 @@ namespace Content.Server.Atmos.Piping.EntitySystems var time = _gameTiming.CurTime; foreach (var device in _joinedDevices) { - RaiseLocalEvent(device.Owner.Uid, _updateEvent, false); + RaiseLocalEvent(device.Owner, _updateEvent, false); device.LastProcess = time; } } diff --git a/Content.Server/Atmos/Piping/EntitySystems/AtmosUnsafeUnanchorSystem.cs b/Content.Server/Atmos/Piping/EntitySystems/AtmosUnsafeUnanchorSystem.cs index 68005e9ff4..7997984658 100644 --- a/Content.Server/Atmos/Piping/EntitySystems/AtmosUnsafeUnanchorSystem.cs +++ b/Content.Server/Atmos/Piping/EntitySystems/AtmosUnsafeUnanchorSystem.cs @@ -31,7 +31,7 @@ namespace Content.Server.Atmos.Piping.EntitySystems if (!component.Enabled || !EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodes)) return; - if (_atmosphereSystem.GetTileMixture(component.Owner.Transform.Coordinates) is not {} environment) + if (_atmosphereSystem.GetTileMixture(EntityManager.GetComponent(component.Owner).Coordinates) is not {} environment) return; foreach (var node in nodes.Nodes.Values) @@ -52,7 +52,7 @@ namespace Content.Server.Atmos.Piping.EntitySystems if (!component.Enabled || !EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodes)) return; - if (_atmosphereSystem.GetTileMixture(component.Owner.Transform.Coordinates, true) is not {} environment) + if (_atmosphereSystem.GetTileMixture(EntityManager.GetComponent(component.Owner).Coordinates, true) is not {} environment) environment = GasMixture.SpaceGas; var lost = 0f; diff --git a/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs b/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs index 0a4379d7f6..3bcb4e602b 100644 --- a/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs +++ b/Content.Server/Atmos/Piping/Other/EntitySystems/GasMinerSystem.cs @@ -37,10 +37,10 @@ namespace Content.Server.Atmos.Piping.Other.EntitySystems private bool CheckMinerOperation(GasMinerComponent miner, [NotNullWhen(true)] out GasMixture? environment) { - environment = _atmosphereSystem.GetTileMixture(miner.Owner.Transform.Coordinates, true); + environment = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(miner.Owner).Coordinates, true); // Space. - if (_atmosphereSystem.IsTileSpace(miner.Owner.Transform.Coordinates)) + if (_atmosphereSystem.IsTileSpace(EntityManager.GetComponent(miner.Owner).Coordinates)) { miner.Broken = true; return false; diff --git a/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs b/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs index cc4032059a..8b770c282f 100644 --- a/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs +++ b/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasFilterSystem.cs @@ -38,7 +38,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems private void OnFilterUpdated(EntityUid uid, GasFilterComponent filter, AtmosDeviceUpdateEvent args) { - var appearance = filter.Owner.GetComponentOrNull(); + var appearance = EntityManager.GetComponentOrNull(filter.Owner); if (!filter.Enabled || !EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodeContainer) @@ -81,10 +81,10 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems private void OnFilterInteractHand(EntityUid uid, GasFilterComponent component, InteractHandEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; - if (component.Owner.Transform.Anchored) + if (EntityManager.GetComponent(component.Owner).Anchored) { _userInterfaceSystem.TryOpen(uid, GasFilterUiKey.Key, actor.PlayerSession); DirtyUI(uid, component); @@ -104,7 +104,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems return; _userInterfaceSystem.TrySetUiState(uid, GasFilterUiKey.Key, - new GasFilterBoundUserInterfaceState(filter.Owner.Name, filter.TransferRate, filter.Enabled, filter.FilteredGas)); + new GasFilterBoundUserInterfaceState(EntityManager.GetComponent(filter.Owner).EntityName, filter.TransferRate, filter.Enabled, filter.FilteredGas)); } private void OnToggleStatusMessage(EntityUid uid, GasFilterComponent filter, GasFilterToggleStatusMessage args) diff --git a/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasMixerSystem.cs b/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasMixerSystem.cs index bcb82771b2..9a44d1f614 100644 --- a/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasMixerSystem.cs +++ b/Content.Server/Atmos/Piping/Trinary/EntitySystems/GasMixerSystem.cs @@ -106,10 +106,10 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems private void OnMixerInteractHand(EntityUid uid, GasMixerComponent component, InteractHandEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; - if (component.Owner.Transform.Anchored) + if (EntityManager.GetComponent(component.Owner).Anchored) { _userInterfaceSystem.TryOpen(uid, GasMixerUiKey.Key, actor.PlayerSession); DirtyUI(uid, component); @@ -128,7 +128,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems return; _userInterfaceSystem.TrySetUiState(uid, GasMixerUiKey.Key, - new GasMixerBoundUserInterfaceState(mixer.Owner.Name, mixer.TargetPressure, mixer.Enabled, mixer.InletOneConcentration)); + new GasMixerBoundUserInterfaceState(EntityManager.GetComponent(mixer.Owner).EntityName, mixer.TargetPressure, mixer.Enabled, mixer.InletOneConcentration)); } private void OnToggleStatusMessage(EntityUid uid, GasMixerComponent mixer, GasMixerToggleStatusMessage args) diff --git a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasCanisterSystem.cs b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasCanisterSystem.cs index 862fa61e96..6e7848a366 100644 --- a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasCanisterSystem.cs +++ b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasCanisterSystem.cs @@ -4,14 +4,11 @@ using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; using Content.Server.Atmos.Piping.Components; using Content.Server.Atmos.Piping.Unary.Components; -using Content.Server.Destructible; using Content.Server.Hands.Components; using Content.Server.NodeContainer; using Content.Server.NodeContainer.NodeGroups; using Content.Server.NodeContainer.Nodes; -using Content.Server.UserInterface; using Content.Shared.ActionBlocker; -using Content.Shared.Administration.Logs; using Content.Shared.Atmos; using Content.Shared.Atmos.Piping.Binary.Components; using Content.Shared.Database; @@ -19,7 +16,6 @@ using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using JetBrains.Annotations; using Robust.Server.GameObjects; -using Robust.Server.Player; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -85,7 +81,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems private bool CheckInteract(ICommonSession session) { - if (session.AttachedEntityUid is not {} uid + if (session.AttachedEntity is not {Valid: true} uid || !_actionBlockerSystem.CanInteract(uid) || !_actionBlockerSystem.CanUse(uid)) return false; @@ -110,14 +106,14 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems if (containerManager.TryGetContainer(canister.ContainerName, out var tankContainer) && tankContainer.ContainedEntities.Count > 0) { - var tank = tankContainer.ContainedEntities[0].Uid; + var tank = tankContainer.ContainedEntities[0]; var tankComponent = EntityManager.GetComponent(tank); tankLabel = EntityManager.GetComponent(tank).EntityName; tankPressure = tankComponent.Air.Pressure; } _userInterfaceSystem.TrySetUiState(uid, GasCanisterUiKey.Key, - new GasCanisterBoundUserInterfaceState(canister.Owner.Name, + new GasCanisterBoundUserInterfaceState(EntityManager.GetComponent(canister.Owner).EntityName, canister.Air.Pressure, portStatus, tankLabel, tankPressure, canister.ReleasePressure, canister.ReleaseValve, canister.MinReleasePressure, canister.MaxReleasePressure)); } @@ -205,12 +201,12 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems if (container.ContainedEntities.Count > 0) { - var gasTank = container.ContainedEntities[0].GetComponent(); + var gasTank = EntityManager.GetComponent(container.ContainedEntities[0]); _atmosphereSystem.ReleaseGasTo(canister.Air, gasTank.Air, canister.ReleasePressure); } else { - var environment = _atmosphereSystem.GetTileMixture(canister.Owner.Transform.Coordinates, true); + var environment = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(canister.Owner).Coordinates, true); _atmosphereSystem.ReleaseGasTo(canister.Air, environment, canister.ReleasePressure); } } @@ -243,7 +239,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems private void OnCanisterActivate(EntityUid uid, GasCanisterComponent component, ActivateInWorldEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; _userInterfaceSystem.GetUiOrNull(uid, GasCanisterUiKey.Key)?.Open(actor.PlayerSession); @@ -253,16 +249,15 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems private void OnCanisterInteractHand(EntityUid uid, GasCanisterComponent component, InteractHandEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; _userInterfaceSystem.GetUiOrNull(uid, GasCanisterUiKey.Key)?.Open(actor.PlayerSession); args.Handled = true; } - private void OnCanisterInteractUsing(EntityUid uid, GasCanisterComponent component, InteractUsingEvent args) + private void OnCanisterInteractUsing(EntityUid canister, GasCanisterComponent component, InteractUsingEvent args) { - var canister = EntityManager.GetEntity(uid); var container = canister.EnsureContainer(component.ContainerName); // Container full. @@ -270,11 +265,11 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems return; // Check the used item is valid... - if (!args.Used.TryGetComponent(out GasTankComponent? _)) + if (!EntityManager.TryGetComponent(args.Used, out GasTankComponent? _)) return; // Check the user has hands. - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!EntityManager.TryGetComponent(args.User, out HandsComponent? hands)) return; if (!args.User.InRangeUnobstructed(canister, SharedInteractionSystem.InteractionRange, popup: true)) @@ -283,7 +278,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems if (!hands.Drop(args.Used, container)) return; - _adminLogSystem.Add(LogType.CanisterTankInserted, LogImpact.Medium, $"Player {args.User:player} inserted tank {container.ContainedEntities[0]} into {uid}"); + _adminLogSystem.Add(LogType.CanisterTankInserted, LogImpact.Medium, $"Player {args.User:player} inserted tank {container.ContainedEntities[0]} into {canister}"); args.Handled = true; } diff --git a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs index 07b81c85c4..1074f84398 100644 --- a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs +++ b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasOutletInjectorSystem.cs @@ -35,7 +35,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems if (!nodeContainer.TryGetNode(injector.InletName, out PipeNode? inlet)) return; - var environment = _atmosphereSystem.GetTileMixture(injector.Owner.Transform.Coordinates, true); + var environment = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(injector.Owner).Coordinates, true); if (environment == null) return; diff --git a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasPassiveVentSystem.cs b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasPassiveVentSystem.cs index a6bb3533ef..f214db1e84 100644 --- a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasPassiveVentSystem.cs +++ b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasPassiveVentSystem.cs @@ -25,7 +25,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems private void OnPassiveVentUpdated(EntityUid uid, GasPassiveVentComponent vent, AtmosDeviceUpdateEvent args) { - var environment = _atmosphereSystem.GetTileMixture(vent.Owner.Transform.Coordinates, true); + var environment = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(vent.Owner).Coordinates, true); if (environment == null) return; diff --git a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasThermoMachineSystem.cs b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasThermoMachineSystem.cs index 2eef750ef9..a7f7c90142 100644 --- a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasThermoMachineSystem.cs +++ b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasThermoMachineSystem.cs @@ -25,7 +25,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems private void OnThermoMachineUpdated(EntityUid uid, GasThermoMachineComponent thermoMachine, AtmosDeviceUpdateEvent args) { - var appearance = thermoMachine.Owner.GetComponentOrNull(); + var appearance = EntityManager.GetComponentOrNull(thermoMachine.Owner); if (!thermoMachine.Enabled || !EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodeContainer) diff --git a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentPumpSystem.cs b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentPumpSystem.cs index 6cedebe94c..dd0b0ee910 100644 --- a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentPumpSystem.cs +++ b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentPumpSystem.cs @@ -27,7 +27,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems private void OnGasVentPumpUpdated(EntityUid uid, GasVentPumpComponent vent, AtmosDeviceUpdateEvent args) { - var appearance = vent.Owner.GetComponentOrNull(); + var appearance = EntityManager.GetComponentOrNull(vent.Owner); //Bingo waz here if (vent.Welded) { @@ -43,7 +43,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems return; } - var environment = _atmosphereSystem.GetTileMixture(vent.Owner.Transform.Coordinates, true); + var environment = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(vent.Owner).Coordinates, true); // We're in an air-blocked tile... Do nothing. if (environment == null) diff --git a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentScrubberSystem.cs b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentScrubberSystem.cs index c59f60aefa..8f08c4c1f8 100644 --- a/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentScrubberSystem.cs +++ b/Content.Server/Atmos/Piping/Unary/EntitySystems/GasVentScrubberSystem.cs @@ -28,7 +28,7 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems private void OnVentScrubberUpdated(EntityUid uid, GasVentScrubberComponent scrubber, AtmosDeviceUpdateEvent args) { - var appearance = scrubber.Owner.GetComponentOrNull(); + var appearance = EntityManager.GetComponentOrNull(scrubber.Owner); if (scrubber.Welded) { @@ -44,14 +44,14 @@ namespace Content.Server.Atmos.Piping.Unary.EntitySystems return; } - var environment = _atmosphereSystem.GetTileMixture(scrubber.Owner.Transform.Coordinates, true); + var environment = _atmosphereSystem.GetTileMixture(EntityManager.GetComponent(scrubber.Owner).Coordinates, true); Scrub(_atmosphereSystem, scrubber, appearance, environment, outlet); if (!scrubber.WideNet) return; // Scrub adjacent tiles too. - foreach (var adjacent in _atmosphereSystem.GetAdjacentTileMixtures(scrubber.Owner.Transform.Coordinates, false, true)) + foreach (var adjacent in _atmosphereSystem.GetAdjacentTileMixtures(EntityManager.GetComponent(scrubber.Owner).Coordinates, false, true)) { Scrub(_atmosphereSystem, scrubber, null, adjacent, outlet); } diff --git a/Content.Server/BarSign/Systems/BarSignSystem.cs b/Content.Server/BarSign/Systems/BarSignSystem.cs index b46ed9d23f..0e05852114 100644 --- a/Content.Server/BarSign/Systems/BarSignSystem.cs +++ b/Content.Server/BarSign/Systems/BarSignSystem.cs @@ -67,9 +67,9 @@ namespace Content.Server.BarSign.Systems return; } - if (component.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (EntityManager.TryGetComponent(component.Owner, out SpriteComponent? sprite)) { - if (!component.Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || !receiver.Powered) + if (!EntityManager.TryGetComponent(component.Owner, out ApcPowerReceiverComponent? receiver) || !receiver.Powered) { sprite.LayerSetState(0, "empty"); sprite.LayerSetShader(0, "shaded"); @@ -83,14 +83,15 @@ namespace Content.Server.BarSign.Systems if (!string.IsNullOrEmpty(prototype.Name)) { - component.Owner.Name = prototype.Name; + EntityManager.GetComponent(component.Owner).EntityName = prototype.Name; } else { - component.Owner.Name = Loc.GetString("barsign-component-name"); + string val = Loc.GetString("barsign-component-name"); + EntityManager.GetComponent(component.Owner).EntityName = val; } - component.Owner.Description = prototype.Description; + EntityManager.GetComponent(component.Owner).EntityDescription = prototype.Description; } } } diff --git a/Content.Server/Body/Commands/AddHandCommand.cs b/Content.Server/Body/Commands/AddHandCommand.cs index 2efa331866..d709c79246 100644 --- a/Content.Server/Body/Commands/AddHandCommand.cs +++ b/Content.Server/Body/Commands/AddHandCommand.cs @@ -1,7 +1,6 @@ using Content.Server.Administration; using Content.Shared.Administration; using Content.Shared.Body.Components; -using Content.Shared.Body.Part; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.GameObjects; @@ -45,14 +44,14 @@ namespace Content.Server.Body.Commands return; } - if (player.AttachedEntityUid == null) + if (player.AttachedEntity == null) { shell.WriteLine("You don't have an entity to add a hand to."); return; } - entity = player.AttachedEntityUid.Value; - hand = entityManager.SpawnEntity(DefaultHandPrototype, entityManager.GetComponent(entity).Coordinates).Uid; + entity = player.AttachedEntity.Value; + hand = entityManager.SpawnEntity(DefaultHandPrototype, entityManager.GetComponent(entity).Coordinates); break; } case 1: @@ -66,7 +65,7 @@ namespace Content.Server.Body.Commands } entity = uid; - hand = entityManager.SpawnEntity(DefaultHandPrototype, entityManager.GetComponent(entity).Coordinates).Uid; + hand = entityManager.SpawnEntity(DefaultHandPrototype, entityManager.GetComponent(entity).Coordinates); } else { @@ -76,14 +75,14 @@ namespace Content.Server.Body.Commands return; } - if (player.AttachedEntityUid == null) + if (player.AttachedEntity == null) { shell.WriteLine("You don't have an entity to add a hand to."); return; } - entity = player.AttachedEntityUid.Value; - hand = entityManager.SpawnEntity(args[0], entityManager.GetComponent(entity).Coordinates).Uid; + entity = player.AttachedEntity.Value; + hand = entityManager.SpawnEntity(args[0], entityManager.GetComponent(entity).Coordinates); } break; @@ -110,7 +109,7 @@ namespace Content.Server.Body.Commands return; } - hand = entityManager.SpawnEntity(args[1], entityManager.GetComponent(entity).Coordinates).Uid; + hand = entityManager.SpawnEntity(args[1], entityManager.GetComponent(entity).Coordinates); break; } diff --git a/Content.Server/Body/Commands/AttachBodyPartCommand.cs b/Content.Server/Body/Commands/AttachBodyPartCommand.cs index 4264b5cf8e..c46e366400 100644 --- a/Content.Server/Body/Commands/AttachBodyPartCommand.cs +++ b/Content.Server/Body/Commands/AttachBodyPartCommand.cs @@ -20,7 +20,7 @@ namespace Content.Server.Body.Commands var player = shell.Player as IPlayerSession; var entityManager = IoCManager.Resolve(); - IEntity entity; + EntityUid entity; EntityUid partUid; switch (args.Length) @@ -44,7 +44,7 @@ namespace Content.Server.Body.Commands return; } - entity = player.AttachedEntity; + entity = player.AttachedEntity.Value; break; case 2: @@ -60,44 +60,44 @@ namespace Content.Server.Body.Commands return; } - if (!entityManager.TryGetEntity(entityUid, out var tempEntity)) + if (!entityManager.EntityExists(entityUid)) { shell.WriteLine($"{entityUid} is not a valid entity."); return; } - entity = tempEntity; + entity = entityUid; break; default: shell.WriteLine(Help); return; } - if (!entity.TryGetComponent(out SharedBodyComponent? body)) + if (!entityManager.TryGetComponent(entity, out SharedBodyComponent? body)) { - shell.WriteLine($"Entity {entity.Name} with uid {entity.Uid} does not have a {nameof(SharedBodyComponent)} component."); + shell.WriteLine($"Entity {entityManager.GetComponent(entity).EntityName} with uid {entity} does not have a {nameof(SharedBodyComponent)} component."); return; } - if (!entityManager.TryGetEntity(partUid, out var partEntity)) + if (!entityManager.EntityExists(partUid)) { shell.WriteLine($"{partUid} is not a valid entity."); return; } - if (!partEntity.TryGetComponent(out SharedBodyPartComponent? part)) + if (!entityManager.TryGetComponent(partUid, out SharedBodyPartComponent? part)) { - shell.WriteLine($"Entity {partEntity.Name} with uid {args[0]} does not have a {nameof(SharedBodyPartComponent)} component."); + shell.WriteLine($"Entity {entityManager.GetComponent(partUid).EntityName} with uid {args[0]} does not have a {nameof(SharedBodyPartComponent)} component."); return; } if (body.HasPart(part)) { - shell.WriteLine($"Body part {partEntity.Name} with uid {partEntity.Uid} is already attached to entity {entity.Name} with uid {entity.Uid}"); + shell.WriteLine($"Body part {entityManager.GetComponent(partUid).EntityName} with uid {partUid} is already attached to entity {entityManager.GetComponent(entity).EntityName} with uid {entity}"); return; } - body.SetPart($"AttachBodyPartVerb-{partEntity.Uid}", part); + body.SetPart($"AttachBodyPartVerb-{partUid}", part); } } } diff --git a/Content.Server/Body/Commands/DestroyMechanismCommand.cs b/Content.Server/Body/Commands/DestroyMechanismCommand.cs index 657e5f3459..a9a3add4a5 100644 --- a/Content.Server/Body/Commands/DestroyMechanismCommand.cs +++ b/Content.Server/Body/Commands/DestroyMechanismCommand.cs @@ -3,6 +3,7 @@ using Content.Shared.Administration; using Content.Shared.Body.Components; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Random; @@ -30,13 +31,13 @@ namespace Content.Server.Body.Commands return; } - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {} attached) { shell.WriteLine("You have no entity."); return; } - if (!player.AttachedEntity.TryGetComponent(out SharedBodyComponent? body)) + if (!IoCManager.Resolve().TryGetComponent(attached, out SharedBodyComponent? body)) { var random = IoCManager.Resolve(); var text = $"You have no body{(random.Prob(0.2f) ? " and you must scream." : ".")}"; diff --git a/Content.Server/Body/Commands/RemoveHandCommand.cs b/Content.Server/Body/Commands/RemoveHandCommand.cs index 184cf7141f..e474ebfb1a 100644 --- a/Content.Server/Body/Commands/RemoveHandCommand.cs +++ b/Content.Server/Body/Commands/RemoveHandCommand.cs @@ -5,6 +5,7 @@ using Content.Shared.Body.Components; using Content.Shared.Body.Part; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Random; @@ -32,7 +33,7 @@ namespace Content.Server.Body.Commands return; } - if (!player.AttachedEntity.TryGetComponent(out SharedBodyComponent? body)) + if (!IoCManager.Resolve().TryGetComponent(player.AttachedEntity, out SharedBodyComponent? body)) { var random = IoCManager.Resolve(); var text = $"You have no body{(random.Prob(0.2f) ? " and you must scream." : ".")}"; diff --git a/Content.Server/Body/Components/BodyComponent.cs b/Content.Server/Body/Components/BodyComponent.cs index b325eea9f1..9fe11422a0 100644 --- a/Content.Server/Body/Components/BodyComponent.cs +++ b/Content.Server/Body/Components/BodyComponent.cs @@ -1,6 +1,5 @@ using Content.Server.Ghost; using Content.Shared.Audio; -using Content.Shared.Body; using Content.Shared.Body.Components; using Content.Shared.Body.Part; using Content.Shared.Random.Helpers; @@ -8,6 +7,7 @@ using Content.Shared.Sound; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -19,6 +19,8 @@ namespace Content.Server.Body.Components [ComponentReference(typeof(IGhostOnMove))] public class BodyComponent : SharedBodyComponent, IGhostOnMove { + [Dependency] private readonly IEntityManager _entMan = default!; + private Container _partContainer = default!; [DataField("gibSound")] private SoundSpecifier _gibSound = new SoundCollectionSpecifier("gib"); @@ -57,9 +59,9 @@ namespace Content.Server.Body.Components { // Using MapPosition instead of Coordinates here prevents // a crash within the character preview menu in the lobby - var entity = Owner.EntityManager.SpawnEntity(preset.PartIDs[slot.Id], Owner.Transform.MapPosition); + var entity = _entMan.SpawnEntity(preset.PartIDs[slot.Id], _entMan.GetComponent(Owner).MapPosition); - if (!entity.TryGetComponent(out SharedBodyPartComponent? part)) + if (!_entMan.TryGetComponent(entity, out SharedBodyPartComponent? part)) { Logger.Error($"Entity {slot.Id} does not have a {nameof(SharedBodyPartComponent)} component."); continue; @@ -87,22 +89,22 @@ namespace Content.Server.Body.Components { base.Gib(gibParts); - SoundSystem.Play(Filter.Pvs(Owner), _gibSound.GetSound(), Owner.Transform.Coordinates, AudioHelpers.WithVariation(0.025f)); + SoundSystem.Play(Filter.Pvs(Owner), _gibSound.GetSound(), _entMan.GetComponent(Owner).Coordinates, AudioHelpers.WithVariation(0.025f)); - if (Owner.TryGetComponent(out ContainerManagerComponent? container)) + if (_entMan.TryGetComponent(Owner, out ContainerManagerComponent? container)) { foreach (var cont in container.GetAllContainers()) { foreach (var ent in cont.ContainedEntities) { cont.ForceRemove(ent); - ent.Transform.Coordinates = Owner.Transform.Coordinates; + _entMan.GetComponent(ent).Coordinates = _entMan.GetComponent(Owner).Coordinates; ent.RandomOffset(0.25f); } } } - Owner.QueueDelete(); + _entMan.QueueDeleteEntity(Owner); } } } diff --git a/Content.Server/Body/Components/BodyPartComponent.cs b/Content.Server/Body/Components/BodyPartComponent.cs index e9cceeb7c6..6cb19ec14f 100644 --- a/Content.Server/Body/Components/BodyPartComponent.cs +++ b/Content.Server/Body/Components/BodyPartComponent.cs @@ -2,13 +2,10 @@ using System.Collections.Generic; using System.Threading.Tasks; using Content.Server.UserInterface; using Content.Shared.Body.Components; -using Content.Shared.Body.Part; using Content.Shared.Body.Surgery; using Content.Shared.Interaction; using Content.Shared.Popups; using Content.Shared.Random.Helpers; -using Content.Shared.Verbs; -using Robust.Server.Console; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Containers; @@ -24,10 +21,12 @@ namespace Content.Server.Body.Components [ComponentReference(typeof(SharedBodyPartComponent))] public class BodyPartComponent : SharedBodyPartComponent, IAfterInteract { + [Dependency] private readonly IEntityManager _entMan = default!; + private readonly Dictionary _optionsCache = new(); private SharedBodyComponent? _owningBodyCache; private int _idHash; - private IEntity? _surgeonCache; + private EntityUid? _surgeonCache; private Container _mechanismContainer = default!; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(SurgeryUIKey.Key); @@ -64,9 +63,9 @@ namespace Content.Server.Body.Components // identical on it foreach (var mechanismId in MechanismIds) { - var entity = Owner.EntityManager.SpawnEntity(mechanismId, Owner.Transform.MapPosition); + var entity = _entMan.SpawnEntity(mechanismId, _entMan.GetComponent(Owner).MapPosition); - if (!entity.TryGetComponent(out SharedMechanismComponent? mechanism)) + if (!_entMan.TryGetComponent(entity, out SharedMechanismComponent? mechanism)) { Logger.Error($"Entity {mechanismId} does not have a {nameof(SharedMechanismComponent)} component."); continue; @@ -104,7 +103,7 @@ namespace Content.Server.Body.Components _surgeonCache = null; _owningBodyCache = null; - if (eventArgs.Target.TryGetComponent(out SharedBodyComponent? body)) + if (_entMan.TryGetComponent(eventArgs.Target.Value, out SharedBodyComponent? body)) { SendSlots(eventArgs, body); } @@ -141,8 +140,8 @@ namespace Content.Server.Body.Components if (_optionsCache.Count > 0) { - OpenSurgeryUI(eventArgs.User.GetComponent().PlayerSession); - BodyPartSlotRequest(eventArgs.User.GetComponent().PlayerSession, + OpenSurgeryUI(_entMan.GetComponent(eventArgs.User).PlayerSession); + BodyPartSlotRequest(_entMan.GetComponent(eventArgs.User).PlayerSession, toSend); _surgeonCache = eventArgs.User; _owningBodyCache = body; @@ -161,7 +160,7 @@ namespace Content.Server.Body.Components private void ReceiveBodyPartSlot(int key) { if (_surgeonCache == null || - !_surgeonCache.TryGetComponent(out ActorComponent? actor)) + !_entMan.TryGetComponent(_surgeonCache.Value, out ActorComponent? actor)) { return; } @@ -176,7 +175,7 @@ namespace Content.Server.Body.Components // TODO: sanity checks to see whether user is in range, user is still able-bodied, target is still the same, etc etc if (!_optionsCache.TryGetValue(key, out var targetObject)) { - _owningBodyCache.Owner.PopupMessage(_surgeonCache, + _owningBodyCache.Owner.PopupMessage(_surgeonCache.Value, Loc.GetString("bodypart-component-no-way-to-attach-message", ("partName", Owner))); } @@ -185,7 +184,7 @@ namespace Content.Server.Body.Components ? Loc.GetString("bodypart-component-attach-success-message",("partName", Owner)) : Loc.GetString("bodypart-component-attach-fail-message",("partName", Owner)); - _owningBodyCache.Owner.PopupMessage(_surgeonCache, message); + _owningBodyCache.Owner.PopupMessage(_surgeonCache.Value, message); } private void OpenSurgeryUI(IPlayerSession session) diff --git a/Content.Server/Body/Components/BodyScannerComponent.cs b/Content.Server/Body/Components/BodyScannerComponent.cs index bd17d36887..a9045bcf11 100644 --- a/Content.Server/Body/Components/BodyScannerComponent.cs +++ b/Content.Server/Body/Components/BodyScannerComponent.cs @@ -3,6 +3,7 @@ using Content.Shared.Body.Components; using Content.Shared.Interaction; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Server.Body.Components @@ -12,23 +13,25 @@ namespace Content.Server.Body.Components [ComponentReference(typeof(SharedBodyScannerComponent))] public class BodyScannerComponent : SharedBodyScannerComponent, IActivate { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(BodyScannerUiKey.Key); void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { return; } var session = actor.PlayerSession; - if (session.AttachedEntity == null) + if (session.AttachedEntity == default) { return; } - if (session.AttachedEntity.TryGetComponent(out SharedBodyComponent? body)) + if (_entMan.TryGetComponent(session.AttachedEntity, out SharedBodyComponent? body)) { var state = InterfaceState(body); UserInterface?.SetState(state); @@ -56,7 +59,7 @@ namespace Content.Server.Body.Components /// private BodyScannerUIState InterfaceState(SharedBodyComponent body) { - return new(body.Owner.Uid); + return new(body.Owner); } } } diff --git a/Content.Server/Body/Components/InternalsComponent.cs b/Content.Server/Body/Components/InternalsComponent.cs index 35a027a175..f2214e9fb9 100644 --- a/Content.Server/Body/Components/InternalsComponent.cs +++ b/Content.Server/Body/Components/InternalsComponent.cs @@ -1,5 +1,6 @@ using Content.Server.Atmos.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Server.Body.Components @@ -7,25 +8,27 @@ namespace Content.Server.Body.Components [RegisterComponent] public class InternalsComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Internals"; - [ViewVariables] public IEntity? GasTankEntity { get; set; } - [ViewVariables] public IEntity? BreathToolEntity { get; set; } + [ViewVariables] public EntityUid GasTankEntity { get; set; } + [ViewVariables] public EntityUid BreathToolEntity { get; set; } public void DisconnectBreathTool() { var old = BreathToolEntity; - BreathToolEntity = null; + BreathToolEntity = default; - if (old != null && old.TryGetComponent(out BreathToolComponent? breathTool) ) + if (old != default && _entMan.TryGetComponent(old, out BreathToolComponent? breathTool) ) { breathTool.DisconnectInternals(); DisconnectTank(); } } - public void ConnectBreathTool(IEntity toolEntity) + public void ConnectBreathTool(EntityUid toolEntity) { - if (BreathToolEntity != null && BreathToolEntity.TryGetComponent(out BreathToolComponent? tool)) + if (BreathToolEntity != default && _entMan.TryGetComponent(BreathToolEntity, out BreathToolComponent? tool)) { tool.DisconnectInternals(); } @@ -35,20 +38,20 @@ namespace Content.Server.Body.Components public void DisconnectTank() { - if (GasTankEntity != null && GasTankEntity.TryGetComponent(out GasTankComponent? tank)) + if (GasTankEntity != default && _entMan.TryGetComponent(GasTankEntity, out GasTankComponent? tank)) { tank.DisconnectFromInternals(Owner); } - GasTankEntity = null; + GasTankEntity = default; } - public bool TryConnectTank(IEntity tankEntity) + public bool TryConnectTank(EntityUid tankEntity) { - if (BreathToolEntity == null) + if (BreathToolEntity == default) return false; - if (GasTankEntity != null && GasTankEntity.TryGetComponent(out GasTankComponent? tank)) + if (GasTankEntity != default && _entMan.TryGetComponent(GasTankEntity, out GasTankComponent? tank)) { tank.DisconnectFromInternals(Owner); } @@ -59,12 +62,12 @@ namespace Content.Server.Body.Components public bool AreInternalsWorking() { - return BreathToolEntity != null && - GasTankEntity != null && - BreathToolEntity.TryGetComponent(out BreathToolComponent? breathTool) && + return BreathToolEntity != default && + GasTankEntity != default && + _entMan.TryGetComponent(BreathToolEntity, out BreathToolComponent? breathTool) && breathTool.IsFunctional && - GasTankEntity.TryGetComponent(out GasTankComponent? gasTank) && - gasTank.Air != null; + _entMan.TryGetComponent(GasTankEntity, out GasTankComponent? gasTank) && + gasTank.Air != default; } } diff --git a/Content.Server/Body/Components/MechanismComponent.cs b/Content.Server/Body/Components/MechanismComponent.cs index d95593fe50..ec5f538c4c 100644 --- a/Content.Server/Body/Components/MechanismComponent.cs +++ b/Content.Server/Body/Components/MechanismComponent.cs @@ -2,13 +2,13 @@ using System.Collections.Generic; using System.Threading.Tasks; using Content.Server.UserInterface; using Content.Shared.Body.Components; -using Content.Shared.Body.Part; using Content.Shared.Body.Surgery; using Content.Shared.Interaction; using Content.Shared.Popups; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -19,6 +19,8 @@ namespace Content.Server.Body.Components [ComponentReference(typeof(SharedMechanismComponent))] public class MechanismComponent : SharedMechanismComponent, IAfterInteract { + [Dependency] private readonly IEntityManager _entities = default!; + [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(SurgeryUIKey.Key); protected override void Initialize() @@ -43,17 +45,17 @@ namespace Content.Server.Body.Components PerformerCache = null; BodyCache = null; - if (eventArgs.Target.TryGetComponent(out SharedBodyComponent? body)) + if (_entities.TryGetComponent(eventArgs.Target.Value, out SharedBodyComponent? body)) { SendBodyPartListToUser(eventArgs, body); } - else if (eventArgs.Target.TryGetComponent(out var part)) + else if (_entities.TryGetComponent(eventArgs.Target.Value, out var part)) { DebugTools.AssertNotNull(part); if (!part.TryAddMechanism(this)) { - eventArgs.Target.PopupMessage(eventArgs.User, Loc.GetString("mechanism-component-cannot-fit-message")); + eventArgs.Target.Value.PopupMessage(eventArgs.User, Loc.GetString("mechanism-component-cannot-fit-message")); } } @@ -76,7 +78,7 @@ namespace Content.Server.Body.Components } if (OptionsCache.Count > 0 && - eventArgs.User.TryGetComponent(out ActorComponent? actor)) + _entities.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { OpenSurgeryUI(actor.PlayerSession); UpdateSurgeryUIBodyPartRequest(actor.PlayerSession, toSend); @@ -86,7 +88,7 @@ namespace Content.Server.Body.Components else // If surgery cannot be performed, show message saying so. { eventArgs.Target?.PopupMessage(eventArgs.User, - Loc.GetString("mechanism-component-no-way-to-install-message", ("partName", Owner.Name))); + Loc.GetString("mechanism-component-no-way-to-install-message", ("partName", Name: _entities.GetComponent(Owner).EntityName))); } } @@ -96,7 +98,7 @@ namespace Content.Server.Body.Components private void HandleReceiveBodyPart(int key) { if (PerformerCache == null || - !PerformerCache.TryGetComponent(out ActorComponent? actor)) + !_entities.TryGetComponent(PerformerCache.Value, out ActorComponent? actor)) { return; } @@ -111,8 +113,8 @@ namespace Content.Server.Body.Components // TODO: sanity checks to see whether user is in range, user is still able-bodied, target is still the same, etc etc if (!OptionsCache.TryGetValue(key, out var targetObject)) { - BodyCache.Owner.PopupMessage(PerformerCache, - Loc.GetString("mechanism-component-no-useful-way-to-use-message",("partName", Owner.Name))); + BodyCache.Owner.PopupMessage(PerformerCache.Value, + Loc.GetString("mechanism-component-no-useful-way-to-use-message",("partName", Name: _entities.GetComponent(Owner).EntityName))); return; } @@ -121,7 +123,7 @@ namespace Content.Server.Body.Components ? Loc.GetString("mechanism-component-jam-inside-message",("ownerName", Owner),("them", PerformerCache)) : Loc.GetString("mechanism-component-cannot-fit-message"); - BodyCache.Owner.PopupMessage(PerformerCache, message); + BodyCache.Owner.PopupMessage(PerformerCache.Value, message); // TODO: {1:theName} } diff --git a/Content.Server/Body/Surgery/BiologicalSurgeryDataComponent.cs b/Content.Server/Body/Surgery/BiologicalSurgeryDataComponent.cs index bece574f9f..1feb8d04be 100644 --- a/Content.Server/Body/Surgery/BiologicalSurgeryDataComponent.cs +++ b/Content.Server/Body/Surgery/BiologicalSurgeryDataComponent.cs @@ -8,6 +8,7 @@ using Content.Shared.Body.Part; using Content.Shared.Body.Surgery; using Content.Shared.Popups; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using static Content.Shared.Body.Surgery.ISurgeryData; @@ -20,6 +21,8 @@ namespace Content.Server.Body.Surgery [ComponentReference(typeof(ISurgeryData))] public class BiologicalSurgeryDataComponent : Component, ISurgeryData { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "BiologicalSurgeryData"; private readonly HashSet _disconnectedOrgans = new(); @@ -30,7 +33,7 @@ namespace Content.Server.Body.Surgery private bool VesselsClamped { get; set; } - public SharedBodyPartComponent? Parent => Owner.GetComponentOrNull(); + public SharedBodyPartComponent? Parent => _entMan.GetComponentOrNull(Owner); public BodyPartType? ParentType => Parent?.PartType; @@ -50,9 +53,9 @@ namespace Content.Server.Body.Surgery } } - private async Task SurgeryDoAfter(IEntity performer) + private async Task SurgeryDoAfter(EntityUid performer) { - if (!performer.HasComponent()) + if (!_entMan.HasComponent(performer)) { return true; } @@ -202,7 +205,7 @@ namespace Content.Server.Body.Surgery return GetSurgeryStep(toolType) != null; } - public bool PerformSurgery(SurgeryType surgeryType, IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + public bool PerformSurgery(SurgeryType surgeryType, IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { var step = GetSurgeryStep(surgeryType); @@ -215,7 +218,7 @@ namespace Content.Server.Body.Surgery return true; } - private async void OpenSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + private async void OpenSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { if (Parent == null) { @@ -230,7 +233,7 @@ namespace Content.Server.Body.Surgery } } - private async void ClampVesselsSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + private async void ClampVesselsSurgery(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { if (Parent == null) return; @@ -242,7 +245,7 @@ namespace Content.Server.Body.Surgery } } - private async void RetractSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + private async void RetractSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { if (Parent == null) return; @@ -254,7 +257,7 @@ namespace Content.Server.Body.Surgery } } - private async void CauterizeIncisionSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + private async void CauterizeIncisionSurgery(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { if (Parent == null) return; @@ -268,7 +271,7 @@ namespace Content.Server.Body.Surgery } } - private void LoosenOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + private void LoosenOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { if (Parent == null) return; if (Parent.Mechanisms.Count <= 0) return; @@ -289,7 +292,7 @@ namespace Content.Server.Body.Surgery } private async void LoosenOrganSurgeryCallback(SharedMechanismComponent? target, IBodyPartContainer container, ISurgeon surgeon, - IEntity performer) + EntityUid performer) { if (Parent == null || target == null || !Parent.Mechanisms.Contains(target)) { @@ -298,7 +301,7 @@ namespace Content.Server.Body.Surgery performer.PopupMessage(Loc.GetString("biological-surgery-data-component-loosen-organ-message")); - if (!performer.HasComponent()) + if (!_entMan.HasComponent(performer)) { AddDisconnectedOrgan(target); return; @@ -310,7 +313,7 @@ namespace Content.Server.Body.Surgery } } - private void RemoveOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + private void RemoveOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { if (Parent == null) return; @@ -330,7 +333,7 @@ namespace Content.Server.Body.Surgery } private async void RemoveOrganSurgeryCallback(SharedMechanismComponent? target, IBodyPartContainer container, ISurgeon surgeon, - IEntity performer) + EntityUid performer) { if (Parent == null || target == null || !Parent.Mechanisms.Contains(target)) { @@ -339,21 +342,21 @@ namespace Content.Server.Body.Surgery performer.PopupMessage(Loc.GetString("biological-surgery-data-component-remove-organ-message")); - if (!performer.HasComponent()) + if (!_entMan.HasComponent(performer)) { - Parent.RemoveMechanism(target, performer.Transform.Coordinates); + Parent.RemoveMechanism(target, _entMan.GetComponent(performer).Coordinates); RemoveDisconnectedOrgan(target); return; } if (await SurgeryDoAfter(performer)) { - Parent.RemoveMechanism(target, performer.Transform.Coordinates); + Parent.RemoveMechanism(target, _entMan.GetComponent(performer).Coordinates); RemoveDisconnectedOrgan(target); } } - private async void RemoveBodyPartSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer) + private async void RemoveBodyPartSurgery(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer) { if (Parent == null) return; if (container is not SharedBodyComponent body) return; diff --git a/Content.Server/Body/Surgery/Components/SurgeryToolComponent.cs b/Content.Server/Body/Surgery/Components/SurgeryToolComponent.cs index 3af071f842..70ccfd94d5 100644 --- a/Content.Server/Body/Surgery/Components/SurgeryToolComponent.cs +++ b/Content.Server/Body/Surgery/Components/SurgeryToolComponent.cs @@ -5,13 +5,13 @@ using Content.Server.Body.Components; using Content.Server.Body.Surgery.Messages; using Content.Server.UserInterface; using Content.Shared.Body.Components; -using Content.Shared.Body.Part; using Content.Shared.Body.Surgery; using Content.Shared.Interaction; using Content.Shared.Popups; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; @@ -26,6 +26,8 @@ namespace Content.Server.Body.Surgery.Components [RegisterComponent] public class SurgeryToolComponent : Component, ISurgeon, IAfterInteract { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "SurgeryTool"; private readonly Dictionary _optionsCache = new(); @@ -44,7 +46,7 @@ namespace Content.Server.Body.Surgery.Components public SharedBodyComponent? BodyCache { get; private set; } - public IEntity? PerformerCache { get; private set; } + public EntityUid? PerformerCache { get; private set; } async Task IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs) { @@ -53,7 +55,7 @@ namespace Content.Server.Body.Surgery.Components return false; } - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { return false; } @@ -61,7 +63,7 @@ namespace Content.Server.Body.Surgery.Components CloseAllSurgeryUIs(); // Attempt surgery on a body by sending a list of operable parts for the client to choose from - if (eventArgs.Target.TryGetComponent(out SharedBodyComponent? body)) + if (_entities.TryGetComponent(eventArgs.Target.Value, out SharedBodyComponent? body)) { // Create dictionary to send to client (text to be shown : data sent back if selected) var toSend = new Dictionary(); @@ -88,7 +90,7 @@ namespace Content.Server.Body.Surgery.Components NotUsefulPopup(); } } - else if (eventArgs.Target.TryGetComponent(out var part)) + else if (_entities.TryGetComponent(eventArgs.Target.Value, out var part)) { // Attempt surgery on a DroppedBodyPart - there's only one possible target so no need for selection UI PerformerCache = eventArgs.User; @@ -108,7 +110,7 @@ namespace Content.Server.Body.Surgery.Components } // Log error if the surgery fails somehow. - Logger.Debug($"Error when trying to perform surgery on ${nameof(SharedBodyPartComponent)} {eventArgs.User.Name}"); + Logger.Debug($"Error when trying to perform surgery on ${nameof(SharedBodyPartComponent)} {_entities.GetComponent(eventArgs.User).EntityName}"); throw new InvalidOperationException(); } @@ -128,8 +130,8 @@ namespace Content.Server.Body.Surgery.Components if (_optionsCache.Count > 0 && PerformerCache != null) { - OpenSurgeryUI(PerformerCache.GetComponent().PlayerSession); - UpdateSurgeryUIMechanismRequest(PerformerCache.GetComponent().PlayerSession, + OpenSurgeryUI(_entities.GetComponent(PerformerCache.Value).PlayerSession); + UpdateSurgeryUIMechanismRequest(_entities.GetComponent(PerformerCache.Value).PlayerSession, toSend); _callbackCache = callback; } @@ -159,7 +161,7 @@ namespace Content.Server.Body.Surgery.Components #pragma warning disable 618 SendMessage(message); #pragma warning restore 618 - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, message); + _entities.EventBus.RaiseEvent(EventSource.Local, message); } private void UpdateSurgeryUIBodyPartRequest(IPlayerSession session, Dictionary options) @@ -213,7 +215,7 @@ namespace Content.Server.Body.Surgery.Components private void HandleReceiveBodyPart(int key) { if (PerformerCache == null || - !PerformerCache.TryGetComponent(out ActorComponent? actor)) + !_entities.TryGetComponent(PerformerCache.Value, out ActorComponent? actor)) { return; } @@ -227,10 +229,10 @@ namespace Content.Server.Body.Surgery.Components return; } - var target = (SharedBodyPartComponent) targetObject!; + var target = (SharedBodyPartComponent) targetObject; // TODO BODY Reconsider - if (!target.AttemptSurgery(_surgeryType, BodyCache, this, PerformerCache)) + if (!target.AttemptSurgery(_surgeryType, BodyCache, this, PerformerCache.Value)) { NotUsefulAnymorePopup(); } @@ -247,21 +249,21 @@ namespace Content.Server.Body.Surgery.Components !_optionsCache.TryGetValue(key, out var targetObject) || targetObject is not MechanismComponent target || PerformerCache == null || - !PerformerCache.TryGetComponent(out ActorComponent? actor)) + !_entities.TryGetComponent(PerformerCache.Value, out ActorComponent? actor)) { NotUsefulAnymorePopup(); return; } CloseSurgeryUI(actor.PlayerSession); - _callbackCache?.Invoke(target, BodyCache, this, PerformerCache); + _callbackCache?.Invoke(target, BodyCache, this, PerformerCache.Value); } private void NotUsefulPopup() { if (PerformerCache == null) return; - BodyCache?.Owner.PopupMessage(PerformerCache, + BodyCache?.Owner.PopupMessage(PerformerCache.Value, Loc.GetString("surgery-tool-component-not-useful-message", ("bodyPart", Owner))); } @@ -269,7 +271,7 @@ namespace Content.Server.Body.Surgery.Components { if (PerformerCache == null) return; - BodyCache?.Owner.PopupMessage(PerformerCache, + BodyCache?.Owner.PopupMessage(PerformerCache.Value, Loc.GetString("surgery-tool-component-not-useful-anymore-message", ("bodyPart", Owner))); } } diff --git a/Content.Server/Body/Surgery/Components/SurgeryToolSystem.cs b/Content.Server/Body/Surgery/Components/SurgeryToolSystem.cs index 63e6ce0242..279e71b7e7 100644 --- a/Content.Server/Body/Surgery/Components/SurgeryToolSystem.cs +++ b/Content.Server/Body/Surgery/Components/SurgeryToolSystem.cs @@ -2,7 +2,6 @@ using Content.Server.Body.Surgery.Messages; using Content.Shared.ActionBlocker; using Content.Shared.GameTicking; -using Content.Shared.Interaction.Events; using Content.Shared.Interaction.Helpers; using JetBrains.Annotations; using Robust.Shared.GameObjects; @@ -57,8 +56,8 @@ namespace Content.Server.Body.Surgery.Components continue; } - if (!_actionBlockerSystem.CanInteract(tool.PerformerCache.Uid) || - !tool.PerformerCache.InRangeUnobstructed(tool.BodyCache)) + if (!_actionBlockerSystem.CanInteract(tool.PerformerCache.Value) || + !tool.PerformerCache.Value.InRangeUnobstructed(tool.BodyCache)) { tool.CloseAllSurgeryUIs(); } diff --git a/Content.Server/Body/Systems/BodySystem.cs b/Content.Server/Body/Systems/BodySystem.cs index 11b79789dc..b776965d24 100644 --- a/Content.Server/Body/Systems/BodySystem.cs +++ b/Content.Server/Body/Systems/BodySystem.cs @@ -56,7 +56,7 @@ namespace Content.Server.Body.Systems foreach (var (part, _) in body.Parts) foreach (var mechanism in part.Mechanisms) { - if (EntityManager.TryGetComponent(mechanism.OwnerUid, out var comp)) + if (EntityManager.TryGetComponent((mechanism).Owner, out var comp)) yield return (comp, mechanism); } } diff --git a/Content.Server/Body/Systems/BrainSystem.cs b/Content.Server/Body/Systems/BrainSystem.cs index 6d842eaf3e..0cb64b4756 100644 --- a/Content.Server/Body/Systems/BrainSystem.cs +++ b/Content.Server/Body/Systems/BrainSystem.cs @@ -14,12 +14,12 @@ namespace Content.Server.Body.Systems { base.Initialize(); - SubscribeLocalEvent((uid, component, args) => HandleMind(args.Body.OwnerUid, uid)); - SubscribeLocalEvent((uid, component, args) => HandleMind(args.Part.OwnerUid, uid)); - SubscribeLocalEvent((uid, component, args) => HandleMind(args.Body.OwnerUid, uid)); + SubscribeLocalEvent((uid, component, args) => HandleMind((args.Body).Owner, uid)); + SubscribeLocalEvent((uid, component, args) => HandleMind((args.Part).Owner, uid)); + SubscribeLocalEvent((uid, component, args) => HandleMind((args.Body).Owner, uid)); SubscribeLocalEvent(OnRemovedFromBody); - SubscribeLocalEvent((uid, component, args) => HandleMind(uid, args.Old.OwnerUid)); - SubscribeLocalEvent((uid, component, args) => HandleMind(args.OldBody.OwnerUid, uid)); + SubscribeLocalEvent((uid, component, args) => HandleMind(uid, (args.Old).Owner)); + SubscribeLocalEvent((uid, component, args) => HandleMind((args.OldBody).Owner, uid)); } private void OnRemovedFromBody(EntityUid uid, BrainComponent component, RemovedFromBodyEvent args) @@ -28,7 +28,7 @@ namespace Content.Server.Body.Systems if (!EntityManager.TryGetComponent(uid, out MechanismComponent mech)) return; - HandleMind(mech.Part!.OwnerUid, args.Old.OwnerUid); + HandleMind((mech.Part!).Owner, (args.Old).Owner); } private void HandleMind(EntityUid newEntity, EntityUid oldEntity) diff --git a/Content.Server/Body/Systems/LungSystem.cs b/Content.Server/Body/Systems/LungSystem.cs index 5893c10c15..89db6d04c8 100644 --- a/Content.Server/Body/Systems/LungSystem.cs +++ b/Content.Server/Body/Systems/LungSystem.cs @@ -57,7 +57,7 @@ public class LungSystem : EntitySystem if (!Resolve(uid, ref lung, ref mech)) return; - if (mech.Body != null && EntityManager.TryGetComponent(mech.Body.OwnerUid, out MobStateComponent? mobState) && mobState.IsCritical()) + if (mech.Body != null && EntityManager.TryGetComponent((mech.Body).Owner, out MobStateComponent? mobState) && mobState.IsCritical()) { return; } @@ -111,12 +111,12 @@ public class LungSystem : EntitySystem // TODO Jesus Christ make this event based. if (mech.Body != null && - EntityManager.TryGetComponent(mech.Body.OwnerUid, out InternalsComponent? internals) && + EntityManager.TryGetComponent((mech.Body).Owner, out InternalsComponent? internals) && internals.BreathToolEntity != null && internals.GasTankEntity != null && - internals.BreathToolEntity.TryGetComponent(out BreathToolComponent? breathTool) && + EntityManager.TryGetComponent(internals.BreathToolEntity, out BreathToolComponent? breathTool) && breathTool.IsFunctional && - internals.GasTankEntity.TryGetComponent(out GasTankComponent? gasTank)) + EntityManager.TryGetComponent(internals.GasTankEntity, out GasTankComponent? gasTank)) { TakeGasFrom(uid, frameTime, gasTank.RemoveAirVolume(Atmospherics.BreathVolume), lung); return; @@ -148,7 +148,7 @@ public class LungSystem : EntitySystem if (mech.Body == null) return; - if (!EntityManager.TryGetComponent(mech.Body.OwnerUid, out BloodstreamComponent? bloodstream)) + if (!EntityManager.TryGetComponent((mech.Body).Owner, out BloodstreamComponent? bloodstream)) return; var to = bloodstream.Air; @@ -189,10 +189,10 @@ public class LungSystem : EntitySystem if (mech.Body == null) return; - if (!EntityManager.TryGetComponent(mech.Body.OwnerUid, out BloodstreamComponent? bloodstream)) + if (!EntityManager.TryGetComponent((mech.Body).Owner, out BloodstreamComponent? bloodstream)) return; - _bloodstreamSystem.PumpToxins(mech.Body.OwnerUid, lung.Air, bloodstream); + _bloodstreamSystem.PumpToxins((mech.Body).Owner, lung.Air, bloodstream); var lungRemoved = lung.Air.RemoveRatio(0.5f); _atmosSys.Merge(to, lungRemoved); diff --git a/Content.Server/Body/Systems/MetabolizerSystem.cs b/Content.Server/Body/Systems/MetabolizerSystem.cs index a619b45f86..792b71ecea 100644 --- a/Content.Server/Body/Systems/MetabolizerSystem.cs +++ b/Content.Server/Body/Systems/MetabolizerSystem.cs @@ -43,7 +43,7 @@ namespace Content.Server.Body.Systems { if (mech.Body != null) { - _solutionContainerSystem.EnsureSolution(mech.Body.OwnerUid, component.SolutionName); + _solutionContainerSystem.EnsureSolution((mech.Body).Owner, component.SolutionName); } } } @@ -61,7 +61,7 @@ namespace Content.Server.Body.Systems if (metab.AccumulatedFrametime >= metab.UpdateFrequency) { metab.AccumulatedFrametime -= metab.UpdateFrequency; - TryMetabolize(metab.OwnerUid, metab); + TryMetabolize((metab).Owner, metab); } } } @@ -86,10 +86,10 @@ namespace Content.Server.Body.Systems if (body != null) { - if (!Resolve(body.OwnerUid, ref manager, false)) + if (!Resolve((body).Owner, ref manager, false)) return; - _solutionContainerSystem.TryGetSolution(body.OwnerUid, meta.SolutionName, out solution, manager); - solutionEntityUid = body.OwnerUid; + _solutionContainerSystem.TryGetSolution((body).Owner, meta.SolutionName, out solution, manager); + solutionEntityUid = body.Owner; } } } @@ -152,7 +152,7 @@ namespace Content.Server.Body.Systems continue; } - var args = new ReagentEffectArgs(solutionEntityUid.Value, meta.OwnerUid, solution, proto, entry.MetabolismRate, + var args = new ReagentEffectArgs(solutionEntityUid.Value, (meta).Owner, solution, proto, entry.MetabolismRate, EntityManager, null); // do all effects, if conditions apply @@ -163,9 +163,9 @@ namespace Content.Server.Body.Systems if (effect.ShouldLog) { - var entity = EntityManager.GetEntity(args.SolutionEntity); + var entity = args.SolutionEntity; _logSystem.Add(LogType.ReagentEffect, effect.LogImpact, - $"Metabolism effect {effect.GetType().Name} of reagent {args.Reagent.Name:reagent} applied on entity {entity} at {entity.Transform.Coordinates}"); + $"Metabolism effect {effect.GetType().Name} of reagent {args.Reagent.Name:reagent} applied on entity {entity} at {EntityManager.GetComponent(entity).Coordinates}"); } effect.Effect(args); diff --git a/Content.Server/Body/Systems/RespiratorSystem.cs b/Content.Server/Body/Systems/RespiratorSystem.cs index fe257f316c..d3c29e80ec 100644 --- a/Content.Server/Body/Systems/RespiratorSystem.cs +++ b/Content.Server/Body/Systems/RespiratorSystem.cs @@ -32,7 +32,7 @@ namespace Content.Server.Body.Systems foreach (var (respirator, blood, body) in EntityManager.EntityQuery()) { - var uid = respirator.OwnerUid; + var uid = respirator.Owner; if (!EntityManager.TryGetComponent(uid, out var state) || state.IsDead()) { @@ -143,7 +143,7 @@ namespace Content.Server.Body.Systems foreach (var (lung, mech) in lungs) { - _lungSystem.UpdateLung(lung.OwnerUid, lung, mech); + _lungSystem.UpdateLung(lung.Owner, lung, mech); } foreach (var (gas, amountNeeded) in needs) @@ -158,7 +158,7 @@ namespace Content.Server.Body.Systems // Panic inhale foreach (var (lung, mech) in lungs) { - _lungSystem.Gasp(lung.OwnerUid, lung, mech); + _lungSystem.Gasp((lung).Owner, lung, mech); } } @@ -198,7 +198,7 @@ namespace Content.Server.Body.Systems private void TakeSuffocationDamage(EntityUid uid, RespiratorComponent respirator) { if (!respirator.Suffocating) - _logSys.Add(LogType.Asphyxiation, $"{EntityManager.GetEntity(uid)} started suffocating"); + _logSys.Add(LogType.Asphyxiation, $"{uid:Entity} started suffocating"); respirator.Suffocating = true; @@ -213,7 +213,7 @@ namespace Content.Server.Body.Systems private void StopSuffocation(EntityUid uid, RespiratorComponent respirator) { if (respirator.Suffocating) - _logSys.Add(LogType.Asphyxiation, $"{EntityManager.GetEntity(uid)} stopped suffocating"); + _logSys.Add(LogType.Asphyxiation, $"{uid:Entity} stopped suffocating"); respirator.Suffocating = false; diff --git a/Content.Server/Body/Systems/StomachSystem.cs b/Content.Server/Body/Systems/StomachSystem.cs index dd35f61122..9f626f718f 100644 --- a/Content.Server/Body/Systems/StomachSystem.cs +++ b/Content.Server/Body/Systems/StomachSystem.cs @@ -35,11 +35,11 @@ namespace Content.Server.Body.Systems stomach.AccumulatedFrameTime -= stomach.UpdateInterval; // Get our solutions - if (!_solutionContainerSystem.TryGetSolution(stomach.OwnerUid, DefaultSolutionName, + if (!_solutionContainerSystem.TryGetSolution((stomach).Owner, DefaultSolutionName, out var stomachSolution, sol)) continue; - if (!_solutionContainerSystem.TryGetSolution(mech.Body.OwnerUid, stomach.BodySolutionName, + if (!_solutionContainerSystem.TryGetSolution((mech.Body).Owner, stomach.BodySolutionName, out var bodySolution)) continue; @@ -56,7 +56,7 @@ namespace Content.Server.Body.Systems if (quant > delta.Quantity) quant = delta.Quantity; - _solutionContainerSystem.TryRemoveReagent(stomach.OwnerUid, stomachSolution, + _solutionContainerSystem.TryRemoveReagent((stomach).Owner, stomachSolution, delta.ReagentId, quant); transferSolution.AddReagent(delta.ReagentId, quant); } @@ -71,7 +71,7 @@ namespace Content.Server.Body.Systems } // Transfer everything to the body solution! - _solutionContainerSystem.TryAddSolution(mech.Body.OwnerUid, bodySolution, transferSolution); + _solutionContainerSystem.TryAddSolution((mech.Body).Owner, bodySolution, transferSolution); } } diff --git a/Content.Server/Body/Systems/ThermalRegulatorSystem.cs b/Content.Server/Body/Systems/ThermalRegulatorSystem.cs index 95d4eaee7d..9de3afae52 100644 --- a/Content.Server/Body/Systems/ThermalRegulatorSystem.cs +++ b/Content.Server/Body/Systems/ThermalRegulatorSystem.cs @@ -22,7 +22,7 @@ public class ThermalRegulatorSystem : EntitySystem continue; regulator.AccumulatedFrametime -= 1; - ProcessThermalRegulation(regulator.OwnerUid, regulator); + ProcessThermalRegulation(regulator.Owner, regulator); } } diff --git a/Content.Server/Botany/Components/LogComponent.cs b/Content.Server/Botany/Components/LogComponent.cs index b12205d205..5b49e35719 100644 --- a/Content.Server/Botany/Components/LogComponent.cs +++ b/Content.Server/Botany/Components/LogComponent.cs @@ -1,10 +1,10 @@ using System.Threading.Tasks; using Content.Shared.ActionBlocker; using Content.Shared.Interaction; -using Content.Shared.Interaction.Events; using Content.Shared.Random.Helpers; using Content.Shared.Tag; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Botany.Components { @@ -15,18 +15,20 @@ namespace Content.Server.Botany.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if (!EntitySystem.Get().CanInteract(eventArgs.User)) return false; + var entMan = IoCManager.Resolve(); + if (eventArgs.Using.HasTag("BotanySharp")) { for (var i = 0; i < 2; i++) { - var plank = Owner.EntityManager.SpawnEntity("MaterialWoodPlank1", Owner.Transform.Coordinates); + var plank = entMan.SpawnEntity("MaterialWoodPlank1", entMan.GetComponent(Owner).Coordinates); plank.RandomOffset(0.25f); } - Owner.QueueDelete(); + entMan.QueueDeleteEntity(Owner); return true; } diff --git a/Content.Server/Botany/Components/PlantHolderComponent.cs b/Content.Server/Botany/Components/PlantHolderComponent.cs index a5a85362a1..9c15a5e5ab 100644 --- a/Content.Server/Botany/Components/PlantHolderComponent.cs +++ b/Content.Server/Botany/Components/PlantHolderComponent.cs @@ -18,7 +18,6 @@ using Content.Shared.Interaction; using Content.Shared.Popups; using Content.Shared.Random.Helpers; using Content.Shared.Tag; -using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -45,6 +44,7 @@ namespace Content.Server.Botany.Components [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; + [Dependency] private readonly IEntityManager _entMan = default!; [ComponentDependency] private readonly AppearanceComponent? _appearanceComponent = default!; public override string Name => "PlantHolder"; @@ -248,7 +248,7 @@ namespace Content.Server.Botany.Components _updateSpriteAfterUpdate = true; } - var environment = EntitySystem.Get().GetTileMixture(Owner.Transform.Coordinates, true) ?? + var environment = EntitySystem.Get().GetTileMixture(_entMan.GetComponent(Owner).Coordinates, true) ?? GasMixture.SpaceGas; if (Seed.ConsumeGasses.Count > 0) @@ -361,7 +361,7 @@ namespace Content.Server.Botany.Components } else if (Age < 0) // Revert back to seed packet! { - Seed.SpawnSeedPacket(Owner.Transform.Coordinates); + Seed.SpawnSeedPacket(_entMan.GetComponent(Owner).Coordinates); RemovePlant(); ForceUpdate = true; Update(); @@ -419,14 +419,14 @@ namespace Content.Server.Botany.Components MutationMod = MathHelper.Clamp(MutationMod, 0f, 3f); } - public bool DoHarvest(IEntity user) + public bool DoHarvest(EntityUid user) { - if (Seed == null || user.Deleted || !EntitySystem.Get().CanInteract(user.Uid)) + if (Seed == null || _entMan.Deleted(user) || !EntitySystem.Get().CanInteract(user)) return false; if (Harvest && !Dead) { - if (user.TryGetComponent(out HandsComponent? hands)) + if (_entMan.TryGetComponent(user, out HandsComponent? hands)) { if (!Seed.CheckHarvest(user, hands.GetActiveHand?.Owner)) return false; @@ -453,7 +453,7 @@ namespace Content.Server.Botany.Components if (Seed == null || !Harvest) return; - Seed.AutoHarvest(Owner.Transform.Coordinates); + Seed.AutoHarvest(_entMan.GetComponent(Owner).Coordinates); AfterHarvest(); } @@ -549,7 +549,7 @@ namespace Content.Server.Botany.Components public void UpdateReagents() { var solutionSystem = EntitySystem.Get(); - if (!solutionSystem.TryGetSolution(Owner.Uid, SoilSolutionName, out var solution)) + if (!solutionSystem.TryGetSolution(Owner, SoilSolutionName, out var solution)) return; if (solution.TotalVolume <= 0 || MutationLevel >= 25) @@ -563,10 +563,10 @@ namespace Content.Server.Botany.Components else { var amt = FixedPoint2.New(1); - foreach (var reagent in solutionSystem.RemoveEachReagent(OwnerUid, solution, amt)) + foreach (var reagent in solutionSystem.RemoveEachReagent(Owner, solution, amt)) { var reagentProto = _prototypeManager.Index(reagent); - reagentProto.ReactionPlant(OwnerUid, new Solution.ReagentQuantity(reagent, amt), solution); + reagentProto.ReactionPlant(Owner, new Solution.ReagentQuantity(reagent, amt), solution); } } @@ -651,17 +651,17 @@ namespace Content.Server.Botany.Components var user = eventArgs.User; var usingItem = eventArgs.Using; - if (usingItem.Deleted || !EntitySystem.Get().CanInteract(user.Uid)) + if ((!_entMan.EntityExists(usingItem) ? EntityLifeStage.Deleted : _entMan.GetComponent(usingItem).EntityLifeStage) >= EntityLifeStage.Deleted || !EntitySystem.Get().CanInteract(user)) return false; - if (usingItem.TryGetComponent(out SeedComponent? seeds)) + if (_entMan.TryGetComponent(usingItem, out SeedComponent? seeds)) { if (Seed == null) { if (seeds.Seed == null) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-empty-seed-packet-message")); - usingItem.QueueDelete(); + _entMan.QueueDeleteEntity(usingItem); return false; } @@ -675,7 +675,7 @@ namespace Content.Server.Botany.Components Health = Seed.Endurance; _lastCycle = _gameTiming.CurTime; - usingItem.QueueDelete(); + _entMan.QueueDeleteEntity(usingItem); CheckLevelSanity(); UpdateSprite(); @@ -684,7 +684,7 @@ namespace Content.Server.Botany.Components } user.PopupMessageCursor(Loc.GetString("plant-holder-component-already-seeded-message", - ("name", Owner.Name))); + ("name", Name: _entMan.GetComponent(Owner).EntityName))); return false; } @@ -693,9 +693,9 @@ namespace Content.Server.Botany.Components if (WeedLevel > 0) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-remove-weeds-message", - ("name", Owner.Name))); + ("name", Name: _entMan.GetComponent(Owner).EntityName))); user.PopupMessageOtherClients(Loc.GetString("plant-holder-component-remove-weeds-others-message", - ("otherName", user.Name))); + ("otherName", Name: _entMan.GetComponent(user).EntityName))); WeedLevel = 0; UpdateSprite(); } @@ -712,9 +712,9 @@ namespace Content.Server.Botany.Components if (Seed != null) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-remove-plant-message", - ("name", Owner.Name))); + ("name", Name: _entMan.GetComponent(Owner).EntityName))); user.PopupMessageOtherClients(Loc.GetString("plant-holder-component-remove-plant-others-message", - ("name", user.Name))); + ("name", Name: _entMan.GetComponent(user).EntityName))); RemovePlant(); } else @@ -726,15 +726,15 @@ namespace Content.Server.Botany.Components } var solutionSystem = EntitySystem.Get(); - if (solutionSystem.TryGetDrainableSolution(usingItem.Uid, out var solution) - && solutionSystem.TryGetSolution(Owner.Uid, SoilSolutionName, out var targetSolution)) + if (solutionSystem.TryGetDrainableSolution(usingItem, out var solution) + && solutionSystem.TryGetSolution(Owner, SoilSolutionName, out var targetSolution)) { var amount = FixedPoint2.New(5); var sprayed = false; - var targetEntity = Owner.Uid; - var solutionEntity = usingItem.Uid; + var targetEntity = Owner; + var solutionEntity = usingItem; - if (usingItem.TryGetComponent(out SprayComponent? spray)) + if (_entMan.TryGetComponent(usingItem, out SprayComponent? spray)) { sprayed = true; amount = FixedPoint2.New(1); @@ -783,7 +783,7 @@ namespace Content.Server.Botany.Components return false; } - var seed = Seed.SpawnSeedPacket(user.Transform.Coordinates); + var seed = Seed.SpawnSeedPacket(_entMan.GetComponent(user).Coordinates); seed.RandomOffset(0.25f); user.PopupMessageCursor(Loc.GetString("plant-holder-component-take-sample-message", ("seedName", Seed.DisplayName))); @@ -804,7 +804,7 @@ namespace Content.Server.Botany.Components return DoHarvest(user); } - if (usingItem.TryGetComponent(out var produce)) + if (_entMan.TryGetComponent(usingItem, out var produce)) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-compost-message", ("owner", Owner), @@ -814,16 +814,16 @@ namespace Content.Server.Botany.Components ("usingItem", usingItem), ("owner", Owner))); - if (solutionSystem.TryGetSolution(usingItem.Uid, produce.SolutionName, out var solution2)) + if (solutionSystem.TryGetSolution(usingItem, produce.SolutionName, out var solution2)) { // This deliberately discards overfill. - solutionSystem.TryAddSolution(usingItem.Uid, solution2, - solutionSystem.SplitSolution(usingItem.Uid, solution2, solution2.TotalVolume)); + solutionSystem.TryAddSolution(usingItem, solution2, + solutionSystem.SplitSolution(usingItem, solution2, solution2.TotalVolume)); ForceUpdateByExternalCause(); } - usingItem.QueueDelete(); + _entMan.QueueDeleteEntity(usingItem); return true; } diff --git a/Content.Server/Botany/Components/ProduceComponent.cs b/Content.Server/Botany/Components/ProduceComponent.cs index ea9fad7ca9..c7623c5e61 100644 --- a/Content.Server/Botany/Components/ProduceComponent.cs +++ b/Content.Server/Botany/Components/ProduceComponent.cs @@ -35,13 +35,13 @@ namespace Content.Server.Botany.Components if (Seed == null) return; - if (Owner.TryGetComponent(out SpriteComponent? sprite)) + if (IoCManager.Resolve().TryGetComponent(Owner, out SpriteComponent? sprite)) { sprite.LayerSetRSI(0, Seed.PlantRsi); sprite.LayerSetState(0, Seed.PlantIconState); } - var solutionContainer = EntitySystem.Get().EnsureSolution(Owner.Uid, SolutionName); + var solutionContainer = EntitySystem.Get().EnsureSolution(Owner, SolutionName); if (solutionContainer == null) { Logger.Warning($"No solution container found in {nameof(ProduceComponent)}."); diff --git a/Content.Server/Botany/Components/SeedExtractorComponent.cs b/Content.Server/Botany/Components/SeedExtractorComponent.cs index 5b638ac7ff..c2a95b37ce 100644 --- a/Content.Server/Botany/Components/SeedExtractorComponent.cs +++ b/Content.Server/Botany/Components/SeedExtractorComponent.cs @@ -14,6 +14,7 @@ namespace Content.Server.Botany.Components { [ComponentDependency] private readonly ApcPowerReceiverComponent? _powerReceiver = default!; + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _random = default!; public override string Name => "SeedExtractor"; @@ -27,17 +28,17 @@ namespace Content.Server.Botany.Components if (!_powerReceiver?.Powered ?? false) return false; - if (eventArgs.Using.TryGetComponent(out ProduceComponent? produce) && produce.Seed != null) + if (_entMan.TryGetComponent(eventArgs.Using, out ProduceComponent? produce) && produce.Seed != null) { - eventArgs.User.PopupMessageCursor(Loc.GetString("seed-extractor-component-interact-message",("name", eventArgs.Using.Name))); + eventArgs.User.PopupMessageCursor(Loc.GetString("seed-extractor-component-interact-message",("name", Name: _entMan.GetComponent(eventArgs.Using).EntityName))); - eventArgs.Using.QueueDelete(); + _entMan.QueueDeleteEntity(eventArgs.Using); var random = _random.Next(_minSeeds, _maxSeeds); for (var i = 0; i < random; i++) { - produce.Seed.SpawnSeedPacket(Owner.Transform.Coordinates, Owner.EntityManager); + produce.Seed.SpawnSeedPacket(_entMan.GetComponent(Owner).Coordinates, _entMan); } return true; diff --git a/Content.Server/Botany/Seed.cs b/Content.Server/Botany/Seed.cs index 5e0545772d..c9123aac14 100644 --- a/Content.Server/Botany/Seed.cs +++ b/Content.Server/Botany/Seed.cs @@ -248,7 +248,7 @@ namespace Content.Server.Botany return newSeed; } - public IEntity SpawnSeedPacket(EntityCoordinates transformCoordinates, IEntityManager? entityManager = null) + public EntityUid SpawnSeedPacket(EntityCoordinates transformCoordinates, IEntityManager? entityManager = null) { entityManager ??= IoCManager.Resolve(); @@ -257,13 +257,14 @@ namespace Content.Server.Botany var seedComp = seed.EnsureComponent(); seedComp.Seed = this; - if (seed.TryGetComponent(out SpriteComponent? sprite)) + if (entityManager.TryGetComponent(seed, out SpriteComponent? sprite)) { // Seed state will always be seed. Blame the spriter if that's not the case! sprite.LayerSetSprite(0, new SpriteSpecifier.Rsi(PlantRsi, "seed")); } - seed.Name = Loc.GetString("botany-seed-packet-name", ("seedName", SeedName), ("seedNoun", SeedNoun)); + string val = Loc.GetString("botany-seed-packet-name", ("seedName", SeedName), ("seedNoun", SeedNoun)); + entityManager.GetComponent(seed).EntityName = val; return seed; } @@ -277,33 +278,33 @@ namespace Content.Server.Botany } } - public IEnumerable AutoHarvest(EntityCoordinates position, int yieldMod = 1) + public IEnumerable AutoHarvest(EntityCoordinates position, int yieldMod = 1) { if (position.IsValid(IoCManager.Resolve()) && ProductPrototypes != null && ProductPrototypes.Count > 0) return GenerateProduct(position, yieldMod); - return Enumerable.Empty(); + return Enumerable.Empty(); } - public IEnumerable Harvest(IEntity user, int yieldMod = 1) + public IEnumerable Harvest(EntityUid user, int yieldMod = 1) { AddToDatabase(); if (user == null) - return Enumerable.Empty(); + return Enumerable.Empty(); if (ProductPrototypes == null || ProductPrototypes.Count == 0 || Yield <= 0) { user.PopupMessageCursor(Loc.GetString("botany-harvest-fail-message")); - return Enumerable.Empty(); + return Enumerable.Empty(); } user.PopupMessageCursor(Loc.GetString("botany-harvest-success-message", ("name", DisplayName))); - return GenerateProduct(user.Transform.Coordinates, yieldMod); + return GenerateProduct(IoCManager.Resolve().GetComponent(user).Coordinates, yieldMod); } - public IEnumerable GenerateProduct(EntityCoordinates position, int yieldMod = 1) + public IEnumerable GenerateProduct(EntityCoordinates position, int yieldMod = 1) { var totalYield = 0; if (Yield > -1) @@ -324,7 +325,7 @@ namespace Content.Server.Botany var random = IoCManager.Resolve(); var entityManager = IoCManager.Resolve(); - var products = new List(); + var products = new List(); for (var i = 0; i < totalYield; i++) { @@ -341,8 +342,9 @@ namespace Content.Server.Botany if (Mysterious) { - entity.Name += "?"; - entity.Description += " " + Loc.GetString("botany-mysterious-description-addon"); + var metaData = entityManager.GetComponent(entity); + metaData.EntityName += "?"; + metaData.EntityDescription += (" " + Loc.GetString("botany-mysterious-description-addon")); } } @@ -354,9 +356,9 @@ namespace Content.Server.Botany return Clone(); } - public bool CheckHarvest(IEntity user, IEntity? held = null) + public bool CheckHarvest(EntityUid user, EntityUid? held = null) { - return (!Ligneous || (Ligneous && held != null && held.HasTag("BotanySharp"))); + return !Ligneous || (Ligneous && held != null && held.Value.HasTag("BotanySharp")); } } } diff --git a/Content.Server/Bql/QuerySelectors.cs b/Content.Server/Bql/QuerySelectors.cs index c173fb9b1f..5431cb19ce 100644 --- a/Content.Server/Bql/QuerySelectors.cs +++ b/Content.Server/Bql/QuerySelectors.cs @@ -1,13 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using Content.Server.Chemistry.Components.SolutionManager; using Content.Server.Mind.Components; using Content.Server.Power.Components; -using Content.Server.Chemistry.Components.SolutionManager; using Content.Shared.Tag; using Robust.Server.Bql; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; namespace Content.Server.Bql { @@ -26,7 +25,7 @@ namespace Content.Server.Bql return input.Where(e => { if (entityManager.TryGetComponent(e, out var mind)) - return (mind.Mind?.VisitingEntity?.Uid == e) ^ isInverted; + return (mind.Mind?.VisitingEntity == e) ^ isInverted; return isInverted; }); @@ -36,7 +35,7 @@ namespace Content.Server.Bql { return DoSelection( - entityManager.EntityQuery().Select(x => x.Owner.Uid), + entityManager.EntityQuery().Select(x => x.Owner), arguments, isInverted, entityManager); } } @@ -57,7 +56,7 @@ namespace Content.Server.Bql public override IEnumerable DoInitialSelection(IReadOnlyList arguments, bool isInverted, IEntityManager entityManager) { - return DoSelection(entityManager.EntityQuery().Select(x => x.Owner.Uid), arguments, + return DoSelection(entityManager.EntityQuery().Select(x => x.Owner), arguments, isInverted, entityManager); } @@ -79,7 +78,7 @@ namespace Content.Server.Bql public override IEnumerable DoInitialSelection(IReadOnlyList arguments, bool isInverted, IEntityManager entityManager) { - return DoSelection(entityManager.EntityQuery().Select(x => x.Owner.Uid), arguments, + return DoSelection(entityManager.EntityQuery().Select(x => x.Owner), arguments, isInverted, entityManager); } } @@ -108,7 +107,7 @@ namespace Content.Server.Bql public override IEnumerable DoInitialSelection(IReadOnlyList arguments, bool isInverted, IEntityManager entityManager) { - return DoSelection(entityManager.EntityQuery().Select(x => x.Owner.Uid), arguments, + return DoSelection(entityManager.EntityQuery().Select(x => x.Owner), arguments, isInverted, entityManager); } } @@ -130,7 +129,7 @@ namespace Content.Server.Bql public override IEnumerable DoInitialSelection(IReadOnlyList arguments, bool isInverted, IEntityManager entityManager) { - return DoSelection(entityManager.EntityQuery().Select(x => x.Owner.Uid), arguments, + return DoSelection(entityManager.EntityQuery().Select(x => x.Owner), arguments, isInverted, entityManager); } } diff --git a/Content.Server/Buckle/Components/BuckleComponent.cs b/Content.Server/Buckle/Components/BuckleComponent.cs index afb1356ed1..0c40c6c768 100644 --- a/Content.Server/Buckle/Components/BuckleComponent.cs +++ b/Content.Server/Buckle/Components/BuckleComponent.cs @@ -3,18 +3,15 @@ using System.Diagnostics.CodeAnalysis; using Content.Server.Alert; using Content.Server.Hands.Components; using Content.Server.Pulling; -using Content.Server.Stunnable.Components; using Content.Shared.ActionBlocker; using Content.Shared.Alert; using Content.Shared.Buckle.Components; using Content.Shared.Interaction.Helpers; using Content.Shared.MobState.Components; using Content.Shared.Popups; -using Content.Shared.Pulling; using Content.Shared.Pulling.Components; using Content.Shared.Standing; using Content.Shared.Stunnable; -using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; @@ -22,7 +19,6 @@ using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Timing; using Robust.Shared.ViewVariables; @@ -36,6 +32,7 @@ namespace Content.Server.Buckle.Components [ComponentReference(typeof(SharedBuckleComponent))] public class BuckleComponent : SharedBuckleComponent { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [ComponentDependency] public readonly AppearanceComponent? Appearance = null; @@ -118,8 +115,8 @@ namespace Content.Server.Buckle.Components /// The strap to reattach to. public void ReAttach(StrapComponent strap) { - var ownTransform = Owner.Transform; - var strapTransform = strap.Owner.Transform; + var ownTransform = _entMan.GetComponent(Owner); + var strapTransform = _entMan.GetComponent(strap.Owner); ownTransform.AttachParent(strapTransform); ownTransform.LocalRotation = Angle.Zero; @@ -129,40 +126,41 @@ namespace Content.Server.Buckle.Components case StrapPosition.None: break; case StrapPosition.Stand: - EntitySystem.Get().Stand(Owner.Uid); + EntitySystem.Get().Stand(Owner); break; case StrapPosition.Down: - EntitySystem.Get().Down(Owner.Uid, false, false); + EntitySystem.Get().Down(Owner, false, false); break; } ownTransform.LocalPosition = Vector2.Zero + BuckleOffset; } - public bool CanBuckle(IEntity? user, IEntity to, [NotNullWhen(true)] out StrapComponent? strap) + public bool CanBuckle(EntityUid user, EntityUid to, [NotNullWhen(true)] out StrapComponent? strap) { + var popupSystem = EntitySystem.Get(); strap = null; - if (user == null || user == to) + if (user == to) { return false; } - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) { - user.PopupMessage(Loc.GetString("buckle-component-cannot-do-that-message")); + popupSystem.PopupEntity(Loc.GetString("buckle-component-cannot-do-that-message"), user, Filter.Entities(user)); return false; } - if (!to.TryGetComponent(out strap)) + if (!_entMan.TryGetComponent(to, out strap)) { return false; } - var component = strap; - bool Ignored(IEntity entity) => entity == Owner || entity == user || entity == component.Owner; + var strapUid = strap.Owner; + bool Ignored(EntityUid entity) => entity == Owner || entity == user || entity == strapUid; - if (!Owner.InRangeUnobstructed(strap, Range, predicate: Ignored, popup: true)) + if (!Owner.InRangeUnobstructed(strapUid, Range, predicate: Ignored, popup: true)) { return false; } @@ -178,9 +176,9 @@ namespace Content.Server.Buckle.Components } } - if (!user.HasComponent()) + if (!_entMan.HasComponent(user)) { - user.PopupMessage(Loc.GetString("buckle-component-no-hands-message ")); + popupSystem.PopupEntity(Loc.GetString("buckle-component-no-hands-message"), user, Filter.Entities(user)); return false; } @@ -189,20 +187,20 @@ namespace Content.Server.Buckle.Components var message = Loc.GetString(Owner == user ? "buckle-component-already-buckled-message" : "buckle-component-other-already-buckled-message", ("owner", Owner)); - Owner.PopupMessage(user, message); + popupSystem.PopupEntity(message, user, Filter.Entities(user)); return false; } - var parent = to.Transform.Parent; + var parent = _entMan.GetComponent(to).Parent; while (parent != null) { - if (parent == user.Transform) + if (parent == _entMan.GetComponent(user)) { var message = Loc.GetString(Owner == user ? "buckle-component-cannot-buckle-message" : "buckle-component-other-cannot-buckle-message", ("owner", Owner)); - Owner.PopupMessage(user, message); + popupSystem.PopupEntity(message, user, Filter.Entities(user)); return false; } @@ -215,7 +213,7 @@ namespace Content.Server.Buckle.Components var message = Loc.GetString(Owner == user ? "buckle-component-cannot-fit-message" : "buckle-component-other-cannot-fit-message", ("owner", Owner)); - Owner.PopupMessage(user, message); + popupSystem.PopupEntity(message, user, Filter.Entities(user)); return false; } @@ -223,9 +221,10 @@ namespace Content.Server.Buckle.Components return true; } - public override bool TryBuckle(IEntity? user, IEntity to) + public override bool TryBuckle(EntityUid user, EntityUid to) { - if (user == null || !CanBuckle(user, to, out var strap)) + var popupSystem = EntitySystem.Get(); + if (!CanBuckle(user, to, out var strap)) { return false; } @@ -237,7 +236,7 @@ namespace Content.Server.Buckle.Components var message = Loc.GetString(Owner == user ? "buckle-component-cannot-buckle-message" : "buckle-component-other-cannot-buckle-message", ("owner", Owner)); - Owner.PopupMessage(user, message); + popupSystem.PopupEntity(message, user, Filter.Entities(user)); return false; } @@ -246,7 +245,7 @@ namespace Content.Server.Buckle.Components ReAttach(strap); BuckledTo = strap; - LastEntityBuckledTo = BuckledTo.Owner.Uid; + LastEntityBuckledTo = BuckledTo.Owner; DontCollide = true; UpdateBuckleStatus(); @@ -255,7 +254,7 @@ namespace Content.Server.Buckle.Components SendMessage(new BuckleMessage(Owner, to)); #pragma warning restore 618 - if (Owner.TryGetComponent(out SharedPullableComponent? ownerPullable)) + if (_entMan.TryGetComponent(Owner, out SharedPullableComponent? ownerPullable)) { if (ownerPullable.Puller != null) { @@ -263,7 +262,7 @@ namespace Content.Server.Buckle.Components } } - if (to.TryGetComponent(out SharedPullableComponent? toPullable)) + if (_entMan.TryGetComponent(to, out SharedPullableComponent? toPullable)) { if (toPullable.Puller == Owner) { @@ -287,7 +286,7 @@ namespace Content.Server.Buckle.Components /// true if the owner was unbuckled, otherwise false even if the owner /// was previously already unbuckled. /// - public bool TryUnbuckle(IEntity user, bool force = false) + public bool TryUnbuckle(EntityUid user, bool force = false) { if (BuckledTo == null) { @@ -303,13 +302,14 @@ namespace Content.Server.Buckle.Components return false; } - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) { - user.PopupMessage(Loc.GetString("buckle-component-cannot-do-that-message")); + var popupSystem = EntitySystem.Get(); + popupSystem.PopupEntity(Loc.GetString("buckle-component-cannot-do-that-message"), user, Filter.Entities(user)); return false; } - if (!user.InRangeUnobstructed(oldBuckledTo, Range, popup: true)) + if (!user.InRangeUnobstructed(oldBuckledTo.Owner, Range, popup: true)) { return false; } @@ -317,25 +317,25 @@ namespace Content.Server.Buckle.Components BuckledTo = null; - if (Owner.Transform.Parent == oldBuckledTo.Owner.Transform) + if (_entMan.GetComponent(Owner).Parent == _entMan.GetComponent(oldBuckledTo.Owner)) { - Owner.Transform.AttachParentToContainerOrGrid(); - Owner.Transform.WorldRotation = oldBuckledTo.Owner.Transform.WorldRotation; + _entMan.GetComponent(Owner).AttachParentToContainerOrGrid(); + _entMan.GetComponent(Owner).WorldRotation = _entMan.GetComponent(oldBuckledTo.Owner).WorldRotation; } Appearance?.SetData(BuckleVisuals.Buckled, false); - if (Owner.HasComponent() + if (_entMan.HasComponent(Owner) || (_mobState?.IsIncapacitated() ?? false)) { - EntitySystem.Get().Down(Owner.Uid); + EntitySystem.Get().Down(Owner); } else { - EntitySystem.Get().Stand(Owner.Uid); + EntitySystem.Get().Stand(Owner); } - _mobState?.CurrentState?.EnterState(Owner.Uid, Owner.EntityManager); + _mobState?.CurrentState?.EnterState(Owner, _entMan); UpdateBuckleStatus(); @@ -363,7 +363,7 @@ namespace Content.Server.Buckle.Components /// unbuckled afterwards. /// /// true if the buckling status was changed, false otherwise. - public bool ToggleBuckle(IEntity user, IEntity to, bool force = false) + public bool ToggleBuckle(EntityUid user, EntityUid to, bool force = false) { if (BuckledTo?.Owner == to) { @@ -395,7 +395,7 @@ namespace Content.Server.Buckle.Components int? drawDepth = null; if (BuckledTo != null && - BuckledTo.Owner.Transform.LocalRotation.GetCardinalDir() == Direction.North && + _entMan.GetComponent(BuckledTo.Owner).LocalRotation.GetCardinalDir() == Direction.North && BuckledTo.SpriteComponent != null) { drawDepth = BuckledTo.SpriteComponent.DrawDepth - 1; diff --git a/Content.Server/Buckle/Components/StrapComponent.cs b/Content.Server/Buckle/Components/StrapComponent.cs index 0fa44f5f1e..3d06c638e0 100644 --- a/Content.Server/Buckle/Components/StrapComponent.cs +++ b/Content.Server/Buckle/Components/StrapComponent.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; -using Content.Shared.ActionBlocker; using Content.Shared.Acts; using Content.Shared.Alert; using Content.Shared.Buckle.Components; @@ -9,7 +8,7 @@ using Content.Shared.Interaction; using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; -using Robust.Shared.Players; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -22,7 +21,9 @@ namespace Content.Server.Buckle.Components { [ComponentDependency] public readonly SpriteComponent? SpriteComponent = null; - private readonly HashSet _buckledEntities = new(); + [Dependency] private readonly IEntityManager _entMan = default!; + + private readonly HashSet _buckledEntities = new(); /// /// The angle in degrees to rotate the player by when they get strapped @@ -39,7 +40,7 @@ namespace Content.Server.Buckle.Components /// /// The entity that is currently buckled here, synced from /// - public IReadOnlyCollection BuckledEntities => _buckledEntities; + public IReadOnlyCollection BuckledEntities => _buckledEntities; /// /// The change in position to the strapped mob @@ -148,7 +149,7 @@ namespace Content.Server.Buckle.Components { foreach (var entity in _buckledEntities.ToArray()) { - if (entity.TryGetComponent(out var buckle)) + if (_entMan.TryGetComponent(entity, out var buckle)) { buckle.TryUnbuckle(entity, true); } @@ -165,7 +166,7 @@ namespace Content.Server.Buckle.Components bool IInteractHand.InteractHand(InteractHandEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out var buckle)) + if (!_entMan.TryGetComponent(eventArgs.User, out var buckle)) { return false; } @@ -175,7 +176,7 @@ namespace Content.Server.Buckle.Components public override bool DragDropOn(DragDropEvent eventArgs) { - if (!eventArgs.Dragged.TryGetComponent(out BuckleComponent? buckleComponent)) return false; + if (!_entMan.TryGetComponent(eventArgs.Dragged, out BuckleComponent? buckleComponent)) return false; return buckleComponent.TryBuckle(eventArgs.User, Owner); } } diff --git a/Content.Server/Buckle/Systems/BuckleSystem.cs b/Content.Server/Buckle/Systems/BuckleSystem.cs index 4337bdd9ad..0135e3aea0 100644 --- a/Content.Server/Buckle/Systems/BuckleSystem.cs +++ b/Content.Server/Buckle/Systems/BuckleSystem.cs @@ -7,6 +7,7 @@ using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; namespace Content.Server.Buckle.Systems @@ -40,7 +41,7 @@ namespace Content.Server.Buckle.Systems { if (!args.CanAccess || !args.CanInteract || !component.Buckled) return; - + Verb verb = new(); verb.Act = () => component.TryUnbuckle(args.User); verb.Text = Loc.GetString("verb-categories-unbuckle"); @@ -78,7 +79,7 @@ namespace Content.Server.Buckle.Systems return; } - var strapPosition = strap.Owner.Transform.Coordinates.Offset(buckle.BuckleOffset); + var strapPosition = EntityManager.GetComponent(strap.Owner).Coordinates.Offset(buckle.BuckleOffset); if (ev.NewPosition.InRange(EntityManager, strapPosition, 0.2f)) { @@ -94,7 +95,7 @@ namespace Content.Server.Buckle.Systems // This fixes buckle offsets and draw depths. foreach (var buckledEntity in strap.BuckledEntities) { - if (!buckledEntity.TryGetComponent(out BuckleComponent? buckled)) + if (!EntityManager.TryGetComponent(buckledEntity, out BuckleComponent? buckled)) { continue; } @@ -111,7 +112,7 @@ namespace Content.Server.Buckle.Systems { foreach (var buckledEntity in strap.BuckledEntities) { - if (!buckledEntity.TryGetComponent(out BuckleComponent? buckled)) + if (!EntityManager.TryGetComponent(buckledEntity, out BuckleComponent? buckled)) { continue; } diff --git a/Content.Server/Buckle/Systems/StrapSystem.cs b/Content.Server/Buckle/Systems/StrapSystem.cs index 1a4206ccf6..9acd58d2db 100644 --- a/Content.Server/Buckle/Systems/StrapSystem.cs +++ b/Content.Server/Buckle/Systems/StrapSystem.cs @@ -1,14 +1,11 @@ using Content.Server.Buckle.Components; using Content.Server.Interaction; -using Content.Shared.Hands.Components; -using Content.Shared.Interaction.Helpers; using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using System.Collections.Generic; namespace Content.Server.Buckle.Systems { @@ -39,7 +36,7 @@ namespace Content.Server.Buckle.Systems // Add unstrap verbs for every strapped entity. foreach (var entity in component.BuckledEntities) { - var buckledComp = entity.GetComponent(); + var buckledComp = EntityManager.GetComponent(entity); if (!_interactionSystem.InRangeUnobstructed(args.User, args.Target, range: buckledComp.Range)) continue; @@ -50,7 +47,7 @@ namespace Content.Server.Buckle.Systems if (entity == args.User) verb.Text = Loc.GetString("verb-self-target-pronoun"); else - verb.Text = entity.Name; + verb.Text = EntityManager.GetComponent(entity).EntityName; // In the event that you have more than once entity with the same name strapped to the same object, // these two verbs will be identical according to Verb.CompareTo, and only one with actually be added to @@ -61,7 +58,7 @@ namespace Content.Server.Buckle.Systems } // Add a verb to buckle the user. - if (args.User.TryGetComponent(out var buckle) && + if (EntityManager.TryGetComponent(args.User, out var buckle) && buckle.BuckledTo != component && args.User != component.Owner && component.HasSpace(buckle) && @@ -75,24 +72,24 @@ namespace Content.Server.Buckle.Systems } // If the user is currently holding/pulling an entity that can be buckled, add a verb for that. - if (args.Using != null && - args.Using.TryGetComponent(out var usingBuckle) && + if (args.Using is {Valid: true} @using && + EntityManager.TryGetComponent(@using, out var usingBuckle) && component.HasSpace(usingBuckle) && - _interactionSystem.InRangeUnobstructed(args.Using, args.Target, range: usingBuckle.Range)) + _interactionSystem.InRangeUnobstructed(@using, args.Target, range: usingBuckle.Range)) { // Check that the entity is unobstructed from the target (ignoring the user). - bool Ignored(IEntity entity) => entity == args.User || entity == args.Target || entity == args.Using; - if (!_interactionSystem.InRangeUnobstructed(args.Using, args.Target, usingBuckle.Range, predicate: Ignored)) + bool Ignored(EntityUid entity) => entity == args.User || entity == args.Target || entity == @using; + if (!_interactionSystem.InRangeUnobstructed(@using, args.Target, usingBuckle.Range, predicate: Ignored)) return; Verb verb = new(); verb.Act = () => usingBuckle.TryBuckle(args.User, args.Target); verb.Category = VerbCategory.Buckle; - verb.Text = args.Using.Name; + verb.Text = EntityManager.GetComponent(@using).EntityName; // If the used entity is a person being pulled, prioritize this verb. Conversely, if it is // just a held object, the user is probably just trying to sit down. - verb.Priority = args.Using.HasComponent() ? 1 : -1; + verb.Priority = EntityManager.HasComponent(@using) ? 1 : -1; args.Verbs.Add(verb); } diff --git a/Content.Server/Cargo/Components/CargoConsoleComponent.cs b/Content.Server/Cargo/Components/CargoConsoleComponent.cs index 9d01c73980..0c23ce8ce4 100644 --- a/Content.Server/Cargo/Components/CargoConsoleComponent.cs +++ b/Content.Server/Cargo/Components/CargoConsoleComponent.cs @@ -4,7 +4,6 @@ using Content.Server.Power.Components; using Content.Server.UserInterface; using Content.Shared.Cargo; using Content.Shared.Cargo.Components; -using Content.Shared.Interaction; using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Shared.Audio; @@ -22,6 +21,7 @@ namespace Content.Server.Cargo.Components public class CargoConsoleComponent : SharedCargoConsoleComponent { [Dependency] private readonly IMapManager _mapManager = default!; + [Dependency] private readonly IEntityManager _entMan = default!; private CargoBankAccount? _bankAccount; @@ -58,7 +58,7 @@ namespace Content.Server.Cargo.Components [DataField("errorSound")] private SoundSpecifier _errorSound = new SoundPathSpecifier("/Audio/Effects/error.ogg"); - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; private CargoConsoleSystem _cargoConsoleSystem = default!; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(CargoConsoleUiKey.Key); @@ -91,7 +91,7 @@ namespace Content.Server.Cargo.Components private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage serverMsg) { - if (!Owner.TryGetComponent(out CargoOrderDatabaseComponent? orders)) + if (!_entMan.TryGetComponent(Owner, out CargoOrderDatabaseComponent? orders)) { return; } @@ -131,8 +131,7 @@ namespace Content.Server.Cargo.Components break; } - var uid = msg.Session.AttachedEntityUid; - if (uid == null) + if (msg.Session.AttachedEntity is not {Valid: true} player) break; PrototypeManager.TryIndex(order.ProductId, out CargoProductPrototype? product); @@ -143,7 +142,7 @@ namespace Content.Server.Cargo.Components (capacity.CurrentCapacity == capacity.MaxCapacity || capacity.CurrentCapacity + order.Amount > capacity.MaxCapacity || !_cargoConsoleSystem.CheckBalance(_bankAccount.Id, (-product.PointCost) * order.Amount) - || !_cargoConsoleSystem.ApproveOrder(Owner.Uid, uid.Value, orders.Database.Id, msg.OrderNumber) + || !_cargoConsoleSystem.ApproveOrder(Owner, player, orders.Database.Id, msg.OrderNumber) || !_cargoConsoleSystem.ChangeBalance(_bankAccount.Id, (-product.PointCost) * order.Amount)) ) { @@ -161,21 +160,21 @@ namespace Content.Server.Cargo.Components // TODO replace with shuttle code // TEMPORARY loop for spawning stuff on telepad (looks for a telepad adjacent to the console) - IEntity? cargoTelepad = null; - var indices = Owner.Transform.Coordinates.ToVector2i(Owner.EntityManager, _mapManager); + EntityUid? cargoTelepad = null; + var indices = _entMan.GetComponent(Owner).Coordinates.ToVector2i(_entMan, _mapManager); var offsets = new Vector2i[] { new Vector2i(0, 1), new Vector2i(1, 1), new Vector2i(1, 0), new Vector2i(1, -1), new Vector2i(0, -1), new Vector2i(-1, -1), new Vector2i(-1, 0), new Vector2i(-1, 1), }; - var adjacentEntities = new List>(); //Probably better than IEnumerable.concat + var adjacentEntities = new List>(); //Probably better than IEnumerable.concat foreach (var offset in offsets) { - adjacentEntities.Add((indices+offset).GetEntitiesInTileFast(Owner.Transform.GridID)); + adjacentEntities.Add((indices+offset).GetEntitiesInTileFast(_entMan.GetComponent(Owner).GridID)); } foreach (var enumerator in adjacentEntities) { - foreach (IEntity entity in enumerator) + foreach (EntityUid entity in enumerator) { - if (entity.HasComponent() && entity.TryGetComponent(out var powerReceiver) && powerReceiver.Powered) + if (_entMan.HasComponent(entity) && _entMan.TryGetComponent(entity, out var powerReceiver) && powerReceiver.Powered) { cargoTelepad = entity; break; @@ -184,7 +183,7 @@ namespace Content.Server.Cargo.Components } if (cargoTelepad != null) { - if (cargoTelepad.TryGetComponent(out var telepadComponent)) + if (_entMan.TryGetComponent(cargoTelepad.Value, out var telepadComponent)) { var approvedOrders = _cargoConsoleSystem.RemoveAndGetApprovedOrders(orders.Database.Id); orders.Database.ClearOrderCapacity(); @@ -201,7 +200,7 @@ namespace Content.Server.Cargo.Components private void UpdateUIState() { - if (_bankAccount == null || !Owner.IsValid()) + if (_bankAccount == null || !_entMan.EntityExists(Owner)) { return; } diff --git a/Content.Server/Cargo/Components/CargoTelepadComponent.cs b/Content.Server/Cargo/Components/CargoTelepadComponent.cs index d674713a4c..b43937af93 100644 --- a/Content.Server/Cargo/Components/CargoTelepadComponent.cs +++ b/Content.Server/Cargo/Components/CargoTelepadComponent.cs @@ -25,6 +25,7 @@ namespace Content.Server.Cargo.Components [RegisterComponent] public class CargoTelepadComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; public override string Name => "CargoTelepad"; @@ -67,14 +68,14 @@ namespace Content.Server.Cargo.Components { if (args.Powered && _currentState == CargoTelepadState.Unpowered) { _currentState = CargoTelepadState.Idle; - if(Owner.TryGetComponent(out var spriteComponent) && spriteComponent.LayerCount > 0) + if(_entMan.TryGetComponent(Owner, out var spriteComponent) && spriteComponent.LayerCount > 0) spriteComponent.LayerSetState(0, "idle"); TeleportLoop(); } else if (!args.Powered) { _currentState = CargoTelepadState.Unpowered; - if (Owner.TryGetComponent(out var spriteComponent) && spriteComponent.LayerCount > 0) + if (_entMan.TryGetComponent(Owner, out var spriteComponent) && spriteComponent.LayerCount > 0) spriteComponent.LayerSetState(0, "offline"); } } @@ -83,23 +84,23 @@ namespace Content.Server.Cargo.Components if (_currentState == CargoTelepadState.Idle && _teleportQueue.Count > 0) { _currentState = CargoTelepadState.Charging; - if (Owner.TryGetComponent(out var spriteComponent) && spriteComponent.LayerCount > 0) + if (_entMan.TryGetComponent(Owner, out var spriteComponent) && spriteComponent.LayerCount > 0) spriteComponent.LayerSetState(0, "idle"); Owner.SpawnTimer((int) (TeleportDelay * 1000), () => { - if (!Deleted && !Owner.Deleted && _currentState == CargoTelepadState.Charging && _teleportQueue.Count > 0) + if (!Deleted && !_entMan.Deleted(Owner) && _currentState == CargoTelepadState.Charging && _teleportQueue.Count > 0) { _currentState = CargoTelepadState.Teleporting; - if (Owner.TryGetComponent(out var spriteComponent) && spriteComponent.LayerCount > 0) + if (_entMan.TryGetComponent(Owner, out var spriteComponent) && spriteComponent.LayerCount > 0) spriteComponent.LayerSetState(0, "beam"); Owner.SpawnTimer((int) (TeleportDuration * 1000), () => { - if (!Deleted && !Owner.Deleted && _currentState == CargoTelepadState.Teleporting && _teleportQueue.Count > 0) + if (!Deleted && !((!_entMan.EntityExists(Owner) ? EntityLifeStage.Deleted : _entMan.GetComponent(Owner).EntityLifeStage) >= EntityLifeStage.Deleted) && _currentState == CargoTelepadState.Teleporting && _teleportQueue.Count > 0) { SoundSystem.Play(Filter.Pvs(Owner), _teleportSound.GetSound(), Owner, AudioParams.Default.WithVolume(-8f)); SpawnProduct(_teleportQueue[0]); _teleportQueue.RemoveAt(0); - if (Owner.TryGetComponent(out var spriteComponent) && spriteComponent.LayerCount > 0) + if (_entMan.TryGetComponent(Owner, out var spriteComponent) && spriteComponent.LayerCount > 0) spriteComponent.LayerSetState(0, "idle"); _currentState = CargoTelepadState.Idle; TeleportLoop(); @@ -119,17 +120,18 @@ namespace Content.Server.Cargo.Components if (!_prototypeManager.TryIndex(data.ProductId, out CargoProductPrototype? prototype)) return; - var product = Owner.EntityManager.SpawnEntity(prototype.Product, Owner.Transform.Coordinates); + var product = _entMan.SpawnEntity(prototype.Product, _entMan.GetComponent(Owner).Coordinates); - product.Transform.Anchored = false; + _entMan.GetComponent(product).Anchored = false; // spawn a piece of paper. - var printed = Owner.EntityManager.SpawnEntity(PrinterOutput, Owner.Transform.Coordinates); - if (!Owner.EntityManager.TryGetComponent(printed.Uid, out PaperComponent paper)) + var printed = _entMan.SpawnEntity(PrinterOutput, _entMan.GetComponent(Owner).Coordinates); + if (!_entMan.TryGetComponent(printed, out PaperComponent paper)) return; // fill in the order data - printed.Name = Loc.GetString("cargo-console-paper-print-name", ("orderNumber", data.OrderNumber)); + string val = Loc.GetString("cargo-console-paper-print-name", ("orderNumber", data.OrderNumber)); + _entMan.GetComponent(printed).EntityName = val; paper.SetContent(Loc.GetString( "cargo-console-paper-print-text", ("orderNumber", data.OrderNumber), @@ -138,9 +140,9 @@ namespace Content.Server.Cargo.Components ("approver", data.Approver))); // attempt to attach the label - if (Owner.EntityManager.TryGetComponent(product.Uid, out PaperLabelComponent label)) + if (_entMan.TryGetComponent(product, out PaperLabelComponent label)) { - EntitySystem.Get().TryInsert(OwnerUid, label.LabelSlot, printed); + EntitySystem.Get().TryInsert(Owner, label.LabelSlot, printed); } } diff --git a/Content.Server/CharacterAppearance/Components/MagicMirrorComponent.cs b/Content.Server/CharacterAppearance/Components/MagicMirrorComponent.cs index 75957f76d0..c980287e5e 100644 --- a/Content.Server/CharacterAppearance/Components/MagicMirrorComponent.cs +++ b/Content.Server/CharacterAppearance/Components/MagicMirrorComponent.cs @@ -17,6 +17,7 @@ namespace Content.Server.CharacterAppearance.Components [ComponentReference(typeof(IActivate))] public class MagicMirrorComponent : SharedMagicMirrorComponent, IActivate { + [Dependency] private readonly IEntityManager _entities = default!; [Dependency] private readonly SpriteAccessoryManager _spriteAccessoryManager = default!; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(MagicMirrorUiKey.Key); @@ -43,12 +44,12 @@ namespace Content.Server.CharacterAppearance.Components private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj) { - if (obj.Session.AttachedEntity == null) + if (obj.Session.AttachedEntity is not {Valid: true} player) { return; } - if (!obj.Session.AttachedEntity.TryGetComponent(out HumanoidAppearanceComponent? looks)) + if (!_entities.TryGetComponent(player, out HumanoidAppearanceComponent? looks)) { return; } @@ -91,17 +92,17 @@ namespace Content.Server.CharacterAppearance.Components break; } - EntitySystem.Get().ForceAppearanceUpdate(obj.Session.AttachedEntity.Uid); + EntitySystem.Get().ForceAppearanceUpdate(player); } void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { return; } - if (!eventArgs.User.TryGetComponent(out HumanoidAppearanceComponent? looks)) + if (!_entities.TryGetComponent(eventArgs.User, out HumanoidAppearanceComponent? looks)) { Owner.PopupMessage(eventArgs.User, Loc.GetString("magic-mirror-component-activate-user-has-no-hair")); return; diff --git a/Content.Server/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs b/Content.Server/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs index 1482c03c31..1866ff3c6b 100644 --- a/Content.Server/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs +++ b/Content.Server/CharacterAppearance/Systems/HumanoidAppearanceSystem.cs @@ -3,6 +3,7 @@ using Content.Shared.CharacterAppearance.Components; using Content.Shared.CharacterAppearance.Systems; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.CharacterAppearance.Systems { @@ -21,7 +22,7 @@ namespace Content.Server.CharacterAppearance.Systems { foreach (var (part, _) in body.Parts) { - if (part.Owner.TryGetComponent(out SpriteComponent? sprite)) + if (EntityManager.TryGetComponent(part.Owner, out SpriteComponent? sprite)) { sprite!.Color = component.Appearance.SkinColor; } diff --git a/Content.Server/CharacterInfo/CharacterInfoComponent.cs b/Content.Server/CharacterInfo/CharacterInfoComponent.cs index 3613fb2fe3..160724ab99 100644 --- a/Content.Server/CharacterInfo/CharacterInfoComponent.cs +++ b/Content.Server/CharacterInfo/CharacterInfoComponent.cs @@ -5,6 +5,7 @@ using Content.Server.Roles; using Content.Shared.CharacterInfo; using Content.Shared.Objectives; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Network; using Robust.Shared.Players; @@ -23,7 +24,7 @@ namespace Content.Server.CharacterInfo case RequestCharacterInfoMessage _: var conditions = new Dictionary>(); var jobTitle = "No Profession"; - if (Owner.TryGetComponent(out MindComponent? mindComponent)) + if (IoCManager.Resolve().TryGetComponent(Owner, out MindComponent? mindComponent)) { var mind = mindComponent.Mind; diff --git a/Content.Server/Chat/Commands/MeCommand.cs b/Content.Server/Chat/Commands/MeCommand.cs index e19c8d2879..94951e1dea 100644 --- a/Content.Server/Chat/Commands/MeCommand.cs +++ b/Content.Server/Chat/Commands/MeCommand.cs @@ -24,7 +24,7 @@ namespace Content.Server.Chat.Commands return; } - if (player.Status != SessionStatus.InGame || !player.AttachedEntityUid.HasValue) + if (player.Status != SessionStatus.InGame || player.AttachedEntity == null) return; if (args.Length < 1) @@ -49,7 +49,7 @@ namespace Content.Server.Chat.Commands return; } - chat.EntityMe(mindComponent.OwnedEntity, action); + chat.EntityMe(mindComponent.OwnedEntity.Value, action); } } } diff --git a/Content.Server/Chat/Commands/SayCommand.cs b/Content.Server/Chat/Commands/SayCommand.cs index 5a31e561d7..a35e51c3c0 100644 --- a/Content.Server/Chat/Commands/SayCommand.cs +++ b/Content.Server/Chat/Commands/SayCommand.cs @@ -5,6 +5,7 @@ using Content.Server.Players; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.Enums; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.Chat.Commands @@ -18,16 +19,21 @@ namespace Content.Server.Chat.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { - var player = shell.Player as IPlayerSession; - if (player == null) + if (shell.Player is not IPlayerSession player) { shell.WriteLine("This command cannot be run from the server."); return; } - if (player.Status != SessionStatus.InGame || !player.AttachedEntityUid.HasValue) + if (player.Status != SessionStatus.InGame) return; + if (player.AttachedEntity is not {} playerEntity) + { + shell.WriteLine("You don't have an entity!"); + return; + } + if (args.Length < 1) return; @@ -37,15 +43,8 @@ namespace Content.Server.Chat.Commands var chat = IoCManager.Resolve(); var chatSanitizer = IoCManager.Resolve(); - var playerEntity = player.AttachedEntity; - if (playerEntity == null) - { - shell.WriteLine("You don't have an entity!"); - return; - } - - if (playerEntity.HasComponent()) + if (IoCManager.Resolve().HasComponent(playerEntity)) chat.SendDeadChat(player, message); else { @@ -57,17 +56,17 @@ namespace Content.Server.Chat.Commands return; } - if (mindComponent.OwnedEntity == null) + if (mindComponent.OwnedEntity is not {Valid: true} owned) { shell.WriteError("You don't have an entity!"); return; } - var emote = chatSanitizer.TrySanitizeOutSmilies(message, mindComponent.OwnedEntity, out var sanitized, out var emoteStr); + var emote = chatSanitizer.TrySanitizeOutSmilies(message, owned, out var sanitized, out var emoteStr); if (sanitized.Length != 0) - chat.EntitySay(mindComponent.OwnedEntity, sanitized); + chat.EntitySay(owned, sanitized); if (emote) - chat.EntityMe(mindComponent.OwnedEntity, emoteStr!); + chat.EntityMe(owned, emoteStr!); } } diff --git a/Content.Server/Chat/Commands/SuicideCommand.cs b/Content.Server/Chat/Commands/SuicideCommand.cs index d4c32071be..82e5a4e45a 100644 --- a/Content.Server/Chat/Commands/SuicideCommand.cs +++ b/Content.Server/Chat/Commands/SuicideCommand.cs @@ -8,7 +8,6 @@ using Content.Server.Hands.Components; using Content.Server.Items; using Content.Server.Players; using Content.Server.Popups; -using Content.Shared.Administration.Logs; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.Database; @@ -26,13 +25,15 @@ namespace Content.Server.Chat.Commands [AnyCommand] internal class SuicideCommand : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "suicide"; public string Description => Loc.GetString("suicide-command-description"); public string Help => Loc.GetString("suicide-command-help-text"); - private void DealDamage(ISuicideAct suicide, IChatManager chat, IEntity target) + private void DealDamage(ISuicideAct suicide, IChatManager chat, EntityUid target) { var kind = suicide.Suicide(target, chat); if (kind != SuicideKind.Special) @@ -54,7 +55,7 @@ namespace Content.Server.Chat.Commands _ => prototypeManager.Index("Blunt") }, 200); - EntitySystem.Get().TryChangeDamage(target.Uid, damage, true); + EntitySystem.Get().TryChangeDamage(target, damage, true); } } @@ -72,10 +73,9 @@ namespace Content.Server.Chat.Commands var chat = IoCManager.Resolve(); var mind = player.ContentData()?.Mind; - var owner = mind?.OwnedComponent?.Owner; // This check also proves mind not-null for at the end when the mob is ghosted. - if (owner == null) + if (mind?.OwnedComponent?.Owner is not {Valid: true} owner) { shell.WriteLine("You don't have a mind!"); return; @@ -87,11 +87,11 @@ namespace Content.Server.Chat.Commands EntitySystem.Get().Add(LogType.Suicide, $"{player.AttachedEntity} is committing suicide"); // Held item suicide - var handsComponent = owner.GetComponent(); + var handsComponent = _entities.GetComponent(owner); var itemComponent = handsComponent.GetActiveHand; if (itemComponent != null) { - var suicide = itemComponent.Owner.GetAllComponents().FirstOrDefault(); + var suicide = _entities.GetComponents(itemComponent.Owner).FirstOrDefault(); if (suicide != null) { @@ -106,9 +106,9 @@ namespace Content.Server.Chat.Commands { foreach (var entity in entities) { - if (entity.HasComponent()) + if (_entities.HasComponent(entity)) continue; - var suicide = entity.GetAllComponents().FirstOrDefault(); + var suicide = _entities.GetComponents(entity).FirstOrDefault(); if (suicide != null) { DealDamage(suicide, chat, owner); @@ -125,7 +125,7 @@ namespace Content.Server.Chat.Commands owner.PopupMessage(selfMessage); DamageSpecifier damage = new(IoCManager.Resolve().Index("Bloodloss"), 200); - EntitySystem.Get().TryChangeDamage(owner.Uid, damage, true); + EntitySystem.Get().TryChangeDamage(owner, damage, true); // Prevent the player from returning to the body. // Note that mind cannot be null because otherwise owner would be null. diff --git a/Content.Server/Chat/Managers/ChatManager.cs b/Content.Server/Chat/Managers/ChatManager.cs index cbad133f93..02cb35f2f4 100644 --- a/Content.Server/Chat/Managers/ChatManager.cs +++ b/Content.Server/Chat/Managers/ChatManager.cs @@ -114,15 +114,15 @@ namespace Content.Server.Chat.Managers _netManager.ServerSendMessage(msg, player.ConnectedClient); } - public void EntitySay(IEntity source, string message, bool hideChat=false) + public void EntitySay(EntityUid source, string message, bool hideChat=false) { - if (!EntitySystem.Get().CanSpeak(source.Uid)) + if (!EntitySystem.Get().CanSpeak(source)) { return; } // Check if message exceeds the character limit if the sender is a player - if (source.TryGetComponent(out ActorComponent? actor) && + if (_entManager.TryGetComponent(source, out ActorComponent? actor) && message.Length > MaxMessageLength) { var feedback = Loc.GetString("chat-manager-max-message-length-exceeded-message", ("limit", MaxMessageLength)); @@ -135,26 +135,29 @@ namespace Content.Server.Chat.Managers foreach (var handler in _chatTransformHandlers) { //TODO: rather return a bool and use a out var? - message = handler(source.Uid, message); + message = handler(source, message); } message = message.Trim(); // We'll try to avoid using MapPosition as EntityCoordinates can early-out and potentially be faster for common use cases // Downside is it may potentially convert to MapPosition unnecessarily. - var sourceMapId = source.Transform.MapID; - var sourceCoords = source.Transform.Coordinates; + var sourceMapId = _entManager.GetComponent(source).MapID; + var sourceCoords = _entManager.GetComponent(source).Coordinates; var clients = new List(); foreach (var player in _playerManager.Sessions) { - if (player.AttachedEntity == null) continue; - var transform = player.AttachedEntity.Transform; + if (player.AttachedEntity is not {Valid: true} playerEntity) + continue; + + var transform = _entManager.GetComponent(playerEntity); if (transform.MapID != sourceMapId || - !player.AttachedEntity.HasComponent() && - !sourceCoords.InRange(_entManager, transform.Coordinates, VoiceRange)) continue; + !_entManager.HasComponent(playerEntity) && + !sourceCoords.InRange(_entManager, transform.Coordinates, VoiceRange)) + continue; clients.Add(player.ConnectedClient); } @@ -168,9 +171,9 @@ namespace Content.Server.Chat.Managers message = message[0].ToString().ToUpper() + message.Remove(0, 1); - if (source.TryGetComponent(out InventoryComponent? inventory) && + if (_entManager.TryGetComponent(source, out InventoryComponent? inventory) && inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.EARS, out ItemComponent? item) && - item.Owner.TryGetComponent(out HeadsetComponent? headset)) + _entManager.TryGetComponent(item.Owner, out HeadsetComponent? headset)) { headset.RadioRequested = true; } @@ -194,21 +197,21 @@ namespace Content.Server.Chat.Managers var msg = _netManager.CreateNetMessage(); msg.Channel = ChatChannel.Local; msg.Message = message; - msg.MessageWrap = Loc.GetString("chat-manager-entity-say-wrap-message",("entityName", source.Name)); - msg.SenderEntity = source.Uid; + msg.MessageWrap = Loc.GetString("chat-manager-entity-say-wrap-message",("entityName", Name: _entManager.GetComponent(source).EntityName)); + msg.SenderEntity = source; msg.HideChat = hideChat; _netManager.ServerSendToMany(msg, clients); } - public void EntityMe(IEntity source, string action) + public void EntityMe(EntityUid source, string action) { - if (!EntitySystem.Get().CanEmote(source.Uid)) + if (!EntitySystem.Get().CanEmote(source)) { return; } // Check if entity is a player - if (!source.TryGetComponent(out ActorComponent? actor)) + if (!_entManager.TryGetComponent(source, out ActorComponent? actor)) { return; } @@ -223,7 +226,7 @@ namespace Content.Server.Chat.Managers action = FormattedMessage.EscapeText(action); var clients = Filter.Empty() - .AddInRange(source.Transform.MapPosition, VoiceRange) + .AddInRange(_entManager.GetComponent(source).MapPosition, VoiceRange) .Recipients .Select(p => p.ConnectedClient) .ToList(); @@ -231,8 +234,8 @@ namespace Content.Server.Chat.Managers var msg = _netManager.CreateNetMessage(); msg.Channel = ChatChannel.Emotes; msg.Message = action; - msg.MessageWrap = Loc.GetString("chat-manager-entity-me-wrap-message", ("entityName",source.Name)); - msg.SenderEntity = source.Uid; + msg.MessageWrap = Loc.GetString("chat-manager-entity-me-wrap-message", ("entityName",Name: _entManager.GetComponent(source).EntityName)); + msg.SenderEntity = source; _netManager.ServerSendToMany(msg, clients); } @@ -296,10 +299,14 @@ namespace Content.Server.Chat.Managers var msg = _netManager.CreateNetMessage(); msg.Channel = ChatChannel.Dead; msg.Message = message; + + var playerName = player.AttachedEntity is {Valid: true} playerEntity + ? _entManager.GetComponent(playerEntity).EntityName + : "???"; msg.MessageWrap = Loc.GetString("chat-manager-send-dead-chat-wrap-message", ("deadChannelName", Loc.GetString("chat-manager-dead-channel-name")), - ("playerName", player.AttachedEntity?.Name ?? "???")); - msg.SenderEntity = player.AttachedEntityUid.GetValueOrDefault(); + ("playerName", (playerName))); + msg.SenderEntity = player.AttachedEntity.GetValueOrDefault(); _netManager.ServerSendToMany(msg, clients.ToList()); } diff --git a/Content.Server/Chat/Managers/ChatSanitizationManager.cs b/Content.Server/Chat/Managers/ChatSanitizationManager.cs index 65a4cc04ba..af246e8f0f 100644 --- a/Content.Server/Chat/Managers/ChatSanitizationManager.cs +++ b/Content.Server/Chat/Managers/ChatSanitizationManager.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; @@ -69,7 +68,7 @@ public class ChatSanitizationManager : IChatSanitizationManager _configurationManager.OnValueChanged(CCVars.ChatSanitizerEnabled, x => doSanitize = x, true); } - public bool TrySanitizeOutSmilies(string input, IEntity speaker, out string sanitized, [NotNullWhen(true)] out string? emote) + public bool TrySanitizeOutSmilies(string input, EntityUid speaker, out string sanitized, [NotNullWhen(true)] out string? emote) { if (!doSanitize) { diff --git a/Content.Server/Chat/Managers/IChatManager.cs b/Content.Server/Chat/Managers/IChatManager.cs index 28c1aec2b9..abf7cd2032 100644 --- a/Content.Server/Chat/Managers/IChatManager.cs +++ b/Content.Server/Chat/Managers/IChatManager.cs @@ -23,8 +23,8 @@ namespace Content.Server.Chat.Managers void DispatchServerMessage(IPlayerSession player, string message); /// If true, message will not be logged to chat boxes but will still produce a speech bubble. - void EntitySay(IEntity source, string message, bool hideChat=false); - void EntityMe(IEntity source, string action); + void EntitySay(EntityUid source, string message, bool hideChat=false); + void EntityMe(EntityUid source, string action); void SendOOC(IPlayerSession player, string message); void SendAdminChat(IPlayerSession player, string message); diff --git a/Content.Server/Chat/Managers/IChatSanitizationManager.cs b/Content.Server/Chat/Managers/IChatSanitizationManager.cs index ebd2a79b03..4538a9d655 100644 --- a/Content.Server/Chat/Managers/IChatSanitizationManager.cs +++ b/Content.Server/Chat/Managers/IChatSanitizationManager.cs @@ -7,5 +7,5 @@ public interface IChatSanitizationManager { public void Initialize(); - public bool TrySanitizeOutSmilies(string input, IEntity speaker, out string sanitized, [NotNullWhen(true)] out string? emote); + public bool TrySanitizeOutSmilies(string input, EntityUid speaker, out string sanitized, [NotNullWhen(true)] out string? emote); } diff --git a/Content.Server/Chemistry/Components/ChemMasterComponent.cs b/Content.Server/Chemistry/Components/ChemMasterComponent.cs index c0e21b0d99..afba36220f 100644 --- a/Content.Server/Chemistry/Components/ChemMasterComponent.cs +++ b/Content.Server/Chemistry/Components/ChemMasterComponent.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; -using System.Threading.Tasks; using Content.Server.Chemistry.Components.SolutionManager; using Content.Server.Chemistry.EntitySystems; using Content.Server.Hands.Components; using Content.Server.Items; -using Content.Server.Sprite; +using Content.Server.Labels.Components; using Content.Server.Power.Components; using Content.Server.UserInterface; using Content.Shared.ActionBlocker; @@ -18,14 +17,12 @@ using Content.Shared.Random.Helpers; using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Shared.Audio; -using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; -using Robust.Shared.Log; -using Content.Server.Labels.Components; namespace Content.Server.Chemistry.Components { @@ -40,6 +37,8 @@ namespace Content.Server.Chemistry.Components [ComponentReference(typeof(SharedChemMasterComponent))] public class ChemMasterComponent : SharedChemMasterComponent, IActivate { + [Dependency] private readonly IEntityManager _entities = default!; + [ViewVariables] private uint _pillType = 1; @@ -50,10 +49,10 @@ namespace Content.Server.Chemistry.Components private bool _bufferModeTransfer = true; [ViewVariables] - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; [ViewVariables] - private Solution BufferSolution => _bufferSolution ??= EntitySystem.Get().EnsureSolution(Owner.Uid, SolutionName); + private Solution BufferSolution => _bufferSolution ??= EntitySystem.Get().EnsureSolution(Owner, SolutionName); private Solution? _bufferSolution; @@ -71,13 +70,13 @@ namespace Content.Server.Chemistry.Components protected override void Initialize() { base.Initialize(); - + if (UserInterface != null) { UserInterface.OnReceiveMessage += OnUiReceiveMessage; } - _bufferSolution = EntitySystem.Get().EnsureSolution(Owner.Uid, SolutionName); + _bufferSolution = EntitySystem.Get().EnsureSolution(Owner, SolutionName); } [Obsolete("Component Messages are deprecated, use Entity Events instead.")] @@ -106,7 +105,7 @@ namespace Content.Server.Chemistry.Components /// A user interface message from the client. private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj) { - if (obj.Session.AttachedEntity == null) + if (obj.Session.AttachedEntity is not {Valid: true} player) return; var msg = (UiActionMessage) obj.Message; @@ -116,13 +115,13 @@ namespace Content.Server.Chemistry.Components _ => true, }; - if (!PlayerCanUseChemMaster(obj.Session.AttachedEntity, needsPower)) + if (!PlayerCanUseChemMaster(player, needsPower)) return; switch (msg.Action) { case UiAction.Eject: - EntitySystem.Get().TryEjectToHands(OwnerUid, BeakerSlot, obj.Session.AttachedEntityUid); + EntitySystem.Get().TryEjectToHands(Owner, BeakerSlot, player); break; case UiAction.ChemButton: TransferReagent(msg.Id, msg.Amount, msg.IsBuffer); @@ -142,7 +141,7 @@ namespace Content.Server.Chemistry.Components case UiAction.CreatePills: case UiAction.CreateBottles: _label = msg.Label; - TryCreatePackage(obj.Session.AttachedEntity, msg.Action, msg.Label, msg.PillAmount, msg.BottleAmount); + TryCreatePackage(player, msg.Action, msg.Label, msg.PillAmount, msg.BottleAmount); break; default: throw new ArgumentOutOfRangeException(); @@ -157,16 +156,16 @@ namespace Content.Server.Chemistry.Components /// The player entity. /// whether the device requires power /// Returns true if the entity can use the chem master, and false if it cannot. - private bool PlayerCanUseChemMaster(IEntity? playerEntity, bool needsPower = true) + private bool PlayerCanUseChemMaster(EntityUid playerEntity, bool needsPower = true) { //Need player entity to check if they are still able to use the chem master - if (playerEntity == null) + if (playerEntity == default) return false; var actionBlocker = EntitySystem.Get(); //Check if player can interact in their current state - if (!actionBlocker.CanInteract(playerEntity.Uid) || !actionBlocker.CanUse(playerEntity.Uid)) + if (!actionBlocker.CanInteract(playerEntity) || !actionBlocker.CanUse(playerEntity)) return false; //Check if device is powered if (needsPower && !Powered) @@ -181,18 +180,18 @@ namespace Content.Server.Chemistry.Components /// Returns a private ChemMasterBoundUserInterfaceState GetUserInterfaceState() { - var beaker = BeakerSlot.Item; - if (beaker is null || !beaker.TryGetComponent(out FitsInDispenserComponent? fits) || - !EntitySystem.Get().TryGetSolution(beaker.Uid, fits.Solution, out var beakerSolution)) + if (BeakerSlot.Item is not {Valid: true} beaker || + !_entities.TryGetComponent(beaker, out FitsInDispenserComponent? fits) || + !EntitySystem.Get().TryGetSolution(beaker, fits.Solution, out var beakerSolution)) { return new ChemMasterBoundUserInterfaceState(Powered, false, FixedPoint2.New(0), FixedPoint2.New(0), - "", _label, Owner.Name, new List(), BufferSolution.Contents, _bufferModeTransfer, + "", _label, _entities.GetComponent(Owner).EntityName, new List(), BufferSolution.Contents, _bufferModeTransfer, BufferSolution.TotalVolume, _pillType); } return new ChemMasterBoundUserInterfaceState(Powered, true, beakerSolution.CurrentVolume, beakerSolution.MaxVolume, - beaker.Name, _label, Owner.Name, beakerSolution.Contents, BufferSolution.Contents, _bufferModeTransfer, + _entities.GetComponent(beaker).EntityName, _label, _entities.GetComponent(Owner).EntityName, beakerSolution.Contents, BufferSolution.Contents, _bufferModeTransfer, BufferSolution.TotalVolume, _pillType); } @@ -204,11 +203,12 @@ namespace Content.Server.Chemistry.Components private void TransferReagent(string id, FixedPoint2 amount, bool isBuffer) { - if (!BeakerSlot.HasItem && _bufferModeTransfer) return; - var beaker = BeakerSlot.Item; + if (!BeakerSlot.HasItem && _bufferModeTransfer) + return; - if (beaker is null || !beaker.TryGetComponent(out FitsInDispenserComponent? fits) || - !EntitySystem.Get().TryGetSolution(beaker.Uid, fits.Solution, out var beakerSolution)) + if (BeakerSlot.Item is not {Valid: true} beaker || + !_entities.TryGetComponent(beaker, out FitsInDispenserComponent? fits) || + !EntitySystem.Get().TryGetSolution(beaker, fits.Solution, out var beakerSolution)) return; if (isBuffer) @@ -234,7 +234,7 @@ namespace Content.Server.Chemistry.Components if (_bufferModeTransfer) { EntitySystem.Get() - .TryAddReagent(beaker.Uid, beakerSolution, id, actualAmount, out var _); + .TryAddReagent(beaker, beakerSolution, id, actualAmount, out var _); // beakerSolution.Solution.AddReagent(id, actualAmount); } @@ -257,8 +257,8 @@ namespace Content.Server.Chemistry.Components { actualAmount = FixedPoint2.Min(reagent.Quantity, amount); } - - EntitySystem.Get().TryRemoveReagent(beaker.Uid, beakerSolution, id, actualAmount); + + EntitySystem.Get().TryRemoveReagent(beaker, beakerSolution, id, actualAmount); BufferSolution.AddReagent(id, actualAmount); break; } @@ -281,7 +281,7 @@ namespace Content.Server.Chemistry.Components return _bufferSolution.Contents[_bufferSolution.Contents.Count - 1].ReagentId; } - private void TryCreatePackage(IEntity user, UiAction action, string label, int pillAmount, int bottleAmount) + private void TryCreatePackage(EntityUid user, UiAction action, string label, int pillAmount, int bottleAmount) { if (BufferSolution.TotalVolume == 0) { @@ -301,22 +301,23 @@ namespace Content.Server.Chemistry.Components var actualVolume = FixedPoint2.Min(individualVolume, FixedPoint2.New(30)); for (int i = 0; i < bottleAmount; i++) { - var bottle = Owner.EntityManager.SpawnEntity("ChemistryEmptyBottle01", Owner.Transform.Coordinates); + var bottle = _entities.SpawnEntity("ChemistryEmptyBottle01", _entities.GetComponent(Owner).Coordinates); //Adding label LabelComponent labelComponent = bottle.EnsureComponent(); - labelComponent.OriginalName = bottle.Name; - bottle.Name += $" ({label})"; + labelComponent.OriginalName = _entities.GetComponent(bottle).EntityName; + string val = _entities.GetComponent(bottle).EntityName + $" ({label})"; + _entities.GetComponent(bottle).EntityName = val; labelComponent.CurrentLabel = label; var bufferSolution = BufferSolution.SplitSolution(actualVolume); - var bottleSolution = EntitySystem.Get().EnsureSolution(bottle.Uid, "drink"); + var bottleSolution = EntitySystem.Get().EnsureSolution(bottle, "drink"); - EntitySystem.Get().TryAddSolution(bottle.Uid, bottleSolution, bufferSolution); + EntitySystem.Get().TryAddSolution(bottle, bottleSolution, bufferSolution); //Try to give them the bottle - if (user.TryGetComponent(out var hands) && - bottle.TryGetComponent(out var item)) + if (_entities.TryGetComponent(user, out var hands) && + _entities.TryGetComponent(bottle, out var item)) { if (hands.CanPutInHand(item)) { @@ -326,7 +327,7 @@ namespace Content.Server.Chemistry.Components } //Put it on the floor - bottle.Transform.Coordinates = user.Transform.Coordinates; + _entities.GetComponent(bottle).Coordinates = _entities.GetComponent(user).Coordinates; //Give it an offset bottle.RandomOffset(0.2f); } @@ -343,28 +344,29 @@ namespace Content.Server.Chemistry.Components var actualVolume = FixedPoint2.Min(individualVolume, FixedPoint2.New(50)); for (int i = 0; i < pillAmount; i++) { - var pill = Owner.EntityManager.SpawnEntity("pill", Owner.Transform.Coordinates); + var pill = _entities.SpawnEntity("pill", _entities.GetComponent(Owner).Coordinates); //Adding label LabelComponent labelComponent = pill.EnsureComponent(); - labelComponent.OriginalName = pill.Name; - pill.Name += $" ({label})"; + labelComponent.OriginalName = _entities.GetComponent(pill).EntityName; + string val = _entities.GetComponent(pill).EntityName + $" ({label})"; + _entities.GetComponent(pill).EntityName = val; labelComponent.CurrentLabel = label; var bufferSolution = BufferSolution.SplitSolution(actualVolume); - var pillSolution = EntitySystem.Get().EnsureSolution(pill.Uid, "food"); - EntitySystem.Get().TryAddSolution(pill.Uid, pillSolution, bufferSolution); + var pillSolution = EntitySystem.Get().EnsureSolution(pill, "food"); + EntitySystem.Get().TryAddSolution(pill, pillSolution, bufferSolution); //Change pill Sprite component state - if (!pill.TryGetComponent(out SpriteComponent? sprite)) + if (!_entities.TryGetComponent(pill, out SpriteComponent? sprite)) { return; } sprite?.LayerSetState(0, "pill" + _pillType); //Try to give them the bottle - if (user.TryGetComponent(out var hands) && - pill.TryGetComponent(out var item)) + if (_entities.TryGetComponent(user, out var hands) && + _entities.TryGetComponent(pill, out var item)) { if (hands.CanPutInHand(item)) { @@ -374,7 +376,7 @@ namespace Content.Server.Chemistry.Components } //Put it on the floor - pill.Transform.Coordinates = user.Transform.Coordinates; + _entities.GetComponent(pill).Coordinates = _entities.GetComponent(user).Coordinates; //Give it an offset pill.RandomOffset(0.2f); } @@ -392,12 +394,12 @@ namespace Content.Server.Chemistry.Components /// Data relevant to the event such as the actor which triggered it. void IActivate.Activate(ActivateEventArgs args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!_entities.TryGetComponent(args.User, out ActorComponent? actor)) { return; } - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!_entities.TryGetComponent(args.User, out HandsComponent? hands)) { Owner.PopupMessage(args.User, Loc.GetString("chem-master-component-activate-no-hands")); return; diff --git a/Content.Server/Chemistry/Components/FoamSolutionAreaEffectComponent.cs b/Content.Server/Chemistry/Components/FoamSolutionAreaEffectComponent.cs index dfbf930a8d..8599d5d773 100644 --- a/Content.Server/Chemistry/Components/FoamSolutionAreaEffectComponent.cs +++ b/Content.Server/Chemistry/Components/FoamSolutionAreaEffectComponent.cs @@ -7,6 +7,7 @@ using Content.Shared.FixedPoint; using Content.Shared.Foam; using Content.Shared.Inventory; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Chemistry.Components @@ -15,6 +16,8 @@ namespace Content.Server.Chemistry.Components [ComponentReference(typeof(SolutionAreaEffectComponent))] public class FoamSolutionAreaEffectComponent : SolutionAreaEffectComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "FoamSolutionAreaEffect"; public new const string SolutionName = "solutionArea"; @@ -22,25 +25,25 @@ namespace Content.Server.Chemistry.Components protected override void UpdateVisuals() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance) && - EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance) && + EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { appearance.SetData(FoamVisuals.Color, solution.Color.WithAlpha(0.80f)); } } - protected override void ReactWithEntity(IEntity entity, double solutionFraction) + protected override void ReactWithEntity(EntityUid entity, double solutionFraction) { - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) return; - if (!entity.TryGetComponent(out BloodstreamComponent? bloodstream)) + if (!_entMan.TryGetComponent(entity, out BloodstreamComponent? bloodstream)) return; // TODO: Add a permeability property to clothing // For now it just adds to protection for each clothing equipped var protection = 0f; - if (entity.TryGetComponent(out InventoryComponent? inventory)) + if (_entMan.TryGetComponent(entity, out InventoryComponent? inventory)) { foreach (var slot in inventory.Slots) { @@ -62,14 +65,14 @@ namespace Content.Server.Chemistry.Components bloodstream.Solution.AvailableVolume); var transferSolution = cloneSolution.SplitSolution(transferAmount); - bloodstreamSys.TryAddToBloodstream(entity.Uid, transferSolution, bloodstream); + bloodstreamSys.TryAddToBloodstream(entity, transferSolution, bloodstream); } protected override void OnKill() { - if (Owner.Deleted) + if (_entMan.Deleted(Owner)) return; - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(FoamVisuals.State, true); } @@ -78,10 +81,10 @@ namespace Content.Server.Chemistry.Components { if (!string.IsNullOrEmpty(_foamedMetalPrototype)) { - Owner.EntityManager.SpawnEntity(_foamedMetalPrototype, Owner.Transform.Coordinates); + _entMan.SpawnEntity(_foamedMetalPrototype, _entMan.GetComponent(Owner).Coordinates); } - Owner.QueueDelete(); + _entMan.QueueDeleteEntity(Owner); }); } } diff --git a/Content.Server/Chemistry/Components/HyposprayComponent.cs b/Content.Server/Chemistry/Components/HyposprayComponent.cs index 0d3f23559e..8512a34109 100644 --- a/Content.Server/Chemistry/Components/HyposprayComponent.cs +++ b/Content.Server/Chemistry/Components/HyposprayComponent.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using Content.Server.Chemistry.Components.SolutionManager; using Content.Server.Chemistry.EntitySystems; using Content.Server.Interaction.Components; @@ -10,10 +11,10 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -22,6 +23,8 @@ namespace Content.Server.Chemistry.Components [RegisterComponent] public sealed class HyposprayComponent : SharedHyposprayComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + [DataField("clumsyFailChance")] [ViewVariables(VVAccess.ReadWrite)] public float ClumsyFailChance { get; set; } = 0.5f; @@ -40,9 +43,9 @@ namespace Content.Server.Chemistry.Components Dirty(); } - public bool TryDoInject(IEntity? target, IEntity user) + public bool TryDoInject(EntityUid? target, EntityUid user) { - if (target == null || !EligibleEntity(target)) + if (!EligibleEntity(target, _entMan)) return false; string? msgFormat = null; @@ -51,14 +54,14 @@ namespace Content.Server.Chemistry.Components { msgFormat = "hypospray-component-inject-self-message"; } - else if (EligibleEntity(user) && ClumsyComponent.TryRollClumsy(user, ClumsyFailChance)) + else if (EligibleEntity(user, _entMan) && ClumsyComponent.TryRollClumsy(user, ClumsyFailChance)) { msgFormat = "hypospray-component-inject-self-clumsy-message"; target = user; } var solutionsSys = EntitySystem.Get(); - solutionsSys.TryGetSolution(Owner.Uid, SolutionName, out var hypoSpraySolution); + solutionsSys.TryGetSolution(Owner, SolutionName, out var hypoSpraySolution); if (hypoSpraySolution == null || hypoSpraySolution.CurrentVolume == 0) { @@ -66,7 +69,7 @@ namespace Content.Server.Chemistry.Components return true; } - if (!solutionsSys.TryGetInjectableSolution(target.Uid, out var targetSolution)) + if (!solutionsSys.TryGetInjectableSolution(target.Value, out var targetSolution)) { user.PopupMessage(user, Loc.GetString("hypospray-cant-inject", ("target", target))); @@ -77,9 +80,9 @@ namespace Content.Server.Chemistry.Components ("other", target))); if (target != user) { - target.PopupMessage(Loc.GetString("hypospray-component-feel-prick-message")); + target.Value.PopupMessage(Loc.GetString("hypospray-component-feel-prick-message")); var meleeSys = EntitySystem.Get(); - var angle = Angle.FromWorldVec(target.Transform.WorldPosition - user.Transform.WorldPosition); + var angle = Angle.FromWorldVec(_entMan.GetComponent(target.Value).WorldPosition - _entMan.GetComponent(user).WorldPosition); meleeSys.SendLunge(angle, user); } @@ -99,24 +102,24 @@ namespace Content.Server.Chemistry.Components // Move units from attackSolution to targetSolution var removedSolution = EntitySystem.Get() - .SplitSolution(Owner.Uid, hypoSpraySolution, realTransferAmount); + .SplitSolution(Owner, hypoSpraySolution, realTransferAmount); if (!targetSolution.CanAddSolution(removedSolution)) { return true; } - removedSolution.DoEntityReaction(target.Uid, ReactionMethod.Injection); + removedSolution.DoEntityReaction(target.Value, ReactionMethod.Injection); - EntitySystem.Get().TryAddSolution(target.Uid, targetSolution, removedSolution); + EntitySystem.Get().TryAddSolution(target.Value, targetSolution, removedSolution); - static bool EligibleEntity(IEntity entity) + static bool EligibleEntity([NotNullWhen(true)] EntityUid? entity, IEntityManager entMan) { // TODO: Does checking for BodyComponent make sense as a "can be hypospray'd" tag? // In SS13 the hypospray ONLY works on mobs, NOT beakers or anything else. - return entity.HasComponent() - && entity.HasComponent(); + return entMan.HasComponent(entity) + && entMan.HasComponent(entity); } return true; @@ -124,8 +127,8 @@ namespace Content.Server.Chemistry.Components public override ComponentState GetComponentState() { - var solutionSys = Owner.EntityManager.EntitySysManager.GetEntitySystem(); - return solutionSys.TryGetSolution(Owner.Uid, SolutionName, out var solution) + var solutionSys = _entMan.EntitySysManager.GetEntitySystem(); + return solutionSys.TryGetSolution(Owner, SolutionName, out var solution) ? new HyposprayComponentState(solution.CurrentVolume, solution.MaxVolume) : new HyposprayComponentState(FixedPoint2.Zero, FixedPoint2.Zero); } diff --git a/Content.Server/Chemistry/Components/InjectorComponent.cs b/Content.Server/Chemistry/Components/InjectorComponent.cs index 446f6e935a..292721c0dd 100644 --- a/Content.Server/Chemistry/Components/InjectorComponent.cs +++ b/Content.Server/Chemistry/Components/InjectorComponent.cs @@ -19,6 +19,7 @@ using Content.Shared.Interaction.Helpers; using Content.Shared.MobState.Components; using Content.Shared.Popups; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Players; @@ -35,6 +36,8 @@ namespace Content.Server.Chemistry.Components [RegisterComponent] public class InjectorComponent : SharedInjectorComponent, IAfterInteract, IUse { + [Dependency] private readonly IEntityManager _entities = default!; + public const string SolutionName = "injector"; /// @@ -98,7 +101,7 @@ namespace Content.Server.Chemistry.Components /// /// Toggle between draw/inject state if applicable /// - private void Toggle(IEntity user) + private void Toggle(EntityUid user) { if (_injectOnly) { @@ -138,38 +141,37 @@ namespace Content.Server.Chemistry.Components if (!eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true)) return false; - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if (!EntitySystem.Get().CanInteract(eventArgs.User)) return false; var solutionsSys = EntitySystem.Get(); //Make sure we have the attacking entity - if (eventArgs.Target == null || !Owner.HasComponent()) + if (eventArgs.Target is not {Valid: true} target || + !_entities.HasComponent(Owner)) { return false; } - var targetEntity = eventArgs.Target; - // Is the target a mob? If yes, use a do-after to give them time to respond. - if (Owner.EntityManager.HasComponent(targetEntity.Uid) || - Owner.EntityManager.HasComponent(targetEntity.Uid)) + if (_entities.HasComponent(target) || + _entities.HasComponent(target)) { - if (!await TryInjectDoAfter(eventArgs.User.Uid, eventArgs.Target.Uid)) + if (!await TryInjectDoAfter(eventArgs.User, target)) return true; } // Handle injecting/drawing for solutions if (ToggleState == InjectorToggleMode.Inject) { - if (solutionsSys.TryGetInjectableSolution(targetEntity.Uid, out var injectableSolution)) + if (solutionsSys.TryGetInjectableSolution(target, out var injectableSolution)) { - TryInject(targetEntity, injectableSolution, eventArgs.User, false); + TryInject(target, injectableSolution, eventArgs.User, false); } - else if (solutionsSys.TryGetRefillableSolution(targetEntity.Uid, out var refillableSolution)) + else if (solutionsSys.TryGetRefillableSolution(target, out var refillableSolution)) { - TryInject(targetEntity, refillableSolution, eventArgs.User, true); + TryInject(target, refillableSolution, eventArgs.User, true); } - else if (targetEntity.TryGetComponent(out BloodstreamComponent? bloodstream)) + else if (_entities.TryGetComponent(target, out BloodstreamComponent? bloodstream)) { TryInjectIntoBloodstream(bloodstream, eventArgs.User); } @@ -177,20 +179,20 @@ namespace Content.Server.Chemistry.Components { eventArgs.User.PopupMessage(eventArgs.User, Loc.GetString("injector-component-cannot-transfer-message", - ("target", targetEntity))); + ("target", target))); } } else if (ToggleState == InjectorToggleMode.Draw) { - if (solutionsSys.TryGetDrawableSolution(targetEntity.Uid, out var drawableSolution)) + if (solutionsSys.TryGetDrawableSolution(target, out var drawableSolution)) { - TryDraw(targetEntity, drawableSolution, eventArgs.User); + TryDraw(target, drawableSolution, eventArgs.User); } else { eventArgs.User.PopupMessage(eventArgs.User, Loc.GetString("injector-component-cannot-draw-message", - ("target", targetEntity))); + ("target", target))); } } @@ -208,25 +210,24 @@ namespace Content.Server.Chemistry.Components popupSys.PopupEntity(Loc.GetString("injector-component-injecting-user"), target, Filter.Entities(user)); // Get entity for logging. Log with EntityUids when? - var userEntity = Owner.EntityManager.GetEntity(user); var logSys = EntitySystem.Get(); var actualDelay = MathF.Max(Delay, 1f); if (user != target) { // Create a pop-up for the target - var userName = Owner.EntityManager.GetComponent(user).EntityName; + var userName = _entities.GetComponent(user).EntityName; popupSys.PopupEntity(Loc.GetString("injector-component-injecting-target", ("user", userName)), user, Filter.Entities(target)); // Check if the target is incapacitated or in combat mode and modify time accordingly. - if (Owner.EntityManager.TryGetComponent(target, out var mobState) && + if (_entities.TryGetComponent(target, out var mobState) && mobState.IsIncapacitated()) { actualDelay /= 2; } - else if (Owner.EntityManager.TryGetComponent(target, out var combat) && - combat.IsInCombatMode) + else if (_entities.TryGetComponent(target, out var combat) && + combat.IsInCombatMode) { // Slightly increase the delay when the target is in combat mode. Helps prevents cheese injections in // combat with fast syringes & lag. @@ -234,11 +235,10 @@ namespace Content.Server.Chemistry.Components } // Add an admin log, using the "force feed" log type. It's not quite feeding, but the effect is the same. - var targetEntity = Owner.EntityManager.GetEntity(target); if (ToggleState == InjectorToggleMode.Inject) { logSys.Add(LogType.ForceFeed, - $"{userEntity} is attempting to inject a solution into {targetEntity}"); + $"{_entities.ToPrettyString(user)} is attempting to inject a solution into {_entities.ToPrettyString(target)}"); // TODO solution pretty string. } } @@ -249,7 +249,7 @@ namespace Content.Server.Chemistry.Components if (ToggleState == InjectorToggleMode.Inject) logSys.Add(LogType.Ingestion, - $"{userEntity} is attempting to inject themselves with a solution."); + $"{_entities.ToPrettyString(user)} is attempting to inject themselves with a solution."); //TODO solution pretty string. } @@ -279,7 +279,7 @@ namespace Content.Server.Chemistry.Components return true; } - private void TryInjectIntoBloodstream(BloodstreamComponent targetBloodstream, IEntity user) + private void TryInjectIntoBloodstream(BloodstreamComponent targetBloodstream, EntityUid user) { // Get transfer amount. May be smaller than _transferAmount if not enough room var realTransferAmount = FixedPoint2.Min(_transferAmount, targetBloodstream.Solution.AvailableVolume); @@ -293,12 +293,12 @@ namespace Content.Server.Chemistry.Components // Move units from attackSolution to targetSolution var removedSolution = - EntitySystem.Get().SplitSolution(user.Uid, targetBloodstream.Solution, realTransferAmount); + EntitySystem.Get().SplitSolution(user, targetBloodstream.Solution, realTransferAmount); var bloodstreamSys = EntitySystem.Get(); - bloodstreamSys.TryAddToBloodstream(targetBloodstream.OwnerUid, removedSolution, targetBloodstream); + bloodstreamSys.TryAddToBloodstream((targetBloodstream).Owner, removedSolution, targetBloodstream); - removedSolution.DoEntityReaction(targetBloodstream.Owner.Uid, ReactionMethod.Injection); + removedSolution.DoEntityReaction(targetBloodstream.Owner, ReactionMethod.Injection); Owner.PopupMessage(user, Loc.GetString("injector-component-inject-success-message", @@ -308,9 +308,9 @@ namespace Content.Server.Chemistry.Components AfterInject(); } - private void TryInject(IEntity targetEntity, Solution targetSolution, IEntity user, bool asRefill) + private void TryInject(EntityUid targetEntity, Solution targetSolution, EntityUid user, bool asRefill) { - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution) || solution.CurrentVolume == 0) { return; @@ -327,19 +327,19 @@ namespace Content.Server.Chemistry.Components } // Move units from attackSolution to targetSolution - var removedSolution = EntitySystem.Get().SplitSolution(Owner.Uid, solution, realTransferAmount); + var removedSolution = EntitySystem.Get().SplitSolution(Owner, solution, realTransferAmount); - removedSolution.DoEntityReaction(targetEntity.Uid, ReactionMethod.Injection); + removedSolution.DoEntityReaction(targetEntity, ReactionMethod.Injection); if (!asRefill) { EntitySystem.Get() - .Inject(targetEntity.Uid, targetSolution, removedSolution); + .Inject(targetEntity, targetSolution, removedSolution); } else { EntitySystem.Get() - .Refill(targetEntity.Uid, targetSolution, removedSolution); + .Refill(targetEntity, targetSolution, removedSolution); } Owner.PopupMessage(user, @@ -353,7 +353,7 @@ namespace Content.Server.Chemistry.Components private void AfterInject() { // Automatically set syringe to draw after completely draining it. - if (EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution) + if (EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution) && solution.CurrentVolume == 0) { ToggleState = InjectorToggleMode.Draw; @@ -363,16 +363,16 @@ namespace Content.Server.Chemistry.Components private void AfterDraw() { // Automatically set syringe to inject after completely filling it. - if (EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution) + if (EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution) && solution.AvailableVolume == 0) { ToggleState = InjectorToggleMode.Inject; } } - private void TryDraw(IEntity targetEntity, Solution targetSolution, IEntity user) + private void TryDraw(EntityUid targetEntity, Solution targetSolution, EntityUid user) { - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution) || solution.AvailableVolume == 0) { return; @@ -390,9 +390,9 @@ namespace Content.Server.Chemistry.Components // Move units from attackSolution to targetSolution var removedSolution = EntitySystem.Get() - .Draw(targetEntity.Uid, targetSolution, realTransferAmount); + .Draw(targetEntity, targetSolution, realTransferAmount); - if (!EntitySystem.Get().TryAddSolution(targetEntity.Uid, solution, removedSolution)) + if (!EntitySystem.Get().TryAddSolution(targetEntity, solution, removedSolution)) { return; } @@ -408,8 +408,8 @@ namespace Content.Server.Chemistry.Components public override ComponentState GetComponentState() { - Owner.EntityManager.EntitySysManager.GetEntitySystem() - .TryGetSolution(Owner.Uid, SolutionName, out var solution); + _entities.EntitySysManager.GetEntitySystem() + .TryGetSolution(Owner, SolutionName, out var solution); var currentVolume = solution?.CurrentVolume ?? FixedPoint2.Zero; var maxVolume = solution?.MaxVolume ?? FixedPoint2.Zero; diff --git a/Content.Server/Chemistry/Components/ReagentDispenserComponent.cs b/Content.Server/Chemistry/Components/ReagentDispenserComponent.cs index 92168f5e13..19c63bba8f 100644 --- a/Content.Server/Chemistry/Components/ReagentDispenserComponent.cs +++ b/Content.Server/Chemistry/Components/ReagentDispenserComponent.cs @@ -43,6 +43,7 @@ namespace Content.Server.Chemistry.Components public static string SolutionName = "reagent"; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; [ViewVariables] [DataField("pack")] private string _packPrototypeId = ""; @@ -57,13 +58,13 @@ namespace Content.Server.Chemistry.Components { get { - EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution); + EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution); return solution; } } [ViewVariables] - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(ReagentDispenserUiKey.Key); @@ -148,7 +149,7 @@ namespace Content.Server.Chemistry.Components switch (msg.Button) { case UiButton.Eject: - EntitySystem.Get().TryEjectToHands(OwnerUid, BeakerSlot, obj.Session.AttachedEntityUid); + EntitySystem.Get().TryEjectToHands(Owner, BeakerSlot, obj.Session.AttachedEntity); break; case UiButton.Clear: TryClear(); @@ -200,7 +201,7 @@ namespace Content.Server.Chemistry.Components /// /// The player entity. /// Returns true if the entity can use the dispenser, and false if it cannot. - private bool PlayerCanUseDispenser(IEntity? playerEntity, bool needsPower = true) + private bool PlayerCanUseDispenser(EntityUid? playerEntity, bool needsPower = true) { //Need player entity to check if they are still able to use the dispenser if (playerEntity == null) @@ -209,7 +210,7 @@ namespace Content.Server.Chemistry.Components var actionBlocker = EntitySystem.Get(); //Check if player can interact in their current state - if (!actionBlocker.CanInteract(playerEntity.Uid) || !actionBlocker.CanUse(playerEntity.Uid)) + if (!actionBlocker.CanInteract(playerEntity.Value) || !actionBlocker.CanUse(playerEntity.Value)) return false; //Check if device is powered if (needsPower && !Powered) @@ -224,18 +225,18 @@ namespace Content.Server.Chemistry.Components /// Returns a private ReagentDispenserBoundUserInterfaceState GetUserInterfaceState() { - var beaker = BeakerSlot.Item; - if (beaker == null || !beaker.TryGetComponent(out FitsInDispenserComponent? fits) || - !EntitySystem.Get().TryGetSolution(beaker.Uid, fits.Solution, out var solution)) + if (BeakerSlot.Item is not {Valid: true} beaker || + !_entities.TryGetComponent(beaker, out FitsInDispenserComponent? fits) || + !EntitySystem.Get().TryGetSolution(beaker, fits.Solution, out var solution)) { return new ReagentDispenserBoundUserInterfaceState(Powered, false, FixedPoint2.New(0), FixedPoint2.New(0), - string.Empty, Inventory, Owner.Name, null, _dispenseAmount); + string.Empty, Inventory, _entities.GetComponent(Owner).EntityName, null, _dispenseAmount); } return new ReagentDispenserBoundUserInterfaceState(Powered, true, solution.CurrentVolume, solution.MaxVolume, - beaker.Name, Inventory, Owner.Name, solution.Contents.ToList(), _dispenseAmount); + _entities.GetComponent(beaker).EntityName, Inventory, _entities.GetComponent(Owner).EntityName, solution.Contents.ToList(), _dispenseAmount); } public void UpdateUserInterface() @@ -249,14 +250,12 @@ namespace Content.Server.Chemistry.Components /// private void TryClear() { - var beaker = BeakerSlot.Item; - - if (beaker == null || !beaker.TryGetComponent(out FitsInDispenserComponent? fits) || - !EntitySystem.Get() - .TryGetSolution(beaker.Uid, fits.Solution, out var solution)) + if (BeakerSlot.Item is not {Valid: true} beaker || + !_entities.TryGetComponent(beaker, out FitsInDispenserComponent? fits) || + !EntitySystem.Get().TryGetSolution(beaker, fits.Solution, out var solution)) return; - EntitySystem.Get().RemoveAllSolution(beaker.Uid, solution); + EntitySystem.Get().RemoveAllSolution(beaker, solution); UpdateUserInterface(); } @@ -267,14 +266,12 @@ namespace Content.Server.Chemistry.Components /// The index of the reagent in Inventory. private void TryDispense(int dispenseIndex) { - var beaker = BeakerSlot.Item; - - if (beaker is null || !beaker.TryGetComponent(out FitsInDispenserComponent? fits) - || !EntitySystem.Get() - .TryGetSolution(beaker.Uid, fits.Solution, out var solution)) return; + if (BeakerSlot.Item is not {Valid: true} beaker || + !_entities.TryGetComponent(beaker, out FitsInDispenserComponent? fits) || + !EntitySystem.Get().TryGetSolution(beaker, fits.Solution, out var solution)) return; EntitySystem.Get() - .TryAddReagent(beaker.Uid, solution, Inventory[dispenseIndex].ID, _dispenseAmount, out _); + .TryAddReagent(beaker, solution, Inventory[dispenseIndex].ID, _dispenseAmount, out _); UpdateUserInterface(); } @@ -285,12 +282,12 @@ namespace Content.Server.Chemistry.Components /// Data relevant to the event such as the actor which triggered it. void IActivate.Activate(ActivateEventArgs args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!_entities.TryGetComponent(args.User, out ActorComponent? actor)) { return; } - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!_entities.TryGetComponent(args.User, out HandsComponent? hands)) { Owner.PopupMessage(args.User, Loc.GetString("reagent-dispenser-component-activate-no-hands")); return; diff --git a/Content.Server/Chemistry/Components/SmokeSolutionAreaEffectComponent.cs b/Content.Server/Chemistry/Components/SmokeSolutionAreaEffectComponent.cs index 92e065147a..02bdc920c3 100644 --- a/Content.Server/Chemistry/Components/SmokeSolutionAreaEffectComponent.cs +++ b/Content.Server/Chemistry/Components/SmokeSolutionAreaEffectComponent.cs @@ -6,6 +6,7 @@ using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Content.Shared.Smoking; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Chemistry.Components { @@ -13,27 +14,29 @@ namespace Content.Server.Chemistry.Components [ComponentReference(typeof(SolutionAreaEffectComponent))] public class SmokeSolutionAreaEffectComponent : SolutionAreaEffectComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "SmokeSolutionAreaEffect"; public new const string SolutionName = "solutionArea"; protected override void UpdateVisuals() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance) && - EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance) && + EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { appearance.SetData(SmokeVisuals.Color, solution.Color); } } - protected override void ReactWithEntity(IEntity entity, double solutionFraction) + protected override void ReactWithEntity(EntityUid entity, double solutionFraction) { - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) return; - if (!entity.TryGetComponent(out BloodstreamComponent? bloodstream)) + if (!_entMan.TryGetComponent(entity, out BloodstreamComponent? bloodstream)) return; - if (entity.TryGetComponent(out InternalsComponent? internals) && + if (_entMan.TryGetComponent(entity, out InternalsComponent? internals) && internals.AreInternalsWorking()) return; @@ -45,19 +48,19 @@ namespace Content.Server.Chemistry.Components foreach (var reagentQuantity in transferSolution.Contents.ToArray()) { if (reagentQuantity.Quantity == FixedPoint2.Zero) continue; - chemistry.ReactionEntity(entity.Uid, ReactionMethod.Ingestion, reagentQuantity.ReagentId, reagentQuantity.Quantity, transferSolution); + chemistry.ReactionEntity(entity, ReactionMethod.Ingestion, reagentQuantity.ReagentId, reagentQuantity.Quantity, transferSolution); } var bloodstreamSys = EntitySystem.Get(); - bloodstreamSys.TryAddToBloodstream(entity.Uid, transferSolution, bloodstream); + bloodstreamSys.TryAddToBloodstream(entity, transferSolution, bloodstream); } protected override void OnKill() { - if (Owner.Deleted) + if (_entMan.Deleted(Owner)) return; - Owner.Delete(); + _entMan.DeleteEntity(Owner); } } } diff --git a/Content.Server/Chemistry/Components/SolutionAreaEffectComponent.cs b/Content.Server/Chemistry/Components/SolutionAreaEffectComponent.cs index eb8d12b716..e7c7f7c66a 100644 --- a/Content.Server/Chemistry/Components/SolutionAreaEffectComponent.cs +++ b/Content.Server/Chemistry/Components/SolutionAreaEffectComponent.cs @@ -26,6 +26,8 @@ namespace Content.Server.Chemistry.Components [Dependency] protected readonly IMapManager MapManager = default!; [Dependency] protected readonly IPrototypeManager PrototypeManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; + public int Amount { get; set; } public SolutionAreaEffectInceptionComponent? Inception { get; set; } @@ -46,11 +48,11 @@ namespace Content.Server.Chemistry.Components if (Inception != null) return; - if (Owner.HasComponent()) + if (_entities.HasComponent(Owner)) return; Amount = amount; - var inception = Owner.AddComponent(); + var inception = _entities.AddComponent(Owner); inception.Add(this); inception.Setup(amount, duration, spreadDelay, removeDelay); @@ -62,7 +64,7 @@ namespace Content.Server.Chemistry.Components /// public void Spread() { - if (Owner.Prototype == null) + if (_entities.GetComponent(Owner).EntityPrototype == null) { Logger.Error("AreaEffectComponent needs its owner to be spawned by a prototype."); return; @@ -70,28 +72,30 @@ namespace Content.Server.Chemistry.Components void SpreadToDir(Direction dir) { - var grid = MapManager.GetGrid(Owner.Transform.GridID); - var coords = Owner.Transform.Coordinates; + var grid = MapManager.GetGrid(_entities.GetComponent(Owner).GridID); + var coords = _entities.GetComponent(Owner).Coordinates; foreach (var neighbor in grid.GetInDir(coords, dir)) { - if (Owner.EntityManager.TryGetComponent(neighbor, + if (_entities.TryGetComponent(neighbor, out SolutionAreaEffectComponent? comp) && comp.Inception == Inception) return; - if (Owner.EntityManager.TryGetComponent(neighbor, + if (_entities.TryGetComponent(neighbor, out AirtightComponent? airtight) && airtight.AirBlocked) return; } - var newEffect = Owner.EntityManager.SpawnEntity(Owner.Prototype.ID, grid.DirectionToGrid(coords, dir)); + var newEffect = _entities.SpawnEntity( + _entities.GetComponent(Owner).EntityPrototype?.ID, + grid.DirectionToGrid(coords, dir)); - if (!newEffect.TryGetComponent(out SolutionAreaEffectComponent? effectComponent)) + if (!_entities.TryGetComponent(newEffect, out SolutionAreaEffectComponent? effectComponent)) { - newEffect.Delete(); + _entities.DeleteEntity(newEffect); return; } - if (EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { effectComponent.TryAddSolution(solution.Clone()); } @@ -128,12 +132,12 @@ namespace Content.Server.Chemistry.Components /// with the other area effects from the inception. public void React(float averageExposures) { - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) return; var chemistry = EntitySystem.Get(); - var mapGrid = MapManager.GetGrid(Owner.Transform.GridID); - var tile = mapGrid.GetTileRef(Owner.Transform.Coordinates.ToVector2i(Owner.EntityManager, MapManager)); + var mapGrid = MapManager.GetGrid(_entities.GetComponent(Owner).GridID); + var tile = mapGrid.GetTileRef(_entities.GetComponent(Owner).Coordinates.ToVector2i(_entities, MapManager)); var solutionFraction = 1 / Math.Floor(averageExposures); @@ -153,7 +157,7 @@ namespace Content.Server.Chemistry.Components // Touch every entity on the tile foreach (var entity in tile.GetEntitiesInTileFast().ToArray()) { - chemistry.ReactionEntity(entity.Uid, ReactionMethod.Touch, reagent, + chemistry.ReactionEntity(entity, ReactionMethod.Touch, reagent, reagentQuantity.Quantity * solutionFraction, solution); } } @@ -164,20 +168,20 @@ namespace Content.Server.Chemistry.Components } } - protected abstract void ReactWithEntity(IEntity entity, double solutionFraction); + protected abstract void ReactWithEntity(EntityUid entity, double solutionFraction); public void TryAddSolution(Solution solution) { if (solution.TotalVolume == 0) return; - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solutionArea)) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solutionArea)) return; var addSolution = solution.SplitSolution(FixedPoint2.Min(solution.TotalVolume, solutionArea.AvailableVolume)); - EntitySystem.Get().TryAddSolution(Owner.Uid, solutionArea, addSolution); + EntitySystem.Get().TryAddSolution(Owner, solutionArea, addSolution); UpdateVisuals(); } diff --git a/Content.Server/Chemistry/Components/SolutionTransferComponent.cs b/Content.Server/Chemistry/Components/SolutionTransferComponent.cs index c25d602c35..0bb22eb62e 100644 --- a/Content.Server/Chemistry/Components/SolutionTransferComponent.cs +++ b/Content.Server/Chemistry/Components/SolutionTransferComponent.cs @@ -5,13 +5,13 @@ using Content.Server.Chemistry.EntitySystems; using Content.Server.UserInterface; using Content.Shared.Chemistry; using Content.Shared.Chemistry.Components; -using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using Content.Shared.Popups; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -24,6 +24,8 @@ namespace Content.Server.Chemistry.Components [RegisterComponent] public sealed class SolutionTransferComponent : Component, IAfterInteract { + [Dependency] private readonly IEntityManager _entities = default!; + // Behavior is as such: // If it's a reagent tank, TAKE reagent. // If it's anything else, GIVE reagent. @@ -87,6 +89,9 @@ namespace Content.Server.Chemistry.Components public void UserInterfaceOnReceiveMessage(ServerBoundUserInterfaceMessage serverMsg) { + if (serverMsg.Session.AttachedEntity == null) + return; + switch (serverMsg.Message) { case TransferAmountSetValueMessage svm: @@ -94,7 +99,7 @@ namespace Content.Server.Chemistry.Components var amount = Math.Clamp(sval, MinimumTransferAmount.Float(), MaximumTransferAmount.Float()); - serverMsg.Session.AttachedEntity?.PopupMessage(Loc.GetString("comp-solution-transfer-set-amount", + serverMsg.Session.AttachedEntity.Value.PopupMessage(Loc.GetString("comp-solution-transfer-set-amount", ("amount", amount))); SetTransferAmount(FixedPoint2.New(amount)); break; @@ -115,21 +120,21 @@ namespace Content.Server.Chemistry.Components if (!eventArgs.InRangeUnobstructed() || eventArgs.Target == null) return false; - if (!Owner.HasComponent()) + if (!_entities.HasComponent(Owner)) return false; - var target = eventArgs.Target!; - if (!target.HasComponent()) + var target = eventArgs.Target!.Value; + if (!_entities.HasComponent(target)) { return false; } - if (CanReceive && target.TryGetComponent(out ReagentTankComponent? tank) - && solutionsSys.TryGetRefillableSolution(Owner.Uid, out var ownerRefill) - && solutionsSys.TryGetDrainableSolution(eventArgs.Target.Uid, out var targetDrain)) + if (CanReceive && _entities.TryGetComponent(target, out ReagentTankComponent? tank) + && solutionsSys.TryGetRefillableSolution(Owner, out var ownerRefill) + && solutionsSys.TryGetDrainableSolution(target, out var targetDrain)) { - var transferred = DoTransfer(eventArgs.User, eventArgs.Target, targetDrain, Owner, ownerRefill, tank.TransferAmount); + var transferred = DoTransfer(eventArgs.User, target, targetDrain, Owner, ownerRefill, tank.TransferAmount); if (transferred > 0) { var toTheBrim = ownerRefill.AvailableVolume == 0; @@ -143,8 +148,8 @@ namespace Content.Server.Chemistry.Components } } - if (CanSend && solutionsSys.TryGetRefillableSolution(eventArgs.Target.Uid, out var targetRefill) - && solutionsSys.TryGetDrainableSolution(Owner.Uid, out var ownerDrain)) + if (CanSend && solutionsSys.TryGetRefillableSolution(target, out var targetRefill) + && solutionsSys.TryGetDrainableSolution(Owner, out var ownerDrain)) { var transferred = DoTransfer(eventArgs.User, Owner, ownerDrain, target, targetRefill, TransferAmount); @@ -163,10 +168,10 @@ namespace Content.Server.Chemistry.Components } /// The actual amount transferred. - private static FixedPoint2 DoTransfer(IEntity user, - IEntity sourceEntity, + private static FixedPoint2 DoTransfer(EntityUid user, + EntityUid sourceEntity, Solution source, - IEntity targetEntity, + EntityUid targetEntity, Solution target, FixedPoint2 amount) { @@ -188,8 +193,8 @@ namespace Content.Server.Chemistry.Components var actualAmount = FixedPoint2.Min(amount, FixedPoint2.Min(source.DrainAvailable, target.AvailableVolume)); - var solution = EntitySystem.Get().Drain(sourceEntity.Uid, source, actualAmount); - EntitySystem.Get().Refill(targetEntity.Uid, target, solution); + var solution = EntitySystem.Get().Drain(sourceEntity, source, actualAmount); + EntitySystem.Get().Refill(targetEntity, target, solution); return actualAmount; } diff --git a/Content.Server/Chemistry/Components/TransformableContainerComponent.cs b/Content.Server/Chemistry/Components/TransformableContainerComponent.cs index f4b506ed15..69f4a527e2 100644 --- a/Content.Server/Chemistry/Components/TransformableContainerComponent.cs +++ b/Content.Server/Chemistry/Components/TransformableContainerComponent.cs @@ -2,6 +2,7 @@ using Content.Server.Chemistry.Components.SolutionManager; using Content.Shared.Chemistry.Reagent; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Utility; namespace Content.Server.Chemistry.Components @@ -9,6 +10,8 @@ namespace Content.Server.Chemistry.Components [RegisterComponent] public class TransformableContainerComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "TransformableContainer"; public SpriteSpecifier? InitialSprite; @@ -22,14 +25,14 @@ namespace Content.Server.Chemistry.Components { base.Initialize(); - if (Owner.TryGetComponent(out SpriteComponent? sprite) && + if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite) && sprite.BaseRSIPath != null) { InitialSprite = new SpriteSpecifier.Rsi(new ResourcePath(sprite.BaseRSIPath), "icon"); } - InitialName = Owner.Name; - InitialDescription = Owner.Description; + InitialName = _entMan.GetComponent(Owner).EntityName; + InitialDescription = _entMan.GetComponent(Owner).EntityDescription; } protected override void Startup() diff --git a/Content.Server/Chemistry/EntitySystems/ChemicalReactionSystem.cs b/Content.Server/Chemistry/EntitySystems/ChemicalReactionSystem.cs index cd5247f3ac..a5131361a7 100644 --- a/Content.Server/Chemistry/EntitySystems/ChemicalReactionSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/ChemicalReactionSystem.cs @@ -1,4 +1,3 @@ -using Content.Shared.Administration.Logs; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.Reaction; using Content.Shared.Chemistry.Reagent; @@ -12,15 +11,16 @@ namespace Content.Server.Chemistry.EntitySystems { public class ChemicalReactionSystem : SharedChemicalReactionSystem { - protected override void OnReaction(Solution solution, ReactionPrototype reaction, ReagentPrototype randomReagent, EntityUid ownerUid, FixedPoint2 unitReactions) + protected override void OnReaction(Solution solution, ReactionPrototype reaction, ReagentPrototype randomReagent, EntityUid Owner, FixedPoint2 unitReactions) { - base.OnReaction(solution, reaction, randomReagent, ownerUid, unitReactions); + base.OnReaction(solution, reaction, randomReagent, Owner, unitReactions); + + var coordinates = EntityManager.GetComponent(Owner).Coordinates; - var entity = EntityManager.GetEntity(ownerUid); _logSystem.Add(LogType.ChemicalReaction, reaction.Impact, - $"Chemical reaction {reaction.ID} occurred with strength {unitReactions:strength} on entity {entity} at {entity.Transform.Coordinates}"); + $"Chemical reaction {reaction.ID} occurred with strength {unitReactions:strength} on entity {Owner} at {coordinates}"); - SoundSystem.Play(Filter.Pvs(ownerUid, entityManager:EntityManager), reaction.Sound.GetSound(), ownerUid); + SoundSystem.Play(Filter.Pvs(Owner, entityManager:EntityManager), reaction.Sound.GetSound(), Owner); } } } diff --git a/Content.Server/Chemistry/EntitySystems/RehydratableSystem.cs b/Content.Server/Chemistry/EntitySystems/RehydratableSystem.cs index 37ab0be606..3ff87ae2b9 100644 --- a/Content.Server/Chemistry/EntitySystems/RehydratableSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/RehydratableSystem.cs @@ -1,6 +1,5 @@ using Content.Server.Chemistry.Components; using Content.Server.Popups; -using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using JetBrains.Annotations; using Robust.Shared.GameObjects; @@ -29,7 +28,7 @@ namespace Content.Server.Chemistry.EntitySystems } // Try not to make this public if you can help it. - private void Expand(RehydratableComponent component, IEntity owner) + private void Expand(RehydratableComponent component, EntityUid owner) { if (component.Expanding) { @@ -40,12 +39,12 @@ namespace Content.Server.Chemistry.EntitySystems owner.PopupMessageEveryone(Loc.GetString("rehydratable-component-expands-message", ("owner", owner))); if (!string.IsNullOrEmpty(component.TargetPrototype)) { - var ent = component.Owner.EntityManager.SpawnEntity(component.TargetPrototype, - owner.Transform.Coordinates); - ent.Transform.AttachToGridOrMap(); + var ent = EntityManager.SpawnEntity(component.TargetPrototype, + EntityManager.GetComponent(owner).Coordinates); + EntityManager.GetComponent(ent).AttachToGridOrMap(); } - owner.QueueDelete(); + EntityManager.QueueDeleteEntity((EntityUid) owner); } } } diff --git a/Content.Server/Chemistry/EntitySystems/SolutionContainerSystem.cs b/Content.Server/Chemistry/EntitySystems/SolutionContainerSystem.cs index 665bacecd1..a7b61f4bbc 100644 --- a/Content.Server/Chemistry/EntitySystems/SolutionContainerSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/SolutionContainerSystem.cs @@ -13,9 +13,7 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Log; -using Robust.Shared.Maths; using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Utility; namespace Content.Server.Chemistry.EntitySystems @@ -67,7 +65,7 @@ namespace Content.Server.Chemistry.EntitySystems ExaminedEvent args) { SolutionContainerManagerComponent? solutionsManager = null; - if (!Resolve(args.Examined.Uid, ref solutionsManager) + if (!Resolve(args.Examined, ref solutionsManager) || !solutionsManager.Solutions.TryGetValue(examinableComponent.Solution, out var solutionHolder)) return; @@ -290,11 +288,11 @@ namespace Content.Server.Chemistry.EntitySystems UpdateChemicals(uid, solution); } - public FixedPoint2 GetReagentQuantity(EntityUid ownerUid, string reagentId) + public FixedPoint2 GetReagentQuantity(EntityUid owner, string reagentId) { var reagentQuantity = FixedPoint2.New(0); - if (EntityManager.TryGetEntity(ownerUid, out var owner) - && owner.TryGetComponent(out SolutionContainerManagerComponent? managerComponent)) + if (EntityManager.EntityExists(owner) + && EntityManager.TryGetComponent(owner, out SolutionContainerManagerComponent? managerComponent)) { foreach (var solution in managerComponent.Solutions.Values) { diff --git a/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs b/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs index 04b1ec19c6..e26ca86fac 100644 --- a/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/SolutionInjectOnCollideSystem.cs @@ -30,15 +30,15 @@ namespace Content.Server.Chemistry.EntitySystems private void HandleInjection(EntityUid uid, SolutionInjectOnCollideComponent component, StartCollideEvent args) { - if (!args.OtherFixture.Body.Owner.TryGetComponent(out var bloodstream) || - !_solutionsSystem.TryGetInjectableSolution(component.Owner.Uid, out var solution)) return; + if (!EntityManager.TryGetComponent(args.OtherFixture.Body.Owner, out var bloodstream) || + !_solutionsSystem.TryGetInjectableSolution(component.Owner, out var solution)) return; var solRemoved = solution.SplitSolution(component.TransferAmount); var solRemovedVol = solRemoved.TotalVolume; var solToInject = solRemoved.SplitSolution(solRemovedVol * component.TransferEfficiency); - _bloodstreamSystem.TryAddToBloodstream(args.OtherFixture.Body.OwnerUid, solToInject, bloodstream); + _bloodstreamSystem.TryAddToBloodstream((args.OtherFixture.Body).Owner, solToInject, bloodstream); } } } diff --git a/Content.Server/Chemistry/EntitySystems/SolutionTransferSystem.cs b/Content.Server/Chemistry/EntitySystems/SolutionTransferSystem.cs index 6be2c98c69..7208f76c49 100644 --- a/Content.Server/Chemistry/EntitySystems/SolutionTransferSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/SolutionTransferSystem.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Content.Shared.Popups; +using Robust.Shared.IoC; namespace Content.Server.Chemistry.EntitySystems { @@ -31,9 +32,9 @@ namespace Content.Server.Chemistry.EntitySystems if (!args.CanAccess || !args.CanInteract || !component.CanChangeTransferAmount) return; - if (!args.User.TryGetComponent(out var actor)) + if (!EntityManager.TryGetComponent(args.User, out var actor)) return; - + // Custom transfer verb Verb custom = new(); custom.Text = Loc.GetString("comp-solution-transfer-verb-custom-amount"); @@ -61,7 +62,7 @@ namespace Content.Server.Chemistry.EntitySystems // we want to sort by size, not alphabetically by the verb text. verb.Priority = priority; priority--; - + args.Verbs.Add(verb); } } diff --git a/Content.Server/Chemistry/EntitySystems/TransformableContainerSystem.cs b/Content.Server/Chemistry/EntitySystems/TransformableContainerSystem.cs index 6a277cb3fe..ff3905dc31 100644 --- a/Content.Server/Chemistry/EntitySystems/TransformableContainerSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/TransformableContainerSystem.cs @@ -22,10 +22,10 @@ namespace Content.Server.Chemistry.EntitySystems SubscribeLocalEvent(OnSolutionChange); } - private void OnSolutionChange(EntityUid uid, TransformableContainerComponent component, + private void OnSolutionChange(EntityUid owner, TransformableContainerComponent component, SolutionChangedEvent args) { - if (!_solutionsSystem.TryGetFitsInDispenser(uid, out var solution)) + if (!_solutionsSystem.TryGetFitsInDispenser(owner, out var solution)) return; //Transform container into initial state when emptied if (component.CurrentReagent != null && solution.Contents.Count == 0) @@ -50,14 +50,14 @@ namespace Content.Server.Chemistry.EntitySystems var spriteSpec = new SpriteSpecifier.Rsi( new ResourcePath("Objects/Consumable/Drinks/" + proto.SpriteReplacementPath), "icon"); - var ownerEntity = EntityManager.GetEntity(uid); - if (ownerEntity.TryGetComponent(out SpriteComponent? sprite)) + if (EntityManager.TryGetComponent(owner, out SpriteComponent? sprite)) { sprite?.LayerSetSprite(0, spriteSpec); } - ownerEntity.Name = proto.Name + " glass"; - ownerEntity.Description = proto.Description; + string val = proto.Name + " glass"; + EntityManager.GetComponent(owner).EntityName = val; + EntityManager.GetComponent(owner).EntityDescription = proto.Description; component.CurrentReagent = proto; component.Transformed = true; } @@ -68,14 +68,14 @@ namespace Content.Server.Chemistry.EntitySystems component.CurrentReagent = null; component.Transformed = false; - if (component.Owner.TryGetComponent(out SpriteComponent? sprite) && + if (EntityManager.TryGetComponent(component.Owner, out SpriteComponent? sprite) && component.InitialSprite != null) { sprite.LayerSetSprite(0, component.InitialSprite); } - component.Owner.Name = component.InitialName; - component.Owner.Description = component.InitialDescription; + EntityManager.GetComponent(component.Owner).EntityName = component.InitialName; + EntityManager.GetComponent(component.Owner).EntityDescription = component.InitialDescription; } } } diff --git a/Content.Server/Chemistry/EntitySystems/VaporSystem.cs b/Content.Server/Chemistry/EntitySystems/VaporSystem.cs index a552c69983..cebe2f846d 100644 --- a/Content.Server/Chemistry/EntitySystems/VaporSystem.cs +++ b/Content.Server/Chemistry/EntitySystems/VaporSystem.cs @@ -36,7 +36,7 @@ namespace Content.Server.Chemistry.EntitySystems foreach (var (_, value) in contents.Solutions) { - value.DoEntityReaction(args.OtherFixture.Body.Owner.Uid, ReactionMethod.Touch); + value.DoEntityReaction(args.OtherFixture.Body.Owner, ReactionMethod.Touch); } // Check for collision with a impassable object (e.g. wall) and stop @@ -52,7 +52,7 @@ namespace Content.Server.Chemistry.EntitySystems vapor.Target = target; vapor.AliveTime = aliveTime; // Set Move - if (vapor.Owner.TryGetComponent(out PhysicsComponent? physics)) + if (EntityManager.TryGetComponent(vapor.Owner, out PhysicsComponent? physics)) { physics.BodyStatus = BodyStatus.InAir; physics.ApplyLinearImpulse(dir * speed); @@ -66,13 +66,13 @@ namespace Content.Server.Chemistry.EntitySystems return false; } - if (!_solutionContainerSystem.TryGetSolution(vapor.Owner.Uid, SharedVaporComponent.SolutionName, + if (!_solutionContainerSystem.TryGetSolution(vapor.Owner, SharedVaporComponent.SolutionName, out var vaporSolution)) { return false; } - return _solutionContainerSystem.TryAddSolution(vapor.Owner.Uid, vaporSolution, solution); + return _solutionContainerSystem.TryAddSolution(vapor.Owner, vaporSolution, solution); } public override void Update(float frameTime) @@ -97,24 +97,24 @@ namespace Content.Server.Chemistry.EntitySystems vapor.Timer += frameTime; vapor.ReactTimer += frameTime; - if (vapor.ReactTimer >= ReactTime && vapor.Owner.Transform.GridID.IsValid()) + if (vapor.ReactTimer >= ReactTime && EntityManager.GetComponent(vapor.Owner).GridID.IsValid()) { vapor.ReactTimer = 0; - var mapGrid = _mapManager.GetGrid(entity.Transform.GridID); + var mapGrid = _mapManager.GetGrid(EntityManager.GetComponent(entity).GridID); - var tile = mapGrid.GetTileRef(entity.Transform.Coordinates.ToVector2i(EntityManager, _mapManager)); + var tile = mapGrid.GetTileRef(EntityManager.GetComponent(entity).Coordinates.ToVector2i(EntityManager, _mapManager)); foreach (var reagentQuantity in contents.Contents.ToArray()) { if (reagentQuantity.Quantity == FixedPoint2.Zero) continue; var reagent = _protoManager.Index(reagentQuantity.ReagentId); - _solutionContainerSystem.TryRemoveReagent(vapor.Owner.Uid, contents, reagentQuantity.ReagentId, + _solutionContainerSystem.TryRemoveReagent(vapor.Owner, contents, reagentQuantity.ReagentId, reagent.ReactionTile(tile, (reagentQuantity.Quantity / vapor.TransferAmount) * 0.25f)); } } // Check if we've reached our target. if (!vapor.Reached && - vapor.Target.TryDistance(EntityManager, entity.Transform.Coordinates, out var distance) && + vapor.Target.TryDistance(EntityManager, EntityManager.GetComponent(entity).Coordinates, out var distance) && distance <= 0.5f) { vapor.Reached = true; @@ -123,7 +123,7 @@ namespace Content.Server.Chemistry.EntitySystems if (contents.CurrentVolume == 0 || vapor.Timer > vapor.AliveTime) { // Delete this - entity.QueueDelete(); + EntityManager.QueueDeleteEntity(entity); } } } diff --git a/Content.Server/Chemistry/ReactionEffects/AreaReactionEffect.cs b/Content.Server/Chemistry/ReactionEffects/AreaReactionEffect.cs index 9418f02d7e..a7dac3c58b 100644 --- a/Content.Server/Chemistry/ReactionEffects/AreaReactionEffect.cs +++ b/Content.Server/Chemistry/ReactionEffects/AreaReactionEffect.cs @@ -2,10 +2,7 @@ using Content.Server.Chemistry.Components; using Content.Server.Chemistry.EntitySystems; using Content.Server.Coordinates.Helpers; -using Content.Shared.Administration.Logs; using Content.Shared.Audio; -using Content.Shared.Chemistry.Components; -using Content.Shared.Chemistry.Reaction; using Content.Shared.Chemistry.Reagent; using Content.Shared.Database; using Content.Shared.Sound; @@ -122,7 +119,7 @@ namespace Content.Server.Chemistry.ReactionEffects if (areaEffectComponent == null) { Logger.Error("Couldn't get AreaEffectComponent from " + _prototypeId); - ent.QueueDelete(); + IoCManager.Resolve().QueueDeleteEntity(ent); return; } @@ -132,6 +129,6 @@ namespace Content.Server.Chemistry.ReactionEffects SoundSystem.Play(Filter.Pvs(args.SolutionEntity), _sound.GetSound(), args.SolutionEntity, AudioHelpers.WithVariation(0.125f)); } - protected abstract SolutionAreaEffectComponent? GetAreaEffectComponent(IEntity entity); + protected abstract SolutionAreaEffectComponent? GetAreaEffectComponent(EntityUid entity); } } diff --git a/Content.Server/Chemistry/ReactionEffects/FoamAreaReactionEffect.cs b/Content.Server/Chemistry/ReactionEffects/FoamAreaReactionEffect.cs index 76f250dced..df7d4f59c1 100644 --- a/Content.Server/Chemistry/ReactionEffects/FoamAreaReactionEffect.cs +++ b/Content.Server/Chemistry/ReactionEffects/FoamAreaReactionEffect.cs @@ -1,6 +1,7 @@ using Content.Server.Chemistry.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Chemistry.ReactionEffects @@ -9,9 +10,9 @@ namespace Content.Server.Chemistry.ReactionEffects [DataDefinition] public class FoamAreaReactionEffect : AreaReactionEffect { - protected override SolutionAreaEffectComponent? GetAreaEffectComponent(IEntity entity) + protected override SolutionAreaEffectComponent? GetAreaEffectComponent(EntityUid entity) { - return entity.GetComponentOrNull(); + return IoCManager.Resolve().GetComponentOrNull(entity); } } } diff --git a/Content.Server/Chemistry/ReactionEffects/SmokeAreaReactionEffect.cs b/Content.Server/Chemistry/ReactionEffects/SmokeAreaReactionEffect.cs index 08032d183e..917f38dbb7 100644 --- a/Content.Server/Chemistry/ReactionEffects/SmokeAreaReactionEffect.cs +++ b/Content.Server/Chemistry/ReactionEffects/SmokeAreaReactionEffect.cs @@ -1,6 +1,7 @@ using Content.Server.Chemistry.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Chemistry.ReactionEffects @@ -9,9 +10,9 @@ namespace Content.Server.Chemistry.ReactionEffects [DataDefinition] public class SmokeAreaReactionEffect : AreaReactionEffect { - protected override SolutionAreaEffectComponent? GetAreaEffectComponent(IEntity entity) + protected override SolutionAreaEffectComponent? GetAreaEffectComponent(EntityUid entity) { - return entity.GetComponentOrNull(); + return IoCManager.Resolve().GetComponentOrNull(entity); } } } diff --git a/Content.Server/Chemistry/ReagentEffects/DoAction.cs b/Content.Server/Chemistry/ReagentEffects/DoAction.cs index ed2acff393..9e83cb30f4 100644 --- a/Content.Server/Chemistry/ReagentEffects/DoAction.cs +++ b/Content.Server/Chemistry/ReagentEffects/DoAction.cs @@ -2,8 +2,6 @@ using Content.Shared.Actions.Components; using Content.Shared.Actions.Prototypes; using Content.Shared.Chemistry.Reagent; -using Content.Shared.Construction.Steps; -using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Prototypes; using Robust.Shared.Serialization.Manager.Attributes; @@ -29,7 +27,7 @@ public class DoAction : ReagentEffect if (actions.IsGranted(proto.ActionType)) { var attempt = new ActionAttempt(proto); - attempt.DoInstantAction(args.EntityManager.GetEntity(args.SolutionEntity)); + attempt.DoInstantAction(args.SolutionEntity); } } } diff --git a/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs b/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs index a022a9c067..341a348341 100644 --- a/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs +++ b/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs @@ -6,6 +6,7 @@ using Content.Shared.Chemistry.Reaction; using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; @@ -23,9 +24,10 @@ namespace Content.Server.Chemistry.TileReactions { var entities = tile.GetEntitiesInTileFast().ToArray(); var amount = FixedPoint2.Zero; + var entMan = IoCManager.Resolve(); foreach (var entity in entities) { - if (entity.TryGetComponent(out CleanableComponent? cleanable)) + if (entMan.TryGetComponent(entity, out CleanableComponent? cleanable)) { var next = (amount + cleanable.CleanAmount) * CleanAmountMultiplier; // Nothing left? @@ -33,7 +35,7 @@ namespace Content.Server.Chemistry.TileReactions break; amount = next; - entity.QueueDelete(); + entMan.QueueDeleteEntity(entity); } } diff --git a/Content.Server/Chemistry/TileReactions/CreateEntityTileReaction.cs b/Content.Server/Chemistry/TileReactions/CreateEntityTileReaction.cs index b6817de8c5..37690a585f 100644 --- a/Content.Server/Chemistry/TileReactions/CreateEntityTileReaction.cs +++ b/Content.Server/Chemistry/TileReactions/CreateEntityTileReaction.cs @@ -51,7 +51,7 @@ public class CreateEntityTileReaction : ITileReaction int acc = 0; foreach (var ent in tile.GetEntitiesInTile()) { - if (Whitelist.IsValid(ent.Uid)) + if (Whitelist.IsValid(ent)) acc += 1; if (acc >= MaxOnTile) diff --git a/Content.Server/Chemistry/TileReactions/SpillTileReaction.cs b/Content.Server/Chemistry/TileReactions/SpillTileReaction.cs index b561de1b68..2123a76722 100644 --- a/Content.Server/Chemistry/TileReactions/SpillTileReaction.cs +++ b/Content.Server/Chemistry/TileReactions/SpillTileReaction.cs @@ -7,6 +7,7 @@ using Content.Shared.FixedPoint; using Content.Shared.Slippery; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Serialization.Manager.Attributes; @@ -31,7 +32,7 @@ namespace Content.Server.Chemistry.TileReactions if (puddle != null) { - var slippery = puddle.Owner.GetComponent(); + var slippery = IoCManager.Resolve().GetComponent(puddle.Owner); slippery.LaunchForwardsMultiplier = _launchForwardsMultiplier; slippery.RequiredSlipSpeed = _requiredSlipSpeed; slippery.ParalyzeTime = _paralyzeTime; diff --git a/Content.Server/Climbing/ClimbSystem.cs b/Content.Server/Climbing/ClimbSystem.cs index 214eb3b3a0..9921bdb333 100644 --- a/Content.Server/Climbing/ClimbSystem.cs +++ b/Content.Server/Climbing/ClimbSystem.cs @@ -37,11 +37,11 @@ namespace Content.Server.Climbing private void AddClimbVerb(EntityUid uid, ClimbableComponent component, GetAlternativeVerbsEvent args) { - if (!args.CanAccess || !args.CanInteract || !_actionBlockerSystem.CanMove(args.User.Uid)) + if (!args.CanAccess || !args.CanInteract || !_actionBlockerSystem.CanMove(args.User)) return; // Check that the user climb. - if (!args.User.TryGetComponent(out ClimbingComponent? climbingComponent) || + if (!EntityManager.TryGetComponent(args.User, out ClimbingComponent? climbingComponent) || climbingComponent.IsClimbing) return; diff --git a/Content.Server/Climbing/Components/ClimbableComponent.cs b/Content.Server/Climbing/Components/ClimbableComponent.cs index 7a9e209243..4dcb0c58cc 100644 --- a/Content.Server/Climbing/Components/ClimbableComponent.cs +++ b/Content.Server/Climbing/Components/ClimbableComponent.cs @@ -8,8 +8,8 @@ using Content.Shared.Climbing; using Content.Shared.DragDrop; using Content.Shared.Interaction.Helpers; using Content.Shared.Popups; -using Content.Shared.Verbs; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Log; using Robust.Shared.Maths; @@ -22,6 +22,8 @@ namespace Content.Server.Climbing.Components [ComponentReference(typeof(IClimbable))] public class ClimbableComponent : SharedClimbableComponent { + [Dependency] private readonly IEntityManager _entities = default!; + /// /// The time it takes to climb onto the entity. /// @@ -35,7 +37,7 @@ namespace Content.Server.Climbing.Components if (!Owner.EnsureComponent(out PhysicsComponent _)) { - Logger.Warning($"Entity {Owner.Name} at {Owner.Transform.MapPosition} didn't have a {nameof(PhysicsComponent)}"); + Logger.Warning($"Entity {_entities.GetComponent(Owner).EntityName} at {_entities.GetComponent(Owner).MapPosition} didn't have a {nameof(PhysicsComponent)}"); } } @@ -65,16 +67,16 @@ namespace Content.Server.Climbing.Components /// The object that is being vaulted /// The reason why it cant be dropped /// - private bool CanVault(IEntity user, IEntity target, out string reason) + private bool CanVault(EntityUid user, EntityUid target, out string reason) { - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) { reason = Loc.GetString("comp-climbable-cant-interact"); return false; } - if (!user.HasComponent() || - !user.TryGetComponent(out SharedBodyComponent? body)) + if (!_entities.HasComponent(user) || + !_entities.TryGetComponent(user, out SharedBodyComponent? body)) { reason = Loc.GetString("comp-climbable-cant-climb"); return false; @@ -105,21 +107,21 @@ namespace Content.Server.Climbing.Components /// The object that is being vaulted onto /// The reason why it cant be dropped /// - private bool CanVault(IEntity user, IEntity dragged, IEntity target, out string reason) + private bool CanVault(EntityUid user, EntityUid dragged, EntityUid target, out string reason) { - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) { reason = Loc.GetString("comp-climbable-cant-interact"); return false; } - if (target == null || !dragged.HasComponent()) + if (target == null || !_entities.HasComponent(dragged)) { reason = Loc.GetString("comp-climbable-cant-climb"); return false; } - bool Ignored(IEntity entity) => entity == target || entity == user || entity == dragged; + bool Ignored(EntityUid entity) => entity == target || entity == user || entity == dragged; if (!user.InRangeUnobstructed(target, Range, predicate: Ignored) || !user.InRangeUnobstructed(dragged, Range, predicate: Ignored)) @@ -146,7 +148,7 @@ namespace Content.Server.Climbing.Components return true; } - private async void TryMoveEntity(IEntity user, IEntity entityToMove) + private async void TryMoveEntity(EntityUid user, EntityUid entityToMove) { var doAfterEventArgs = new DoAfterEventArgs(user, _climbDelay, default, entityToMove) { @@ -158,14 +160,14 @@ namespace Content.Server.Climbing.Components var result = await EntitySystem.Get().WaitDoAfter(doAfterEventArgs); - if (result != DoAfterStatus.Cancelled && entityToMove.TryGetComponent(out PhysicsComponent? body) && body.Fixtures.Count >= 1) + if (result != DoAfterStatus.Cancelled && _entities.TryGetComponent(entityToMove, out PhysicsComponent? body) && body.Fixtures.Count >= 1) { - var entityPos = entityToMove.Transform.WorldPosition; + var entityPos = _entities.GetComponent(entityToMove).WorldPosition; - var direction = (Owner.Transform.WorldPosition - entityPos).Normalized; - var endPoint = Owner.Transform.WorldPosition; + var direction = (_entities.GetComponent(Owner).WorldPosition - entityPos).Normalized; + var endPoint = _entities.GetComponent(Owner).WorldPosition; - var climbMode = entityToMove.GetComponent(); + var climbMode = _entities.GetComponent(entityToMove); climbMode.IsClimbing = true; if (MathF.Abs(direction.X) < 0.6f) // user climbed mostly vertically so lets make it a clean straight line @@ -190,9 +192,9 @@ namespace Content.Server.Climbing.Components } } - public async void TryClimb(IEntity user) + public async void TryClimb(EntityUid user) { - if (!user.TryGetComponent(out ClimbingComponent? climbingComponent) || climbingComponent.IsClimbing) + if (!_entities.TryGetComponent(user, out ClimbingComponent? climbingComponent) || climbingComponent.IsClimbing) return; var doAfterEventArgs = new DoAfterEventArgs(user, _climbDelay, default, Owner) @@ -205,24 +207,24 @@ namespace Content.Server.Climbing.Components var result = await EntitySystem.Get().WaitDoAfter(doAfterEventArgs); - if (result != DoAfterStatus.Cancelled && user.TryGetComponent(out PhysicsComponent? body) && body.Fixtures.Count >= 1) + if (result != DoAfterStatus.Cancelled && _entities.TryGetComponent(user, out PhysicsComponent? body) && body.Fixtures.Count >= 1) { // TODO: Remove the copy-paste code - var userPos = user.Transform.WorldPosition; + var userPos = _entities.GetComponent(user).WorldPosition; - var direction = (Owner.Transform.WorldPosition - userPos).Normalized; - var endPoint = Owner.Transform.WorldPosition; + var direction = (_entities.GetComponent(Owner).WorldPosition - userPos).Normalized; + var endPoint = _entities.GetComponent(Owner).WorldPosition; - var climbMode = user.GetComponent(); + var climbMode = _entities.GetComponent(user); climbMode.IsClimbing = true; if (MathF.Abs(direction.X) < 0.6f) // user climbed mostly vertically so lets make it a clean straight line { - endPoint = new Vector2(user.Transform.WorldPosition.X, endPoint.Y); + endPoint = new Vector2(_entities.GetComponent(user).WorldPosition.X, endPoint.Y); } else if (MathF.Abs(direction.Y) < 0.6f) // user climbed mostly horizontally so lets make it a clean straight line { - endPoint = new Vector2(endPoint.X, user.Transform.WorldPosition.Y); + endPoint = new Vector2(endPoint.X, _entities.GetComponent(user).WorldPosition.Y); } climbMode.TryMoveTo(userPos, endPoint); diff --git a/Content.Server/Climbing/Components/ClimbingComponent.cs b/Content.Server/Climbing/Components/ClimbingComponent.cs index eec79514ec..8bcc497b4d 100644 --- a/Content.Server/Climbing/Components/ClimbingComponent.cs +++ b/Content.Server/Climbing/Components/ClimbingComponent.cs @@ -81,11 +81,11 @@ namespace Content.Server.Climbing.Components // Since there are bodies with different masses: // mass * 5 seems enough to move entity - // instead of launching cats like rockets against the walls with constant impulse value. + // instead of launching cats like rockets against the walls with constant impulse value. Body.ApplyLinearImpulse((to - from).Normalized * velocity * Body.Mass * 5); OwnerIsTransitioning = true; - EntitySystem.Get().UnsetTransitionBoolAfterBufferTime(OwnerUid, this); + EntitySystem.Get().UnsetTransitionBoolAfterBufferTime(Owner, this); } public void Update() diff --git a/Content.Server/Cloning/CloningSystem.cs b/Content.Server/Cloning/CloningSystem.cs index fa3b2a1cfc..28089177c9 100644 --- a/Content.Server/Cloning/CloningSystem.cs +++ b/Content.Server/Cloning/CloningSystem.cs @@ -34,13 +34,13 @@ namespace Content.Server.Cloning internal void TransferMindToClone(Mind.Mind mind) { - if (!ClonesWaitingForMind.TryGetValue(mind, out var entityUid) || - !EntityManager.TryGetEntity(entityUid, out var entity) || - !entity.TryGetComponent(out MindComponent? mindComp) || + if (!ClonesWaitingForMind.TryGetValue(mind, out var entity) || + !EntityManager.EntityExists(entity) || + !EntityManager.TryGetComponent(entity, out MindComponent? mindComp) || mindComp.Mind != null) return; - mind.TransferTo(entity.Uid, ghostCheckOverride: true); + mind.TransferTo(entity, ghostCheckOverride: true); mind.UnVisit(); ClonesWaitingForMind.Remove(mind); } @@ -48,7 +48,7 @@ namespace Content.Server.Cloning private void HandleActivate(EntityUid uid, CloningPodComponent component, ActivateInWorldEvent args) { if (!component.Powered || - !args.User.TryGetComponent(out ActorComponent? actor)) + !EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) { return; } @@ -59,11 +59,11 @@ namespace Content.Server.Cloning private void HandleMindAdded(EntityUid uid, BeingClonedComponent component, MindAddedMessage message) { if (component.Parent == EntityUid.Invalid || - !EntityManager.TryGetEntity(component.Parent, out var parent) || - !parent.TryGetComponent(out var cloningPodComponent) || + !EntityManager.EntityExists(component.Parent) || + !EntityManager.TryGetComponent(component.Parent, out var cloningPodComponent) || component.Owner != cloningPodComponent.BodyContainer?.ContainedEntity) { - component.Owner.RemoveComponent(); + EntityManager.RemoveComponent(component.Owner); return; } diff --git a/Content.Server/Cloning/Components/CloningPodComponent.cs b/Content.Server/Cloning/Components/CloningPodComponent.cs index d9faa3d082..6a00e39095 100644 --- a/Content.Server/Cloning/Components/CloningPodComponent.cs +++ b/Content.Server/Cloning/Components/CloningPodComponent.cs @@ -1,6 +1,6 @@ using System; -using Content.Server.EUI; using Content.Server.Climbing; +using Content.Server.EUI; using Content.Server.Mind.Components; using Content.Server.Power.Components; using Content.Server.UserInterface; @@ -23,10 +23,12 @@ namespace Content.Server.Cloning.Components public class CloningPodComponent : SharedCloningPodComponent { [Dependency] private readonly IPlayerManager _playerManager = null!; + [Dependency] private readonly IEntityManager _entities = default!; + [Dependency] private readonly EuiManager _euiManager = null!; [ViewVariables] - public bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + public bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; [ViewVariables] public BoundUserInterface? UserInterface => @@ -70,7 +72,7 @@ namespace Content.Server.Cloning.Components private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(CloningPodVisuals.Status, Status); } @@ -78,20 +80,21 @@ namespace Content.Server.Cloning.Components private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj) { - if (obj.Message is not CloningPodUiButtonPressedMessage message) return; + if (obj.Message is not CloningPodUiButtonPressedMessage message || obj.Session.AttachedEntity == null) + return; switch (message.Button) { case UiButton.Clone: if (BodyContainer.ContainedEntity != null) { - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-occupied")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-occupied")); return; } if (message.ScanId == null) { - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-no-selection")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-no-selection")); return; } @@ -99,21 +102,21 @@ namespace Content.Server.Cloning.Components if (!cloningSystem.IdToDNA.TryGetValue(message.ScanId.Value, out var dna)) { - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-bad-selection")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-bad-selection")); return; // ScanId is not in database } var mind = dna.Mind; - if (cloningSystem.ClonesWaitingForMind.TryGetValue(mind, out var cloneUid)) + if (cloningSystem.ClonesWaitingForMind.TryGetValue(mind, out var clone)) { - if (Owner.EntityManager.TryGetEntity(cloneUid, out var clone) && - clone.TryGetComponent(out var cloneState) && + if (_entities.EntityExists(clone) && + _entities.TryGetComponent(clone, out var cloneState) && !cloneState.IsDead() && - clone.TryGetComponent(out MindComponent? cloneMindComp) && + _entities.TryGetComponent(clone, out MindComponent? cloneMindComp) && (cloneMindComp.Mind == null || cloneMindComp.Mind == mind)) { - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-already-cloning")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-already-cloning")); return; // Mind already has clone } @@ -121,33 +124,33 @@ namespace Content.Server.Cloning.Components } if (mind.OwnedEntity != null && - mind.OwnedEntity.TryGetComponent(out var state) && + _entities.TryGetComponent(mind.OwnedEntity.Value, out var state) && !state.IsDead()) { - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-already-alive")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-already-alive")); return; // Body controlled by mind is not dead } // Yes, we still need to track down the client because we need to open the Eui if (mind.UserId == null || !_playerManager.TryGetSessionById(mind.UserId.Value, out var client)) { - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-user-offline")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("cloning-pod-component-msg-user-offline")); return; // If we can't track down the client, we can't offer transfer. That'd be quite bad. } - var mob = Owner.EntityManager.SpawnEntity("MobHuman", Owner.Transform.MapPosition); + var mob = _entities.SpawnEntity("MobHuman", _entities.GetComponent(Owner).MapPosition); - EntitySystem.Get().UpdateFromProfile(mob.Uid, dna.Profile); - mob.Name = dna.Profile.Name; + EntitySystem.Get().UpdateFromProfile(mob, dna.Profile); + _entities.GetComponent(mob).EntityName = dna.Profile.Name; - var cloneMindReturn = mob.AddComponent(); + var cloneMindReturn = _entities.AddComponent(mob); cloneMindReturn.Mind = mind; - cloneMindReturn.Parent = Owner.Uid; + cloneMindReturn.Parent = Owner; BodyContainer.Insert(mob); CapturedMind = mind; - cloningSystem.ClonesWaitingForMind.Add(mind, mob.Uid); + cloningSystem.ClonesWaitingForMind.Add(mind, mob); UpdateStatus(CloningPodStatus.NoMind); @@ -167,16 +170,15 @@ namespace Content.Server.Cloning.Components public void Eject() { - var entity = BodyContainer.ContainedEntity; - if (entity == null || CloningProgress < CloningTime) + if (BodyContainer.ContainedEntity is not {Valid: true} entity || CloningProgress < CloningTime) return; - entity.RemoveComponent(); - BodyContainer.Remove(entity!); + _entities.RemoveComponent(entity); + BodyContainer.Remove(entity); CapturedMind = null; CloningProgress = 0f; UpdateStatus(CloningPodStatus.Idle); - EntitySystem.Get().ForciblySetClimbing(entity.Uid); + EntitySystem.Get().ForciblySetClimbing(entity); } public void UpdateStatus(CloningPodStatus status) diff --git a/Content.Server/Clothing/Components/ClothingComponent.cs b/Content.Server/Clothing/Components/ClothingComponent.cs index 98249d4ab8..101af363e8 100644 --- a/Content.Server/Clothing/Components/ClothingComponent.cs +++ b/Content.Server/Clothing/Components/ClothingComponent.cs @@ -8,7 +8,7 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; -using Robust.Shared.Players; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; using static Content.Shared.Inventory.EquipmentSlotDefines; @@ -21,6 +21,8 @@ namespace Content.Server.Clothing.Components [NetworkedComponent()] public class ClothingComponent : ItemComponent, IUse { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "Clothing"; [ViewVariables] @@ -60,8 +62,8 @@ namespace Content.Server.Clothing.Components bool IUse.UseEntity(UseEntityEventArgs eventArgs) { if (!_quickEquipEnabled) return false; - if (!eventArgs.User.TryGetComponent(out InventoryComponent? inv) - || !eventArgs.User.TryGetComponent(out HandsComponent? hands)) return false; + if (!_entities.TryGetComponent(eventArgs.User, out InventoryComponent? inv) + || !_entities.TryGetComponent(eventArgs.User, out HandsComponent? hands)) return false; foreach (var (slot, flag) in SlotMasks) { @@ -79,14 +81,14 @@ namespace Content.Server.Clothing.Components { hands.Drop(item.Owner); inv.Equip(slot, item); - hands.PutInHand(Owner.GetComponent()); + hands.PutInHand(_entities.GetComponent(Owner)); } } else { hands.Drop(Owner); if (!TryEquip(inv, slot, eventArgs.User)) - hands.PutInHand(Owner.GetComponent()); + hands.PutInHand(_entities.GetComponent(Owner)); } return true; @@ -95,7 +97,7 @@ namespace Content.Server.Clothing.Components return false; } - public bool TryEquip(InventoryComponent inv, Slots slot, IEntity user) + public bool TryEquip(InventoryComponent inv, Slots slot, EntityUid user) { if (!inv.Equip(slot, this, true, out var reason)) { diff --git a/Content.Server/Clothing/Components/MagbootsComponent.cs b/Content.Server/Clothing/Components/MagbootsComponent.cs index dc000ac78e..a0e19db7cc 100644 --- a/Content.Server/Clothing/Components/MagbootsComponent.cs +++ b/Content.Server/Clothing/Components/MagbootsComponent.cs @@ -2,7 +2,6 @@ using Content.Server.Alert; using Content.Server.Atmos.Components; using Content.Server.Inventory.Components; using Content.Server.Items; -using Content.Shared.ActionBlocker; using Content.Shared.Actions; using Content.Shared.Actions.Behaviors.Item; using Content.Shared.Actions.Components; @@ -10,13 +9,11 @@ using Content.Shared.Alert; using Content.Shared.Clothing; using Content.Shared.Interaction; using Content.Shared.Inventory; -using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; -using Robust.Shared.Localization; -using Robust.Shared.Players; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; using static Content.Shared.Inventory.EquipmentSlotDefines; @@ -30,6 +27,9 @@ namespace Content.Server.Clothing.Components [ComponentDependency] private ItemComponent? _item = null; [ComponentDependency] private ItemActionsComponent? _itemActions = null; [ComponentDependency] private SpriteComponent? _sprite = null; + + [Dependency] private readonly IEntityManager _entMan = default!; + private bool _on; [ViewVariables] @@ -50,7 +50,7 @@ namespace Content.Server.Clothing.Components } } - public void Toggle(IEntity user) + public void Toggle(EntityUid user) { On = !On; } @@ -59,12 +59,12 @@ namespace Content.Server.Clothing.Components { if (On && eventArgs.Slot == Slots.SHOES) { - if (eventArgs.User.TryGetComponent(out MovedByPressureComponent? movedByPressure)) + if (_entMan.TryGetComponent(eventArgs.User, out MovedByPressureComponent? movedByPressure)) { movedByPressure.Enabled = true; } - if (eventArgs.User.TryGetComponent(out ServerAlertsComponent? alerts)) + if (_entMan.TryGetComponent(eventArgs.User, out ServerAlertsComponent? alerts)) { alerts.ClearAlert(AlertType.Magboots); } @@ -81,15 +81,15 @@ namespace Content.Server.Clothing.Components if (!Owner.TryGetContainer(out var container)) return; - if (container.Owner.TryGetComponent(out InventoryComponent? inventoryComponent) + if (_entMan.TryGetComponent(container.Owner, out InventoryComponent? inventoryComponent) && inventoryComponent.GetSlotItem(Slots.SHOES)?.Owner == Owner) { - if (container.Owner.TryGetComponent(out MovedByPressureComponent? movedByPressure)) + if (_entMan.TryGetComponent(container.Owner, out MovedByPressureComponent? movedByPressure)) { movedByPressure.Enabled = false; } - if (container.Owner.TryGetComponent(out ServerAlertsComponent? alerts)) + if (_entMan.TryGetComponent(container.Owner, out ServerAlertsComponent? alerts)) { if (On) { @@ -126,7 +126,7 @@ namespace Content.Server.Clothing.Components { public bool DoToggleAction(ToggleItemActionEventArgs args) { - if (!args.Item.TryGetComponent(out var magboots)) + if (!IoCManager.Resolve().TryGetComponent(args.Item, out var magboots)) return false; magboots.Toggle(args.Performer); diff --git a/Content.Server/Commands/CommandUtils.cs b/Content.Server/Commands/CommandUtils.cs index a1f42144b8..2efd80be47 100644 --- a/Content.Server/Commands/CommandUtils.cs +++ b/Content.Server/Commands/CommandUtils.cs @@ -39,9 +39,9 @@ namespace Content.Server.Commands /// sending a failure to the performer if unable to. /// public static bool TryGetAttachedEntityByUsernameOrId(IConsoleShell shell, - string usernameOrId, IPlayerSession performer, [NotNullWhen(true)] out IEntity? attachedEntity) + string usernameOrId, IPlayerSession performer, out EntityUid attachedEntity) { - attachedEntity = null; + attachedEntity = default; if (!TryGetSessionByUsernameOrId(shell, usernameOrId, performer, out var session)) return false; if (session.AttachedEntity == null) { @@ -49,38 +49,42 @@ namespace Content.Server.Commands return false; } - attachedEntity = session.AttachedEntity; + attachedEntity = session.AttachedEntity.Value; return true; } - public static string SubstituteEntityDetails(IConsoleShell shell, IEntity ent, string ruleString) + public static string SubstituteEntityDetails(IConsoleShell shell, EntityUid ent, string ruleString) { + var entMan = IoCManager.Resolve(); + var transform = entMan.GetComponent(ent); + // gross, is there a better way to do this? - ruleString = ruleString.Replace("$ID", ent.Uid.ToString()); + ruleString = ruleString.Replace("$ID", ent.ToString()); ruleString = ruleString.Replace("$WX", - ent.Transform.WorldPosition.X.ToString(CultureInfo.InvariantCulture)); + transform.WorldPosition.X.ToString(CultureInfo.InvariantCulture)); ruleString = ruleString.Replace("$WY", - ent.Transform.WorldPosition.Y.ToString(CultureInfo.InvariantCulture)); + transform.WorldPosition.Y.ToString(CultureInfo.InvariantCulture)); ruleString = ruleString.Replace("$LX", - ent.Transform.LocalPosition.X.ToString(CultureInfo.InvariantCulture)); + transform.LocalPosition.X.ToString(CultureInfo.InvariantCulture)); ruleString = ruleString.Replace("$LY", - ent.Transform.LocalPosition.Y.ToString(CultureInfo.InvariantCulture)); - ruleString = ruleString.Replace("$NAME", ent.Name); + transform.LocalPosition.Y.ToString(CultureInfo.InvariantCulture)); + ruleString = ruleString.Replace("$NAME", entMan.GetComponent(ent).EntityName); if (shell.Player is IPlayerSession player) { - if (player.AttachedEntity != null) + if (player.AttachedEntity is {Valid: true} p) { - var p = player.AttachedEntity; - ruleString = ruleString.Replace("$PID", ent.Uid.ToString()); + var pTransform = entMan.GetComponent(p); + + ruleString = ruleString.Replace("$PID", ent.ToString()); ruleString = ruleString.Replace("$PWX", - p.Transform.WorldPosition.X.ToString(CultureInfo.InvariantCulture)); + pTransform.WorldPosition.X.ToString(CultureInfo.InvariantCulture)); ruleString = ruleString.Replace("$PWY", - p.Transform.WorldPosition.Y.ToString(CultureInfo.InvariantCulture)); + pTransform.WorldPosition.Y.ToString(CultureInfo.InvariantCulture)); ruleString = ruleString.Replace("$PLX", - p.Transform.LocalPosition.X.ToString(CultureInfo.InvariantCulture)); + pTransform.LocalPosition.X.ToString(CultureInfo.InvariantCulture)); ruleString = ruleString.Replace("$PLY", - p.Transform.LocalPosition.Y.ToString(CultureInfo.InvariantCulture)); + pTransform.LocalPosition.Y.ToString(CultureInfo.InvariantCulture)); } } return ruleString; diff --git a/Content.Server/Communications/CommunicationsConsoleComponent.cs b/Content.Server/Communications/CommunicationsConsoleComponent.cs index 117d24e691..7d8b826bcb 100644 --- a/Content.Server/Communications/CommunicationsConsoleComponent.cs +++ b/Content.Server/Communications/CommunicationsConsoleComponent.cs @@ -7,13 +7,9 @@ using Content.Server.Power.Components; using Content.Server.RoundEnd; using Content.Server.UserInterface; using Content.Shared.Communications; -using Content.Shared.Interaction; using Robust.Server.GameObjects; -using Robust.Server.Player; -using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Player; using Robust.Shared.Timing; using Robust.Shared.ViewVariables; using Timer = Robust.Shared.Timing.Timer; @@ -25,7 +21,9 @@ namespace Content.Server.Communications { [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly IChatManager _chatManager = default!; - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + [Dependency] private readonly IEntityManager _entities = default!; + + private bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; private RoundEndSystem RoundEndSystem => EntitySystem.Get(); @@ -109,8 +107,7 @@ namespace Content.Server.Communications var message = msg.Message.Length <= 256 ? msg.Message.Trim() : $"{msg.Message.Trim().Substring(0, 256)}..."; var author = "Unknown"; - var mob = obj.Session.AttachedEntity; - if (mob != null && mob.TryGetHeldId(out var id)) + if (obj.Session.AttachedEntity is {Valid: true} mob && mob.TryGetHeldId(out var id)) { author = $"{id.FullName} ({CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id.JobTitle ?? string.Empty)})".Trim(); } diff --git a/Content.Server/Computer/ComputerComponent.cs b/Content.Server/Computer/ComputerComponent.cs index 8985fcd82e..fd8d06c597 100644 --- a/Content.Server/Computer/ComputerComponent.cs +++ b/Content.Server/Computer/ComputerComponent.cs @@ -5,6 +5,7 @@ using Content.Server.Power.Components; using Content.Shared.Computer; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -14,6 +15,8 @@ namespace Content.Server.Computer [RegisterComponent] public sealed class ComputerComponent : SharedComputerComponent, IMapInit { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables] [DataField("board")] private string? _boardPrototype; @@ -25,8 +28,8 @@ namespace Content.Server.Computer // Let's ensure the container manager and container are here. Owner.EnsureContainer("board", out var _); - if (Owner.TryGetComponent(out ApcPowerReceiverComponent? powerReceiver) && - Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? powerReceiver) && + _entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(ComputerVisuals.Powered, powerReceiver.Powered); } @@ -48,7 +51,7 @@ namespace Content.Server.Computer private void PowerReceiverOnOnPowerStateChanged(PowerChangedMessage e) { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(ComputerVisuals.Powered, e.Powered); } @@ -62,8 +65,8 @@ namespace Content.Server.Computer private void CreateComputerBoard() { // Ensure that the construction component is aware of the board container. - if (Owner.TryGetComponent(out ConstructionComponent? construction)) - EntitySystem.Get().AddContainer(Owner.Uid, "board", construction); + if (_entMan.TryGetComponent(Owner, out ConstructionComponent? construction)) + EntitySystem.Get().AddContainer(Owner, "board", construction); // We don't do anything if this is null or empty. if (string.IsNullOrEmpty(_boardPrototype)) @@ -78,7 +81,7 @@ namespace Content.Server.Computer return; } - var board = Owner.EntityManager.SpawnEntity(_boardPrototype, Owner.Transform.Coordinates); + var board = _entMan.SpawnEntity(_boardPrototype, _entMan.GetComponent(Owner).Coordinates); if(!container.Insert(board)) Logger.Warning($"Couldn't insert board {board} to computer {Owner}!"); diff --git a/Content.Server/Configurable/ConfigurationComponent.cs b/Content.Server/Configurable/ConfigurationComponent.cs index 570c193a95..d3ef71b925 100644 --- a/Content.Server/Configurable/ConfigurationComponent.cs +++ b/Content.Server/Configurable/ConfigurationComponent.cs @@ -12,6 +12,7 @@ using Content.Shared.Verbs; using Robust.Server.Console; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; @@ -23,6 +24,8 @@ namespace Content.Server.Configurable [ComponentReference(typeof(SharedConfigurationComponent))] public class ConfigurationComponent : SharedConfigurationComponent, IInteractUsing, ISerializationHooks { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(ConfigurationUiKey.Key); [DataField("keys")] private List _keys = new(); @@ -80,10 +83,10 @@ namespace Content.Server.Configurable async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (UserInterface == null || !eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (UserInterface == null || !_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return false; - if (!eventArgs.Using.TryGetComponent(out var tool) || !tool.Qualities.Contains(_qualityNeeded)) + if (!_entMan.TryGetComponent(eventArgs.Using, out var tool) || !tool.Qualities.Contains(_qualityNeeded)) return false; OpenUserInterface(actor); diff --git a/Content.Server/Construction/AnchorableSystem.cs b/Content.Server/Construction/AnchorableSystem.cs index 2e82c95e55..358379a621 100644 --- a/Content.Server/Construction/AnchorableSystem.cs +++ b/Content.Server/Construction/AnchorableSystem.cs @@ -30,10 +30,10 @@ namespace Content.Server.Construction return; // If the used entity doesn't have a tool, return early. - if (!EntityManager.TryGetComponent(args.UsedUid, out ToolComponent? usedTool)) + if (!EntityManager.TryGetComponent(args.Used, out ToolComponent? usedTool)) return; - args.Handled = await TryToggleAnchor(uid, args.UserUid, args.UsedUid, anchorable, usingTool:usedTool); + args.Handled = await TryToggleAnchor(uid, args.User, args.Used, anchorable, usingTool:usedTool); } /// diff --git a/Content.Server/Construction/Commands/FixRotationsCommand.cs b/Content.Server/Construction/Commands/FixRotationsCommand.cs index 318c21edc9..34c6cdcd49 100644 --- a/Content.Server/Construction/Commands/FixRotationsCommand.cs +++ b/Content.Server/Construction/Commands/FixRotationsCommand.cs @@ -1,5 +1,4 @@ using Content.Server.Administration; -using Content.Server.Window; using Content.Server.Power.Components; using Content.Shared.Administration; using Content.Shared.Construction; @@ -24,19 +23,19 @@ namespace Content.Server.Construction.Commands public void Execute(IConsoleShell shell, string argsOther, string[] args) { var player = shell.Player as IPlayerSession; - + var entityManager = IoCManager.Resolve(); GridId gridId; switch (args.Length) { case 0: - if (player?.AttachedEntity == null) + if (player?.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine("Only a player can run this command."); return; } - gridId = player.AttachedEntity.Transform.GridID; + gridId = entityManager.GetComponent(playerEntity).GridID; break; case 1: if (!int.TryParse(args[0], out var id)) @@ -59,17 +58,16 @@ namespace Content.Server.Construction.Commands return; } - var entityManager = IoCManager.Resolve(); - if (!entityManager.TryGetEntity(grid.GridEntityId, out var gridEntity)) + if (!entityManager.EntityExists(grid.GridEntityId)) { shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity."); return; } var changed = 0; - foreach (var childUid in gridEntity.Transform.ChildEntityUids) + foreach (var child in entityManager.GetComponent(grid.GridEntityId).ChildEntities) { - if (!entityManager.TryGetEntity(childUid, out var childEntity)) + if (!entityManager.EntityExists(child)) { continue; } @@ -78,27 +76,27 @@ namespace Content.Server.Construction.Commands // Occluders should only count if the state of it right now is enabled. // This prevents issues with edge firelocks. - if (entityManager.TryGetComponent(childUid, out var occluder)) + if (entityManager.TryGetComponent(child, out var occluder)) { valid |= occluder.Enabled; } // low walls & grilles - valid |= childEntity.HasComponent(); + valid |= entityManager.HasComponent(child); // cables - valid |= childEntity.HasComponent(); + valid |= entityManager.HasComponent(child); // anything else that might need this forced - valid |= childEntity.HasTag("ForceFixRotations"); + valid |= child.HasTag("ForceFixRotations"); // override - valid &= !childEntity.HasTag("ForceNoFixRotations"); + valid &= !child.HasTag("ForceNoFixRotations"); if (!valid) { continue; } - if (childEntity.Transform.LocalRotation != Angle.Zero) + if (entityManager.GetComponent(child).LocalRotation != Angle.Zero) { - childEntity.Transform.LocalRotation = Angle.Zero; + entityManager.GetComponent(child).LocalRotation = Angle.Zero; changed++; } } diff --git a/Content.Server/Construction/Commands/TileWallsCommand.cs b/Content.Server/Construction/Commands/TileWallsCommand.cs index eeb1e32552..caaab9fa97 100644 --- a/Content.Server/Construction/Commands/TileWallsCommand.cs +++ b/Content.Server/Construction/Commands/TileWallsCommand.cs @@ -21,18 +21,19 @@ namespace Content.Server.Construction.Commands public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; + var entityManager = IoCManager.Resolve(); GridId gridId; switch (args.Length) { case 0: - if (player?.AttachedEntity == null) + if (player?.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine("Only a player can run this command."); return; } - gridId = player.AttachedEntity.Transform.GridID; + gridId = entityManager.GetComponent(playerEntity).GridID; break; case 1: if (!int.TryParse(args[0], out var id)) @@ -55,8 +56,7 @@ namespace Content.Server.Construction.Commands return; } - var entityManager = IoCManager.Resolve(); - if (!entityManager.TryGetEntity(grid.GridEntityId, out var gridEntity)) + if (!entityManager.EntityExists(grid.GridEntityId)) { shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity."); return; @@ -65,16 +65,16 @@ namespace Content.Server.Construction.Commands var tileDefinitionManager = IoCManager.Resolve(); var prototypeManager = IoCManager.Resolve(); var underplating = tileDefinitionManager["underplating"]; - var underplatingTile = new Robust.Shared.Map.Tile(underplating.TileId); + var underplatingTile = new Tile(underplating.TileId); var changed = 0; - foreach (var childUid in gridEntity.Transform.ChildEntityUids) + foreach (var child in entityManager.GetComponent(grid.GridEntityId).ChildEntities) { - if (!entityManager.TryGetEntity(childUid, out var childEntity)) + if (!entityManager.EntityExists(child)) { continue; } - var prototype = childEntity.Prototype; + var prototype = entityManager.GetComponent(child).EntityPrototype; while (true) { if (prototype?.Parent == null) @@ -90,12 +90,14 @@ namespace Content.Server.Construction.Commands continue; } - if (!childEntity.Transform.Anchored) + var childTransform = entityManager.GetComponent(child); + + if (!childTransform.Anchored) { continue; } - var tile = grid.GetTileRef(childEntity.Transform.Coordinates); + var tile = grid.GetTileRef(childTransform.Coordinates); var tileDef = (ContentTileDefinition) tileDefinitionManager[tile.Tile.TypeId]; if (tileDef.Name == "underplating") @@ -103,7 +105,7 @@ namespace Content.Server.Construction.Commands continue; } - grid.SetTile(childEntity.Transform.Coordinates, underplatingTile); + grid.SetTile(childTransform.Coordinates, underplatingTile); changed++; } diff --git a/Content.Server/Construction/Completions/BuildComputer.cs b/Content.Server/Construction/Completions/BuildComputer.cs index fdf7d6c134..f5618e10a1 100644 --- a/Content.Server/Construction/Completions/BuildComputer.cs +++ b/Content.Server/Construction/Completions/BuildComputer.cs @@ -1,11 +1,11 @@ using System.Linq; -using System.Threading.Tasks; using Content.Server.Construction.Components; using Content.Shared.Construction; using JetBrains.Annotations; using Robust.Server.Containers; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; @@ -40,7 +40,7 @@ namespace Content.Server.Construction.Completions var board = container.ContainedEntities[0]; - if (!board.TryGetComponent(out ComputerBoardComponent? boardComponent)) + if (!entityManager.TryGetComponent(board, out ComputerBoardComponent? boardComponent)) { Logger.Warning($"Computer entity {uid} had an invalid entity in container \"{Container}\"! Aborting build computer action."); return; @@ -50,21 +50,21 @@ namespace Content.Server.Construction.Completions var transform = entityManager.GetComponent(uid); var computer = entityManager.SpawnEntity(boardComponent.Prototype, transform.Coordinates); - computer.Transform.LocalRotation = transform.LocalRotation; + entityManager.GetComponent(computer).LocalRotation = transform.LocalRotation; - var computerContainer = containerSystem.EnsureContainer(computer.Uid, Container); + var computerContainer = containerSystem.EnsureContainer(computer, Container); // In case it already existed and there are any entities inside the container, delete them. foreach (var ent in computerContainer.ContainedEntities.ToArray()) { computerContainer.ForceRemove(ent); - ent.Delete(); + entityManager.DeleteEntity(ent); } computerContainer.Insert(board); // We only add this container. If some construction needs to take other containers into account, fix this. - entityManager.EntitySysManager.GetEntitySystem().AddContainer(computer.Uid, Container); + entityManager.EntitySysManager.GetEntitySystem().AddContainer(computer, Container); // Delete the original entity. entityManager.DeleteEntity(uid); diff --git a/Content.Server/Construction/Completions/BuildMachine.cs b/Content.Server/Construction/Completions/BuildMachine.cs index 499c942243..8dc732f7c7 100644 --- a/Content.Server/Construction/Completions/BuildMachine.cs +++ b/Content.Server/Construction/Completions/BuildMachine.cs @@ -5,6 +5,7 @@ using Content.Shared.Construction; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; @@ -53,7 +54,7 @@ namespace Content.Server.Construction.Completions var board = entBoardContainer.ContainedEntities[0]; - if (!board.TryGetComponent(out MachineBoardComponent? boardComponent)) + if (!entityManager.TryGetComponent(board, out MachineBoardComponent? boardComponent)) { Logger.Warning($"Machine frame entity {uid} had an invalid entity in container \"{MachineFrameComponent.BoardContainer}\"! Aborting build machine action."); return; @@ -63,7 +64,7 @@ namespace Content.Server.Construction.Completions var transform = entityManager.GetComponent(uid); var machine = entityManager.SpawnEntity(boardComponent.Prototype, transform.Coordinates); - machine.Transform.LocalRotation = transform.LocalRotation; + entityManager.GetComponent(machine).LocalRotation = transform.LocalRotation; var boardContainer = machine.EnsureContainer(MachineFrameComponent.BoardContainer, out var existed); @@ -91,14 +92,14 @@ namespace Content.Server.Construction.Completions } var constructionSystem = entityManager.EntitySysManager.GetEntitySystem(); - if (machine.TryGetComponent(out ConstructionComponent? construction)) + if (entityManager.TryGetComponent(machine, out ConstructionComponent? construction)) { // We only add these two container. If some construction needs to take other containers into account, fix this. - constructionSystem.AddContainer(machine.Uid, MachineFrameComponent.BoardContainer, construction); - constructionSystem.AddContainer(machine.Uid, MachineFrameComponent.PartContainer, construction); + constructionSystem.AddContainer(machine, MachineFrameComponent.BoardContainer, construction); + constructionSystem.AddContainer(machine, MachineFrameComponent.PartContainer, construction); } - if (machine.TryGetComponent(out MachineComponent? machineComp)) + if (entityManager.TryGetComponent(machine, out MachineComponent? machineComp)) { machineComp.RefreshParts(); } diff --git a/Content.Server/Construction/Completions/DeleteEntitiesInContainer.cs b/Content.Server/Construction/Completions/DeleteEntitiesInContainer.cs index c66e8abf1d..db0d71c58a 100644 --- a/Content.Server/Construction/Completions/DeleteEntitiesInContainer.cs +++ b/Content.Server/Construction/Completions/DeleteEntitiesInContainer.cs @@ -1,8 +1,8 @@ using System.Linq; -using System.Threading.Tasks; using Content.Shared.Construction; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Construction.Completions @@ -22,7 +22,7 @@ namespace Content.Server.Construction.Completions foreach (var contained in container.ContainedEntities.ToArray()) { if(container.Remove(contained)) - contained.QueueDelete(); + entityManager.QueueDeleteEntity(contained); } } } diff --git a/Content.Server/Construction/Completions/EmptyContainer.cs b/Content.Server/Construction/Completions/EmptyContainer.cs index 7cb0c7791f..a1e866a5d5 100644 --- a/Content.Server/Construction/Completions/EmptyContainer.cs +++ b/Content.Server/Construction/Completions/EmptyContainer.cs @@ -25,8 +25,9 @@ namespace Content.Server.Construction.Completions foreach (var contained in container.ContainedEntities.ToArray()) { container.ForceRemove(contained); - contained.Transform.Coordinates = transform.Coordinates; - contained.Transform.AttachToGridOrMap(); + var cTransform = entityManager.GetComponent(contained); + cTransform.Coordinates = transform.Coordinates; + cTransform.AttachToGridOrMap(); } } } diff --git a/Content.Server/Construction/Completions/SpawnPrototype.cs b/Content.Server/Construction/Completions/SpawnPrototype.cs index 391ac5d3f3..226cfb567e 100644 --- a/Content.Server/Construction/Completions/SpawnPrototype.cs +++ b/Content.Server/Construction/Completions/SpawnPrototype.cs @@ -26,8 +26,8 @@ namespace Content.Server.Construction.Completions if (EntityPrototypeHelpers.HasComponent(Prototype)) { var stackEnt = entityManager.SpawnEntity(Prototype, coordinates); - var stack = stackEnt.GetComponent(); - entityManager.EntitySysManager.GetEntitySystem().SetCount(stackEnt.Uid, Amount, stack); + var stack = entityManager.GetComponent(stackEnt); + entityManager.EntitySysManager.GetEntitySystem().SetCount(stackEnt, Amount, stack); } else { diff --git a/Content.Server/Construction/Components/MachineComponent.cs b/Content.Server/Construction/Components/MachineComponent.cs index 2c970c3843..4614dd4cf5 100644 --- a/Content.Server/Construction/Components/MachineComponent.cs +++ b/Content.Server/Construction/Components/MachineComponent.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Content.Server.Stack; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Construction.Components @@ -10,6 +11,8 @@ namespace Content.Server.Construction.Components [RegisterComponent] public class MachineComponent : Component, IMapInit { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Machine"; [DataField("board")] @@ -30,14 +33,14 @@ namespace Content.Server.Construction.Components { foreach (var entity in _partContainer.ContainedEntities) { - if (entity.TryGetComponent(out var machinePart)) + if (_entMan.TryGetComponent(entity, out var machinePart)) yield return machinePart; } } public void RefreshParts() { - foreach (var refreshable in Owner.GetAllComponents()) + foreach (var refreshable in _entMan.GetComponents(Owner)) { refreshable.RefreshParts(GetAllParts()); } @@ -52,7 +55,7 @@ namespace Content.Server.Construction.Components if (string.IsNullOrEmpty(BoardPrototype)) return; - var entityManager = Owner.EntityManager; + var entityManager = _entMan; if (existedBoard || existedParts) { @@ -61,14 +64,14 @@ namespace Content.Server.Construction.Components return; } - var board = entityManager.SpawnEntity(BoardPrototype, Owner.Transform.Coordinates); + var board = entityManager.SpawnEntity(BoardPrototype, _entMan.GetComponent(Owner).Coordinates); if (!_boardContainer.Insert(board)) { - throw new Exception($"Couldn't insert board with prototype {BoardPrototype} to machine with prototype {Owner.Prototype?.ID ?? "N/A"}!"); + throw new Exception($"Couldn't insert board with prototype {BoardPrototype} to machine with prototype {_entMan.GetComponent(Owner).EntityPrototype?.ID ?? "N/A"}!"); } - if (!board.TryGetComponent(out var machineBoard)) + if (!_entMan.TryGetComponent(board, out var machineBoard)) { throw new Exception($"Entity with prototype {BoardPrototype} doesn't have a {nameof(MachineBoardComponent)}!"); } @@ -77,29 +80,29 @@ namespace Content.Server.Construction.Components { for (var i = 0; i < amount; i++) { - var p = entityManager.SpawnEntity(MachinePartComponent.Prototypes[part], Owner.Transform.Coordinates); + var p = entityManager.SpawnEntity(MachinePartComponent.Prototypes[part], _entMan.GetComponent(Owner).Coordinates); if (!partContainer.Insert(p)) - throw new Exception($"Couldn't insert machine part of type {part} to machine with prototype {Owner.Prototype?.ID ?? "N/A"}!"); + throw new Exception($"Couldn't insert machine part of type {part} to machine with prototype {_entMan.GetComponent(Owner).EntityPrototype?.ID ?? "N/A"}!"); } } foreach (var (stackType, amount) in machineBoard.MaterialRequirements) { - var stack = EntitySystem.Get().Spawn(amount, stackType, Owner.Transform.Coordinates); + var stack = EntitySystem.Get().Spawn(amount, stackType, _entMan.GetComponent(Owner).Coordinates); - if (!partContainer.Insert(Owner.EntityManager.GetEntity(stack))) - throw new Exception($"Couldn't insert machine material of type {stackType} to machine with prototype {Owner.Prototype?.ID ?? "N/A"}"); + if (!partContainer.Insert(stack)) + throw new Exception($"Couldn't insert machine material of type {stackType} to machine with prototype {_entMan.GetComponent(Owner).EntityPrototype?.ID ?? "N/A"}"); } foreach (var (compName, info) in machineBoard.ComponentRequirements) { for (var i = 0; i < info.Amount; i++) { - var c = entityManager.SpawnEntity(info.DefaultPrototype, Owner.Transform.Coordinates); + var c = entityManager.SpawnEntity(info.DefaultPrototype, _entMan.GetComponent(Owner).Coordinates); if(!partContainer.Insert(c)) - throw new Exception($"Couldn't insert machine component part with default prototype '{compName}' to machine with prototype {Owner.Prototype?.ID ?? "N/A"}"); + throw new Exception($"Couldn't insert machine component part with default prototype '{compName}' to machine with prototype {_entMan.GetComponent(Owner).EntityPrototype?.ID ?? "N/A"}"); } } @@ -107,10 +110,10 @@ namespace Content.Server.Construction.Components { for (var i = 0; i < info.Amount; i++) { - var c = entityManager.SpawnEntity(info.DefaultPrototype, Owner.Transform.Coordinates); + var c = entityManager.SpawnEntity(info.DefaultPrototype, _entMan.GetComponent(Owner).Coordinates); if(!partContainer.Insert(c)) - throw new Exception($"Couldn't insert machine component part with default prototype '{tagName}' to machine with prototype {Owner.Prototype?.ID ?? "N/A"}"); + throw new Exception($"Couldn't insert machine component part with default prototype '{tagName}' to machine with prototype {_entMan.GetComponent(Owner).EntityPrototype?.ID ?? "N/A"}"); } } } diff --git a/Content.Server/Construction/Components/MachineFrameComponent.cs b/Content.Server/Construction/Components/MachineFrameComponent.cs index 7dfe524b50..8b4eccb4d8 100644 --- a/Content.Server/Construction/Components/MachineFrameComponent.cs +++ b/Content.Server/Construction/Components/MachineFrameComponent.cs @@ -15,6 +15,7 @@ namespace Content.Server.Construction.Components [RegisterComponent] public class MachineFrameComponent : Component, IInteractUsing { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IComponentFactory _componentFactory = default!; public const string PartContainer = "machine_parts"; @@ -121,10 +122,10 @@ namespace Content.Server.Construction.Components RegenerateProgress(); - if (Owner.TryGetComponent(out var construction)) + if (_entMan.TryGetComponent(Owner, out var construction)) { // Attempt to set pathfinding to the machine node... - EntitySystem.Get().SetPathfindingTarget(OwnerUid, "machine", construction); + EntitySystem.Get().SetPathfindingTarget(Owner, "machine", construction); } } @@ -167,7 +168,7 @@ namespace Content.Server.Construction.Components if (!HasBoard) { - if (Owner.TryGetComponent(out appearance)) + if (_entMan.TryGetComponent(Owner, out appearance)) { appearance.SetData(MachineFrameVisuals.State, 1); } @@ -186,10 +187,10 @@ namespace Content.Server.Construction.Components var board = _boardContainer.ContainedEntities[0]; - if (!board.TryGetComponent(out var machineBoard)) + if (!_entMan.TryGetComponent(board, out var machineBoard)) return; - if (Owner.TryGetComponent(out appearance)) + if (_entMan.TryGetComponent(Owner, out appearance)) { appearance.SetData(MachineFrameVisuals.State, 2); } @@ -198,7 +199,7 @@ namespace Content.Server.Construction.Components foreach (var part in _partContainer.ContainedEntities) { - if (part.TryGetComponent(out var machinePart)) + if (_entMan.TryGetComponent(part, out var machinePart)) { // Check this is part of the requirements... if (!Requirements.ContainsKey(machinePart.PartType)) @@ -210,7 +211,7 @@ namespace Content.Server.Construction.Components _progress[machinePart.PartType]++; } - if (part.TryGetComponent(out var stack)) + if (_entMan.TryGetComponent(part, out var stack)) { var type = stack.StackTypeId; // Check this is part of the requirements... @@ -228,7 +229,7 @@ namespace Content.Server.Construction.Components { var registration = _componentFactory.GetRegistration(compName); - if (!part.HasComponent(registration.Type)) + if (!_entMan.HasComponent(part, registration.Type)) continue; if (!_componentProgress.ContainsKey(compName)) @@ -253,7 +254,7 @@ namespace Content.Server.Construction.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (!HasBoard && eventArgs.Using.TryGetComponent(out var machineBoard)) + if (!HasBoard && _entMan.TryGetComponent(eventArgs.Using, out var machineBoard)) { if (eventArgs.Using.TryRemoveFromContainer()) { @@ -263,15 +264,15 @@ namespace Content.Server.Construction.Components // Setup requirements and progress... ResetProgressAndRequirements(machineBoard); - if (Owner.TryGetComponent(out var appearance)) + if (_entMan.TryGetComponent(Owner, out var appearance)) { appearance.SetData(MachineFrameVisuals.State, 2); } - if (Owner.TryGetComponent(out ConstructionComponent? construction)) + if (_entMan.TryGetComponent(Owner, out ConstructionComponent? construction)) { // So prying the components off works correctly. - EntitySystem.Get().ResetEdge(OwnerUid, construction); + EntitySystem.Get().ResetEdge(Owner, construction); } return true; @@ -279,7 +280,7 @@ namespace Content.Server.Construction.Components } else if (HasBoard) { - if (eventArgs.Using.TryGetComponent(out var machinePart)) + if (_entMan.TryGetComponent(eventArgs.Using, out var machinePart)) { if (!Requirements.ContainsKey(machinePart.PartType)) return false; @@ -292,7 +293,7 @@ namespace Content.Server.Construction.Components } } - if (eventArgs.Using.TryGetComponent(out var stack)) + if (_entMan.TryGetComponent(eventArgs.Using, out var stack)) { var type = stack.StackTypeId; if (!MaterialRequirements.ContainsKey(type)) @@ -313,12 +314,12 @@ namespace Content.Server.Construction.Components return true; } - var splitStack = EntitySystem.Get().Split(eventArgs.Using.Uid, needed, Owner.Transform.Coordinates, stack); + var splitStack = EntitySystem.Get().Split(eventArgs.Using, needed, _entMan.GetComponent(Owner).Coordinates, stack); if (splitStack == null) return false; - if(!_partContainer.Insert(Owner.EntityManager.GetEntity(splitStack.Value))) + if(!_partContainer.Insert(splitStack.Value)) return false; _materialProgress[type] += needed; @@ -332,7 +333,7 @@ namespace Content.Server.Construction.Components var registration = _componentFactory.GetRegistration(compName); - if (!eventArgs.Using.HasComponent(registration.Type)) + if (!_entMan.HasComponent(eventArgs.Using, registration.Type)) continue; if (!eventArgs.Using.TryRemoveFromContainer() || !_partContainer.Insert(eventArgs.Using)) continue; diff --git a/Content.Server/Construction/Components/WelderRefinableComponent.cs b/Content.Server/Construction/Components/WelderRefinableComponent.cs index c6eb09027d..8c54997437 100644 --- a/Content.Server/Construction/Components/WelderRefinableComponent.cs +++ b/Content.Server/Construction/Components/WelderRefinableComponent.cs @@ -4,13 +4,11 @@ using Content.Server.Stack; using Content.Server.Tools; using Content.Server.Tools.Components; using Content.Shared.Interaction; -using Content.Shared.Stacks; using Content.Shared.Tools; -using Content.Shared.Tools.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; -using Robust.Shared.ViewVariables; namespace Content.Server.Construction.Components { @@ -21,6 +19,8 @@ namespace Content.Server.Construction.Components [RegisterComponent] public class WelderRefinableComponent : Component, IInteractUsing { + [Dependency] private readonly IEntityManager _entMan = default!; + [DataField("refineResult")] private HashSet? _refineResult = new() { }; @@ -40,7 +40,7 @@ namespace Content.Server.Construction.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { // check if object is welder - if (!eventArgs.Using.TryGetComponent(out ToolComponent? tool)) + if (!_entMan.TryGetComponent(eventArgs.Using, out ToolComponent? tool)) return false; // check if someone is already welding object @@ -51,7 +51,7 @@ namespace Content.Server.Construction.Components var toolSystem = EntitySystem.Get(); - if (!await toolSystem.UseTool(eventArgs.Using.Uid, eventArgs.User.Uid, Owner.Uid, _refineFuel, _refineTime, _qualityNeeded)) + if (!await toolSystem.UseTool(eventArgs.Using, eventArgs.User, Owner, _refineFuel, _refineTime, _qualityNeeded)) { // failed to veld - abort refine _beingWelded = false; @@ -59,18 +59,18 @@ namespace Content.Server.Construction.Components } // get last owner coordinates and delete it - var resultPosition = Owner.Transform.Coordinates; - Owner.Delete(); + var resultPosition = _entMan.GetComponent(Owner).Coordinates; + _entMan.DeleteEntity(Owner); // spawn each result after refine foreach (var result in _refineResult!) { - var droppedEnt = Owner.EntityManager.SpawnEntity(result, resultPosition); + var droppedEnt = _entMan.SpawnEntity(result, resultPosition); // TODO: If something has a stack... Just use a prototype with a single thing in the stack. // This is not a good way to do it. - if (droppedEnt.TryGetComponent(out var stack)) - EntitySystem.Get().SetCount(droppedEnt.Uid,1, stack); + if (_entMan.TryGetComponent(droppedEnt, out var stack)) + EntitySystem.Get().SetCount(droppedEnt,1, stack); } return true; diff --git a/Content.Server/Construction/Conditions/AirlockBolted.cs b/Content.Server/Construction/Conditions/AirlockBolted.cs index 0314d208b6..db5c289747 100644 --- a/Content.Server/Construction/Conditions/AirlockBolted.cs +++ b/Content.Server/Construction/Conditions/AirlockBolted.cs @@ -8,6 +8,7 @@ using Robust.Shared.Utility; using System.Threading.Tasks; using Content.Server.Doors.Components; using Content.Shared.Examine; +using Robust.Shared.IoC; namespace Content.Server.Construction.Conditions { @@ -30,14 +31,16 @@ namespace Content.Server.Construction.Conditions { var entity = args.Examined; - if (!entity.TryGetComponent(out AirlockComponent? airlock)) return false; + var entMan = IoCManager.Resolve(); + + if (!entMan.TryGetComponent(entity, out AirlockComponent? airlock)) return false; if (airlock.BoltsDown != Value) { if (Value == true) - args.PushMarkup(Loc.GetString("construction-examine-condition-airlock-bolt", ("entityName", entity.Name)) + "\n"); + args.PushMarkup(Loc.GetString("construction-examine-condition-airlock-bolt", ("entityName", Name: entMan.GetComponent(entity).EntityName)) + "\n"); else - args.PushMarkup(Loc.GetString("construction-examine-condition-airlock-unbolt", ("entityName", entity.Name)) + "\n"); + args.PushMarkup(Loc.GetString("construction-examine-condition-airlock-unbolt", ("entityName", Name: entMan.GetComponent(entity).EntityName)) + "\n"); return true; } diff --git a/Content.Server/Construction/Conditions/ComponentInTile.cs b/Content.Server/Construction/Conditions/ComponentInTile.cs index 05fb8674ce..5cea711ce6 100644 --- a/Content.Server/Construction/Conditions/ComponentInTile.cs +++ b/Content.Server/Construction/Conditions/ComponentInTile.cs @@ -56,7 +56,7 @@ namespace Content.Server.Construction.Conditions foreach (var ent in entities) { - if (ent.HasComponent(type)) + if (entityManager.HasComponent(ent, type)) return HasEntity; } diff --git a/Content.Server/Construction/Conditions/ContainerEmpty.cs b/Content.Server/Construction/Conditions/ContainerEmpty.cs index 9eeb81aafa..be149bb975 100644 --- a/Content.Server/Construction/Conditions/ContainerEmpty.cs +++ b/Content.Server/Construction/Conditions/ContainerEmpty.cs @@ -6,6 +6,7 @@ using JetBrains.Annotations; using Robust.Server.Containers; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -44,7 +45,7 @@ namespace Content.Server.Construction.Conditions var entity = args.Examined; - if (!entity.TryGetComponent(out ContainerManagerComponent? containerManager) || + if (!IoCManager.Resolve().TryGetComponent(entity, out ContainerManagerComponent? containerManager) || !containerManager.TryGetContainer(Container, out var container)) return false; if (container.ContainedEntities.Count == 0) diff --git a/Content.Server/Construction/Conditions/ContainerNotEmpty.cs b/Content.Server/Construction/Conditions/ContainerNotEmpty.cs index 3c384b498c..5daa7b61f0 100644 --- a/Content.Server/Construction/Conditions/ContainerNotEmpty.cs +++ b/Content.Server/Construction/Conditions/ContainerNotEmpty.cs @@ -6,6 +6,7 @@ using JetBrains.Annotations; using Robust.Server.Containers; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -37,7 +38,7 @@ namespace Content.Server.Construction.Conditions var entity = args.Examined; - if (!entity.TryGetComponent(out ContainerManagerComponent? containerManager) || + if (!IoCManager.Resolve().TryGetComponent(entity, out ContainerManagerComponent? containerManager) || !containerManager.TryGetContainer(Container, out var container)) return false; if (container.ContainedEntities.Count != 0) diff --git a/Content.Server/Construction/Conditions/DoorWelded.cs b/Content.Server/Construction/Conditions/DoorWelded.cs index 147b3a63ad..2ba8f99c92 100644 --- a/Content.Server/Construction/Conditions/DoorWelded.cs +++ b/Content.Server/Construction/Conditions/DoorWelded.cs @@ -4,6 +4,7 @@ using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; @@ -28,14 +29,16 @@ namespace Content.Server.Construction.Conditions { var entity = args.Examined; - if (!entity.TryGetComponent(out ServerDoorComponent? door)) return false; + var entMan = IoCManager.Resolve(); + + if (!entMan.TryGetComponent(entity, out ServerDoorComponent? door)) return false; if (door.IsWeldedShut != Welded) { if (Welded == true) - args.PushMarkup(Loc.GetString("construction-examine-condition-door-weld", ("entityName", entity.Name)) + "\n"); + args.PushMarkup(Loc.GetString("construction-examine-condition-door-weld", ("entityName", Name: entMan.GetComponent(entity).EntityName)) + "\n"); else - args.PushMarkup(Loc.GetString("construction-examine-condition-door-unweld", ("entityName", entity.Name)) + "\n"); + args.PushMarkup(Loc.GetString("construction-examine-condition-door-unweld", ("entityName", Name: entMan.GetComponent(entity).EntityName)) + "\n"); return true; } diff --git a/Content.Server/Construction/Conditions/EntityAnchored.cs b/Content.Server/Construction/Conditions/EntityAnchored.cs index e1b503c440..9c89e89aa4 100644 --- a/Content.Server/Construction/Conditions/EntityAnchored.cs +++ b/Content.Server/Construction/Conditions/EntityAnchored.cs @@ -4,6 +4,7 @@ using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Physics; using Robust.Shared.Serialization.Manager.Attributes; @@ -27,12 +28,14 @@ namespace Content.Server.Construction.Conditions { var entity = args.Examined; + var anchored = IoCManager.Resolve().GetComponent(entity).Anchored; + switch (Anchored) { - case true when !entity.Transform.Anchored: + case true when !anchored: args.PushMarkup(Loc.GetString("construction-examine-condition-entity-anchored")); return true; - case false when entity.Transform.Anchored: + case false when anchored: args.PushMarkup(Loc.GetString("construction-examine-condition-entity-unanchored")); return true; } diff --git a/Content.Server/Construction/Conditions/Locked.cs b/Content.Server/Construction/Conditions/Locked.cs index 6204b42067..36f6c1899d 100644 --- a/Content.Server/Construction/Conditions/Locked.cs +++ b/Content.Server/Construction/Conditions/Locked.cs @@ -5,6 +5,7 @@ using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -28,9 +29,10 @@ namespace Content.Server.Construction.Conditions public bool DoExamine(ExaminedEvent args) { + var entMan = IoCManager.Resolve(); var entity = args.Examined; - if (!entity.TryGetComponent(out LockComponent? lockcomp)) return false; + if (!entMan.TryGetComponent(entity, out LockComponent? lockcomp)) return false; switch (IsLocked) { diff --git a/Content.Server/Construction/Conditions/MachineFrameComplete.cs b/Content.Server/Construction/Conditions/MachineFrameComplete.cs index 9b598be314..7e4fec885a 100644 --- a/Content.Server/Construction/Conditions/MachineFrameComplete.cs +++ b/Content.Server/Construction/Conditions/MachineFrameComplete.cs @@ -5,6 +5,7 @@ using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -37,7 +38,7 @@ namespace Content.Server.Construction.Conditions { var entity = args.Examined; - if (!entity.TryGetComponent(out var machineFrame)) + if (!IoCManager.Resolve().TryGetComponent(entity, out var machineFrame)) return false; if (!machineFrame.HasBoard) diff --git a/Content.Server/Construction/Conditions/StorageWelded.cs b/Content.Server/Construction/Conditions/StorageWelded.cs index 435b16dcf9..b3780821c2 100644 --- a/Content.Server/Construction/Conditions/StorageWelded.cs +++ b/Content.Server/Construction/Conditions/StorageWelded.cs @@ -4,6 +4,7 @@ using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; @@ -26,16 +27,19 @@ namespace Content.Server.Construction.Conditions public bool DoExamine(ExaminedEvent args) { + var entMan = IoCManager.Resolve(); var entity = args.Examined; - if (!entity.TryGetComponent(out EntityStorageComponent? entityStorage)) return false; + if (!entMan.TryGetComponent(entity, out EntityStorageComponent? entityStorage)) return false; + + var metaData = entMan.GetComponent(entity); if (entityStorage.IsWeldedShut != Welded) { if (Welded == true) - args.PushMarkup(Loc.GetString("construction-examine-condition-door-weld", ("entityName", entity.Name)) + "\n"); + args.PushMarkup(Loc.GetString("construction-examine-condition-door-weld", ("entityName", metaData.EntityName)) + "\n"); else - args.PushMarkup(Loc.GetString("construction-examine-condition-door-unweld", ("entityName", entity.Name)) + "\n"); + args.PushMarkup(Loc.GetString("construction-examine-condition-door-unweld", ("entityName", metaData.EntityName)) + "\n"); return true; } diff --git a/Content.Server/Construction/Conditions/ToiletLidClosed.cs b/Content.Server/Construction/Conditions/ToiletLidClosed.cs index 490113cb83..52aca37833 100644 --- a/Content.Server/Construction/Conditions/ToiletLidClosed.cs +++ b/Content.Server/Construction/Conditions/ToiletLidClosed.cs @@ -4,6 +4,7 @@ using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; @@ -25,7 +26,7 @@ namespace Content.Server.Construction.Conditions { var entity = args.Examined; - if (!entity.TryGetComponent(out ToiletComponent? toilet)) return false; + if (!IoCManager.Resolve().TryGetComponent(entity, out ToiletComponent? toilet)) return false; if (!toilet.LidOpen) return false; args.PushMarkup(Loc.GetString("construction-examine-condition-toilet-lid-closed") + "\n"); diff --git a/Content.Server/Construction/Conditions/WirePanel.cs b/Content.Server/Construction/Conditions/WirePanel.cs index 859c5af53c..9a818ea1ae 100644 --- a/Content.Server/Construction/Conditions/WirePanel.cs +++ b/Content.Server/Construction/Conditions/WirePanel.cs @@ -5,6 +5,7 @@ using Content.Shared.Construction; using Content.Shared.Examine; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -29,7 +30,7 @@ namespace Content.Server.Construction.Conditions { var entity = args.Examined; - if (!entity.TryGetComponent(out WiresComponent? wires)) return false; + if (!IoCManager.Resolve().TryGetComponent(entity, out WiresComponent? wires)) return false; switch (Open) { diff --git a/Content.Server/Construction/ConstructionSystem.Graph.cs b/Content.Server/Construction/ConstructionSystem.Graph.cs index 128273bdb8..109a89c445 100644 --- a/Content.Server/Construction/ConstructionSystem.Graph.cs +++ b/Content.Server/Construction/ConstructionSystem.Graph.cs @@ -1,9 +1,7 @@ -using System.Collections.Generic; using Content.Server.Construction.Components; using Content.Shared.Construction; using Content.Shared.Construction.Prototypes; using Content.Shared.Construction.Steps; -using Microsoft.EntityFrameworkCore.Metadata.Builders; using Robust.Server.Containers; using Robust.Shared.Containers; using Robust.Shared.GameObjects; @@ -166,7 +164,7 @@ namespace Content.Server.Construction Resolve(uid, ref containerManager, false); // We create the new entity. - var newUid = EntityManager.SpawnEntity(newEntity, transform.Coordinates).Uid; + var newUid = EntityManager.SpawnEntity(newEntity, transform.Coordinates); // Construction transferring. var newConstruction = EntityManager.EnsureComponent(newUid); diff --git a/Content.Server/Construction/ConstructionSystem.Initial.cs b/Content.Server/Construction/ConstructionSystem.Initial.cs index 3da7c15098..5de9d4f8a5 100644 --- a/Content.Server/Construction/ConstructionSystem.Initial.cs +++ b/Content.Server/Construction/ConstructionSystem.Initial.cs @@ -43,13 +43,13 @@ namespace Content.Server.Construction } // LEGACY CODE. See warning at the top of the file! - private IEnumerable EnumerateNearby(IEntity user) + private IEnumerable EnumerateNearby(EntityUid user) { - if (user.TryGetComponent(out HandsComponent? hands)) + if (EntityManager.TryGetComponent(user, out HandsComponent? hands)) { foreach (var itemComponent in hands?.GetAllHeldItems()!) { - if (itemComponent.Owner.TryGetComponent(out ServerStorageComponent? storage)) + if (EntityManager.TryGetComponent(itemComponent.Owner, out ServerStorageComponent? storage)) { foreach (var storedEntity in storage.StoredEntities!) { @@ -61,11 +61,11 @@ namespace Content.Server.Construction } } - if (user!.TryGetComponent(out InventoryComponent? inventory)) + if (EntityManager.TryGetComponent(user!, out InventoryComponent? inventory)) { foreach (var held in inventory.GetAllHeldItems()) { - if (held.TryGetComponent(out ServerStorageComponent? storage)) + if (EntityManager.TryGetComponent(held, out ServerStorageComponent? storage)) { foreach (var storedEntity in storage.StoredEntities!) { @@ -84,7 +84,7 @@ namespace Content.Server.Construction } // LEGACY CODE. See warning at the top of the file! - private async Task Construct(IEntity user, string materialContainer, ConstructionGraphPrototype graph, ConstructionGraphEdge edge, ConstructionGraphNode targetNode) + private async Task Construct(EntityUid user, string materialContainer, ConstructionGraphPrototype graph, ConstructionGraphEdge edge, ConstructionGraphNode targetNode) { // We need a place to hold our construction items! var container = ContainerHelpers.EnsureContainer(user, materialContainer, out var existed); @@ -164,17 +164,17 @@ namespace Content.Server.Construction if (!materialStep.EntityValid(entity, out var stack)) continue; - var splitStack = _stackSystem.Split(entity.Uid, materialStep.Amount, user.ToCoordinates(), stack); + var splitStack = _stackSystem.Split(entity, materialStep.Amount, user.ToCoordinates(0, 0), stack); if (splitStack == null) continue; if (string.IsNullOrEmpty(materialStep.Store)) { - if (!container.Insert(EntityManager.GetEntity(splitStack.Value))) + if (!container.Insert(splitStack.Value)) continue; } - else if (!GetContainer(materialStep.Store).Insert(EntityManager.GetEntity(splitStack.Value))) + else if (!GetContainer(materialStep.Store).Insert(splitStack.Value)) continue; handled = true; @@ -186,7 +186,7 @@ namespace Content.Server.Construction case ArbitraryInsertConstructionGraphStep arbitraryStep: foreach (var entity in EnumerateNearby(user)) { - if (!arbitraryStep.EntityValid(entity.Uid, EntityManager)) + if (!arbitraryStep.EntityValid(entity, EntityManager)) continue; if (string.IsNullOrEmpty(arbitraryStep.Store)) @@ -235,13 +235,13 @@ namespace Content.Server.Construction return null; } - var newEntity = EntityManager.SpawnEntity(graph.Nodes[edge.Target].Entity, user.Transform.Coordinates); + var newEntity = EntityManager.SpawnEntity(graph.Nodes[edge.Target].Entity, EntityManager.GetComponent(user).Coordinates); // Yes, this should throw if it's missing the component. - var construction = newEntity.GetComponent(); + var construction = EntityManager.GetComponent(newEntity); // We attempt to set the pathfinding target. - SetPathfindingTarget(newEntity.Uid, targetNode.Name, construction); + SetPathfindingTarget(newEntity, targetNode.Name, construction); // We preserve the containers... foreach (var (name, cont) in containers) @@ -263,14 +263,14 @@ namespace Content.Server.Construction { foreach (var completed in step.Completed) { - completed.PerformAction(newEntity.Uid, user.Uid, EntityManager); + completed.PerformAction(newEntity, user, EntityManager); } } // And we also have edge completed effects! foreach (var completed in edge.Completed) { - completed.PerformAction(newEntity.Uid, user.Uid, EntityManager); + completed.PerformAction(newEntity, user, EntityManager); } return newEntity; @@ -285,9 +285,11 @@ namespace Content.Server.Construction return; } - if (!_prototypeManager.TryIndex(constructionPrototype.Graph, out ConstructionGraphPrototype? constructionGraph)) + if (!_prototypeManager.TryIndex(constructionPrototype.Graph, + out ConstructionGraphPrototype? constructionGraph)) { - _sawmill.Error($"Invalid construction graph '{constructionPrototype.Graph}' in recipe '{ev.PrototypeName}'!"); + _sawmill.Error( + $"Invalid construction graph '{constructionPrototype.Graph}' in recipe '{ev.PrototypeName}'!"); return; } @@ -295,25 +297,26 @@ namespace Content.Server.Construction var targetNode = constructionGraph.Nodes[constructionPrototype.TargetNode]; var pathFind = constructionGraph.Path(startNode.Name, targetNode.Name); - var user = args.SenderSession.AttachedEntity; + if (args.SenderSession.AttachedEntity is not {Valid: true} user || + !Get().CanInteract(user)) return; - if (user == null || !Get().CanInteract(user.Uid)) return; - - if (!user.TryGetComponent(out HandsComponent? hands)) return; + if (!EntityManager.TryGetComponent(user, out HandsComponent? hands)) return; foreach (var condition in constructionPrototype.Conditions) { - if (!condition.Condition(user, user.ToCoordinates(), Direction.South)) + if (!condition.Condition(user, user.ToCoordinates(0, 0), Direction.South)) return; } - if(pathFind == null) - throw new InvalidDataException($"Can't find path from starting node to target node in construction! Recipe: {ev.PrototypeName}"); + if (pathFind == null) + throw new InvalidDataException( + $"Can't find path from starting node to target node in construction! Recipe: {ev.PrototypeName}"); var edge = startNode.GetEdge(pathFind[0].Name); - if(edge == null) - throw new InvalidDataException($"Can't find edge from starting node to the next node in pathfinding! Recipe: {ev.PrototypeName}"); + if (edge == null) + throw new InvalidDataException( + $"Can't find edge from starting node to the next node in pathfinding! Recipe: {ev.PrototypeName}"); // No support for conditions here! @@ -326,9 +329,8 @@ namespace Content.Server.Construction } } - var item = await Construct(user, "item_construction", constructionGraph, edge, targetNode); - - if(item != null && item.TryGetComponent(out ItemComponent? itemComp)) + if (await Construct(user, "item_construction", constructionGraph, edge, targetNode) is {Valid: true} item && + EntityManager.TryGetComponent(item, out ItemComponent? itemComp)) hands.PutInHandOrDrop(itemComp); } @@ -350,9 +352,7 @@ namespace Content.Server.Construction return; } - var user = args.SenderSession.AttachedEntity; - - if (user == null) + if (args.SenderSession.AttachedEntity is not {Valid: true} user) { _sawmill.Error($"Client sent {nameof(TryStartStructureConstructionMessage)} with no attached entity!"); return; @@ -397,9 +397,8 @@ namespace Content.Server.Construction _beingBuilt[args.SenderSession].Remove(ev.Ack); } - if (user == null - || !Get().CanInteract(user.Uid) - || !user.TryGetComponent(out HandsComponent? hands) || hands.GetActiveHand == null + if (!Get().CanInteract(user) + || !EntityManager.TryGetComponent(user, out HandsComponent? hands) || hands.GetActiveHand == null || !user.InRangeUnobstructed(ev.Location, ignoreInsideBlocker:constructionPrototype.CanBuildInImpassable)) { Cleanup(); @@ -415,9 +414,8 @@ namespace Content.Server.Construction throw new InvalidDataException($"Can't find edge from starting node to the next node in pathfinding! Recipe: {ev.PrototypeName}"); var valid = false; - var holding = hands.GetActiveHand?.Owner; - if (holding == null) + if (hands.GetActiveHand?.Owner is not {Valid: true} holding) { Cleanup(); return; @@ -430,7 +428,7 @@ namespace Content.Server.Construction switch (step) { case EntityInsertConstructionGraphStep entityInsert: - if (entityInsert.EntityValid(holding.Uid, EntityManager)) + if (entityInsert.EntityValid(holding, EntityManager)) valid = true; break; case ToolConstructionGraphStep _: @@ -447,9 +445,8 @@ namespace Content.Server.Construction return; } - var structure = await Construct(user, (ev.Ack + constructionPrototype.GetHashCode()).ToString(), constructionGraph, edge, targetNode); - - if (structure == null) + if (await Construct(user, (ev.Ack + constructionPrototype.GetHashCode()).ToString(), constructionGraph, + edge, targetNode) is not {Valid: true} structure) { Cleanup(); return; @@ -457,13 +454,13 @@ namespace Content.Server.Construction // We do this to be able to move the construction to its proper position in case it's anchored... // Oh wow transform anchoring is amazing wow I love it!!!! - var wasAnchored = structure.Transform.Anchored; - structure.Transform.Anchored = false; + var wasAnchored = EntityManager.GetComponent(structure).Anchored; + EntityManager.GetComponent(structure).Anchored = false; - structure.Transform.Coordinates = ev.Location; - structure.Transform.LocalRotation = constructionPrototype.CanRotate ? ev.Angle : Angle.Zero; + EntityManager.GetComponent(structure).Coordinates = ev.Location; + EntityManager.GetComponent(structure).LocalRotation = constructionPrototype.CanRotate ? ev.Angle : Angle.Zero; - structure.Transform.Anchored = wasAnchored; + EntityManager.GetComponent(structure).Anchored = wasAnchored; RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack)); diff --git a/Content.Server/Construction/ConstructionSystem.Interactions.cs b/Content.Server/Construction/ConstructionSystem.Interactions.cs index 30a95d9d81..f506471150 100644 --- a/Content.Server/Construction/ConstructionSystem.Interactions.cs +++ b/Content.Server/Construction/ConstructionSystem.Interactions.cs @@ -273,7 +273,7 @@ namespace Content.Server.Construction if (doAfterState == DoAfterState.Cancelled) return HandleResult.False; - var insert = interactUsing.UsedUid; + var insert = interactUsing.Used; // Since many things inherit this step, we delegate the "is this entity valid?" logic to them. // While this is very OOP and I find it icky, I must admit that it simplifies the code here a lot. @@ -312,7 +312,7 @@ namespace Content.Server.Construction // we split the stack in two and insert the split stack. if (insertStep is MaterialConstructionGraphStep materialInsertStep) { - if (_stackSystem.Split(insert, materialInsertStep.Amount, EntityManager.GetComponent(interactUsing.UserUid).Coordinates) is not {} stack) + if (_stackSystem.Split(insert, materialInsertStep.Amount, EntityManager.GetComponent(interactUsing.User).Coordinates) is not {} stack) return HandleResult.False; insert = stack; @@ -329,8 +329,7 @@ namespace Content.Server.Construction construction.Containers.Add(store); // The container doesn't necessarily need to exist, so we ensure it. - _containerSystem.EnsureContainer(uid, store) - .Insert(EntityManager.GetEntity(insert)); + _containerSystem.EnsureContainer(uid, store).Insert(insert); } else { @@ -349,13 +348,13 @@ namespace Content.Server.Construction // TODO: Sanity checks. - user = interactUsing.User.Uid; + user = interactUsing.User; // If we're validating whether this event handles the step... if (doAfterState == DoAfterState.Validation) { // Then we only really need to check whether the tool entity has that quality or not. - return _toolSystem.HasQuality(interactUsing.Used.Uid, toolInsertStep.Tool) + return _toolSystem.HasQuality(interactUsing.Used, toolInsertStep.Tool) ? HandleResult.Validated : HandleResult.False; } @@ -363,7 +362,7 @@ namespace Content.Server.Construction if (doAfterState != DoAfterState.None) return doAfterState == DoAfterState.Completed ? HandleResult.True : HandleResult.False; - if (!_toolSystem.UseTool(interactUsing.Used.Uid, interactUsing.User.Uid, + if (!_toolSystem.UseTool(interactUsing.Used, interactUsing.User, uid, toolInsertStep.Fuel, toolInsertStep.DoAfter, toolInsertStep.Tool, new ConstructionDoAfterComplete(uid, ev), new ConstructionDoAfterCancelled(uid, ev))) return HandleResult.False; diff --git a/Content.Server/Construction/ConstructionSystem.cs b/Content.Server/Construction/ConstructionSystem.cs index 7aee035026..9386cf1889 100644 --- a/Content.Server/Construction/ConstructionSystem.cs +++ b/Content.Server/Construction/ConstructionSystem.cs @@ -51,13 +51,13 @@ namespace Content.Server.Construction { if (GetCurrentGraph(uid, construction) is not {} graph) { - _sawmill.Warning($"Prototype {construction.Owner.Prototype?.ID}'s construction component has an invalid graph specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid graph specified."); return; } if (GetNodeFromGraph(graph, construction.Node) is not {} node) { - _sawmill.Warning($"Prototype {construction.Owner.Prototype?.ID}'s construction component has an invalid node specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid node specified."); return; } @@ -66,7 +66,7 @@ namespace Content.Server.Construction { if (GetEdgeFromNode(node, edgeIndex) is not {} currentEdge) { - _sawmill.Warning($"Prototype {construction.Owner.Prototype?.ID}'s construction component has an invalid edge index specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid edge index specified."); return; } @@ -77,7 +77,7 @@ namespace Content.Server.Construction { if (GetNodeFromGraph(graph, targetNodeId) is not { } targetNode) { - _sawmill.Warning($"Prototype {construction.Owner.Prototype?.ID}'s construction component has an invalid target node specified."); + _sawmill.Warning($"Prototype {EntityManager.GetComponent(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid target node specified."); return; } diff --git a/Content.Server/Containers/ContainerExt.cs b/Content.Server/Containers/ContainerExt.cs index ed7c338dd0..69e763d1db 100644 --- a/Content.Server/Containers/ContainerExt.cs +++ b/Content.Server/Containers/ContainerExt.cs @@ -1,4 +1,7 @@ using Robust.Shared.Containers; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; +using Robust.Shared.Prototypes; namespace Content.Server.Containers { @@ -6,13 +9,14 @@ namespace Content.Server.Containers { public static int CountPrototypeOccurencesRecursive(this ContainerManagerComponent mgr, string prototypeId) { + var entMan = IoCManager.Resolve(); int total = 0; foreach (var container in mgr.GetAllContainers()) { foreach (var entity in container.ContainedEntities) { - if (entity.Prototype?.ID == prototypeId) total++; - if(!entity.TryGetComponent(out var component)) continue; + if (entMan.GetComponent(entity).EntityPrototype?.ID == prototypeId) total++; + if(!entMan.TryGetComponent(entity, out var component)) continue; total += component.CountPrototypeOccurencesRecursive(prototypeId); } } diff --git a/Content.Server/Containers/EmptyOnMachineDeconstructSystem.cs b/Content.Server/Containers/EmptyOnMachineDeconstructSystem.cs index 14e495edee..1642319c08 100644 --- a/Content.Server/Containers/EmptyOnMachineDeconstructSystem.cs +++ b/Content.Server/Containers/EmptyOnMachineDeconstructSystem.cs @@ -1,8 +1,9 @@ using Content.Server.Construction.Components; +using Content.Shared.Containers.ItemSlots; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; -using Content.Shared.Containers.ItemSlots; +using Robust.Shared.IoC; namespace Content.Server.Containers { @@ -26,7 +27,7 @@ namespace Content.Server.Containers foreach (var slot in component.Slots.Values) { if (slot.EjectOnDeconstruct && slot.Item != null) - slot.ContainerSlot.Remove(slot.Item); + slot.ContainerSlot.Remove(slot.Item.Value); } } @@ -34,7 +35,7 @@ namespace Content.Server.Containers { if (!EntityManager.TryGetComponent(uid, out var mComp)) return; - var baseCoords = component.Owner.Transform.Coordinates; + var baseCoords = EntityManager.GetComponent(component.Owner).Coordinates; foreach (var v in component.Containers) { if (mComp.TryGetContainer(v, out var container)) diff --git a/Content.Server/Conveyor/ConveyorSystem.cs b/Content.Server/Conveyor/ConveyorSystem.cs index f3a56fc9b3..91668d58c9 100644 --- a/Content.Server/Conveyor/ConveyorSystem.cs +++ b/Content.Server/Conveyor/ConveyorSystem.cs @@ -5,12 +5,10 @@ using Content.Server.MachineLinking.Events; using Content.Server.MachineLinking.Models; using Content.Server.Power.Components; using Content.Server.Stunnable; -using Content.Server.Stunnable.Components; using Content.Shared.Conveyor; using Content.Shared.MachineLinking; using Content.Shared.Movement.Components; using Content.Shared.Popups; -using Content.Shared.Stunnable; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -42,9 +40,9 @@ namespace Content.Server.Conveyor private void UpdateAppearance(ConveyorComponent component) { - if (component.Owner.TryGetComponent(out var appearance)) + if (EntityManager.TryGetComponent(component.Owner, out var appearance)) { - if (component.Owner.TryGetComponent(out var receiver) && receiver.Powered) + if (EntityManager.TryGetComponent(component.Owner, out var receiver) && receiver.Powered) { appearance.SetData(ConveyorVisuals.State, component.State); } @@ -100,13 +98,13 @@ namespace Content.Server.Conveyor return false; } - if (component.Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) && + if (EntityManager.TryGetComponent(component.Owner, out ApcPowerReceiverComponent? receiver) && !receiver.Powered) { return false; } - if (component.Owner.HasComponent()) + if (EntityManager.HasComponent(component.Owner)) { return false; } @@ -126,15 +124,15 @@ namespace Content.Server.Conveyor var adjustment = component.State == ConveyorState.Reversed ? MathHelper.Pi/2 : -MathHelper.Pi/2; var radians = MathHelper.DegreesToRadians(component.Angle); - return new Angle(component.Owner.Transform.LocalRotation.Theta + radians + adjustment); + return new Angle(EntityManager.GetComponent(component.Owner).LocalRotation.Theta + radians + adjustment); } - public IEnumerable<(IEntity, IPhysBody)> GetEntitiesToMove(ConveyorComponent comp) + public IEnumerable<(EntityUid, IPhysBody)> GetEntitiesToMove(ConveyorComponent comp) { //todo uuuhhh cache this foreach (var entity in _entityLookup.GetEntitiesIntersecting(comp.Owner, flags: LookupFlags.Approximate)) { - if (entity.Deleted) + if (Deleted(entity)) { continue; } @@ -144,13 +142,13 @@ namespace Content.Server.Conveyor continue; } - if (!entity.TryGetComponent(out IPhysBody? physics) || + if (!EntityManager.TryGetComponent(entity, out IPhysBody? physics) || physics.BodyType == BodyType.Static || physics.BodyStatus == BodyStatus.InAir || entity.IsWeightless()) { continue; } - if (entity.HasComponent()) + if (EntityManager.HasComponent(entity)) { continue; } diff --git a/Content.Server/Coordinates/Helpers/GridTileLookupHelpers.cs b/Content.Server/Coordinates/Helpers/GridTileLookupHelpers.cs index 41587963d4..6eb3297fbf 100644 --- a/Content.Server/Coordinates/Helpers/GridTileLookupHelpers.cs +++ b/Content.Server/Coordinates/Helpers/GridTileLookupHelpers.cs @@ -13,7 +13,7 @@ namespace Content.Server.Coordinates.Helpers /// Helper that returns all entities in a turf very fast. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable GetEntitiesInTileFast(this TileRef turf, GridTileLookupSystem? gridTileLookup = null) + public static IEnumerable GetEntitiesInTileFast(this TileRef turf, GridTileLookupSystem? gridTileLookup = null) { gridTileLookup ??= EntitySystem.Get(); @@ -24,7 +24,7 @@ namespace Content.Server.Coordinates.Helpers /// Helper that returns all entities in a turf. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable GetEntitiesInTileFast(this Vector2i indices, GridId gridId, GridTileLookupSystem? gridTileLookup = null) + public static IEnumerable GetEntitiesInTileFast(this Vector2i indices, GridId gridId, GridTileLookupSystem? gridTileLookup = null) { gridTileLookup ??= EntitySystem.Get(); return gridTileLookup.GetEntitiesIntersecting(gridId, indices); diff --git a/Content.Server/Coordinates/Helpers/SnapgridHelper.cs b/Content.Server/Coordinates/Helpers/SnapgridHelper.cs index c2ab7f3124..8121a064f1 100644 --- a/Content.Server/Coordinates/Helpers/SnapgridHelper.cs +++ b/Content.Server/Coordinates/Helpers/SnapgridHelper.cs @@ -7,17 +7,18 @@ namespace Content.Server.Coordinates.Helpers { public static class SnapgridHelper { - public static void SnapToGrid(this IEntity entity, IEntityManager? entityManager = null, IMapManager? mapManager = null) + public static void SnapToGrid(this EntityUid entity, IEntityManager? entMan = null, IMapManager? mapManager = null) { - entity.Transform.Coordinates = entity.Transform.Coordinates.SnapToGrid(entityManager, mapManager); + IoCManager.Resolve(ref entMan, ref mapManager); + var transform = entMan.GetComponent(entity); + transform.Coordinates = transform.Coordinates.SnapToGrid(entMan, mapManager); } - public static EntityCoordinates SnapToGrid(this EntityCoordinates coordinates, IEntityManager? entityManager = null, IMapManager? mapManager = null) + public static EntityCoordinates SnapToGrid(this EntityCoordinates coordinates, IEntityManager? entMan = null, IMapManager? mapManager = null) { - entityManager ??= IoCManager.Resolve(); - mapManager ??= IoCManager.Resolve(); + IoCManager.Resolve(ref entMan, ref mapManager); - var gridId = coordinates.GetGridId(entityManager); + var gridId = coordinates.GetGridId(entMan); var tileSize = 1f; diff --git a/Content.Server/Crayon/CrayonComponent.cs b/Content.Server/Crayon/CrayonComponent.cs index 302ad335e2..c58fc4d15c 100644 --- a/Content.Server/Crayon/CrayonComponent.cs +++ b/Content.Server/Crayon/CrayonComponent.cs @@ -29,6 +29,7 @@ namespace Content.Server.Crayon [RegisterComponent] public class CrayonComponent : SharedCrayonComponent, IAfterInteract, IUse, IDropped, ISerializationHooks { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [DataField("useSound")] @@ -91,7 +92,7 @@ namespace Content.Server.Crayon // Opens the selection window bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - if (eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { UserInterface?.Toggle(actor.PlayerSession); if (UserInterface?.SessionHasOpen(actor.PlayerSession) == true) @@ -119,7 +120,7 @@ namespace Content.Server.Crayon return true; } - if (!eventArgs.ClickLocation.IsValid(Owner.EntityManager)) + if (!eventArgs.ClickLocation.IsValid(_entMan)) { eventArgs.User.PopupMessage(Loc.GetString("crayon-interact-invalid-location")); return true; @@ -140,7 +141,7 @@ namespace Content.Server.Crayon void IDropped.Dropped(DroppedEventArgs eventArgs) { - if (eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) UserInterface?.Close(actor.PlayerSession); } } diff --git a/Content.Server/Cuffs/Components/CuffableComponent.cs b/Content.Server/Cuffs/Components/CuffableComponent.cs index 367c426388..3c15fdbb6c 100644 --- a/Content.Server/Cuffs/Components/CuffableComponent.cs +++ b/Content.Server/Cuffs/Components/CuffableComponent.cs @@ -4,21 +4,19 @@ using System.Linq; using Content.Server.Alert; using Content.Server.DoAfter; using Content.Server.Hands.Components; -using Content.Shared.ActionBlocker; using Content.Shared.Alert; using Content.Shared.Cuffs.Components; using Content.Shared.Interaction.Helpers; using Content.Shared.Popups; -using Content.Shared.Verbs; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.ViewVariables; namespace Content.Server.Cuffs.Components @@ -27,15 +25,17 @@ namespace Content.Server.Cuffs.Components [ComponentReference(typeof(SharedCuffableComponent))] public class CuffableComponent : SharedCuffableComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + /// /// How many of this entity's hands are currently cuffed. /// [ViewVariables] public int CuffedHandCount => Container.ContainedEntities.Count * 2; - protected IEntity LastAddedCuffs => Container.ContainedEntities[^1]; + protected EntityUid LastAddedCuffs => Container.ContainedEntities[^1]; - public IReadOnlyList StoredEntities => Container.ContainedEntities; + public IReadOnlyList StoredEntities => Container.ContainedEntities; /// /// Container of various handcuffs currently applied to the entity. @@ -66,7 +66,7 @@ namespace Content.Server.Cuffs.Components if (CuffedHandCount > 0) { - if (LastAddedCuffs.TryGetComponent(out var cuffs)) + if (_entMan.TryGetComponent(LastAddedCuffs, out var cuffs)) { return new CuffableComponentState(CuffedHandCount, CanStillInteract, @@ -89,9 +89,9 @@ namespace Content.Server.Cuffs.Components /// Add a set of cuffs to an existing CuffedComponent. /// /// - public bool TryAddNewCuffs(IEntity user, IEntity handcuff) + public bool TryAddNewCuffs(EntityUid user, EntityUid handcuff) { - if (!handcuff.HasComponent()) + if (!_entMan.HasComponent(handcuff)) { Logger.Warning($"Handcuffs being applied to player are missing a {nameof(HandcuffComponent)}!"); return false; @@ -104,14 +104,14 @@ namespace Content.Server.Cuffs.Components } // Success! - if (user.TryGetComponent(out HandsComponent? handsComponent) && handsComponent.IsHolding(handcuff)) + if (_entMan.TryGetComponent(user, out HandsComponent? handsComponent) && handsComponent.IsHolding(handcuff)) { // Good lord handscomponent is scuffed, I hope some smug person will fix it someday handsComponent.Drop(handcuff); } Container.Insert(handcuff); - CanStillInteract = Owner.TryGetComponent(out HandsComponent? ownerHands) && ownerHands.HandNames.Count() > CuffedHandCount; + CanStillInteract = _entMan.TryGetComponent(Owner, out HandsComponent? ownerHands) && ownerHands.HandNames.Count() > CuffedHandCount; OnCuffedStateChanged?.Invoke(); UpdateAlert(); @@ -131,7 +131,7 @@ namespace Content.Server.Cuffs.Components /// public void UpdateHeldItems() { - if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) return; + if (!_entMan.TryGetComponent(Owner, out HandsComponent? handsComponent)) return; var itemCount = handsComponent.GetAllHeldItems().Count(); var freeHandCount = handsComponent.HandNames.Count() - CuffedHandCount; @@ -158,7 +158,7 @@ namespace Content.Server.Cuffs.Components /// private void UpdateAlert() { - if (Owner.TryGetComponent(out ServerAlertsComponent? status)) + if (_entMan.TryGetComponent(Owner, out ServerAlertsComponent? status)) { if (CanStillInteract) { @@ -177,7 +177,7 @@ namespace Content.Server.Cuffs.Components /// /// The cuffed entity /// Optional param for the handcuff entity to remove from the cuffed entity. If null, uses the most recently added handcuff entity. - public async void TryUncuff(IEntity user, IEntity? cuffsToRemove = null) + public async void TryUncuff(EntityUid user, EntityUid cuffsToRemove = default) { if (_uncuffing) return; @@ -200,14 +200,14 @@ namespace Content.Server.Cuffs.Components } } - if (!cuffsToRemove.TryGetComponent(out var cuff)) + if (!_entMan.TryGetComponent(cuffsToRemove, out var cuff)) { Logger.Warning($"A user is trying to remove handcuffs without a {nameof(HandcuffComponent)}. This should never happen!"); return; } - var attempt = new UncuffAttemptEvent(user.Uid, Owner.Uid); - Owner.EntityManager.EventBus.RaiseLocalEvent(user.Uid, attempt); + var attempt = new UncuffAttemptEvent(user, Owner); + _entMan.EventBus.RaiseLocalEvent(user, attempt); if (attempt.Cancelled) { @@ -259,23 +259,23 @@ namespace Content.Server.Cuffs.Components SoundSystem.Play(Filter.Pvs(Owner), cuff.EndUncuffSound.GetSound(), Owner); Container.ForceRemove(cuffsToRemove); - cuffsToRemove.Transform.AttachToGridOrMap(); - cuffsToRemove.Transform.WorldPosition = Owner.Transform.WorldPosition; + _entMan.GetComponent(cuffsToRemove).AttachToGridOrMap(); + _entMan.GetComponent(cuffsToRemove).WorldPosition = _entMan.GetComponent(Owner).WorldPosition; if (cuff.BreakOnRemove) { cuff.Broken = true; - cuffsToRemove.Name = cuff.BrokenName; - cuffsToRemove.Description = cuff.BrokenDesc; + _entMan.GetComponent(cuffsToRemove).EntityName = cuff.BrokenName; + _entMan.GetComponent(cuffsToRemove).EntityDescription = cuff.BrokenDesc; - if (cuffsToRemove.TryGetComponent(out var sprite) && cuff.BrokenState != null) + if (_entMan.TryGetComponent(cuffsToRemove, out var sprite) && cuff.BrokenState != null) { sprite.LayerSetState(0, cuff.BrokenState); // TODO: safety check to see if RSI contains the state? } } - CanStillInteract = Owner.TryGetComponent(out HandsComponent? handsComponent) && handsComponent.HandNames.Count() > CuffedHandCount; + CanStillInteract = _entMan.TryGetComponent(Owner, out HandsComponent? handsComponent) && handsComponent.HandNames.Count() > CuffedHandCount; OnCuffedStateChanged?.Invoke(); UpdateAlert(); Dirty(); diff --git a/Content.Server/Cuffs/Components/HandcuffComponent.cs b/Content.Server/Cuffs/Components/HandcuffComponent.cs index 6110ff60dc..eedbf35fa8 100644 --- a/Content.Server/Cuffs/Components/HandcuffComponent.cs +++ b/Content.Server/Cuffs/Components/HandcuffComponent.cs @@ -2,7 +2,6 @@ using System; using System.Threading.Tasks; using Content.Server.DoAfter; using Content.Server.Hands.Components; -using Content.Server.Stunnable.Components; using Content.Shared.ActionBlocker; using Content.Shared.Cuffs.Components; using Content.Shared.Interaction; @@ -12,10 +11,10 @@ using Content.Shared.Sound; using Content.Shared.Stunnable; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -25,6 +24,8 @@ namespace Content.Server.Cuffs.Components [ComponentReference(typeof(SharedHandcuffComponent))] public class HandcuffComponent : SharedHandcuffComponent, IAfterInteract { + [Dependency] private readonly IEntityManager _entities = default!; + /// /// The time it takes to apply a to an entity. /// @@ -147,7 +148,9 @@ namespace Content.Server.Cuffs.Components { if (_cuffing) return true; - if (eventArgs.Target == null || !EntitySystem.Get().CanUse(eventArgs.User.Uid) || !eventArgs.Target.TryGetComponent(out var cuffed)) + if (eventArgs.Target is not {Valid: true} target || + !EntitySystem.Get().CanUse(eventArgs.User) || + !_entities.TryGetComponent(eventArgs.Target.Value, out var cuffed)) { return false; } @@ -164,7 +167,7 @@ namespace Content.Server.Cuffs.Components return true; } - if (!eventArgs.Target.TryGetComponent(out var hands)) + if (!_entities.TryGetComponent(target, out var hands)) { eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-target-has-no-hands-error",("targetName", eventArgs.Target))); return true; @@ -183,22 +186,22 @@ namespace Content.Server.Cuffs.Components } eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-start-cuffing-target-message",("targetName", eventArgs.Target))); - eventArgs.User.PopupMessage(eventArgs.Target, Loc.GetString("handcuff-component-start-cuffing-by-other-message",("otherName", eventArgs.User))); + eventArgs.User.PopupMessage(target, Loc.GetString("handcuff-component-start-cuffing-by-other-message",("otherName", eventArgs.User))); SoundSystem.Play(Filter.Pvs(Owner), StartCuffSound.GetSound(), Owner); - TryUpdateCuff(eventArgs.User, eventArgs.Target, cuffed); + TryUpdateCuff(eventArgs.User, target, cuffed); return true; } /// /// Update the cuffed state of an entity /// - private async void TryUpdateCuff(IEntity user, IEntity target, CuffableComponent cuffs) + private async void TryUpdateCuff(EntityUid user, EntityUid target, CuffableComponent cuffs) { var cuffTime = CuffTime; - if (target.HasComponent()) + if (_entities.HasComponent(target)) { cuffTime = MathF.Max(0.1f, cuffTime - StunBonus); } diff --git a/Content.Server/Cuffs/CuffableSystem.cs b/Content.Server/Cuffs/CuffableSystem.cs index aaced49f5b..1ca61281d9 100644 --- a/Content.Server/Cuffs/CuffableSystem.cs +++ b/Content.Server/Cuffs/CuffableSystem.cs @@ -55,7 +55,7 @@ namespace Content.Server.Cuffs { return; } - if (!EntityManager.TryGetEntity(args.User, out var userEntity)) + if (!EntityManager.EntityExists(args.User)) { // Should this even be possible? args.Cancel(); @@ -66,7 +66,7 @@ namespace Content.Server.Cuffs if (args.User == args.Target) { // This UncuffAttemptEvent check should probably be In MobStateSystem, not here? - if (userEntity.TryGetComponent(out var state)) + if (EntityManager.TryGetComponent(args.User, out var state)) { // Manually check this. if (state.IsIncapacitated()) @@ -83,14 +83,14 @@ namespace Content.Server.Cuffs else { // Check if the user can interact. - if (!_actionBlockerSystem.CanInteract(userEntity.Uid)) + if (!_actionBlockerSystem.CanInteract(args.User)) { args.Cancel(); } } if (args.Cancelled) { - _popupSystem.PopupEntity(Loc.GetString("cuffable-component-cannot-interact-message"), args.Target, Filter.Entities(userEntity.Uid)); + _popupSystem.PopupEntity(Loc.GetString("cuffable-component-cannot-interact-message"), args.Target, Filter.Entities(args.User)); } } @@ -101,11 +101,11 @@ namespace Content.Server.Cuffs { var owner = message.Sender; - if (!owner.TryGetComponent(out CuffableComponent? cuffable) || + if (!EntityManager.TryGetComponent(owner, out CuffableComponent? cuffable) || !cuffable.Initialized) return; var dirty = false; - var handCount = owner.GetComponentOrNull()?.Count ?? 0; + var handCount = EntityManager.GetComponentOrNull(owner)?.Count ?? 0; while (cuffable.CuffedHandCount > handCount && cuffable.CuffedHandCount > 0) { @@ -115,7 +115,7 @@ namespace Content.Server.Cuffs var entity = container.ContainedEntities[^1]; container.Remove(entity); - entity.Transform.WorldPosition = owner.Transform.WorldPosition; + EntityManager.GetComponent(entity).WorldPosition = EntityManager.GetComponent(owner).WorldPosition; } if (dirty) diff --git a/Content.Server/Damage/Commands/GodModeCommand.cs b/Content.Server/Damage/Commands/GodModeCommand.cs index 80535aac80..1d79d7c20c 100644 --- a/Content.Server/Damage/Commands/GodModeCommand.cs +++ b/Content.Server/Damage/Commands/GodModeCommand.cs @@ -31,13 +31,13 @@ namespace Content.Server.Damage.Commands return; } - if (player.AttachedEntityUid == null) + if (player.AttachedEntity == null) { shell.WriteLine("An entity needs to be specified when you aren't attached to an entity."); return; } - entity = player.AttachedEntityUid.Value; + entity = player.AttachedEntity.Value; break; case 1: if (!EntityUid.TryParse(args[0], out var id)) diff --git a/Content.Server/Damage/Commands/HurtCommand.cs b/Content.Server/Damage/Commands/HurtCommand.cs index 16ddeabb7f..c5b1e28525 100644 --- a/Content.Server/Damage/Commands/HurtCommand.cs +++ b/Content.Server/Damage/Commands/HurtCommand.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; @@ -42,18 +41,15 @@ namespace Content.Server.Damage.Commands return $"Damage Types:{msg}"; } - private delegate void Damage(IEntity entity, bool ignoreResistances); + private delegate void Damage(EntityUid entity, bool ignoreResistances); - private bool TryParseEntity(IConsoleShell shell, IPlayerSession? player, string arg, - [NotNullWhen(true)] out IEntity? entity) + private bool TryParseEntity(IConsoleShell shell, IPlayerSession? player, string arg, out EntityUid entity) { - entity = null; + entity = default; if (arg == "_") { - var playerEntity = player?.AttachedEntity; - - if (playerEntity == null) + if (player?.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine($"You must have a player entity to use this command without specifying an entity.\n{Help}"); return false; @@ -63,33 +59,30 @@ namespace Content.Server.Damage.Commands return true; } - if (!EntityUid.TryParse(arg, out var entityUid)) + if (!EntityUid.TryParse(arg, out entity)) { shell.WriteLine($"{arg} is not a valid entity uid.\n{Help}"); - return false; } var entityManager = IoCManager.Resolve(); - if (!entityManager.TryGetEntity(entityUid, out var parsedEntity)) + if (!entityManager.EntityExists(entity)) { - shell.WriteLine($"No entity found with uid {entityUid}"); - + shell.WriteLine($"No entity found with uid {entity}"); return false; } - entity = parsedEntity; return true; } private bool TryParseDamageArgs( IConsoleShell shell, - IEntity target, + EntityUid target, string[] args, [NotNullWhen(true)] out Damage? func) { - + var entMan = IoCManager.Resolve(); if (!int.TryParse(args[1], out var amount)) { @@ -104,9 +97,9 @@ namespace Content.Server.Damage.Commands func = (entity, ignoreResistances) => { var damage = new DamageSpecifier(damageGroup, amount); - EntitySystem.Get().TryChangeDamage(entity.Uid, damage, ignoreResistances); + EntitySystem.Get().TryChangeDamage(entity, damage, ignoreResistances); - shell.WriteLine($"Damaged entity {entity.Name} with id {entity.Uid} for {amount} {damageGroup} damage{(ignoreResistances ? ", ignoring resistances." : ".")}"); + shell.WriteLine($"Damaged entity {entMan.GetComponent(entity).EntityName} with id {entity} for {amount} {damageGroup} damage{(ignoreResistances ? ", ignoring resistances." : ".")}"); }; return true; @@ -117,9 +110,9 @@ namespace Content.Server.Damage.Commands func = (entity, ignoreResistances) => { var damage = new DamageSpecifier(damageType, amount); - EntitySystem.Get().TryChangeDamage(entity.Uid, damage, ignoreResistances); + EntitySystem.Get().TryChangeDamage(entity, damage, ignoreResistances); - shell.WriteLine($"Damaged entity {entity.Name} with id {entity.Uid} for {amount} {damageType} damage{(ignoreResistances ? ", ignoring resistances." : ".")}"); + shell.WriteLine($"Damaged entity {entMan.GetComponent(entity).EntityName} with id {entity} for {amount} {damageType} damage{(ignoreResistances ? ", ignoring resistances." : ".")}"); }; return true; @@ -141,9 +134,11 @@ namespace Content.Server.Damage.Commands { var player = shell.Player as IPlayerSession; bool ignoreResistances; - IEntity entity; + EntityUid entity; Damage? damageFunc; + var entMan = IoCManager.Resolve(); + switch (args.Length) { // Check if we have enough for the dmg types to show @@ -197,9 +192,9 @@ namespace Content.Server.Damage.Commands return; } - if (!entity.TryGetComponent(out DamageableComponent? damageable)) + if (!entMan.TryGetComponent(entity, out DamageableComponent? damageable)) { - shell.WriteLine($"Entity {entity.Name} with id {entity.Uid} does not have a {nameof(DamageableComponent)}."); + shell.WriteLine($"Entity {entMan.GetComponent(entity).EntityName} with id {entity} does not have a {nameof(DamageableComponent)}."); return; } diff --git a/Content.Server/Damage/Systems/DamageOnToolInteractSystem.cs b/Content.Server/Damage/Systems/DamageOnToolInteractSystem.cs index c15d66126b..3b0303f2ff 100644 --- a/Content.Server/Damage/Systems/DamageOnToolInteractSystem.cs +++ b/Content.Server/Damage/Systems/DamageOnToolInteractSystem.cs @@ -28,10 +28,10 @@ namespace Content.Server.Damage.Systems return; if (component.WeldingDamage is {} weldingDamage - && args.Used.TryGetComponent(out var welder) + && EntityManager.TryGetComponent(args.Used, out var welder) && welder.Lit) { - var dmg = _damageableSystem.TryChangeDamage(args.Target.Uid, weldingDamage); + var dmg = _damageableSystem.TryChangeDamage(args.Target, weldingDamage); if (dmg != null) _logSystem.Add(LogType.Damaged, @@ -40,10 +40,10 @@ namespace Content.Server.Damage.Systems args.Handled = true; } else if (component.DefaultDamage is {} damage - && args.Used.TryGetComponent(out var tool) + && EntityManager.TryGetComponent(args.Used, out var tool) && tool.Qualities.ContainsAny(component.Tools)) { - var dmg = _damageableSystem.TryChangeDamage(args.Target.Uid, damage); + var dmg = _damageableSystem.TryChangeDamage(args.Target, damage); if (dmg != null) _logSystem.Add(LogType.Damaged, diff --git a/Content.Server/Damage/Systems/DamageOtherOnHitSystem.cs b/Content.Server/Damage/Systems/DamageOtherOnHitSystem.cs index 8f7d1f4aca..da72fe3455 100644 --- a/Content.Server/Damage/Systems/DamageOtherOnHitSystem.cs +++ b/Content.Server/Damage/Systems/DamageOtherOnHitSystem.cs @@ -21,7 +21,7 @@ namespace Content.Server.Damage.Systems private void OnDoHit(EntityUid uid, DamageOtherOnHitComponent component, ThrowDoHitEvent args) { - var dmg = _damageableSystem.TryChangeDamage(args.Target.Uid, component.Damage, component.IgnoreResistances); + var dmg = _damageableSystem.TryChangeDamage(args.Target, component.Damage, component.IgnoreResistances); if (dmg != null) _logSystem.Add(LogType.ThrowHit, $"{args.Target} received {dmg.Total} damage from collision"); } diff --git a/Content.Server/Decals/DecalSystem.cs b/Content.Server/Decals/DecalSystem.cs index d35f2c57ad..f7f4f9525c 100644 --- a/Content.Server/Decals/DecalSystem.cs +++ b/Content.Server/Decals/DecalSystem.cs @@ -305,10 +305,10 @@ namespace Content.Server.Decals private HashSet GetSessionViewers(IPlayerSession session) { var viewers = new HashSet(); - if (session.Status != SessionStatus.InGame || session.AttachedEntityUid is null) + if (session.Status != SessionStatus.InGame || session.AttachedEntity is null) return viewers; - viewers.Add(session.AttachedEntityUid.Value); + viewers.Add(session.AttachedEntity.Value); foreach (var uid in session.ViewSubscriptions) { diff --git a/Content.Server/Destructible/DestructibleComponent.cs b/Content.Server/Destructible/DestructibleComponent.cs index 069a3be4ff..aab1e5008a 100644 --- a/Content.Server/Destructible/DestructibleComponent.cs +++ b/Content.Server/Destructible/DestructibleComponent.cs @@ -8,7 +8,7 @@ using Robust.Shared.ViewVariables; namespace Content.Server.Destructible { /// - /// When attached to an , allows it to take damage + /// When attached to an , allows it to take damage /// and triggers thresholds when reached. /// [RegisterComponent] diff --git a/Content.Server/Destructible/Thresholds/Behaviors/SpawnEntitiesBehavior.cs b/Content.Server/Destructible/Thresholds/Behaviors/SpawnEntitiesBehavior.cs index c607c7ef47..bdf7172f1a 100644 --- a/Content.Server/Destructible/Thresholds/Behaviors/SpawnEntitiesBehavior.cs +++ b/Content.Server/Destructible/Thresholds/Behaviors/SpawnEntitiesBehavior.cs @@ -4,6 +4,7 @@ using Content.Server.Stack; using Content.Shared.Prototypes; using Content.Shared.Random.Helpers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Destructible.Thresholds.Behaviors @@ -33,8 +34,8 @@ namespace Content.Server.Destructible.Thresholds.Behaviors if (EntityPrototypeHelpers.HasComponent(entityId)) { var spawned = system.EntityManager.SpawnEntity(entityId, position); - var stack = spawned.GetComponent(); - EntitySystem.Get().SetCount(spawned.Uid, count, stack); + var stack = IoCManager.Resolve().GetComponent(spawned); + EntitySystem.Get().SetCount(spawned, count, stack); spawned.RandomOffset(0.5f); } else diff --git a/Content.Server/Destructible/Thresholds/Behaviors/SpillBehavior.cs b/Content.Server/Destructible/Thresholds/Behaviors/SpillBehavior.cs index 0697ab1e60..dbb9a8fca6 100644 --- a/Content.Server/Destructible/Thresholds/Behaviors/SpillBehavior.cs +++ b/Content.Server/Destructible/Thresholds/Behaviors/SpillBehavior.cs @@ -15,7 +15,7 @@ namespace Content.Server.Destructible.Thresholds.Behaviors public string? Solution; /// - /// If there is a SpillableComponent on IEntity owner use it to create a puddle/smear. + /// If there is a SpillableComponent on EntityUidowner use it to create a puddle/smear. /// Or whatever solution is specified in the behavior itself. /// If none are available do nothing. /// diff --git a/Content.Server/DeviceNetwork/Systems/ApcNetworkSystem.cs b/Content.Server/DeviceNetwork/Systems/ApcNetworkSystem.cs index 2320420f83..ee8278fbe1 100644 --- a/Content.Server/DeviceNetwork/Systems/ApcNetworkSystem.cs +++ b/Content.Server/DeviceNetwork/Systems/ApcNetworkSystem.cs @@ -4,6 +4,7 @@ using JetBrains.Annotations; using Robust.Shared.GameObjects; using Content.Server.Power.EntitySystems; using Content.Server.Power.Nodes; +using Robust.Shared.IoC; namespace Content.Server.DeviceNetwork.Systems { @@ -35,7 +36,7 @@ namespace Content.Server.DeviceNetwork.Systems private void OnProviderConnected(EntityUid uid, ApcNetworkComponent component, ExtensionCableSystem.ProviderConnectedEvent args) { - if (!args.Provider.Owner.TryGetComponent(out NodeContainerComponent? nodeContainer)) return; + if (!EntityManager.TryGetComponent(args.Provider.Owner, out NodeContainerComponent? nodeContainer)) return; if (nodeContainer.TryGetNode("power", out CableNode? node)) { diff --git a/Content.Server/DeviceNetwork/Systems/DeviceNetworkSystem.cs b/Content.Server/DeviceNetwork/Systems/DeviceNetworkSystem.cs index 244ce6b4c2..3826029ad6 100644 --- a/Content.Server/DeviceNetwork/Systems/DeviceNetworkSystem.cs +++ b/Content.Server/DeviceNetwork/Systems/DeviceNetworkSystem.cs @@ -51,7 +51,7 @@ namespace Content.Server.DeviceNetwork.Systems /// The Entity containing a DeviceNetworkComponent public void Connect(EntityUid uid) { - if (EntityManager.GetEntity(uid).TryGetComponent(out var component)) + if (EntityManager.TryGetComponent(uid, out var component)) { AddConnection(component); } @@ -90,7 +90,7 @@ namespace Content.Server.DeviceNetwork.Systems /// The Entity containing a DeviceNetworkComponent public void Disconnect(EntityUid uid) { - if (EntityManager.GetEntity(uid).TryGetComponent(out var component)) + if (EntityManager.TryGetComponent(uid, out var component)) { RemoveConnection(component); } @@ -211,12 +211,12 @@ namespace Content.Server.DeviceNetwork.Systems { foreach (var connection in connections) { - var beforeEvent = new BeforePacketSentEvent(packet.Sender.Owner.Uid); - RaiseLocalEvent(connection.Owner.Uid, beforeEvent, false); + var beforeEvent = new BeforePacketSentEvent(packet.Sender.Owner); + RaiseLocalEvent(connection.Owner, beforeEvent, false); if (!beforeEvent.Cancelled) { - RaiseLocalEvent(connection.Owner.Uid, new PacketSentEvent(connection.Frequency, packet.Sender.Address, packet.Data, packet.Broadcast) , false); + RaiseLocalEvent(connection.Owner, new PacketSentEvent(connection.Frequency, packet.Sender.Address, packet.Data, packet.Broadcast) , false); } } } diff --git a/Content.Server/DeviceNetwork/Systems/WiredNetworkSystem.cs b/Content.Server/DeviceNetwork/Systems/WiredNetworkSystem.cs index 11eda63575..6c34bafb39 100644 --- a/Content.Server/DeviceNetwork/Systems/WiredNetworkSystem.cs +++ b/Content.Server/DeviceNetwork/Systems/WiredNetworkSystem.cs @@ -1,10 +1,6 @@ using Content.Server.DeviceNetwork.Components; -using Content.Server.NodeContainer; -using Content.Server.NodeContainer.NodeGroups; -using Content.Server.Power.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; -using System.Diagnostics.CodeAnalysis; namespace Content.Server.DeviceNetwork.Systems { @@ -22,10 +18,7 @@ namespace Content.Server.DeviceNetwork.Systems /// private void OnBeforePacketSent(EntityUid uid, WiredNetworkComponent component, BeforePacketSentEvent args) { - IEntity sender = EntityManager.GetEntity(args.Sender); - IEntity receiver = EntityManager.GetEntity(uid); - - if (receiver.Transform.GridID != sender.Transform.GridID) + if (EntityManager.GetComponent(uid).GridID != EntityManager.GetComponent(args.Sender).GridID) { args.Cancel(); } diff --git a/Content.Server/DeviceNetwork/Systems/WirelessNetworkSystem.cs b/Content.Server/DeviceNetwork/Systems/WirelessNetworkSystem.cs index be009b6543..d85bff0736 100644 --- a/Content.Server/DeviceNetwork/Systems/WirelessNetworkSystem.cs +++ b/Content.Server/DeviceNetwork/Systems/WirelessNetworkSystem.cs @@ -18,13 +18,11 @@ namespace Content.Server.DeviceNetwork.Systems /// private void OnBeforePacketSent(EntityUid uid, WirelessNetworkComponent component, BeforePacketSentEvent args) { - var sender = EntityManager.GetEntity(args.Sender); - - var ownPosition = component.Owner.Transform.WorldPosition; - var position = sender.Transform.WorldPosition; + var ownPosition = EntityManager.GetComponent(component.Owner).WorldPosition; + var position = EntityManager.GetComponent(args.Sender).WorldPosition; var distance = (ownPosition - position).Length; - if(sender.TryGetComponent(out var sendingComponent) && distance > sendingComponent.Range) + if (EntityManager.TryGetComponent(args.Sender, out var sendingComponent) && distance > sendingComponent.Range) { args.Cancel(); } diff --git a/Content.Server/Disposal/Tube/Components/DisposalBendComponent.cs b/Content.Server/Disposal/Tube/Components/DisposalBendComponent.cs index 5475e14510..e461004734 100644 --- a/Content.Server/Disposal/Tube/Components/DisposalBendComponent.cs +++ b/Content.Server/Disposal/Tube/Components/DisposalBendComponent.cs @@ -1,5 +1,6 @@ using Content.Server.Disposal.Unit.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; @@ -16,7 +17,7 @@ namespace Content.Server.Disposal.Tube.Components protected override Direction[] ConnectableDirections() { - var direction = Owner.Transform.LocalRotation; + var direction = IoCManager.Resolve().GetComponent(Owner).LocalRotation; var side = new Angle(MathHelper.DegreesToRadians(direction.Degrees + _sideDegrees)); return new[] {direction.GetDir(), side.GetDir()}; diff --git a/Content.Server/Disposal/Tube/Components/DisposalEntryComponent.cs b/Content.Server/Disposal/Tube/Components/DisposalEntryComponent.cs index 3b30f4275b..aaf9be47dd 100644 --- a/Content.Server/Disposal/Tube/Components/DisposalEntryComponent.cs +++ b/Content.Server/Disposal/Tube/Components/DisposalEntryComponent.cs @@ -15,14 +15,16 @@ namespace Content.Server.Disposal.Tube.Components [ComponentReference(typeof(IDisposalTubeComponent))] public class DisposalEntryComponent : DisposalTubeComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + private const string HolderPrototypeId = "DisposalHolder"; public override string Name => "DisposalEntry"; public bool TryInsert(DisposalUnitComponent from) { - var holder = Owner.EntityManager.SpawnEntity(HolderPrototypeId, Owner.Transform.MapPosition); - var holderComponent = holder.GetComponent(); + var holder = _entMan.SpawnEntity(HolderPrototypeId, _entMan.GetComponent(Owner).MapPosition); + var holderComponent = _entMan.GetComponent(holder); foreach (var entity in from.ContainedEntities.ToArray()) { @@ -32,12 +34,12 @@ namespace Content.Server.Disposal.Tube.Components EntitySystem.Get().Merge(holderComponent.Air, from.Air); from.Air.Clear(); - return EntitySystem.Get().EnterTube(holderComponent.OwnerUid, OwnerUid, holderComponent, null, this); + return EntitySystem.Get().EnterTube((holderComponent).Owner, Owner, holderComponent, null, this); } protected override Direction[] ConnectableDirections() { - return new[] {Owner.Transform.LocalRotation.GetDir()}; + return new[] {_entMan.GetComponent(Owner).LocalRotation.GetDir()}; } /// diff --git a/Content.Server/Disposal/Tube/Components/DisposalJunctionComponent.cs b/Content.Server/Disposal/Tube/Components/DisposalJunctionComponent.cs index 73eb40a516..1f420ef9e1 100644 --- a/Content.Server/Disposal/Tube/Components/DisposalJunctionComponent.cs +++ b/Content.Server/Disposal/Tube/Components/DisposalJunctionComponent.cs @@ -14,6 +14,7 @@ namespace Content.Server.Disposal.Tube.Components [ComponentReference(typeof(IDisposalTubeComponent))] public class DisposalJunctionComponent : DisposalTubeComponent { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _random = default!; /// @@ -27,14 +28,14 @@ namespace Content.Server.Disposal.Tube.Components protected override Direction[] ConnectableDirections() { - var direction = Owner.Transform.LocalRotation; + var direction = _entMan.GetComponent(Owner).LocalRotation; return _degrees.Select(degree => new Angle(degree.Theta + direction.Theta).GetDir()).ToArray(); } public override Direction NextDirection(DisposalHolderComponent holder) { - var next = Owner.Transform.LocalRotation.GetDir(); + var next = _entMan.GetComponent(Owner).LocalRotation.GetDir(); var directions = ConnectableDirections().Skip(1).ToArray(); if (holder.PreviousDirectionFrom == Direction.Invalid || diff --git a/Content.Server/Disposal/Tube/Components/DisposalRouterComponent.cs b/Content.Server/Disposal/Tube/Components/DisposalRouterComponent.cs index 524d386406..4a5c5df272 100644 --- a/Content.Server/Disposal/Tube/Components/DisposalRouterComponent.cs +++ b/Content.Server/Disposal/Tube/Components/DisposalRouterComponent.cs @@ -29,6 +29,8 @@ namespace Content.Server.Disposal.Tube.Components [ComponentReference(typeof(IDisposalTubeComponent))] public class DisposalRouterComponent : DisposalJunctionComponent, IActivate { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "DisposalRouter"; [ViewVariables] @@ -36,7 +38,7 @@ namespace Content.Server.Disposal.Tube.Components [ViewVariables] public bool Anchored => - !Owner.TryGetComponent(out IPhysBody? physics) || + !_entMan.TryGetComponent(Owner, out IPhysBody? physics) || physics.BodyType == BodyType.Static; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(DisposalRouterUiKey.Key); @@ -52,7 +54,7 @@ namespace Content.Server.Disposal.Tube.Components return directions[1]; } - return Owner.Transform.LocalRotation.GetDir(); + return _entMan.GetComponent(Owner).LocalRotation.GetDir(); } protected override void Initialize() @@ -104,7 +106,7 @@ namespace Content.Server.Disposal.Tube.Components private bool PlayerCanUseDisposalTagger(IPlayerSession session) { //Need player entity to check if they are still able to use the configuration interface - if (session.AttachedEntity == null) + if (session.AttachedEntity is not {} attached) return false; if (!Anchored) return false; @@ -112,7 +114,7 @@ namespace Content.Server.Disposal.Tube.Components var actionBlocker = EntitySystem.Get(); var groupController = IoCManager.Resolve(); //Check if player can interact in their current state - if (!groupController.CanAdminMenu(session) && (!actionBlocker.CanInteract(session.AttachedEntityUid!.Value) || !actionBlocker.CanUse(session.AttachedEntityUid!.Value))) + if (!groupController.CanAdminMenu(session) && (!actionBlocker.CanInteract(attached) || !actionBlocker.CanUse(attached))) return false; return true; @@ -160,12 +162,12 @@ namespace Content.Server.Disposal.Tube.Components /// Data relevant to the event such as the actor which triggered it. void IActivate.Activate(ActivateEventArgs args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(args.User, out ActorComponent? actor)) { return; } - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!_entMan.TryGetComponent(args.User, out HandsComponent? hands)) { Owner.PopupMessage(args.User, Loc.GetString("disposal-router-window-tag-input-activate-no-hands")); return; diff --git a/Content.Server/Disposal/Tube/Components/DisposalTaggerComponent.cs b/Content.Server/Disposal/Tube/Components/DisposalTaggerComponent.cs index 9c88780bfa..1c354acd59 100644 --- a/Content.Server/Disposal/Tube/Components/DisposalTaggerComponent.cs +++ b/Content.Server/Disposal/Tube/Components/DisposalTaggerComponent.cs @@ -26,6 +26,8 @@ namespace Content.Server.Disposal.Tube.Components [ComponentReference(typeof(IDisposalTubeComponent))] public class DisposalTaggerComponent : DisposalTransitComponent, IActivate { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "DisposalTagger"; [ViewVariables(VVAccess.ReadWrite)] @@ -33,7 +35,7 @@ namespace Content.Server.Disposal.Tube.Components [ViewVariables] public bool Anchored => - !Owner.TryGetComponent(out PhysicsComponent? physics) || + !_entMan.TryGetComponent(Owner, out PhysicsComponent? physics) || physics.BodyType == BodyType.Static; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(DisposalTaggerUiKey.Key); @@ -86,7 +88,7 @@ namespace Content.Server.Disposal.Tube.Components private bool PlayerCanUseDisposalTagger(IPlayerSession session) { //Need player entity to check if they are still able to use the configuration interface - if (session.AttachedEntity == null) + if (session.AttachedEntity is not {} attached) return false; if (!Anchored) return false; @@ -94,7 +96,7 @@ namespace Content.Server.Disposal.Tube.Components var actionBlocker = EntitySystem.Get(); var groupController = IoCManager.Resolve(); //Check if player can interact in their current state - if (!groupController.CanAdminMenu(session) && (!actionBlocker.CanInteract(session.AttachedEntityUid!.Value) || !actionBlocker.CanUse(session.AttachedEntityUid!.Value))) + if (!groupController.CanAdminMenu(session) && (!actionBlocker.CanInteract(attached) || !actionBlocker.CanUse(attached))) return false; return true; @@ -126,12 +128,12 @@ namespace Content.Server.Disposal.Tube.Components /// Data relevant to the event such as the actor which triggered it. void IActivate.Activate(ActivateEventArgs args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(args.User, out ActorComponent? actor)) { return; } - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!_entMan.TryGetComponent(args.User, out HandsComponent? hands)) { Owner.PopupMessage(args.User, Loc.GetString("disposal-tagger-window-activate-no-hands")); return; diff --git a/Content.Server/Disposal/Tube/Components/DisposalTransitComponent.cs b/Content.Server/Disposal/Tube/Components/DisposalTransitComponent.cs index e67b92d774..e6bc59d070 100644 --- a/Content.Server/Disposal/Tube/Components/DisposalTransitComponent.cs +++ b/Content.Server/Disposal/Tube/Components/DisposalTransitComponent.cs @@ -1,6 +1,7 @@ using System; using Content.Server.Disposal.Unit.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Server.Disposal.Tube.Components @@ -14,7 +15,7 @@ namespace Content.Server.Disposal.Tube.Components protected override Direction[] ConnectableDirections() { - var rotation = Owner.Transform.LocalRotation; + var rotation = IoCManager.Resolve().GetComponent(Owner).LocalRotation; var opposite = new Angle(rotation.Theta + Math.PI); return new[] {rotation.GetDir(), opposite.GetDir()}; diff --git a/Content.Server/Disposal/Tube/Components/DisposalTubeComponent.cs b/Content.Server/Disposal/Tube/Components/DisposalTubeComponent.cs index 4c101fd752..c815119c90 100644 --- a/Content.Server/Disposal/Tube/Components/DisposalTubeComponent.cs +++ b/Content.Server/Disposal/Tube/Components/DisposalTubeComponent.cs @@ -7,13 +7,10 @@ using Content.Shared.Acts; using Content.Shared.Disposal.Components; using Content.Shared.Popups; using Content.Shared.Sound; -using Content.Shared.Verbs; -using Robust.Server.Console; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Serialization.Manager.Attributes; @@ -23,6 +20,8 @@ namespace Content.Server.Disposal.Tube.Components { public abstract class DisposalTubeComponent : Component, IDisposalTubeComponent, IBreakAct { + [Dependency] private readonly IEntityManager _entMan = default!; + public static readonly TimeSpan ClangDelay = TimeSpan.FromSeconds(0.5); public TimeSpan LastClang; @@ -38,7 +37,7 @@ namespace Content.Server.Disposal.Tube.Components [ViewVariables] private bool Anchored => - !Owner.TryGetComponent(out PhysicsComponent? physics) || + !_entMan.TryGetComponent(Owner, out PhysicsComponent? physics) || physics.BodyType == BodyType.Static; /// @@ -91,16 +90,16 @@ namespace Content.Server.Disposal.Tube.Components foreach (var entity in Contents.ContainedEntities.ToArray()) { - if (!entity.TryGetComponent(out DisposalHolderComponent? holder)) + if (!_entMan.TryGetComponent(entity, out DisposalHolderComponent? holder)) { continue; } - EntitySystem.Get().ExitDisposals(holder.OwnerUid); + EntitySystem.Get().ExitDisposals((holder).Owner); } } - public void PopupDirections(IEntity entity) + public void PopupDirections(EntityUid entity) { var directions = string.Join(", ", ConnectableDirections()); @@ -109,7 +108,7 @@ namespace Content.Server.Disposal.Tube.Components private void UpdateVisualState() { - if (!Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (!_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { return; } @@ -125,7 +124,7 @@ namespace Content.Server.Disposal.Tube.Components public void AnchoredChanged() { - if (!Owner.TryGetComponent(out PhysicsComponent? physics)) + if (!_entMan.TryGetComponent(Owner, out PhysicsComponent? physics)) { return; } diff --git a/Content.Server/Disposal/Tube/Components/IDisposalTubeComponent.cs b/Content.Server/Disposal/Tube/Components/IDisposalTubeComponent.cs index 8110acb798..3f31ead82a 100644 --- a/Content.Server/Disposal/Tube/Components/IDisposalTubeComponent.cs +++ b/Content.Server/Disposal/Tube/Components/IDisposalTubeComponent.cs @@ -11,6 +11,6 @@ namespace Content.Server.Disposal.Tube.Components Direction NextDirection(DisposalHolderComponent holder); bool CanConnect(Direction direction, IDisposalTubeComponent with); - void PopupDirections(IEntity entity); + void PopupDirections(EntityUid entity); } } diff --git a/Content.Server/Disposal/Tube/DisposalTubeSystem.cs b/Content.Server/Disposal/Tube/DisposalTubeSystem.cs index 8feae7c746..32b9546a2f 100644 --- a/Content.Server/Disposal/Tube/DisposalTubeSystem.cs +++ b/Content.Server/Disposal/Tube/DisposalTubeSystem.cs @@ -5,9 +5,9 @@ using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; +using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Maths; -using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Timing; @@ -28,13 +28,13 @@ namespace Content.Server.Disposal.Tube SubscribeLocalEvent(AddOpenUIVerbs); SubscribeLocalEvent(AddOpenUIVerbs); } - + private void AddOpenUIVerbs(EntityUid uid, DisposalTaggerComponent component, GetInteractionVerbsEvent args) { if (!args.CanAccess || !args.CanInteract) return; - if (!args.User.TryGetComponent(out var actor)) + if (!EntityManager.TryGetComponent(args.User, out var actor)) return; var player = actor.PlayerSession; @@ -42,7 +42,7 @@ namespace Content.Server.Disposal.Tube verb.Text = Loc.GetString("configure-verb-get-data-text"); verb.IconTexture = "/Textures/Interface/VerbIcons/settings.svg.192dpi.png"; verb.Act = () => component.OpenUserInterface(actor); - args.Verbs.Add(verb); + args.Verbs.Add(verb); } private void AddOpenUIVerbs(EntityUid uid, DisposalRouterComponent component, GetInteractionVerbsEvent args) @@ -50,7 +50,7 @@ namespace Content.Server.Disposal.Tube if (!args.CanAccess || !args.CanInteract) return; - if (!args.User.TryGetComponent(out var actor)) + if (!EntityManager.TryGetComponent(args.User, out var actor)) return; var player = actor.PlayerSession; @@ -68,9 +68,8 @@ namespace Content.Server.Disposal.Tube return; } - var entity = EntityManager.GetEntity(uid); component.LastClang = _gameTiming.CurTime; - SoundSystem.Play(Filter.Pvs(entity), component.ClangSound.GetSound(), entity); + SoundSystem.Play(Filter.Pvs(uid), component.ClangSound.GetSound(), uid); } private static void BodyTypeChanged( @@ -87,8 +86,8 @@ namespace Content.Server.Disposal.Tube return null; var oppositeDirection = nextDirection.GetOpposite(); - var grid = _mapManager.GetGrid(targetTube.Owner.Transform.GridID); - var position = targetTube.Owner.Transform.Coordinates; + var grid = _mapManager.GetGrid(EntityManager.GetComponent(targetTube.Owner).GridID); + var position = EntityManager.GetComponent(targetTube.Owner).Coordinates; foreach (var entity in grid.GetInDir(position, nextDirection)) { if (!EntityManager.TryGetComponent(entity, out IDisposalTubeComponent? tube)) diff --git a/Content.Server/Disposal/TubeConnectionsCommand.cs b/Content.Server/Disposal/TubeConnectionsCommand.cs index ba56e48582..0a7d023c36 100644 --- a/Content.Server/Disposal/TubeConnectionsCommand.cs +++ b/Content.Server/Disposal/TubeConnectionsCommand.cs @@ -38,13 +38,13 @@ namespace Content.Server.Disposal } var entityManager = IoCManager.Resolve(); - if (!entityManager.TryGetEntity(id, out var entity)) + if (!entityManager.EntityExists(id)) { shell.WriteLine(Loc.GetString("shell-could-not-find-entity-with-uid",("uid", id))); return; } - if (!entity.TryGetComponent(out IDisposalTubeComponent? tube)) + if (!entityManager.TryGetComponent(id, out IDisposalTubeComponent? tube)) { shell.WriteLine(Loc.GetString("shell-entity-with-uid-lacks-component", ("uid", id), @@ -52,7 +52,7 @@ namespace Content.Server.Disposal return; } - tube.PopupDirections(player.AttachedEntity); + tube.PopupDirections(player.AttachedEntity.Value); } } } diff --git a/Content.Server/Disposal/Unit/Components/DisposalHolderComponent.cs b/Content.Server/Disposal/Unit/Components/DisposalHolderComponent.cs index 79d6c804f7..aab960bba6 100644 --- a/Content.Server/Disposal/Unit/Components/DisposalHolderComponent.cs +++ b/Content.Server/Disposal/Unit/Components/DisposalHolderComponent.cs @@ -1,11 +1,6 @@ -using System; using System.Collections.Generic; -using System.Linq; using Content.Server.Atmos; -using Content.Server.Atmos.EntitySystems; using Content.Server.Disposal.Tube.Components; -using Content.Server.Disposal.Tube; -using Content.Server.Disposal.Unit.EntitySystems; using Content.Server.Items; using Content.Shared.Atmos; using Content.Shared.Body.Components; @@ -23,6 +18,8 @@ namespace Content.Server.Disposal.Unit.Components [RegisterComponent] public class DisposalHolderComponent : Component, IGasMixtureHolder { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "DisposalHolder"; public Container Container = null!; @@ -77,25 +74,25 @@ namespace Content.Server.Disposal.Unit.Components Container = ContainerHelpers.EnsureContainer(Owner, nameof(DisposalHolderComponent)); } - private bool CanInsert(IEntity entity) + private bool CanInsert(EntityUid entity) { if (!Container.CanInsert(entity)) { return false; } - return entity.HasComponent() || - entity.HasComponent(); + return _entMan.HasComponent(entity) || + _entMan.HasComponent(entity); } - public bool TryInsert(IEntity entity) + public bool TryInsert(EntityUid entity) { if (!CanInsert(entity) || !Container.Insert(entity)) { return false; } - if (entity.TryGetComponent(out IPhysBody? physics)) + if (_entMan.TryGetComponent(entity, out IPhysBody? physics)) { physics.CanCollide = false; } diff --git a/Content.Server/Disposal/Unit/Components/DisposalUnitComponent.cs b/Content.Server/Disposal/Unit/Components/DisposalUnitComponent.cs index 72f0be5e07..54c63038c8 100644 --- a/Content.Server/Disposal/Unit/Components/DisposalUnitComponent.cs +++ b/Content.Server/Disposal/Unit/Components/DisposalUnitComponent.cs @@ -14,6 +14,7 @@ using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -70,11 +71,11 @@ namespace Content.Server.Disposal.Unit.Components /// [ViewVariables] public Container Container = default!; - [ViewVariables] public IReadOnlyList ContainedEntities => Container.ContainedEntities; + [ViewVariables] public IReadOnlyList ContainedEntities => Container.ContainedEntities; [ViewVariables] public bool Powered => - !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || + !IoCManager.Resolve().TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; [ViewVariables] public PressureState State => Pressure >= 1 ? PressureState.Ready : PressureState.Pressurizing; @@ -87,7 +88,7 @@ namespace Content.Server.Disposal.Unit.Components [DataField("air")] public GasMixture Air { get; set; } = new(Atmospherics.CellVolume); - private bool PlayerCanUse(IEntity? player) + private bool PlayerCanUse(EntityUid player) { if (player == null) { @@ -96,8 +97,8 @@ namespace Content.Server.Disposal.Unit.Components var actionBlocker = EntitySystem.Get(); - if (!actionBlocker.CanInteract(player.Uid) || - !actionBlocker.CanUse(player.Uid)) + if (!actionBlocker.CanInteract(player) || + !actionBlocker.CanUse(player)) { return false; } @@ -107,12 +108,12 @@ namespace Content.Server.Disposal.Unit.Components public void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj) { - if (obj.Session.AttachedEntity == null) + if (obj.Session.AttachedEntity is not {Valid: true} player) { return; } - if (!PlayerCanUse(obj.Session.AttachedEntity)) + if (!PlayerCanUse(player)) { return; } @@ -148,7 +149,7 @@ namespace Content.Server.Disposal.Unit.Components public override bool DragDropOn(DragDropEvent eventArgs) { - EntitySystem.Get().TryInsert(Owner.Uid, eventArgs.Dragged.Uid, eventArgs.User.Uid); + EntitySystem.Get().TryInsert(Owner, eventArgs.Dragged, eventArgs.User); return true; } diff --git a/Content.Server/Disposal/Unit/EntitySystems/DisposableSystem.cs b/Content.Server/Disposal/Unit/EntitySystems/DisposableSystem.cs index c596e61e5f..867fee4dd4 100644 --- a/Content.Server/Disposal/Unit/EntitySystems/DisposableSystem.cs +++ b/Content.Server/Disposal/Unit/EntitySystems/DisposableSystem.cs @@ -1,5 +1,5 @@ using System.Linq; -using Content.Server.Atmos; + using Content.Server.Atmos; using Content.Server.Atmos.EntitySystems; using Content.Server.Disposal.Tube.Components; using Content.Server.Disposal.Tube; @@ -47,24 +47,24 @@ namespace Content.Server.Disposal.Unit.EntitySystems foreach (var entity in holder.Container.ContainedEntities.ToArray()) { - if (entity.TryGetComponent(out IPhysBody? physics)) + if (EntityManager.TryGetComponent(entity, out IPhysBody? physics)) { physics.CanCollide = true; } holder.Container.ForceRemove(entity); - if (entity.Transform.Parent == holderTransform) + if (EntityManager.GetComponent(entity).Parent == holderTransform) { if (duc != null) { // Insert into disposal unit - entity.Transform.Coordinates = new EntityCoordinates(duc.OwnerUid, Vector2.Zero); + EntityManager.GetComponent(entity).Coordinates = new EntityCoordinates((duc).Owner, Vector2.Zero); duc.Container.Insert(entity); } else { - entity.Transform.AttachParentToContainerOrGrid(); + EntityManager.GetComponent(entity).AttachParentToContainerOrGrid(); } } } @@ -154,18 +154,18 @@ namespace Content.Server.Disposal.Unit.EntitySystems var currentTube = holder.CurrentTube; if (currentTube == null || currentTube.Deleted) { - ExitDisposals(holder.OwnerUid); + ExitDisposals((holder).Owner); break; } if (holder.TimeLeft > 0) { var progress = 1 - holder.TimeLeft / holder.StartingTime; - var origin = currentTube.Owner.Transform.Coordinates; + var origin = EntityManager.GetComponent(currentTube.Owner).Coordinates; var destination = holder.CurrentDirection.ToVec(); var newPosition = destination * progress; - holder.Owner.Transform.Coordinates = origin.Offset(newPosition); + EntityManager.GetComponent(holder.Owner).Coordinates = origin.Offset(newPosition); continue; } @@ -175,15 +175,15 @@ namespace Content.Server.Disposal.Unit.EntitySystems currentTube.Contents.ForceRemove(holder.Owner); // Find next tube - var nextTube = _disposalTubeSystem.NextTubeFor(currentTube.OwnerUid, holder.CurrentDirection); + var nextTube = _disposalTubeSystem.NextTubeFor(currentTube.Owner, holder.CurrentDirection); if (nextTube == null || nextTube.Deleted) { - ExitDisposals(holder.OwnerUid); + ExitDisposals((holder).Owner); break; } // Perform remainder of entry process - if (!EnterTube(holder.OwnerUid, nextTube.OwnerUid, holder, null, nextTube, null)) + if (!EnterTube((holder).Owner, nextTube.Owner, holder, null, nextTube, null)) { break; } diff --git a/Content.Server/Disposal/Unit/EntitySystems/DisposalUnitSystem.cs b/Content.Server/Disposal/Unit/EntitySystems/DisposalUnitSystem.cs index 38e4436659..65d13c5495 100644 --- a/Content.Server/Disposal/Unit/EntitySystems/DisposalUnitSystem.cs +++ b/Content.Server/Disposal/Unit/EntitySystems/DisposalUnitSystem.cs @@ -98,13 +98,13 @@ namespace Content.Server.Disposal.Unit.EntitySystems if (!args.CanAccess || !args.CanInteract || component.ContainedEntities.Contains(args.User) || - !_actionBlockerSystem.CanMove(args.User.Uid)) + !_actionBlockerSystem.CanMove(args.User)) return; // Add verb to climb inside of the unit, Verb verb = new() { - Act = () => TryInsert(component.Owner.Uid, args.User.Uid, args.User.Uid), + Act = () => TryInsert(component.Owner, args.User, args.User), Text = Loc.GetString("disposal-self-insert-verb-get-data-text") }; // TODO VERN ICON @@ -116,7 +116,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems private void DoInsertDisposalUnit(DoInsertDisposalUnitEvent ev) { - var toInsert = EntityManager.GetEntity(ev.ToInsert); + var toInsert = ev.ToInsert; if (!EntityManager.TryGetComponent(ev.Unit, out DisposalUnitComponent? unit)) { @@ -159,7 +159,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems public void TogglePower(DisposalUnitComponent component) { - if (!EntityManager.TryGetComponent(component.Owner.Uid, out ApcPowerReceiverComponent? receiver)) + if (!EntityManager.TryGetComponent(component.Owner, out ApcPowerReceiverComponent? receiver)) { return; } @@ -172,7 +172,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems #region Eventbus Handlers private void HandleActivate(EntityUid uid, DisposalUnitComponent component, ActivateInWorldEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) { return; } @@ -187,7 +187,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems private void HandleInteractHand(EntityUid uid, DisposalUnitComponent component, InteractHandEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) return; + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; // Duplicated code here, not sure how else to get actor inside to make UserInterface happy. @@ -198,7 +198,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems private void HandleInteractUsing(EntityUid uid, DisposalUnitComponent component, InteractUsingEvent args) { - if (!args.User.TryGetComponent(out HandsComponent? hands)) + if (!EntityManager.TryGetComponent(args.User, out HandsComponent? hands)) { return; } @@ -238,7 +238,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems UpdateInterface(component, component.Powered); - if (!component.Owner.HasComponent()) + if (!EntityManager.HasComponent(component.Owner)) { Logger.WarningS("VitalComponentMissing", $"Disposal unit {uid} is missing an {nameof(AnchorableComponent)}"); } @@ -302,7 +302,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems { var currentTime = GameTiming.CurTime; - if (!args.Entity.TryGetComponent(out HandsComponent? hands) || + if (!EntityManager.TryGetComponent(args.Entity, out HandsComponent? hands) || hands.Count == 0 || currentTime < component.LastExitAttempt + ExitAttemptDelay) { @@ -351,7 +351,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems if (count > 0) { - if (!component.Owner.TryGetComponent(out PhysicsComponent? disposalsBody)) + if (!EntityManager.TryGetComponent(component.Owner, out PhysicsComponent? disposalsBody)) { component.RecentlyEjected.Clear(); } @@ -382,7 +382,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems private bool IsValidInteraction(ITargetedInteractEventArgs eventArgs) { - if (!Get().CanInteract(eventArgs.User.Uid)) + if (!Get().CanInteract(eventArgs.User)) { eventArgs.Target.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-cannot=interact")); return false; @@ -395,7 +395,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems } // This popup message doesn't appear on clicks, even when code was seperate. Unsure why. - if (!eventArgs.User.HasComponent()) + if (!EntityManager.HasComponent(eventArgs.User)) { eventArgs.Target.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-no-hands")); return false; @@ -444,8 +444,8 @@ namespace Content.Server.Disposal.Unit.EntitySystems return false; } - var grid = _mapManager.GetGrid(component.Owner.Transform.GridID); - var coords = component.Owner.Transform.Coordinates; + var grid = _mapManager.GetGrid(EntityManager.GetComponent(component.Owner).GridID); + var coords = EntityManager.GetComponent(component.Owner).Coordinates; var entry = grid.GetLocal(coords) .FirstOrDefault(entity => EntityManager.HasComponent(entity)); @@ -457,7 +457,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems var air = component.Air; var entryComponent = EntityManager.GetComponent(entry); - if (_atmosSystem.GetTileMixture(component.Owner.Transform.Coordinates, true) is {Temperature: > 0} environment) + if (_atmosSystem.GetTileMixture(EntityManager.GetComponent(component.Owner).Coordinates, true) is {Temperature: > 0} environment) { var transferMoles = 0.1f * (0.05f * Atmospherics.OneAtmosphere * 1.01f - air.Pressure) * air.Volume / (environment.Temperature * Atmospherics.R); @@ -483,7 +483,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems public void UpdateInterface(DisposalUnitComponent component, bool powered) { var stateString = Loc.GetString($"{component.State}"); - var state = new SharedDisposalUnitComponent.DisposalUnitBoundUserInterfaceState(component.Owner.Name, stateString, EstimatedFullPressure(component), powered, component.Engaged); + var state = new SharedDisposalUnitComponent.DisposalUnitBoundUserInterfaceState(EntityManager.GetComponent(component.Owner).EntityName, stateString, EstimatedFullPressure(component), powered, component.Engaged); component.UserInterface?.SetState(state); } @@ -504,12 +504,12 @@ namespace Content.Server.Disposal.Unit.EntitySystems public void UpdateVisualState(DisposalUnitComponent component, bool flush) { - if (!component.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (!EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearance)) { return; } - if (!component.Owner.Transform.Anchored) + if (!EntityManager.GetComponent(component.Owner).Anchored) { appearance.SetData(SharedDisposalUnitComponent.Visuals.VisualState, SharedDisposalUnitComponent.VisualState.UnAnchored); appearance.SetData(SharedDisposalUnitComponent.Visuals.Handle, SharedDisposalUnitComponent.HandleState.Normal); @@ -547,7 +547,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems : SharedDisposalUnitComponent.LightState.Ready); } - public void Remove(DisposalUnitComponent component, IEntity entity) + public void Remove(DisposalUnitComponent component, EntityUid entity) { component.Container.Remove(entity); @@ -557,8 +557,8 @@ namespace Content.Server.Disposal.Unit.EntitySystems component.AutomaticEngageToken = null; } - if (!component.RecentlyEjected.Contains(entity.Uid)) - component.RecentlyEjected.Add(entity.Uid); + if (!component.RecentlyEjected.Contains(entity)) + component.RecentlyEjected.Add(entity); component.Dirty(); HandleStateChange(component, true); @@ -567,7 +567,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems public bool CanFlush(DisposalUnitComponent component) { - return component.State == SharedDisposalUnitComponent.PressureState.Ready && component.Powered && component.Owner.Transform.Anchored; + return component.State == SharedDisposalUnitComponent.PressureState.Ready && component.Powered && EntityManager.GetComponent(component.Owner).Anchored; } public void Engage(DisposalUnitComponent component) @@ -600,7 +600,7 @@ namespace Content.Server.Disposal.Unit.EntitySystems } } - public override bool CanInsert(SharedDisposalUnitComponent component, IEntity entity) + public override bool CanInsert(SharedDisposalUnitComponent component, EntityUid entity) { if (!base.CanInsert(component, entity) || component is not DisposalUnitComponent serverComp) return false; @@ -629,11 +629,11 @@ namespace Content.Server.Disposal.Unit.EntitySystems }, component.AutomaticEngageToken.Token); } - public void AfterInsert(DisposalUnitComponent component, IEntity entity) + public void AfterInsert(DisposalUnitComponent component, EntityUid entity) { TryQueueEngage(component); - if (entity.TryGetComponent(out ActorComponent? actor)) + if (EntityManager.TryGetComponent(entity, out ActorComponent? actor)) { component.UserInterface?.Close(actor.PlayerSession); } diff --git a/Content.Server/DoAfter/DoAfterEventArgs.cs b/Content.Server/DoAfter/DoAfterEventArgs.cs index 7f61ea07bf..b53d2237a9 100644 --- a/Content.Server/DoAfter/DoAfterEventArgs.cs +++ b/Content.Server/DoAfter/DoAfterEventArgs.cs @@ -1,11 +1,7 @@ using System; using System.Threading; -using Content.Shared.Interaction.Helpers; -using Content.Shared.Physics; using Robust.Shared.GameObjects; -// ReSharper disable UnassignedReadonlyField - namespace Content.Server.DoAfter { public sealed class DoAfterEventArgs @@ -98,14 +94,6 @@ namespace Content.Server.DoAfter /// public object? BroadcastFinishedEvent { get; set; } - public DoAfterEventArgs( - IEntity user, - float delay, - CancellationToken cancelToken = default, - IEntity? target = null) : this(user.Uid, delay, cancelToken, target?.Uid ?? null) - { - } - public DoAfterEventArgs( EntityUid user, float delay, diff --git a/Content.Server/Doors/Components/AirlockComponent.cs b/Content.Server/Doors/Components/AirlockComponent.cs index 06fafb4818..b03f0dcb40 100644 --- a/Content.Server/Doors/Components/AirlockComponent.cs +++ b/Content.Server/Doors/Components/AirlockComponent.cs @@ -7,6 +7,7 @@ using Content.Shared.Doors; using Content.Shared.Sound; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -175,7 +176,7 @@ namespace Content.Server.Doors.Components _boltLightsWirePulsed ? StatusLightState.On : StatusLightState.Off, "BLTL"); var ev = new DoorGetCloseTimeModifierEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + IoCManager.Resolve().EventBus.RaiseLocalEvent(Owner, ev, false); var timingStatus = new StatusLightData(Color.Orange, !AutoClose ? StatusLightState.Off : diff --git a/Content.Server/Doors/Components/FirelockComponent.cs b/Content.Server/Doors/Components/FirelockComponent.cs index 1e43518e69..7634a0d3b1 100644 --- a/Content.Server/Doors/Components/FirelockComponent.cs +++ b/Content.Server/Doors/Components/FirelockComponent.cs @@ -2,6 +2,7 @@ using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; using Content.Shared.Doors; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Doors.Components @@ -13,6 +14,8 @@ namespace Content.Server.Doors.Components [RegisterComponent] public class FirelockComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Firelock"; [ComponentDependency] @@ -30,7 +33,7 @@ namespace Content.Server.Doors.Components if (DoorComponent != null && DoorComponent.State == SharedDoorComponent.DoorState.Open && DoorComponent.CanCloseGeneric()) { DoorComponent.Close(); - if (Owner.TryGetComponent(out AirtightComponent? airtight)) + if (_entMan.TryGetComponent(Owner, out AirtightComponent? airtight)) { EntitySystem.Get().SetAirblocked(airtight, true); } @@ -46,7 +49,7 @@ namespace Content.Server.Doors.Components var minMoles = float.MaxValue; var maxMoles = 0f; - foreach (var adjacent in atmosphereSystem.GetAdjacentTileMixtures(Owner.Transform.Coordinates)) + foreach (var adjacent in atmosphereSystem.GetAdjacentTileMixtures(_entMan.GetComponent(Owner).Coordinates)) { var moles = adjacent.TotalMoles; if (moles < minMoles) @@ -62,7 +65,7 @@ namespace Content.Server.Doors.Components { var atmosphereSystem = EntitySystem.Get(); - if (!atmosphereSystem.TryGetGridAndTile(Owner.Transform.Coordinates, out var tuple)) + if (!atmosphereSystem.TryGetGridAndTile(_entMan.GetComponent(Owner).Coordinates, out var tuple)) return false; if (atmosphereSystem.GetTileMixture(tuple.Value.Grid, tuple.Value.Tile) == null) @@ -71,7 +74,7 @@ namespace Content.Server.Doors.Components if (atmosphereSystem.IsHotspotActive(tuple.Value.Grid, tuple.Value.Tile)) return true; - foreach (var adjacent in atmosphereSystem.GetAdjacentTiles(Owner.Transform.Coordinates)) + foreach (var adjacent in atmosphereSystem.GetAdjacentTiles(_entMan.GetComponent(Owner).Coordinates)) { if (atmosphereSystem.IsHotspotActive(tuple.Value.Grid, adjacent)) return true; diff --git a/Content.Server/Doors/Components/ServerDoorComponent.cs b/Content.Server/Doors/Components/ServerDoorComponent.cs index a6fa7a4e9e..c0acc07b1e 100644 --- a/Content.Server/Doors/Components/ServerDoorComponent.cs +++ b/Content.Server/Doors/Components/ServerDoorComponent.cs @@ -21,10 +21,10 @@ using Content.Shared.Tools; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Prototypes; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; @@ -38,6 +38,8 @@ namespace Content.Server.Doors.Components [ComponentReference(typeof(SharedDoorComponent))] public class ServerDoorComponent : SharedDoorComponent, IActivate, IInteractUsing, IMapInit { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables] [DataField("board", customTypeSerializer:typeof(PrototypeIdSerializer))] private string? _boardPrototype; @@ -77,7 +79,7 @@ namespace Content.Server.Doors.Components _ => throw new ArgumentOutOfRangeException(), }; - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new DoorStateChangedEvent(State), false); + _entMan.EventBus.RaiseLocalEvent(Owner, new DoorStateChangedEvent(State), false); _autoCloseCancelTokenSource?.Cancel(); Dirty(); @@ -219,7 +221,7 @@ namespace Content.Server.Doors.Components { if (!CanWeldShut) { - Logger.Warning("{0} prototype loaded with incompatible flags: 'welded' is true, but door cannot be welded.", Owner.Name); + Logger.Warning("{0} prototype loaded with incompatible flags: 'welded' is true, but door cannot be welded.", _entMan.GetComponent(Owner).EntityName); return; } SetAppearance(DoorVisualState.Welded); @@ -242,7 +244,7 @@ namespace Content.Server.Doors.Components { if (IsWeldedShut) { - Logger.Warning("{0} prototype loaded with incompatible flags: 'welded' and 'startOpen' are both true.", Owner.Name); + Logger.Warning("{0} prototype loaded with incompatible flags: 'welded' and 'startOpen' are both true.", _entMan.GetComponent(Owner).EntityName); return; } QuickOpen(false); @@ -256,8 +258,8 @@ namespace Content.Server.Doors.Components if (!ClickOpen) return; - DoorClickShouldActivateEvent ev = new DoorClickShouldActivateEvent(eventArgs); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + var ev = new DoorClickShouldActivateEvent(eventArgs); + _entMan.EventBus.RaiseLocalEvent(Owner, ev, false); if (ev.Handled) return; @@ -273,24 +275,23 @@ namespace Content.Server.Doors.Components #region Opening - public void TryOpen(IEntity? user=null) + public void TryOpen(EntityUid user = default) { var msg = new DoorOpenAttemptEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, msg); + _entMan.EventBus.RaiseLocalEvent(Owner, msg); if (msg.Cancelled) return; - if (user == null) + if (!user.Valid) { // a machine opened it or something, idk Open(); - return; } else if (CanOpenByEntity(user)) { Open(); - if (user.TryGetComponent(out HandsComponent? hands) && hands.Count == 0) + if (_entMan.TryGetComponent(user, out HandsComponent? hands) && hands.Count == 0) { SoundSystem.Play(Filter.Pvs(Owner), _tryOpenDoorSound.GetSound(), Owner, AudioParams.Default.WithVolume(-2)); @@ -302,14 +303,14 @@ namespace Content.Server.Doors.Components } } - public bool CanOpenByEntity(IEntity user) + public bool CanOpenByEntity(EntityUid user) { - if(!CanOpenGeneric()) + if (!CanOpenGeneric()) { return false; } - if (!Owner.TryGetComponent(out AccessReader? access)) + if (!_entMan.TryGetComponent(Owner, out AccessReader? access)) { return true; } @@ -321,9 +322,9 @@ namespace Content.Server.Doors.Components return doorSystem.AccessType switch { DoorSystem.AccessTypes.AllowAll => true, - DoorSystem.AccessTypes.AllowAllIdExternal => isAirlockExternal || accessSystem.IsAllowed(access, user.Uid), + DoorSystem.AccessTypes.AllowAllIdExternal => isAirlockExternal || accessSystem.IsAllowed(access, user), DoorSystem.AccessTypes.AllowAllNoExternal => !isAirlockExternal, - _ => accessSystem.IsAllowed(access, user.Uid) + _ => accessSystem.IsAllowed(access, user) }; } @@ -333,7 +334,7 @@ namespace Content.Server.Doors.Components /// private bool HasAccessType(string accessType) { - if (Owner.TryGetComponent(out AccessReader? access)) + if (_entMan.TryGetComponent(Owner, out AccessReader? access)) { return access.AccessLists.Any(list => list.Contains(accessType)); } @@ -354,7 +355,7 @@ namespace Content.Server.Doors.Components } var ev = new BeforeDoorOpenedEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + _entMan.EventBus.RaiseLocalEvent(Owner, ev, false); return !ev.Cancelled; } @@ -364,12 +365,12 @@ namespace Content.Server.Doors.Components public void Open() { State = DoorState.Opening; - if (Occludes && Owner.TryGetComponent(out OccluderComponent? occluder)) + if (Occludes && _entMan.TryGetComponent(Owner, out OccluderComponent? occluder)) { occluder.Enabled = false; } - if (ChangeAirtight && Owner.TryGetComponent(out AirtightComponent? airtight)) + if (ChangeAirtight && _entMan.TryGetComponent(Owner, out AirtightComponent? airtight)) { EntitySystem.Get().SetAirblocked(airtight, false); } @@ -397,17 +398,17 @@ namespace Content.Server.Doors.Components { base.OnPartialOpen(); - if (ChangeAirtight && Owner.TryGetComponent(out AirtightComponent? airtight)) + if (ChangeAirtight && _entMan.TryGetComponent(Owner, out AirtightComponent? airtight)) { EntitySystem.Get().SetAirblocked(airtight, false); } - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new AccessReaderChangeMessage(Owner, false)); + _entMan.EventBus.RaiseEvent(EventSource.Local, new AccessReaderChangeMessage(Owner, false)); } private void QuickOpen(bool refresh) { - if (Occludes && Owner.TryGetComponent(out OccluderComponent? occluder)) + if (Occludes && _entMan.TryGetComponent(Owner, out OccluderComponent? occluder)) { occluder.Enabled = false; } @@ -421,14 +422,14 @@ namespace Content.Server.Doors.Components #region Closing - public void TryClose(IEntity? user=null) + public void TryClose(EntityUid user = default) { var msg = new DoorCloseAttemptEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, msg); + _entMan.EventBus.RaiseLocalEvent(Owner, msg); if (msg.Cancelled) return; - if (user != null && !CanCloseByEntity(user)) + if (user != default && !CanCloseByEntity(user)) { Deny(); return; @@ -437,20 +438,20 @@ namespace Content.Server.Doors.Components Close(); } - public bool CanCloseByEntity(IEntity user) + public bool CanCloseByEntity(EntityUid user) { if (!CanCloseGeneric()) { return false; } - if (!Owner.TryGetComponent(out AccessReader? access)) + if (!_entMan.TryGetComponent(Owner, out AccessReader? access)) { return true; } var accessSystem = EntitySystem.Get(); - return accessSystem.IsAllowed(access, user.Uid); + return accessSystem.IsAllowed(access, user); } /// @@ -460,7 +461,7 @@ namespace Content.Server.Doors.Components public bool CanCloseGeneric() { var ev = new BeforeDoorClosedEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + _entMan.EventBus.RaiseLocalEvent(Owner, ev, false); if (ev.Cancelled) return false; @@ -470,7 +471,7 @@ namespace Content.Server.Doors.Components private bool SafetyCheck() { var ev = new DoorSafetyEnabledEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + _entMan.EventBus.RaiseLocalEvent(Owner, ev, false); return ev.Safety || _inhibitCrush; } @@ -482,7 +483,7 @@ namespace Content.Server.Doors.Components { var safety = SafetyCheck(); - if (safety && Owner.TryGetComponent(out PhysicsComponent? physicsComponent)) + if (safety && _entMan.TryGetComponent(Owner, out PhysicsComponent? physicsComponent)) { var broadPhaseSystem = EntitySystem.Get(); @@ -526,7 +527,7 @@ namespace Content.Server.Doors.Components OnPartialClose(); await Timer.Delay(CloseTimeTwo, _stateChangeCancelTokenSource.Token); - if (Occludes && Owner.TryGetComponent(out OccluderComponent? occluder)) + if (Occludes && _entMan.TryGetComponent(Owner, out OccluderComponent? occluder)) { occluder.Enabled = true; } @@ -542,12 +543,12 @@ namespace Content.Server.Doors.Components // if safety is off, crushes people inside of the door, temporarily turning off collisions with them while doing so. var becomeairtight = ChangeAirtight && (SafetyCheck() || !TryCrush()); - if (becomeairtight && Owner.TryGetComponent(out AirtightComponent? airtight)) + if (becomeairtight && _entMan.TryGetComponent(Owner, out AirtightComponent? airtight)) { EntitySystem.Get().SetAirblocked(airtight, true); } - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new AccessReaderChangeMessage(Owner, true)); + _entMan.EventBus.RaiseEvent(EventSource.Local, new AccessReaderChangeMessage(Owner, true)); } /// @@ -580,12 +581,12 @@ namespace Content.Server.Doors.Components continue; hitsomebody = true; - CurrentlyCrushing.Add(e.Owner.Uid); + CurrentlyCrushing.Add(e.Owner); - if (e.Owner.HasComponent()) - EntitySystem.Get().TryChangeDamage(e.Owner.Uid, CrushDamage); + if (_entMan.HasComponent(e.Owner)) + EntitySystem.Get().TryChangeDamage(e.Owner, CrushDamage); - EntitySystem.Get().TryParalyze(e.Owner.Uid, TimeSpan.FromSeconds(DoorStunTime), true); + EntitySystem.Get().TryParalyze(e.Owner, TimeSpan.FromSeconds(DoorStunTime), true); } // If we hit someone, open up after stun (opens right when stun ends) @@ -603,7 +604,7 @@ namespace Content.Server.Doors.Components public void Deny() { var ev = new BeforeDoorDeniedEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + _entMan.EventBus.RaiseLocalEvent(Owner, ev, false); if (ev.Cancelled) return; @@ -650,14 +651,14 @@ namespace Content.Server.Doors.Components return; var autoev = new BeforeDoorAutoCloseEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, autoev, false); + _entMan.EventBus.RaiseLocalEvent(Owner, autoev, false); if (autoev.Cancelled) return; _autoCloseCancelTokenSource = new(); var ev = new DoorGetCloseTimeModifierEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + _entMan.EventBus.RaiseLocalEvent(Owner, ev, false); var realCloseTime = AutoCloseDelay * ev.CloseTimeModifier; Owner.SpawnRepeatingTimer(realCloseTime, async () => @@ -672,7 +673,7 @@ namespace Content.Server.Doors.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if(!eventArgs.Using.TryGetComponent(out ToolComponent? tool)) + if(!_entMan.TryGetComponent(eventArgs.Using, out ToolComponent? tool)) { return false; } @@ -683,19 +684,19 @@ namespace Content.Server.Doors.Components if (tool.Qualities.Contains(_pryingQuality) && !IsWeldedShut) { var ev = new DoorGetPryTimeModifierEvent(); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, ev, false); + _entMan.EventBus.RaiseLocalEvent(Owner, ev, false); var canEv = new BeforeDoorPryEvent(eventArgs); - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, canEv, false); + _entMan.EventBus.RaiseLocalEvent(Owner, canEv, false); if (canEv.Cancelled) return false; - var successfulPry = await toolSystem.UseTool(eventArgs.Using.Uid, eventArgs.User.Uid, Owner.Uid, + var successfulPry = await toolSystem.UseTool(eventArgs.Using, eventArgs.User, Owner, 0f, ev.PryTimeModifier * PryTime, _pryingQuality); if (successfulPry && !IsWeldedShut) { - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new OnDoorPryEvent(eventArgs), false); + _entMan.EventBus.RaiseLocalEvent(Owner, new OnDoorPryEvent(eventArgs), false); if (State == DoorState.Closed) { Open(); @@ -709,12 +710,12 @@ namespace Content.Server.Doors.Components } // for welding doors - if (CanWeldShut && tool.Owner.TryGetComponent(out WelderComponent? welder) && welder.Lit) + if (CanWeldShut && _entMan.TryGetComponent(tool.Owner, out WelderComponent? welder) && welder.Lit) { if(!_beingWelded) { _beingWelded = true; - if(await toolSystem.UseTool(eventArgs.Using.Uid, eventArgs.User.Uid, Owner.Uid, 3f, 3f, _weldingQuality, () => CanWeldShut)) + if(await toolSystem.UseTool(eventArgs.Using, eventArgs.User, Owner, 3f, 3f, _weldingQuality, () => CanWeldShut)) { // just in case if (!CanWeldShut) @@ -744,8 +745,8 @@ namespace Content.Server.Doors.Components private void CreateDoorElectronicsBoard() { // Ensure that the construction component is aware of the board container. - if (Owner.TryGetComponent(out ConstructionComponent? construction)) - EntitySystem.Get().AddContainer(Owner.Uid, "board", construction); + if (_entMan.TryGetComponent(Owner, out ConstructionComponent? construction)) + EntitySystem.Get().AddContainer(Owner, "board", construction); // We don't do anything if this is null or empty. if (string.IsNullOrEmpty(_boardPrototype)) diff --git a/Content.Server/Doors/Systems/AirlockSystem.cs b/Content.Server/Doors/Systems/AirlockSystem.cs index ea5dc50f6b..14ef8d6a95 100644 --- a/Content.Server/Doors/Systems/AirlockSystem.cs +++ b/Content.Server/Doors/Systems/AirlockSystem.cs @@ -4,6 +4,7 @@ using Content.Shared.Doors; using Content.Shared.Popups; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; namespace Content.Server.Doors.Systems @@ -87,7 +88,7 @@ namespace Content.Server.Doors.Systems private void OnDoorClickShouldActivate(EntityUid uid, AirlockComponent component, DoorClickShouldActivateEvent args) { if (component.WiresComponent != null && component.WiresComponent.IsPanelOpen && - args.Args.User.TryGetComponent(out ActorComponent? actor)) + EntityManager.TryGetComponent(args.Args.User, out ActorComponent? actor)) { component.WiresComponent.OpenInterface(actor.PlayerSession); args.Handled = true; diff --git a/Content.Server/Doors/Systems/DoorSystem.cs b/Content.Server/Doors/Systems/DoorSystem.cs index e24a838fa9..54b781ec72 100644 --- a/Content.Server/Doors/Systems/DoorSystem.cs +++ b/Content.Server/Doors/Systems/DoorSystem.cs @@ -1,6 +1,7 @@ using Content.Server.Doors.Components; using Content.Shared.Doors; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Physics.Dynamics; namespace Content.Server.Doors @@ -45,7 +46,7 @@ namespace Content.Server.Doors private void HandleCollide(EntityUid uid, ServerDoorComponent component, StartCollideEvent args) { - if (!args.OtherFixture.Body.Owner.HasComponent()) + if (!EntityManager.HasComponent(args.OtherFixture.Body.Owner)) { return; } diff --git a/Content.Server/Electrocution/ElectrocutionSystem.cs b/Content.Server/Electrocution/ElectrocutionSystem.cs index a80ea11a81..72d2fe4f42 100644 --- a/Content.Server/Electrocution/ElectrocutionSystem.cs +++ b/Content.Server/Electrocution/ElectrocutionSystem.cs @@ -9,7 +9,6 @@ using Content.Server.Power.Components; using Content.Server.Power.EntitySystems; using Content.Server.Power.NodeGroups; using Content.Server.Window; -using Content.Shared.Administration.Logs; using Content.Shared.Alert; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; @@ -24,7 +23,6 @@ using Content.Shared.Speech.EntitySystems; using Content.Shared.StatusEffect; using Content.Shared.Stunnable; using Content.Shared.Weapons.Melee; -using Robust.Shared.Console; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; @@ -100,7 +98,7 @@ namespace Content.Server.Electrocution foreach (var finished in finishedElectrocutionsQueue) { - var uid = finished.Owner.Uid; + var uid = finished.Owner; if (EntityManager.EntityExists(finished.Electrocuting)) { // TODO: damage should be scaled by shock damage multiplier @@ -124,7 +122,7 @@ namespace Content.Server.Electrocution if (!electrified.OnBump) return; - TryDoElectrifiedAct(uid, args.OtherFixture.Body.Owner.Uid, electrified); + TryDoElectrifiedAct(uid, args.OtherFixture.Body.Owner, electrified); } private void OnElectrifiedAttacked(EntityUid uid, ElectrifiedComponent electrified, AttackedEvent args) @@ -132,7 +130,7 @@ namespace Content.Server.Electrocution if (!electrified.OnAttacked) return; - TryDoElectrifiedAct(uid, args.User.Uid, electrified); + TryDoElectrifiedAct(uid, args.User, electrified); } private void OnElectrifiedHandInteract(EntityUid uid, ElectrifiedComponent electrified, InteractHandEvent args) @@ -140,7 +138,7 @@ namespace Content.Server.Electrocution if (!electrified.OnHandInteract) return; - TryDoElectrifiedAct(uid, args.User.Uid, electrified); + TryDoElectrifiedAct(uid, args.User, electrified); } private void OnElectrifiedInteractUsing(EntityUid uid, ElectrifiedComponent electrified, InteractUsingEvent args) @@ -148,7 +146,7 @@ namespace Content.Server.Electrocution if (!electrified.OnInteractUsing) return; - TryDoElectrifiedAct(uid, args.User.Uid, electrified); + TryDoElectrifiedAct(uid, args.User, electrified); } public bool TryDoElectrifiedAct(EntityUid uid, EntityUid targetUid, @@ -167,7 +165,7 @@ namespace Content.Server.Electrocution foreach (var entity in transform.Coordinates.GetEntitiesInTile( LookupFlags.Approximate | LookupFlags.IncludeAnchored, _entityLookup)) { - if (entity.HasComponent()) + if (EntityManager.HasComponent(entity)) return false; } } @@ -287,11 +285,10 @@ namespace Content.Server.Electrocution var electrocutionEntity = EntityManager.SpawnEntity( $"VirtualElectrocutionLoad{node.NodeGroupID}", sourceTransform.Coordinates); - var electrocutionNode = electrocutionEntity - .GetComponent() + var electrocutionNode = EntityManager.GetComponent(electrocutionEntity) .GetNode("electrocution"); - var electrocutionComponent = electrocutionEntity.GetComponent(); + var electrocutionComponent = EntityManager.GetComponent(electrocutionEntity); electrocutionNode.CableEntity = sourceUid; electrocutionNode.NodeName = node.Name; @@ -377,13 +374,12 @@ namespace Content.Server.Electrocution if (sourceUid != null) { _popupSystem.PopupEntity(Loc.GetString("electrocuted-component-mob-shocked-by-source-popup-others", - ("mob", EntityManager.GetEntity(uid)), ("source", EntityManager.GetEntity(sourceUid.Value))), - uid, filter); + ("mob", uid), ("source", (sourceUid.Value))), uid, filter); } else { _popupSystem.PopupEntity(Loc.GetString("electrocuted-component-mob-shocked-popup-others", - ("mob", EntityManager.GetEntity(uid))), uid, filter); + ("mob", uid)), uid, filter); } return true; @@ -406,17 +402,17 @@ namespace Content.Server.Electrocution visited.Add(entity); if (EntityManager.TryGetComponent(entity, out SharedPullableComponent? pullable) - && pullable.Puller != null - && !visited.Contains(pullable.Puller.Uid)) + && pullable.Puller is {Valid: true} pullerId + && !visited.Contains(pullerId)) { - GetChainedElectrocutionTargetsRecurse(pullable.Puller.Uid, depth + 1, visited, all); + GetChainedElectrocutionTargetsRecurse(pullerId, depth + 1, visited, all); } if (EntityManager.TryGetComponent(entity, out SharedPullerComponent? puller) - && puller.Pulling != null - && !visited.Contains(puller.Pulling.Uid)) + && puller.Pulling is {Valid: true} pullingId + && !visited.Contains(pullingId)) { - GetChainedElectrocutionTargetsRecurse(puller.Pulling.Uid, depth + 1, visited, all); + GetChainedElectrocutionTargetsRecurse(pullingId, depth + 1, visited, all); } } diff --git a/Content.Server/Engineering/EntitySystems/DisassembleOnActivateSystem.cs b/Content.Server/Engineering/EntitySystems/DisassembleOnActivateSystem.cs index 7dedae6d28..28684dc9ca 100644 --- a/Content.Server/Engineering/EntitySystems/DisassembleOnActivateSystem.cs +++ b/Content.Server/Engineering/EntitySystems/DisassembleOnActivateSystem.cs @@ -6,6 +6,7 @@ using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Engineering.EntitySystems { @@ -40,18 +41,18 @@ namespace Content.Server.Engineering.EntitySystems component.TokenSource.Cancel(); } - if (component.Deleted || component.Owner.Deleted) + if (component.Deleted || Deleted(component.Owner)) return; - var entity = EntityManager.SpawnEntity(component.Prototype, component.Owner.Transform.Coordinates); + var entity = EntityManager.SpawnEntity(component.Prototype, EntityManager.GetComponent(component.Owner).Coordinates); - if (args.User.TryGetComponent(out var hands) - && entity.TryGetComponent(out var item)) + if (EntityManager.TryGetComponent(args.User, out var hands) + && EntityManager.TryGetComponent(entity, out var item)) { hands.PutInHandOrDrop(item); } - component.Owner.Delete(); + EntityManager.DeleteEntity(component.Owner); return; } diff --git a/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs b/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs index 7fcad8a294..b7f4037eaf 100644 --- a/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs +++ b/Content.Server/Engineering/EntitySystems/SpawnAfterInteractSystem.cs @@ -57,10 +57,10 @@ namespace Content.Server.Engineering.EntitySystems return; } - if (component.Deleted || component.Owner.Deleted) + if (component.Deleted || Deleted(component.Owner)) return; - if (component.Owner.TryGetComponent(out var stackComp) + if (EntityManager.TryGetComponent(component.Owner, out var stackComp) && component.RemoveOnInteract && !_stackSystem.Use(uid, 1, stackComp)) { return; @@ -68,8 +68,8 @@ namespace Content.Server.Engineering.EntitySystems EntityManager.SpawnEntity(component.Prototype, args.ClickLocation.SnapToGrid(grid)); - if (component.RemoveOnInteract && stackComp == null && !component.Owner.Deleted) - component.Owner.Delete(); + if (component.RemoveOnInteract && stackComp == null && !((!EntityManager.EntityExists(component.Owner) ? EntityLifeStage.Deleted : EntityManager.GetComponent(component.Owner).EntityLifeStage) >= EntityLifeStage.Deleted)) + EntityManager.DeleteEntity(component.Owner); } } } diff --git a/Content.Server/EntityList/SpawnEntityListCommand.cs b/Content.Server/EntityList/SpawnEntityListCommand.cs index aaf85a2171..966b206a13 100644 --- a/Content.Server/EntityList/SpawnEntityListCommand.cs +++ b/Content.Server/EntityList/SpawnEntityListCommand.cs @@ -30,7 +30,7 @@ namespace Content.Server.EntityList return; } - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {} attached) { shell.WriteError("You must have an entity to run this command."); return; @@ -49,7 +49,7 @@ namespace Content.Server.EntityList foreach (var entity in prototype.Entities(prototypeManager)) { - entityManager.SpawnEntity(entity.ID, player.AttachedEntity.Transform.Coordinates); + entityManager.SpawnEntity(entity.ID, entityManager.GetComponent(attached).Coordinates); i++; } diff --git a/Content.Server/Examine/ExamineSystem.cs b/Content.Server/Examine/ExamineSystem.cs index 037913bb63..eb91139539 100644 --- a/Content.Server/Examine/ExamineSystem.cs +++ b/Content.Server/Examine/ExamineSystem.cs @@ -32,19 +32,18 @@ namespace Content.Server.Examine { var player = (IPlayerSession) eventArgs.SenderSession; var session = eventArgs.SenderSession; - var playerEnt = session.AttachedEntity; var channel = player.ConnectedClient; - if (playerEnt == null - || !EntityManager.TryGetEntity(request.EntityUid, out var entity) - || !CanExamine(playerEnt, entity)) + if (session.AttachedEntity is not {Valid: true} playerEnt + || !EntityManager.EntityExists(request.EntityUid) + || !CanExamine(playerEnt, request.EntityUid)) { RaiseNetworkEvent(new ExamineSystemMessages.ExamineInfoResponseMessage( request.EntityUid, _entityNotFoundMessage), channel); return; } - var text = GetExamineText(entity, player.AttachedEntity); + var text = GetExamineText(request.EntityUid, player.AttachedEntity); RaiseNetworkEvent(new ExamineSystemMessages.ExamineInfoResponseMessage(request.EntityUid, text), channel); } } diff --git a/Content.Server/Explosion/Components/ClusterFlashComponent.cs b/Content.Server/Explosion/Components/ClusterFlashComponent.cs index 7cd50c5e12..f05d88fa43 100644 --- a/Content.Server/Explosion/Components/ClusterFlashComponent.cs +++ b/Content.Server/Explosion/Components/ClusterFlashComponent.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Content.Server.Explosion.EntitySystems; using Content.Server.Flash.Components; @@ -19,6 +18,8 @@ namespace Content.Server.Explosion.Components [RegisterComponent] public sealed class ClusterFlashComponent : Component, IInteractUsing, IUse { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "ClusterFlash"; private Container _grenadesContainer = default!; @@ -60,7 +61,7 @@ namespace Content.Server.Explosion.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs args) { if (_grenadesContainer.ContainedEntities.Count >= _maxGrenades || - !args.Using.HasComponent()) + !_entMan.HasComponent(args.Using)) return false; _grenadesContainer.Insert(args.Using); @@ -93,14 +94,14 @@ namespace Content.Server.Explosion.Components return false; Owner.SpawnTimer((int) (_delay * 1000), () => { - if (Owner.Deleted) + if (_entMan.Deleted(Owner)) return; _countDown = true; var random = IoCManager.Resolve(); var delay = 20; var grenadesInserted = _grenadesContainer.ContainedEntities.Count + _unspawnedCount; var thrownCount = 0; - var segmentAngle = (int) (360 / grenadesInserted); + var segmentAngle = 360 / grenadesInserted; while (TryGetGrenade(out var grenade)) { var angleMin = segmentAngle * thrownCount; @@ -116,26 +117,26 @@ namespace Content.Server.Explosion.Components grenade.SpawnTimer(delay, () => { - if (grenade.Deleted) + if ((!_entMan.EntityExists(grenade) ? EntityLifeStage.Deleted : _entMan.GetComponent(grenade).EntityLifeStage) >= EntityLifeStage.Deleted) return; - EntitySystem.Get().Trigger(grenade, eventArgs.User.Uid); + EntitySystem.Get().Trigger(grenade, eventArgs.User); }); } - Owner.Delete(); + _entMan.DeleteEntity(Owner); }); return true; } - private bool TryGetGrenade([NotNullWhen(true)] out IEntity? grenade) + private bool TryGetGrenade(out EntityUid grenade) { - grenade = null; + grenade = default; if (_unspawnedCount > 0) { _unspawnedCount--; - grenade = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.MapPosition); + grenade = _entMan.SpawnEntity(_fillPrototype, _entMan.GetComponent(Owner).MapPosition); return true; } @@ -155,7 +156,7 @@ namespace Content.Server.Explosion.Components private void UpdateAppearance() { - if (!Owner.TryGetComponent(out AppearanceComponent? appearance)) return; + if (!_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) return; appearance.SetData(ClusterFlashVisuals.GrenadesCounter, _grenadesContainer.ContainedEntities.Count + _unspawnedCount); } diff --git a/Content.Server/Explosion/Components/ExplosionLaunchedComponent.cs b/Content.Server/Explosion/Components/ExplosionLaunchedComponent.cs index d71ccba148..32f3e95ea4 100644 --- a/Content.Server/Explosion/Components/ExplosionLaunchedComponent.cs +++ b/Content.Server/Explosion/Components/ExplosionLaunchedComponent.cs @@ -1,6 +1,7 @@ using Content.Server.Throwing; using Content.Shared.Acts; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Server.Explosion.Components @@ -8,19 +9,21 @@ namespace Content.Server.Explosion.Components [RegisterComponent] public class ExplosionLaunchedComponent : Component, IExAct { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "ExplosionLaunched"; void IExAct.OnExplosion(ExplosionEventArgs eventArgs) { - if (Owner.Deleted) + if (_entMan.Deleted(Owner)) return; var sourceLocation = eventArgs.Source; - var targetLocation = Owner.EntityManager.GetComponent(eventArgs.Target).Coordinates; + var targetLocation = _entMan.GetComponent(eventArgs.Target).Coordinates; if (sourceLocation.Equals(targetLocation)) return; - var offset = (targetLocation.ToMapPos(Owner.EntityManager) - sourceLocation.ToMapPos(Owner.EntityManager)); + var offset = (targetLocation.ToMapPos(_entMan) - sourceLocation.ToMapPos(_entMan)); //Don't throw if the direction is center (0,0) if (offset == Vector2.Zero) return; diff --git a/Content.Server/Explosion/Components/OnUseTimerTriggerComponent.cs b/Content.Server/Explosion/Components/OnUseTimerTriggerComponent.cs index ede6e6fbd2..c43149b88f 100644 --- a/Content.Server/Explosion/Components/OnUseTimerTriggerComponent.cs +++ b/Content.Server/Explosion/Components/OnUseTimerTriggerComponent.cs @@ -3,6 +3,7 @@ using Content.Server.Explosion.EntitySystems; using Content.Shared.Interaction; using Content.Shared.Trigger; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Explosion.Components @@ -18,7 +19,7 @@ namespace Content.Server.Explosion.Components // TODO: Need to split this out so it's a generic "OnUseTimerTrigger" component. public void Trigger(EntityUid user) { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (IoCManager.Resolve().TryGetComponent(Owner, out AppearanceComponent? appearance)) appearance.SetData(TriggerVisuals.VisualState, TriggerVisualState.Primed); EntitySystem.Get().HandleTimerTrigger(TimeSpan.FromSeconds(_delay), Owner, user); @@ -26,7 +27,7 @@ namespace Content.Server.Explosion.Components bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - Trigger(eventArgs.User.Uid); + Trigger(eventArgs.User); return true; } } diff --git a/Content.Server/Explosion/EntitySystems/ExplosionSystem.cs b/Content.Server/Explosion/EntitySystems/ExplosionSystem.cs index d3f021ab44..ebe85c615d 100644 --- a/Content.Server/Explosion/EntitySystems/ExplosionSystem.cs +++ b/Content.Server/Explosion/EntitySystems/ExplosionSystem.cs @@ -5,7 +5,6 @@ using Content.Server.Administration.Logs; using Content.Server.Camera; using Content.Server.Explosion.Components; using Content.Shared.Acts; -using Content.Shared.Administration.Logs; using Content.Shared.Database; using Content.Shared.Interaction.Helpers; using Content.Shared.Maps; @@ -53,7 +52,7 @@ namespace Content.Server.Explosion.EntitySystems [Dependency] private readonly TriggerSystem _triggers = default!; [Dependency] private readonly AdminLogSystem _logSystem = default!; - private bool IgnoreExplosivePassable(IEntity e) + private bool IgnoreExplosivePassable(EntityUid e) { return e.HasTag("ExplosivePassable"); } @@ -82,12 +81,13 @@ namespace Content.Server.Explosion.EntitySystems foreach (var player in players) { - if (player.AttachedEntity == null || !player.AttachedEntity.TryGetComponent(out CameraRecoilComponent? recoil)) + if (player.AttachedEntity is not {Valid: true} playerEntity || + !EntityManager.TryGetComponent(playerEntity, out CameraRecoilComponent? recoil)) { continue; } - var playerPos = player.AttachedEntity.Transform.WorldPosition; + var playerPos = EntityManager.GetComponent(playerEntity).WorldPosition; var delta = epicenter.ToMapPos(EntityManager) - playerPos; //Change if zero. Will result in a NaN later breaking camera shake if not changed @@ -122,26 +122,26 @@ namespace Content.Server.Explosion.EntitySystems { var entitiesInRange = _entityLookup.GetEntitiesInRange(mapId, boundingBox, 0).ToList(); - var impassableEntities = new List<(IEntity, float)>(); - var nonImpassableEntities = new List<(IEntity, float)>(); + var impassableEntities = new List<(EntityUid, float)>(); + var nonImpassableEntities = new List<(EntityUid, float)>(); // TODO: Given this seems to rely on physics it should just query directly like everything else. // The entities are paired with their distance to the epicenter // and splitted into two lists based on if they are Impassable or not foreach (var entity in entitiesInRange) { - if (entity.Deleted || entity.IsInContainer()) + if (Deleted(entity) || entity.IsInContainer()) { continue; } - if (!entity.Transform.Coordinates.TryDistance(EntityManager, epicenter, out var distance) || + if (!EntityManager.GetComponent(entity).Coordinates.TryDistance(EntityManager, epicenter, out var distance) || distance > maxRange) { continue; } - if (!entity.TryGetComponent(out PhysicsComponent? body) || body.Fixtures.Count < 1) + if (!EntityManager.TryGetComponent(entity, out PhysicsComponent? body) || body.Fixtures.Count < 1) { continue; } @@ -171,7 +171,7 @@ namespace Content.Server.Explosion.EntitySystems continue; } - _acts.HandleExplosion(epicenter, entity.Uid, CalculateSeverity(distance, devastationRange, heavyRange)); + _acts.HandleExplosion(epicenter, entity, CalculateSeverity(distance, devastationRange, heavyRange)); } // Impassable entities were handled first so NonImpassable entities have a bigger chance to get hit. As now @@ -183,7 +183,7 @@ namespace Content.Server.Explosion.EntitySystems continue; } - _acts.HandleExplosion(epicenter, entity.Uid, CalculateSeverity(distance, devastationRange, heavyRange)); + _acts.HandleExplosion(epicenter, entity, CalculateSeverity(distance, devastationRange, heavyRange)); } } @@ -311,9 +311,9 @@ namespace Content.Server.Explosion.EntitySystems } else { - while (EntityManager.TryGetEntity(entity, out var e) && e.TryGetContainer(out var container)) + while (EntityManager.EntityExists(entity) && entity.TryGetContainer(out var container)) { - entity = container.Owner.Uid; + entity = container.Owner; } if (!EntityManager.TryGetComponent(entity, out transform)) @@ -351,12 +351,12 @@ namespace Content.Server.Explosion.EntitySystems else if (user == null) { _logSystem.Add(LogType.Explosion, LogImpact.High, - $"{EntityManager.GetEntity(entity.Value)} exploded at {text}"); + $"{entity.Value} exploded at {text}"); } else { _logSystem.Add(LogType.Explosion, LogImpact.High, - $"{EntityManager.GetEntity(user.Value)} caused {EntityManager.GetEntity(entity.Value)} to explode at {text}"); + $"{user.Value} caused {entity.Value} to explode at {text}"); } var maxRange = MathHelper.Max(devastationRange, heavyImpactRange, lightImpactRange, 0); diff --git a/Content.Server/Explosion/EntitySystems/TriggerSystem.cs b/Content.Server/Explosion/EntitySystems/TriggerSystem.cs index 39f41b6d47..a282d38b30 100644 --- a/Content.Server/Explosion/EntitySystems/TriggerSystem.cs +++ b/Content.Server/Explosion/EntitySystems/TriggerSystem.cs @@ -24,10 +24,10 @@ namespace Content.Server.Explosion.EntitySystems /// public class TriggerEvent : HandledEntityEventArgs { - public IEntity Triggered { get; } + public EntityUid Triggered { get; } public EntityUid? User { get; } - public TriggerEvent(IEntity triggered, EntityUid? user = null) + public TriggerEvent(EntityUid triggered, EntityUid? user = null) { Triggered = triggered; User = user; @@ -127,18 +127,19 @@ namespace Content.Server.Explosion.EntitySystems if (EntityManager.TryGetComponent(uid, out ProjectileComponent projectile)) user = projectile.Shooter; else if (EntityManager.TryGetComponent(uid, out ThrownItemComponent thrown)) - user = thrown.Thrower?.Uid; + user = thrown.Thrower; Trigger(component.Owner, user); } - public void Trigger(IEntity trigger, EntityUid? user = null) + + public void Trigger(EntityUid trigger, EntityUid? user = null) { var triggerEvent = new TriggerEvent(trigger, user); - EntityManager.EventBus.RaiseLocalEvent(trigger.Uid, triggerEvent); + EntityManager.EventBus.RaiseLocalEvent(trigger, triggerEvent); } - public void HandleTimerTrigger(TimeSpan delay, IEntity triggered, EntityUid? user = null) + public void HandleTimerTrigger(TimeSpan delay, EntityUid triggered, EntityUid? user = null) { if (delay.TotalSeconds <= 0) { @@ -148,7 +149,7 @@ namespace Content.Server.Explosion.EntitySystems Timer.Spawn(delay, () => { - if (triggered.Deleted) return; + if (Deleted(triggered)) return; Trigger(triggered, user); }); } diff --git a/Content.Server/Extinguisher/FireExtinguisherComponent.cs b/Content.Server/Extinguisher/FireExtinguisherComponent.cs index 6a88316af5..240777dc2a 100644 --- a/Content.Server/Extinguisher/FireExtinguisherComponent.cs +++ b/Content.Server/Extinguisher/FireExtinguisherComponent.cs @@ -1,17 +1,16 @@ -using System; using System.Threading.Tasks; using Content.Server.Chemistry.Components; using Content.Server.Chemistry.EntitySystems; using Content.Shared.ActionBlocker; using Content.Shared.Audio; -using Content.Shared.Chemistry.Reagent; +using Content.Shared.Extinguisher; +using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Popups; using Content.Shared.Sound; -using Content.Shared.Extinguisher; -using Content.Shared.FixedPoint; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -21,6 +20,8 @@ namespace Content.Server.Extinguisher [RegisterComponent] public class FireExtinguisherComponent : SharedFireExtinguisherComponent, IAfterInteract, IUse, IActivate, IDropped { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "FireExtinguisher"; [DataField("refillSound")] @@ -58,26 +59,27 @@ namespace Content.Server.Extinguisher return false; } - var targetEntity = eventArgs.Target; - if (eventArgs.Target.HasComponent() - && solutionContainerSystem.TryGetDrainableSolution(targetEntity.Uid, out var targetSolution) - && solutionContainerSystem.TryGetDrainableSolution(Owner.Uid, out var container)) + if (eventArgs.Target is not {Valid: true} target || + !_entMan.HasComponent(target) || + !solutionContainerSystem.TryGetDrainableSolution(target, out var targetSolution) || + !solutionContainerSystem.TryGetDrainableSolution(Owner, out var container)) { - var transfer = FixedPoint2.Min(container.AvailableVolume, targetSolution.DrainAvailable); - if (transfer > 0) - { - var drained = solutionContainerSystem.Drain(targetEntity.Uid, targetSolution, transfer); - solutionContainerSystem.TryAddSolution(Owner.Uid, container, drained); - - SoundSystem.Play(Filter.Pvs(Owner), _refillSound.GetSound(), Owner); - eventArgs.Target.PopupMessage(eventArgs.User, - Loc.GetString("fire-extingusiher-component-after-interact-refilled-message", ("owner", Owner))); - } - - return true; + return false; } - return false; + var transfer = FixedPoint2.Min(container.AvailableVolume, targetSolution.DrainAvailable); + if (transfer > 0) + { + var drained = solutionContainerSystem.Drain(target, targetSolution, transfer); + solutionContainerSystem.TryAddSolution(Owner, container, drained); + + SoundSystem.Play(Filter.Pvs(Owner), _refillSound.GetSound(), Owner); + eventArgs.Target.Value.PopupMessage(eventArgs.User, + Loc.GetString("fire-extingusiher-component-after-interact-refilled-message", ("owner", Owner))); + } + + return true; + } bool IUse.UseEntity(UseEntityEventArgs eventArgs) { @@ -90,26 +92,26 @@ namespace Content.Server.Extinguisher ToggleSafety(eventArgs.User); } - private void ToggleSafety(IEntity user) + private void ToggleSafety(EntityUid user) { SoundSystem.Play(Filter.Pvs(Owner), SafetySound.GetSound(), Owner, AudioHelpers.WithVariation(0.125f).WithVolume(-4f)); SetSafety(user, !_safety); } - private void SetSafety(IEntity user, bool state) + private void SetSafety(EntityUid user, bool state) { - if (!EntitySystem.Get().CanInteract(user.Uid) || !_hasSafety) + if (!EntitySystem.Get().CanInteract(user) || !_hasSafety) return; _safety = state; - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) appearance.SetData(FireExtinguisherVisuals.Safety, _safety); } void IDropped.Dropped(DroppedEventArgs eventArgs) { - if (_hasSafety && Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_hasSafety && _entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) appearance.SetData(FireExtinguisherVisuals.Safety, _safety); } } diff --git a/Content.Server/Flash/FlashSystem.cs b/Content.Server/Flash/FlashSystem.cs index 442f23d7e8..1471a5e2ec 100644 --- a/Content.Server/Flash/FlashSystem.cs +++ b/Content.Server/Flash/FlashSystem.cs @@ -3,7 +3,6 @@ using Content.Server.Flash.Components; using Content.Server.Inventory.Components; using Content.Server.Items; using Content.Server.Stunnable; -using Content.Server.Stunnable.Components; using Content.Server.Weapon.Melee; using Content.Shared.Examine; using Content.Shared.Flash; @@ -13,7 +12,6 @@ using Content.Shared.Inventory; using Content.Shared.Physics; using Content.Shared.Popups; using Content.Shared.Sound; -using Content.Shared.Stunnable; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; @@ -50,9 +48,9 @@ namespace Content.Server.Flash } args.Handled = true; - foreach (IEntity e in args.HitEntities) + foreach (var e in args.HitEntities) { - Flash(e.Uid, args.User.Uid, uid, comp.FlashDuration, comp.SlowTo); + Flash(e, args.User, uid, comp.FlashDuration, comp.SlowTo); } } @@ -63,10 +61,10 @@ namespace Content.Server.Flash return; } - if (args.Entity.HasComponent()) + if (EntityManager.HasComponent(args.Entity)) { args.CanInteract = true; - Flash(args.Entity.Uid, args.User.Uid, uid, comp.FlashDuration, comp.SlowTo); + Flash(args.Entity, args.User, uid, comp.FlashDuration, comp.SlowTo); } } @@ -77,18 +75,18 @@ namespace Content.Server.Flash return; } - foreach (var entity in _entityLookup.GetEntitiesInRange(comp.Owner.Transform.Coordinates, comp.Range)) + foreach (var entity in _entityLookup.GetEntitiesInRange(EntityManager.GetComponent(comp.Owner).Coordinates, comp.Range)) { - Flash(entity.Uid, args.User.Uid, uid, comp.AoeFlashDuration, comp.SlowTo); + Flash(entity, args.User, uid, comp.AoeFlashDuration, comp.SlowTo); } } - private bool UseFlash(FlashComponent comp, IEntity user) + private bool UseFlash(FlashComponent comp, EntityUid user) { if (comp.HasUses) { // TODO flash visualizer - if (!comp.Owner.TryGetComponent(out var sprite)) + if (!EntityManager.TryGetComponent(comp.Owner, out var sprite)) return false; if (--comp.Uses == 0) @@ -136,16 +134,12 @@ namespace Content.Server.Flash if (displayPopup && user != null && target != user) { - // TODO Resolving the IEntity here bad. - if(EntityManager.TryGetEntity(user.Value, out var userEntity) - && EntityManager.TryGetEntity(target, out var targetEntity)) - - userEntity.PopupMessage(targetEntity, - Loc.GetString( - "flash-component-user-blinds-you", - ("user", userEntity) - ) - ); + // TODO Resolving the EntityUidhere bad. + if (EntityManager.EntityExists(user.Value) && EntityManager.EntityExists(target)) + { + user.Value.PopupMessage(target, Loc.GetString("flash-component-user-blinds-you", + ("user", user.Value))); + } } } @@ -155,10 +149,10 @@ namespace Content.Server.Flash foreach (var entity in _entityLookup.GetEntitiesInRange(transform.Coordinates, range)) { - if (!entity.HasComponent() || + if (!EntityManager.HasComponent(entity) || !transform.InRangeUnobstructed(entity, range, CollisionGroup.Opaque)) continue; - Flash(entity.Uid, user, source, duration, slowTo, displayPopup); + Flash(entity, user, source, duration, slowTo, displayPopup); } if (sound != null) @@ -191,7 +185,7 @@ namespace Content.Server.Flash { // Forward the event to the glasses, if any. if(component.TryGetSlotItem(EquipmentSlotDefines.Slots.EYES, out ItemComponent? glasses)) - RaiseLocalEvent(glasses.Owner.Uid, args); + RaiseLocalEvent(glasses.Owner, args); } private void OnFlashImmunityFlashAttempt(EntityUid uid, FlashImmunityComponent component, FlashAttemptEvent args) diff --git a/Content.Server/Fluids/Components/BucketComponent.cs b/Content.Server/Fluids/Components/BucketComponent.cs index b4f5695e35..df8d832091 100644 --- a/Content.Server/Fluids/Components/BucketComponent.cs +++ b/Content.Server/Fluids/Components/BucketComponent.cs @@ -10,6 +10,7 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -22,6 +23,8 @@ namespace Content.Server.Fluids.Components [RegisterComponent] public class BucketComponent : Component, IInteractUsing { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Bucket"; public const string SolutionName = "bucket"; @@ -30,19 +33,19 @@ namespace Content.Server.Fluids.Components public FixedPoint2 MaxVolume { get => - EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution) + EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution) ? solution.MaxVolume : FixedPoint2.Zero; set { - if (EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { solution.MaxVolume = value; } } } - public FixedPoint2 CurrentVolume => EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution) + public FixedPoint2 CurrentVolume => EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution) ? solution.CurrentVolume : FixedPoint2.Zero; @@ -53,9 +56,9 @@ namespace Content.Server.Fluids.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { var solutionsSys = EntitySystem.Get(); - if (!solutionsSys.TryGetSolution(Owner.Uid, SolutionName, out var contents) || - _currentlyUsing.Contains(eventArgs.Using.Uid) || - !eventArgs.Using.TryGetComponent(out MopComponent? mopComponent) || + if (!solutionsSys.TryGetSolution(Owner, SolutionName, out var contents) || + _currentlyUsing.Contains(eventArgs.Using) || + !_entMan.TryGetComponent(eventArgs.Using, out MopComponent? mopComponent) || mopComponent.Mopping) { return false; @@ -73,7 +76,7 @@ namespace Content.Server.Fluids.Components return false; } - _currentlyUsing.Add(eventArgs.Using.Uid); + _currentlyUsing.Add(eventArgs.Using); // IMO let em move while doing it. var doAfterArgs = new DoAfterEventArgs(eventArgs.User, 1.0f, target: eventArgs.Target) @@ -83,13 +86,10 @@ namespace Content.Server.Fluids.Components }; var result = await EntitySystem.Get().WaitDoAfter(doAfterArgs); - _currentlyUsing.Remove(eventArgs.Using.Uid); + _currentlyUsing.Remove(eventArgs.Using); - if (result == DoAfterStatus.Cancelled || - Owner.Deleted || - mopComponent.Deleted || - CurrentVolume <= 0 || - !Owner.InRangeUnobstructed(mopComponent.Owner)) + if (result == DoAfterStatus.Cancelled || _entMan.Deleted(Owner) || mopComponent.Deleted || + CurrentVolume <= 0 || !Owner.InRangeUnobstructed(mopComponent.Owner)) return false; // Top up mops solution given it needs it to annihilate puddles I guess @@ -107,8 +107,8 @@ namespace Content.Server.Fluids.Components return false; } - var solution = solutionsSys.SplitSolution(Owner.Uid, contents, transferAmount); - if (!solutionsSys.TryAddSolution(mopComponent.Owner.Uid, mopContents, solution)) + var solution = solutionsSys.SplitSolution(Owner, contents, transferAmount); + if (!solutionsSys.TryAddSolution(mopComponent.Owner, mopContents, solution)) { return false; } diff --git a/Content.Server/Fluids/Components/MopComponent.cs b/Content.Server/Fluids/Components/MopComponent.cs index b13cd385c3..aae996a535 100644 --- a/Content.Server/Fluids/Components/MopComponent.cs +++ b/Content.Server/Fluids/Components/MopComponent.cs @@ -3,7 +3,6 @@ using Content.Server.Chemistry.EntitySystems; using Content.Server.DoAfter; using Content.Server.Fluids.EntitySystems; using Content.Shared.Chemistry.Components; -using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; @@ -11,6 +10,7 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -24,6 +24,8 @@ namespace Content.Server.Fluids.Components [RegisterComponent] public class MopComponent : Component, IAfterInteract { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "Mop"; public const string SolutionName = "mop"; @@ -36,7 +38,7 @@ namespace Content.Server.Fluids.Components { get { - EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution); + EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution); return solution; } } @@ -90,7 +92,7 @@ namespace Content.Server.Fluids.Components var solutionSystem = EntitySystem.Get(); var spillableSystem = EntitySystem.Get(); - if (!solutionSystem.TryGetSolution(Owner.Uid, SolutionName, out var contents ) || + if (!solutionSystem.TryGetSolution(Owner, SolutionName, out var contents ) || Mopping || !eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true)) { @@ -103,21 +105,21 @@ namespace Content.Server.Fluids.Components return false; } - if (eventArgs.Target == null) + if (eventArgs.Target is not {Valid: true} target) { // Drop the liquid on the mop on to the ground - var solution = solutionSystem.SplitSolution(Owner.Uid, contents, FixedPoint2.Min(ResidueAmount, CurrentVolume)); + var solution = solutionSystem.SplitSolution(Owner, contents, FixedPoint2.Min(ResidueAmount, CurrentVolume)); spillableSystem.SpillAt(solution, eventArgs.ClickLocation, "PuddleSmear"); return true; } - if (!eventArgs.Target.TryGetComponent(out PuddleComponent? puddleComponent) || - !solutionSystem.TryGetSolution(puddleComponent.OwnerUid, puddleComponent.SolutionName, out var puddleSolution)) + if (!_entities.TryGetComponent(target, out PuddleComponent? puddleComponent) || + !solutionSystem.TryGetSolution((puddleComponent).Owner, puddleComponent.SolutionName, out var puddleSolution)) return false; // So if the puddle has 20 units we mop in 2 seconds. Don't just store CurrentVolume given it can change so need to re-calc it anyway. var doAfterArgs = new DoAfterEventArgs(eventArgs.User, _mopSpeed * puddleSolution.CurrentVolume.Float() / 10.0f, - target: eventArgs.Target) + target: target) { BreakOnUserMove = true, BreakOnStun = true, @@ -128,7 +130,7 @@ namespace Content.Server.Fluids.Components Mopping = false; if (result == DoAfterStatus.Cancelled || - Owner.Deleted || + _entities.Deleted(Owner) || puddleComponent.Deleted) return false; @@ -141,23 +143,23 @@ namespace Content.Server.Fluids.Components transferAmount = FixedPoint2.Min(PickupAmount, puddleSolution.TotalVolume, CurrentVolume); // is the puddle cleaned? - if (puddleSolution.TotalVolume - transferAmount <= 0) + if (puddleSolution.TotalVolume - transferAmount <= 0) { - puddleComponent.Owner.Delete(); + _entities.DeleteEntity(puddleComponent.Owner); // After cleaning the puddle, make a new puddle with solution from the mop as a "wet floor". Then evaporate it slowly. // we do this WITHOUT adding to the existing puddle. Otherwise we have might have water puddles with the vomit sprite. - var splitSolution = solutionSystem.SplitSolution(Owner.Uid, contents, transferAmount) + var splitSolution = solutionSystem.SplitSolution(Owner, contents, transferAmount) .SplitSolution(ResidueAmount); spillableSystem.SpillAt(splitSolution, eventArgs.ClickLocation, "PuddleSmear", combine: false); } else { // remove solution from the puddle - solutionSystem.SplitSolution(eventArgs.Target.Uid, puddleSolution, transferAmount); + solutionSystem.SplitSolution(target, puddleSolution, transferAmount); // and from the mop - solutionSystem.SplitSolution(Owner.Uid, contents, transferAmount); + solutionSystem.SplitSolution(Owner, contents, transferAmount); } SoundSystem.Play(Filter.Pvs(Owner), _pickupSound.GetSound(), Owner); diff --git a/Content.Server/Fluids/Components/PuddleComponent.cs b/Content.Server/Fluids/Components/PuddleComponent.cs index bd020bf788..da545e805e 100644 --- a/Content.Server/Fluids/Components/PuddleComponent.cs +++ b/Content.Server/Fluids/Components/PuddleComponent.cs @@ -47,7 +47,7 @@ namespace Content.Server.Fluids.Components public bool Overflown; [ViewVariables(VVAccess.ReadOnly)] - public FixedPoint2 CurrentVolume => EntitySystem.Get().CurrentVolume(Owner.Uid); + public FixedPoint2 CurrentVolume => EntitySystem.Get().CurrentVolume(Owner); [ViewVariables] [DataField("overflowVolume")] public FixedPoint2 OverflowVolume = DefaultOverflowVolume; diff --git a/Content.Server/Fluids/Components/SprayComponent.cs b/Content.Server/Fluids/Components/SprayComponent.cs index f2d5f96d53..e9c3433fed 100644 --- a/Content.Server/Fluids/Components/SprayComponent.cs +++ b/Content.Server/Fluids/Components/SprayComponent.cs @@ -31,6 +31,7 @@ namespace Content.Server.Fluids.Components public const float SprayDistance = 3f; public const string SolutionName = "spray"; + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [DataField("transferAmount")] @@ -78,14 +79,14 @@ namespace Content.Server.Fluids.Components public FixedPoint2 CurrentVolume { get { - EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution); + EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution); return solution?.CurrentVolume ?? FixedPoint2.Zero; } } async Task IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs) { - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if (!EntitySystem.Get().CanInteract(eventArgs.User)) return false; if (CurrentVolume <= 0) @@ -99,13 +100,13 @@ namespace Content.Server.Fluids.Components if(curTime < _cooldownEnd) return true; - var playerPos = eventArgs.User.Transform.Coordinates; - var entManager = Owner.EntityManager; + var playerPos = _entMan.GetComponent(eventArgs.User).Coordinates; + var entManager = _entMan; if (eventArgs.ClickLocation.GetGridId(entManager) != playerPos.GetGridId(entManager)) return true; - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var contents)) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var contents)) return true; var direction = (eventArgs.ClickLocation.Position - playerPos.Position).Normalized; @@ -124,35 +125,35 @@ namespace Content.Server.Fluids.Components var diffNorm = diffPos.Normalized; var diffLength = diffPos.Length; - var target = eventArgs.User.Transform.Coordinates.Offset((diffNorm + rotation.ToVec()).Normalized * diffLength + quarter); + var target = _entMan.GetComponent(eventArgs.User).Coordinates.Offset((diffNorm + rotation.ToVec()).Normalized * diffLength + quarter); - if (target.TryDistance(Owner.EntityManager, playerPos, out var distance) && distance > SprayDistance) - target = eventArgs.User.Transform.Coordinates.Offset(diffNorm * SprayDistance); + if (target.TryDistance(_entMan, playerPos, out var distance) && distance > SprayDistance) + target = _entMan.GetComponent(eventArgs.User).Coordinates.Offset(diffNorm * SprayDistance); - var solution = EntitySystem.Get().SplitSolution(Owner.Uid, contents, _transferAmount); + var solution = EntitySystem.Get().SplitSolution(Owner, contents, _transferAmount); if (solution.TotalVolume <= FixedPoint2.Zero) break; var vapor = entManager.SpawnEntity(_vaporPrototype, playerPos.Offset(distance < 1 ? quarter : threeQuarters)); - vapor.Transform.LocalRotation = rotation; + _entMan.GetComponent(vapor).LocalRotation = rotation; - if (vapor.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(vapor, out AppearanceComponent? appearance)) { appearance.SetData(VaporVisuals.Color, contents.Color.WithAlpha(1f)); appearance.SetData(VaporVisuals.State, true); } // Add the solution to the vapor and actually send the thing - var vaporComponent = vapor.GetComponent(); + var vaporComponent = _entMan.GetComponent(vapor); var vaporSystem = EntitySystem.Get(); vaporSystem.TryAddSolution(vaporComponent, solution); // impulse direction is defined in world-coordinates, not local coordinates - var impulseDirection = vapor.Transform.WorldRotation.ToVec(); + var impulseDirection = _entMan.GetComponent(vapor).WorldRotation.ToVec(); vaporSystem.Start(vaporComponent, impulseDirection, _sprayVelocity, target, _sprayAliveTime); - if (_impulse > 0f && eventArgs.User.TryGetComponent(out IPhysBody? body)) + if (_impulse > 0f && _entMan.TryGetComponent(eventArgs.User, out IPhysBody? body)) { body.ApplyLinearImpulse(-impulseDirection * _impulse); } @@ -163,7 +164,7 @@ namespace Content.Server.Fluids.Components _lastUseTime = curTime; _cooldownEnd = _lastUseTime + TimeSpan.FromSeconds(_cooldownTime); - if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown)) + if (_entMan.TryGetComponent(Owner, out ItemCooldownComponent? cooldown)) { cooldown.CooldownStart = _lastUseTime; cooldown.CooldownEnd = _cooldownEnd; diff --git a/Content.Server/Fluids/EntitySystems/EvaporationSystem.cs b/Content.Server/Fluids/EntitySystems/EvaporationSystem.cs index 0ca5a761bf..5bac9f8434 100644 --- a/Content.Server/Fluids/EntitySystems/EvaporationSystem.cs +++ b/Content.Server/Fluids/EntitySystems/EvaporationSystem.cs @@ -1,6 +1,5 @@ using Content.Server.Chemistry.EntitySystems; using Content.Server.Fluids.Components; -using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using JetBrains.Annotations; using Robust.Shared.GameObjects; @@ -20,7 +19,7 @@ namespace Content.Server.Fluids.EntitySystems var queueDelete = new RemQueue(); foreach (var evaporationComponent in EntityManager.EntityQuery()) { - var uid = evaporationComponent.Owner.Uid; + var uid = evaporationComponent.Owner; evaporationComponent.Accumulator += frameTime; if (!_solutionContainerSystem.TryGetSolution(uid, evaporationComponent.SolutionName, out var solution)) @@ -52,7 +51,7 @@ namespace Content.Server.Fluids.EntitySystems foreach (var evaporationComponent in queueDelete) { - EntityManager.RemoveComponent(evaporationComponent.Owner.Uid, evaporationComponent); + EntityManager.RemoveComponent(evaporationComponent.Owner, evaporationComponent); } } } diff --git a/Content.Server/Fluids/EntitySystems/PuddleSystem.cs b/Content.Server/Fluids/EntitySystems/PuddleSystem.cs index 011c17b031..8c24dbbd91 100644 --- a/Content.Server/Fluids/EntitySystems/PuddleSystem.cs +++ b/Content.Server/Fluids/EntitySystems/PuddleSystem.cs @@ -5,9 +5,7 @@ using System.Linq; using Content.Server.Chemistry.EntitySystems; using Content.Server.Construction.Components; using Content.Server.Fluids.Components; -using Content.Shared.Administration.Logs; using Content.Shared.Chemistry.Components; -using Content.Shared.Chemistry.Reagent; using Content.Shared.Database; using Content.Shared.Directions; using Content.Shared.Examine; @@ -59,7 +57,7 @@ namespace Content.Server.Fluids.EntitySystems private void UpdateVisuals(EntityUid uid, PuddleComponent puddleComponent) { - if (puddleComponent.Owner.Deleted || EmptyHolder(uid, puddleComponent) || + if (Deleted(puddleComponent.Owner) || EmptyHolder(uid, puddleComponent) || !EntityManager.TryGetComponent(uid, out var appearanceComponent)) { return; @@ -89,8 +87,6 @@ namespace Content.Server.Fluids.EntitySystems } } - - private void HandlePuddleExamined(EntityUid uid, PuddleComponent component, ExaminedEvent args) { if (EntityManager.TryGetComponent(uid, out var slippery) && slippery.Slippery) @@ -101,10 +97,10 @@ namespace Content.Server.Fluids.EntitySystems private void OnUnanchored(EntityUid uid, PuddleComponent puddle, UnanchoredEvent unanchoredEvent) { - if (!puddle.Owner.Transform.Anchored) + if (!EntityManager.GetComponent(puddle.Owner).Anchored) return; - puddle.Owner.QueueDelete(); + EntityManager.QueueDeleteEntity(puddle.Owner); } /// @@ -127,7 +123,7 @@ namespace Content.Server.Fluids.EntitySystems if (!Resolve(uid, ref puddleComponent)) return true; - return !_solutionContainerSystem.TryGetSolution(puddleComponent.Owner.Uid, puddleComponent.SolutionName, + return !_solutionContainerSystem.TryGetSolution(puddleComponent.Owner, puddleComponent.SolutionName, out var solution) || solution.Contents.Count == 0; } @@ -137,7 +133,7 @@ namespace Content.Server.Fluids.EntitySystems if (!Resolve(uid, ref puddleComponent)) return FixedPoint2.Zero; - return _solutionContainerSystem.TryGetSolution(puddleComponent.Owner.Uid, puddleComponent.SolutionName, + return _solutionContainerSystem.TryGetSolution(puddleComponent.Owner, puddleComponent.SolutionName, out var solution) ? solution.CurrentVolume : FixedPoint2.Zero; @@ -152,7 +148,7 @@ namespace Content.Server.Fluids.EntitySystems return false; if (solution.TotalVolume == 0 || - !_solutionContainerSystem.TryGetSolution(puddleComponent.Owner.Uid, puddleComponent.SolutionName, + !_solutionContainerSystem.TryGetSolution(puddleComponent.Owner, puddleComponent.SolutionName, out var puddleSolution)) { return false; @@ -160,13 +156,13 @@ namespace Content.Server.Fluids.EntitySystems var result = _solutionContainerSystem - .TryAddSolution(puddleComponent.Owner.Uid, puddleSolution, solution); + .TryAddSolution(puddleComponent.Owner, puddleSolution, solution); if (!result) { return false; } - RaiseLocalEvent(puddleComponent.Owner.Uid, new SolutionChangedEvent()); + RaiseLocalEvent(puddleComponent.Owner, new SolutionChangedEvent()); if (checkForOverflow) { @@ -221,12 +217,12 @@ namespace Content.Server.Fluids.EntitySystems { var adjacentPuddle = adjacent(); var quantity = FixedPoint2.Min(overflowSplit, adjacentPuddle.OverflowVolume); - var puddleSolution = _solutionContainerSystem.EnsureSolution(puddleComponent.Owner.Uid, + var puddleSolution = _solutionContainerSystem.EnsureSolution(puddleComponent.Owner, puddleComponent.SolutionName); - var spillAmount = _solutionContainerSystem.SplitSolution(puddleComponent.Owner.Uid, + var spillAmount = _solutionContainerSystem.SplitSolution(puddleComponent.Owner, puddleSolution, quantity); - TryAddSolution(adjacentPuddle.Owner.Uid, spillAmount, false, false); + TryAddSolution(adjacentPuddle.Owner, spillAmount, false, false); nextPuddles.Add(adjacentPuddle); } } @@ -268,11 +264,11 @@ namespace Content.Server.Fluids.EntitySystems puddle = default; // We're most likely in space, do nothing. - if (!puddleComponent.Owner.Transform.GridID.IsValid()) + if (!EntityManager.GetComponent(puddleComponent.Owner).GridID.IsValid()) return false; - var mapGrid = _mapManager.GetGrid(puddleComponent.Owner.Transform.GridID); - var coords = puddleComponent.Owner.Transform.Coordinates; + var mapGrid = _mapManager.GetGrid(EntityManager.GetComponent(puddleComponent.Owner).GridID); + var coords = EntityManager.GetComponent(puddleComponent.Owner).Coordinates; if (!coords.Offset(direction).TryGetTileRef(out var tile)) { @@ -285,7 +281,7 @@ namespace Content.Server.Fluids.EntitySystems return false; } - if (!puddleComponent.Owner.Transform.Anchored) + if (!EntityManager.GetComponent(puddleComponent.Owner).Anchored) return false; foreach (var entity in mapGrid.GetInDir(coords, direction)) @@ -309,9 +305,12 @@ namespace Content.Server.Fluids.EntitySystems } puddle ??= () => - puddleComponent.Owner.EntityManager.SpawnEntity(puddleComponent.Owner.Prototype?.ID, - mapGrid.DirectionToGrid(coords, direction)) - .GetComponent(); + { + var id = EntityManager.SpawnEntity( + EntityManager.GetComponent(puddleComponent.Owner).EntityPrototype?.ID, + mapGrid.DirectionToGrid(coords, direction)); + return EntityManager.GetComponent(id); + }; return true; } diff --git a/Content.Server/Fluids/EntitySystems/SpillableSystem.cs b/Content.Server/Fluids/EntitySystems/SpillableSystem.cs index b7d9e935af..1153a0f2d6 100644 --- a/Content.Server/Fluids/EntitySystems/SpillableSystem.cs +++ b/Content.Server/Fluids/EntitySystems/SpillableSystem.cs @@ -77,7 +77,7 @@ public class SpillableSystem : EntitySystem if (!args.CanAccess || !args.CanInteract) return; - if (!_solutionContainerSystem.TryGetDrainableSolution(args.Target.Uid, out var solution)) + if (!_solutionContainerSystem.TryGetDrainableSolution(args.Target, out var solution)) return; if (solution.DrainAvailable == FixedPoint2.Zero) @@ -88,9 +88,9 @@ public class SpillableSystem : EntitySystem // TODO VERB ICONS spill icon? pouring out a glass/beaker? verb.Act = () => { - var puddleSolution = _solutionContainerSystem.SplitSolution(args.Target.Uid, + var puddleSolution = _solutionContainerSystem.SplitSolution(args.Target, solution, solution.DrainAvailable); - SpillAt(puddleSolution, args.Target.Transform.Coordinates, "PuddleSmear"); + SpillAt(puddleSolution, Transform(args.Target).Coordinates, "PuddleSmear"); }; verb.Impact = LogImpact.Medium; // dangerous reagent reaction are logged separately. args.Verbs.Add(verb); @@ -123,7 +123,7 @@ public class SpillableSystem : EntitySystem { foreach (var entity in tileRef.GetEntitiesInTileFast(_gridTileLookupSystem)) { - if (entity.TryGetComponent(out PuddleComponent? p)) + if (EntityManager.TryGetComponent(entity, out PuddleComponent? p)) { puddle = p; return true; @@ -166,9 +166,9 @@ public class SpillableSystem : EntitySystem var spillEntities = _entityLookup.GetEntitiesIntersecting(mapGrid.ParentMapId, spillGridCoords.Position).ToArray(); foreach (var spillEntity in spillEntities) { - if (_solutionContainerSystem.TryGetRefillableSolution(spillEntity.Uid, out var solutionContainerComponent)) + if (_solutionContainerSystem.TryGetRefillableSolution(spillEntity, out var solutionContainerComponent)) { - _solutionContainerSystem.Refill(spillEntity.Uid, solutionContainerComponent, + _solutionContainerSystem.Refill(spillEntity, solutionContainerComponent, solution.SplitSolution(FixedPoint2.Min( solutionContainerComponent.AvailableVolume, solutionContainerComponent.MaxSpillRefill)) @@ -180,21 +180,21 @@ public class SpillableSystem : EntitySystem { foreach (var spillEntity in spillEntities) { - if (!spillEntity.TryGetComponent(out PuddleComponent? puddleComponent)) continue; + if (!EntityManager.TryGetComponent(spillEntity, out PuddleComponent? puddleComponent)) continue; - if (!overflow && _puddleSystem.WouldOverflow(puddleComponent.Owner.Uid, solution, puddleComponent)) + if (!overflow && _puddleSystem.WouldOverflow(puddleComponent.Owner, solution, puddleComponent)) return null; - if (!_puddleSystem.TryAddSolution(puddleComponent.Owner.Uid, solution, sound)) continue; + if (!_puddleSystem.TryAddSolution(puddleComponent.Owner, solution, sound)) continue; return puddleComponent; } } var puddleEnt = EntityManager.SpawnEntity(prototype, spillGridCoords); - var newPuddleComponent = puddleEnt.GetComponent(); + var newPuddleComponent = EntityManager.GetComponent(puddleEnt); - _puddleSystem.TryAddSolution(newPuddleComponent.Owner.Uid, solution, sound); + _puddleSystem.TryAddSolution(newPuddleComponent.Owner, solution, sound); return newPuddleComponent; } diff --git a/Content.Server/GameTicking/Commands/MappingCommand.cs b/Content.Server/GameTicking/Commands/MappingCommand.cs index 4909402ea3..0edea9a995 100644 --- a/Content.Server/GameTicking/Commands/MappingCommand.cs +++ b/Content.Server/GameTicking/Commands/MappingCommand.cs @@ -6,8 +6,10 @@ using Content.Server.Administration; using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; +using Robust.Shared.Prototypes; using Robust.Shared.Timing; using Robust.Shared.Utility; @@ -16,6 +18,8 @@ namespace Content.Server.GameTicking.Commands [AdminCommand(AdminFlags.Server | AdminFlags.Mapping)] class MappingCommand : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "mapping"; public string Description => "Creates and teleports you to a new uninitialized map for mapping."; public string Help => $"Usage: {Command} / {Command} "; @@ -74,8 +78,11 @@ namespace Content.Server.GameTicking.Commands shell.ExecuteCommand($"addmap {mapId} false"); shell.ExecuteCommand($"loadbp {mapId} \"{CommandParsing.Escape(mapName)}\" true"); - if (player.AttachedEntity?.Prototype?.ID != "AdminObserver") + if (player.AttachedEntity is {Valid: true} playerEntity && + _entities.GetComponent(playerEntity).EntityPrototype?.ID != "AdminObserver") + { shell.ExecuteCommand("aghost"); + } shell.ExecuteCommand($"tp 0 0 {mapId}"); shell.RemoteExecuteCommand("showmarkers"); diff --git a/Content.Server/GameTicking/GameTicker.RoundFlow.cs b/Content.Server/GameTicking/GameTicker.RoundFlow.cs index 87d1f657c5..1cd48d0180 100644 --- a/Content.Server/GameTicking/GameTicker.RoundFlow.cs +++ b/Content.Server/GameTicking/GameTicker.RoundFlow.cs @@ -3,11 +3,9 @@ using System.Collections.Generic; using System.Linq; using Content.Server.Database; using Content.Server.GameTicking.Events; -using Content.Server.Players; -using Content.Server.Mind; using Content.Server.Ghost; -using Content.Server.Roles; -using Content.Server.Station; +using Content.Server.Mind; +using Content.Server.Players; using Content.Shared.CCVar; using Content.Shared.Coordinates; using Content.Shared.GameTicking; @@ -274,13 +272,21 @@ namespace Content.Server.GameTicking } // Finish var antag = mind.AllRoles.Any(role => role.Antagonist); + + var playerIcName = string.Empty; + + if (mind.CharacterName != null) + playerIcName = mind.CharacterName; + else if (mind.CurrentEntity != null) + playerIcName = EntityManager.GetComponent(mind.CurrentEntity.Value).EntityName; + var playerEndRoundInfo = new RoundEndMessageEvent.RoundEndPlayerInfo() { // Note that contentPlayerData?.Name sticks around after the player is disconnected. // This is as opposed to ply?.Name which doesn't. PlayerOOCName = contentPlayerData?.Name ?? "(IMPOSSIBLE: REGISTERED MIND WITH NO OWNER)", // Character name takes precedence over current entity name - PlayerICName = mind.CharacterName ?? mind.CurrentEntity?.Name, + PlayerICName = playerIcName, Role = antag ? mind.AllRoles.First(role => role.Antagonist).Name : mind.AllRoles.FirstOrDefault()?.Name ?? Loc.GetString("game-ticker-unknown-role"), @@ -363,7 +369,7 @@ namespace Content.Server.GameTicking { // TODO: Maybe something less naive here? // FIXME: Actually, definitely. - entity.Delete(); + EntityManager.DeleteEntity(entity); } _mapManager.Restart(); diff --git a/Content.Server/GameTicking/GameTicker.Spawning.cs b/Content.Server/GameTicking/GameTicker.Spawning.cs index f2e4ac19e3..07b57abc42 100644 --- a/Content.Server/GameTicking/GameTicker.Spawning.cs +++ b/Content.Server/GameTicking/GameTicker.Spawning.cs @@ -119,11 +119,11 @@ namespace Content.Server.GameTicking } var mob = SpawnPlayerMob(job, character, station, lateJoin); - newMind.TransferTo(mob.Uid); + newMind.TransferTo(mob); if (player.UserId == new Guid("{e887eb93-f503-4b65-95b6-2f282c014192}")) { - mob.AddComponent(); + EntityManager.AddComponent(mob); } AddManifestEntry(character.Name, jobId); @@ -190,17 +190,17 @@ namespace Content.Server.GameTicking newMind.AddRole(new ObserverRole(newMind)); var mob = SpawnObserverMob(); - mob.Name = name; - var ghost = mob.GetComponent(); + EntityManager.GetComponent(mob).EntityName = name; + var ghost = EntityManager.GetComponent(mob); EntitySystem.Get().SetCanReturnToBody(ghost, false); - newMind.TransferTo(mob.Uid); + newMind.TransferTo(mob); _playersInLobby[player] = LobbyPlayerStatus.Observer; RaiseNetworkEvent(GetStatusSingle(player, LobbyPlayerStatus.Observer)); } #region Mob Spawning Helpers - private IEntity SpawnPlayerMob(Job job, HumanoidCharacterProfile? profile, StationId station, bool lateJoin = true) + private EntityUid SpawnPlayerMob(Job job, HumanoidCharacterProfile? profile, StationId station, bool lateJoin = true) { var coordinates = lateJoin ? GetLateJoinSpawnPoint(station) : GetJobSpawnPoint(job.Prototype.ID, station); var entity = EntityManager.SpawnEntity(PlayerPrototypeName, coordinates); @@ -213,14 +213,14 @@ namespace Content.Server.GameTicking if (profile != null) { - EntitySystem.Get().UpdateFromProfile(entity.Uid, profile); - entity.Name = profile.Name; + _humanoidAppearanceSystem.UpdateFromProfile(entity, profile); + EntityManager.GetComponent(entity).EntityName = profile.Name; } return entity; } - private IEntity SpawnObserverMob() + private EntityUid SpawnObserverMob() { var coordinates = GetObserverSpawnPoint(); return EntityManager.SpawnEntity(ObserverPrototypeName, coordinates); @@ -228,35 +228,35 @@ namespace Content.Server.GameTicking #endregion #region Equip Helpers - public void EquipStartingGear(IEntity entity, StartingGearPrototype startingGear, HumanoidCharacterProfile? profile) + public void EquipStartingGear(EntityUid entity, StartingGearPrototype startingGear, HumanoidCharacterProfile? profile) { - if (entity.TryGetComponent(out InventoryComponent? inventory)) + if (EntityManager.TryGetComponent(entity, out InventoryComponent? inventory)) { foreach (var slot in EquipmentSlotDefines.AllSlots) { var equipmentStr = startingGear.GetGear(slot, profile); if (!string.IsNullOrEmpty(equipmentStr)) { - var equipmentEntity = EntityManager.SpawnEntity(equipmentStr, entity.Transform.Coordinates); - inventory.Equip(slot, equipmentEntity.GetComponent()); + var equipmentEntity = EntityManager.SpawnEntity(equipmentStr, EntityManager.GetComponent(entity).Coordinates); + inventory.Equip(slot, EntityManager.GetComponent(equipmentEntity)); } } } - if (entity.TryGetComponent(out HandsComponent? handsComponent)) + if (EntityManager.TryGetComponent(entity, out HandsComponent? handsComponent)) { var inhand = startingGear.Inhand; foreach (var (hand, prototype) in inhand) { - var inhandEntity = EntityManager.SpawnEntity(prototype, entity.Transform.Coordinates); + var inhandEntity = EntityManager.SpawnEntity(prototype, EntityManager.GetComponent(entity).Coordinates); handsComponent.TryPickupEntity(hand, inhandEntity, checkActionBlocker: false); } } } - public void EquipIdCard(IEntity entity, string characterName, JobPrototype jobPrototype) + public void EquipIdCard(EntityUid entity, string characterName, JobPrototype jobPrototype) { - if (!entity.TryGetComponent(out InventoryComponent? inventory)) + if (!EntityManager.TryGetComponent(entity, out InventoryComponent? inventory)) return; if (!inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent? item)) @@ -266,18 +266,17 @@ namespace Content.Server.GameTicking var itemEntity = item.Owner; - if (!itemEntity.TryGetComponent(out PDAComponent? pdaComponent) || pdaComponent.ContainedID == null) + if (!EntityManager.TryGetComponent(itemEntity, out PDAComponent? pdaComponent) || pdaComponent.ContainedID == null) return; var card = pdaComponent.ContainedID; - _cardSystem.TryChangeFullName(card.Owner.Uid, characterName, card); - _cardSystem.TryChangeJobTitle(card.Owner.Uid, jobPrototype.Name, card); + _cardSystem.TryChangeFullName(card.Owner, characterName, card); + _cardSystem.TryChangeJobTitle(card.Owner, jobPrototype.Name, card); - var access = card.Owner.GetComponent(); + var access = EntityManager.GetComponent(card.Owner); var accessTags = access.Tags; accessTags.UnionWith(jobPrototype.Access); - EntityManager.EntitySysManager.GetEntitySystem() - .SetOwner(pdaComponent, characterName); + _pdaSystem.SetOwner(pdaComponent, characterName); } #endregion diff --git a/Content.Server/GameTicking/GameTicker.cs b/Content.Server/GameTicking/GameTicker.cs index 91c0d74492..25fecfc3d5 100644 --- a/Content.Server/GameTicking/GameTicker.cs +++ b/Content.Server/GameTicking/GameTicker.cs @@ -1,6 +1,8 @@ using Content.Server.Administration.Logs; +using Content.Server.CharacterAppearance.Systems; using Content.Server.Chat.Managers; using Content.Server.Maps; +using Content.Server.PDA; using Content.Server.Preferences.Managers; using Content.Server.Roles; using Content.Server.Station; @@ -91,5 +93,7 @@ namespace Content.Server.GameTicking [Dependency] private readonly IGameMapManager _gameMapManager = default!; [Dependency] private readonly StationSystem _stationSystem = default!; [Dependency] private readonly AdminLogSystem _adminLogSystem = default!; + [Dependency] private readonly HumanoidAppearanceSystem _humanoidAppearanceSystem = default!; + [Dependency] private readonly PDASystem _pdaSystem = default!; } } diff --git a/Content.Server/GameTicking/Presets/GamePreset.cs b/Content.Server/GameTicking/Presets/GamePreset.cs index 0f5e19d316..f9cb77de42 100644 --- a/Content.Server/GameTicking/Presets/GamePreset.cs +++ b/Content.Server/GameTicking/Presets/GamePreset.cs @@ -19,6 +19,8 @@ namespace Content.Server.GameTicking.Presets /// public abstract class GamePreset { + [Dependency] private readonly IEntityManager _entities = default!; + public abstract bool Start(IReadOnlyList readyPlayers, bool force = false); public virtual string ModeTitle => "Sandbox"; public virtual string Description => "Secret!"; @@ -30,7 +32,7 @@ namespace Content.Server.GameTicking.Presets /// /// Called when a player is spawned in (this includes, but is not limited to, before Start) /// - public virtual void OnSpawnPlayerCompleted(IPlayerSession session, IEntity mob, bool lateJoin) { } + public virtual void OnSpawnPlayerCompleted(IPlayerSession session, EntityUid mob, bool lateJoin) { } /// /// Called when a player attempts to ghost. @@ -39,15 +41,18 @@ namespace Content.Server.GameTicking.Presets { var playerEntity = mind.OwnedEntity; - if (playerEntity != null && playerEntity.HasComponent()) + var entities = IoCManager.Resolve(); + if (entities.HasComponent(playerEntity)) return false; - if (mind.VisitingEntity != null) + if (mind.VisitingEntity != default) { mind.UnVisit(); } - var position = playerEntity?.Transform.Coordinates ?? EntitySystem.Get().GetObserverSpawnPoint(); + var position = playerEntity is {Valid: true} + ? _entities.GetComponent(playerEntity.Value).Coordinates + : EntitySystem.Get().GetObserverSpawnPoint(); // Ok, so, this is the master place for the logic for if ghosting is "too cheaty" to allow returning. // There's no reason at this time to move it to any other place, especially given that the 'side effects required' situations would also have to be moved. // + If CharacterDeadPhysically applies, we're physically dead. Therefore, ghosting OK, and we can return (this is critical for gibbing) @@ -58,7 +63,7 @@ namespace Content.Server.GameTicking.Presets // (If the mob survives, that's a bug. Ghosting is kept regardless.) var canReturn = canReturnGlobal && mind.CharacterDeadPhysically; - if (playerEntity != null && canReturnGlobal && playerEntity.TryGetComponent(out MobStateComponent? mobState)) + if (canReturnGlobal && entities.TryGetComponent(playerEntity, out MobStateComponent? mobState)) { if (mobState.IsCritical()) { @@ -67,22 +72,21 @@ namespace Content.Server.GameTicking.Presets //todo: what if they dont breathe lol //cry deeply DamageSpecifier damage = new(IoCManager.Resolve().Index("Asphyxiation"), 200); - EntitySystem.Get().TryChangeDamage(playerEntity.Uid, damage, true); + EntitySystem.Get().TryChangeDamage(playerEntity, damage, true); } } - var entityManager = IoCManager.Resolve(); - var ghost = entityManager.SpawnEntity("MobObserver", position.ToMap(entityManager)); + var ghost = entities.SpawnEntity("MobObserver", position.ToMap(entities)); // Try setting the ghost entity name to either the character name or the player name. // If all else fails, it'll default to the default entity prototype name, "observer". // However, that should rarely happen. if(!string.IsNullOrWhiteSpace(mind.CharacterName)) - ghost.Name = mind.CharacterName; + entities.GetComponent(ghost).EntityName = mind.CharacterName; else if (!string.IsNullOrWhiteSpace(mind.Session?.Name)) - ghost.Name = mind.Session.Name; + entities.GetComponent(ghost).EntityName = mind.Session.Name; - var ghostComponent = ghost.GetComponent(); + var ghostComponent = entities.GetComponent(ghost); if (mind.TimeOfDeath.HasValue) { @@ -94,7 +98,7 @@ namespace Content.Server.GameTicking.Presets if (canReturn) mind.Visit(ghost); else - mind.TransferTo(ghost.Uid); + mind.TransferTo(ghost); return true; } diff --git a/Content.Server/GameTicking/Presets/PresetSuspicion.cs b/Content.Server/GameTicking/Presets/PresetSuspicion.cs index 59f3e7d1db..d68aa75611 100644 --- a/Content.Server/GameTicking/Presets/PresetSuspicion.cs +++ b/Content.Server/GameTicking/Presets/PresetSuspicion.cs @@ -1,16 +1,12 @@ using System.Collections.Generic; using Content.Server.Chat.Managers; using Content.Server.GameTicking.Rules; -using Content.Server.Inventory.Components; -using Content.Server.Items; using Content.Server.Players; using Content.Server.Suspicion; using Content.Server.Suspicion.Roles; using Content.Server.Traitor.Uplink; using Content.Server.Traitor.Uplink.Account; -using Content.Server.Traitor.Uplink.Components; using Content.Shared.CCVar; -using Content.Shared.Inventory; using Content.Shared.Roles; using Content.Shared.Traitor.Uplink; using Robust.Server.Player; @@ -70,13 +66,13 @@ namespace Content.Server.GameTicking.Presets foreach (var player in list) { - if (!ReadyProfiles.ContainsKey(player.UserId)) + if (!ReadyProfiles.ContainsKey(player.UserId) || player.AttachedEntity is not {} attached) { continue; } prefList.Add(player); - player.AttachedEntity?.EnsureComponent(); + attached.EnsureComponent(); } var numTraitors = MathHelper.Clamp(readyPlayers.Count / PlayersPerTraitor, @@ -115,13 +111,13 @@ namespace Content.Server.GameTicking.Presets // creadth: we need to create uplink for the antag. // PDA should be in place already, so we just need to // initiate uplink account. - var uplinkAccount = new UplinkAccount(TraitorStartingBalance, mind.OwnedEntity!.Uid); + var uplinkAccount = new UplinkAccount(TraitorStartingBalance, mind.OwnedEntity!); var accounts = EntityManager.EntitySysManager.GetEntitySystem(); accounts.AddNewAccount(uplinkAccount); // try to place uplink if (!EntityManager.EntitySysManager.GetEntitySystem() - .AddUplink(mind.OwnedEntity, uplinkAccount)) + .AddUplink(mind.OwnedEntity!.Value, uplinkAccount)) continue; } diff --git a/Content.Server/GameTicking/Presets/PresetTraitor.cs b/Content.Server/GameTicking/Presets/PresetTraitor.cs index e89f15cff1..fb85f34af7 100644 --- a/Content.Server/GameTicking/Presets/PresetTraitor.cs +++ b/Content.Server/GameTicking/Presets/PresetTraitor.cs @@ -3,19 +3,14 @@ using System.Collections.Generic; using System.Linq; using Content.Server.Chat.Managers; using Content.Server.GameTicking.Rules; -using Content.Server.Inventory.Components; -using Content.Server.Items; using Content.Server.Objectives.Interfaces; -using Content.Server.PDA; using Content.Server.Players; using Content.Server.Roles; using Content.Server.Traitor; using Content.Server.Traitor.Uplink; using Content.Server.Traitor.Uplink.Account; -using Content.Server.Traitor.Uplink.Components; using Content.Shared.CCVar; using Content.Shared.Dataset; -using Content.Shared.Inventory; using Content.Shared.Traitor.Uplink; using Robust.Server.Player; using Robust.Shared.Configuration; @@ -126,12 +121,12 @@ namespace Content.Server.GameTicking.Presets // initiate uplink account. DebugTools.AssertNotNull(mind.OwnedEntity); - var uplinkAccount = new UplinkAccount(StartingBalance, mind.OwnedEntity!.Uid); + var uplinkAccount = new UplinkAccount(StartingBalance, mind.OwnedEntity!); var accounts = EntityManager.EntitySysManager.GetEntitySystem(); accounts.AddNewAccount(uplinkAccount); if (!EntityManager.EntitySysManager.GetEntitySystem() - .AddUplink(mind.OwnedEntity, uplinkAccount)) + .AddUplink(mind.OwnedEntity!.Value, uplinkAccount)) continue; var traitorRole = new TraitorRole(mind); diff --git a/Content.Server/GameTicking/Presets/PresetTraitorDeathMatch.cs b/Content.Server/GameTicking/Presets/PresetTraitorDeathMatch.cs index 14a784ab6a..8e240b9bc8 100644 --- a/Content.Server/GameTicking/Presets/PresetTraitorDeathMatch.cs +++ b/Content.Server/GameTicking/Presets/PresetTraitorDeathMatch.cs @@ -63,7 +63,7 @@ namespace Content.Server.GameTicking.Presets return true; } - public override void OnSpawnPlayerCompleted(IPlayerSession session, IEntity mob, bool lateJoin) + public override void OnSpawnPlayerCompleted(IPlayerSession session, EntityUid mob, bool lateJoin) { var startingBalance = _cfg.GetCVar(CCVars.TraitorDeathMatchStartingBalance); @@ -80,50 +80,50 @@ namespace Content.Server.GameTicking.Presets // Delete anything that may contain "dangerous" role-specific items. // (This includes the PDA, as everybody gets the captain PDA in this mode for true-all-access reasons.) - if (mind.OwnedEntity != null && mind.OwnedEntity.TryGetComponent(out InventoryComponent? inventory)) + if (mind.OwnedEntity is {Valid: true} owned && _entityManager.TryGetComponent(owned, out InventoryComponent? inventory)) { var victimSlots = new[] {EquipmentSlotDefines.Slots.IDCARD, EquipmentSlotDefines.Slots.BELT, EquipmentSlotDefines.Slots.BACKPACK}; foreach (var slot in victimSlots) { if (inventory.TryGetSlotItem(slot, out ItemComponent? vItem)) - vItem.Owner.Delete(); + _entityManager.DeleteEntity(vItem.Owner); } // Replace their items: // pda - var newPDA = _entityManager.SpawnEntity(PDAPrototypeName, mind.OwnedEntity.Transform.Coordinates); - inventory.Equip(EquipmentSlotDefines.Slots.IDCARD, newPDA.GetComponent()); + var newPDA = _entityManager.SpawnEntity(PDAPrototypeName, _entityManager.GetComponent(owned).Coordinates); + inventory.Equip(EquipmentSlotDefines.Slots.IDCARD, _entityManager.GetComponent(newPDA)); // belt - var newTmp = _entityManager.SpawnEntity(BeltPrototypeName, mind.OwnedEntity.Transform.Coordinates); - inventory.Equip(EquipmentSlotDefines.Slots.BELT, newTmp.GetComponent()); + var newTmp = _entityManager.SpawnEntity(BeltPrototypeName, _entityManager.GetComponent(owned).Coordinates); + inventory.Equip(EquipmentSlotDefines.Slots.BELT, _entityManager.GetComponent(newTmp)); // backpack - newTmp = _entityManager.SpawnEntity(BackpackPrototypeName, mind.OwnedEntity.Transform.Coordinates); - inventory.Equip(EquipmentSlotDefines.Slots.BACKPACK, newTmp.GetComponent()); + newTmp = _entityManager.SpawnEntity(BackpackPrototypeName, _entityManager.GetComponent(owned).Coordinates); + inventory.Equip(EquipmentSlotDefines.Slots.BACKPACK, _entityManager.GetComponent(newTmp)); // Like normal traitors, they need access to a traitor account. - var uplinkAccount = new UplinkAccount(startingBalance, mind.OwnedEntity.Uid); + var uplinkAccount = new UplinkAccount(startingBalance, owned); var accounts = _entityManager.EntitySysManager.GetEntitySystem(); accounts.AddNewAccount(uplinkAccount); _entityManager.EntitySysManager.GetEntitySystem() - .AddUplink(mind.OwnedEntity, uplinkAccount, newPDA); + .AddUplink(owned, uplinkAccount, newPDA); - _allOriginalNames[uplinkAccount] = mind.OwnedEntity.Name; + _allOriginalNames[uplinkAccount] = _entityManager.GetComponent(owned).EntityName; // The PDA needs to be marked with the correct owner. - var pda = newPDA.GetComponent(); + var pda = _entityManager.GetComponent(newPDA); _entityManager.EntitySysManager.GetEntitySystem() - .SetOwner(pda, mind.OwnedEntity.Name); - newPDA.AddComponent().UserId = mind.UserId; + .SetOwner(pda, _entityManager.GetComponent(owned).EntityName); + _entityManager.AddComponent(newPDA).UserId = mind.UserId; } // Finally, it would be preferrable if they spawned as far away from other players as reasonably possible. if (mind.OwnedEntity != null && FindAnyIsolatedSpawnLocation(mind, out var bestTarget)) { - mind.OwnedEntity.Transform.Coordinates = bestTarget; + _entityManager.GetComponent(mind.OwnedEntity.Value).Coordinates = bestTarget; } else { @@ -151,7 +151,7 @@ namespace Content.Server.GameTicking.Presets var avoidMeEntity = avoidMeMind.OwnedEntity; if (avoidMeEntity == null) continue; - if (avoidMeEntity.TryGetComponent(out MobStateComponent? mobState)) + if (_entityManager.TryGetComponent(avoidMeEntity.Value, out MobStateComponent? mobState)) { // Does have mob state component; if critical or dead, they don't really matter for spawn checks if (mobState.IsCritical() || mobState.IsDead()) @@ -162,7 +162,7 @@ namespace Content.Server.GameTicking.Presets // Doesn't have mob state component. Assume something interesting is going on and don't count this as someone to avoid. continue; } - existingPlayerPoints.Add(avoidMeEntity.Transform.Coordinates); + existingPlayerPoints.Add(_entityManager.GetComponent(avoidMeEntity.Value).Coordinates); } // Iterate over each possible spawn point, comparing to the existing player points. @@ -176,18 +176,18 @@ namespace Content.Server.GameTicking.Presets var atmosphereSystem = EntitySystem.Get(); foreach (var entity in ents) { - if (!atmosphereSystem.IsTileMixtureProbablySafe(entity.Transform.Coordinates)) + if (!atmosphereSystem.IsTileMixtureProbablySafe(_entityManager.GetComponent(entity).Coordinates)) continue; var distanceFromNearest = float.PositiveInfinity; foreach (var existing in existingPlayerPoints) { - if (entity.Transform.Coordinates.TryDistance(_entityManager, existing, out var dist)) + if (_entityManager.GetComponent(entity).Coordinates.TryDistance(_entityManager, existing, out var dist)) distanceFromNearest = Math.Min(distanceFromNearest, dist); } if (bestTargetDistanceFromNearest < distanceFromNearest) { - bestTarget = entity.Transform.Coordinates; + bestTarget = _entityManager.GetComponent(entity).Coordinates; bestTargetDistanceFromNearest = distanceFromNearest; foundATarget = true; } @@ -197,18 +197,17 @@ namespace Content.Server.GameTicking.Presets public override bool OnGhostAttempt(Mind.Mind mind, bool canReturnGlobal) { - var entity = mind.OwnedEntity; - if ((entity != null) && (entity.TryGetComponent(out MobStateComponent? mobState))) + if (mind.OwnedEntity is {Valid: true} entity && _entityManager.TryGetComponent(entity, out MobStateComponent? mobState)) { if (mobState.IsCritical()) { // TODO BODY SYSTEM KILL var damage = new DamageSpecifier(_prototypeManager.Index("Asphyxiation"), 100); - EntitySystem.Get().TryChangeDamage(entity.Uid, damage, true); + EntitySystem.Get().TryChangeDamage(entity, damage, true); } else if (!mobState.IsDead()) { - if (entity.HasComponent()) + if (_entityManager.HasComponent(entity)) { return false; } diff --git a/Content.Server/GameTicking/Rules/RuleDeathMatch.cs b/Content.Server/GameTicking/Rules/RuleDeathMatch.cs index 003cb8d4fb..0a51de949c 100644 --- a/Content.Server/GameTicking/Rules/RuleDeathMatch.cs +++ b/Content.Server/GameTicking/Rules/RuleDeathMatch.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Threading; using Content.Server.Chat.Managers; using Content.Shared.CCVar; @@ -62,9 +60,8 @@ namespace Content.Server.GameTicking.Rules IPlayerSession? winner = null; foreach (var playerSession in _playerManager.ServerSessions) { - var playerEntity = playerSession.AttachedEntity; - if (playerEntity == null - || !playerEntity.TryGetComponent(out MobStateComponent? state)) + if (playerSession.AttachedEntity is not {Valid: true} playerEntity + || !_entityManager.TryGetComponent(playerEntity, out MobStateComponent? state)) { continue; } diff --git a/Content.Server/GameTicking/Rules/RuleSuspicion.cs b/Content.Server/GameTicking/Rules/RuleSuspicion.cs index d5634d7ff2..cb6f34735a 100644 --- a/Content.Server/GameTicking/Rules/RuleSuspicion.cs +++ b/Content.Server/GameTicking/Rules/RuleSuspicion.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Threading; using Content.Server.Chat.Managers; using Content.Server.Doors; @@ -35,6 +33,7 @@ namespace Content.Server.GameTicking.Rules [Dependency] private readonly IChatManager _chatManager = default!; [Dependency] private readonly IConfigurationManager _cfg = default!; [Dependency] private readonly IGameTiming _timing = default!; + [Dependency] private readonly IEntityManager _entities = default!; [DataField("addedSound")] private SoundSpecifier _addedSound = new SoundPathSpecifier("/Audio/Misc/tatoralert.ogg"); @@ -90,9 +89,9 @@ namespace Content.Server.GameTicking.Rules foreach (var playerSession in _playerManager.ServerSessions) { - if (playerSession.AttachedEntity == null - || !playerSession.AttachedEntity.TryGetComponent(out MobStateComponent? mobState) - || !playerSession.AttachedEntity.HasComponent()) + if (playerSession.AttachedEntity is not {Valid: true} playerEntity + || !_entities.TryGetComponent(playerEntity, out MobStateComponent? mobState) + || !_entities.HasComponent(playerEntity)) { continue; } diff --git a/Content.Server/Ghost/Components/GhostRadioComponent.cs b/Content.Server/Ghost/Components/GhostRadioComponent.cs index 7ce0d58b50..382424b138 100644 --- a/Content.Server/Ghost/Components/GhostRadioComponent.cs +++ b/Content.Server/Ghost/Components/GhostRadioComponent.cs @@ -1,8 +1,7 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Content.Server.Radio.Components; using Content.Shared.Chat; using Robust.Server.GameObjects; -using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; @@ -16,6 +15,7 @@ namespace Content.Server.Ghost.Components public class GhostRadioComponent : Component, IRadio { [Dependency] private readonly IServerNetManager _netManager = default!; + [Dependency] private readonly IEntityManager _entMan = default!; public override string Name => "GhostRadio"; @@ -24,9 +24,9 @@ namespace Content.Server.Ghost.Components public IReadOnlyList Channels => _channels; - public void Receive(string message, int channel, IEntity speaker) + public void Receive(string message, int channel, EntityUid speaker) { - if (!Owner.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(Owner, out ActorComponent? actor)) return; var playerChannel = actor.PlayerSession.ConnectedClient; @@ -36,10 +36,10 @@ namespace Content.Server.Ghost.Components msg.Channel = ChatChannel.Radio; msg.Message = message; //Square brackets are added here to avoid issues with escaping - msg.MessageWrap = Loc.GetString("chat-radio-message-wrap", ("channel", $"\\[{channel}\\]"), ("name", speaker.Name)); + msg.MessageWrap = Loc.GetString("chat-radio-message-wrap", ("channel", $"\\[{channel}\\]"), ("name", Name: _entMan.GetComponent(speaker).EntityName)); _netManager.ServerSendMessage(msg, playerChannel); } - public void Broadcast(string message, IEntity speaker) { } + public void Broadcast(string message, EntityUid speaker) { } } } diff --git a/Content.Server/Ghost/GhostSystem.cs b/Content.Server/Ghost/GhostSystem.cs index 1972d5637e..8c959bc39a 100644 --- a/Content.Server/Ghost/GhostSystem.cs +++ b/Content.Server/Ghost/GhostSystem.cs @@ -64,7 +64,7 @@ namespace Content.Server.Ghost visibility.Layer |= (int) VisibilityFlags.Ghost; visibility.Layer &= ~(int) VisibilityFlags.Normal; - if (component.Owner.TryGetComponent(out EyeComponent? eye)) + if (EntityManager.TryGetComponent(component.Owner, out EyeComponent? eye)) { eye.VisibilityMask |= (uint) VisibilityFlags.Ghost; } @@ -75,17 +75,17 @@ namespace Content.Server.Ghost private void OnGhostShutdown(EntityUid uid, GhostComponent component, ComponentShutdown args) { // Perf: If the entity is deleting itself, no reason to change these back. - if (component.Owner.LifeStage < EntityLifeStage.Terminating) + if (!Terminating(uid)) { // Entity can't be seen by ghosts anymore. - if (component.Owner.TryGetComponent(out VisibilityComponent? visibility)) + if (EntityManager.TryGetComponent(component.Owner, out VisibilityComponent? visibility)) { visibility.Layer &= ~(int) VisibilityFlags.Ghost; visibility.Layer |= (int) VisibilityFlags.Normal; } // Entity can't see ghosts anymore. - if (component.Owner.TryGetComponent(out EyeComponent? eye)) + if (EntityManager.TryGetComponent(component.Owner, out EyeComponent? eye)) { eye.VisibilityMask &= ~(uint) VisibilityFlags.Ghost; } @@ -114,27 +114,23 @@ namespace Content.Server.Ghost private void OnGhostWarpsRequest(GhostWarpsRequestEvent msg, EntitySessionEventArgs args) { - var entity = args.SenderSession.AttachedEntity; - - if (entity == null || - !entity.HasComponent()) + if (args.SenderSession.AttachedEntity is not {Valid: true} entity || + !EntityManager.HasComponent(entity)) { Logger.Warning($"User {args.SenderSession.Name} sent a {nameof(GhostWarpsRequestEvent)} without being a ghost."); return; } - var response = new GhostWarpsResponseEvent(GetLocationNames().ToList(), GetPlayerWarps(entity.Uid)); + var response = new GhostWarpsResponseEvent(GetLocationNames().ToList(), GetPlayerWarps(entity)); RaiseNetworkEvent(response, args.SenderSession.ConnectedClient); } private void OnGhostReturnToBodyRequest(GhostReturnToBodyRequest msg, EntitySessionEventArgs args) { - var entity = args.SenderSession.AttachedEntity; - - if (entity == null || - !entity.TryGetComponent(out GhostComponent? ghost) || + if (args.SenderSession.AttachedEntity is not {Valid: true} attached || + !EntityManager.TryGetComponent(attached, out GhostComponent? ghost) || !ghost.CanReturnToBody || - !entity.TryGetComponent(out ActorComponent? actor)) + !EntityManager.TryGetComponent(attached, out ActorComponent? actor)) { Logger.Warning($"User {args.SenderSession.Name} sent an invalid {nameof(GhostReturnToBodyRequest)}"); return; @@ -145,8 +141,8 @@ namespace Content.Server.Ghost private void OnGhostWarpToLocationRequest(GhostWarpToLocationRequestEvent msg, EntitySessionEventArgs args) { - if (args.SenderSession.AttachedEntity == null || - !args.SenderSession.AttachedEntity.TryGetComponent(out GhostComponent? ghost)) + if (args.SenderSession.AttachedEntity is not {Valid: true} attached || + !EntityManager.TryGetComponent(attached, out GhostComponent? ghost)) { Logger.Warning($"User {args.SenderSession.Name} tried to warp to {msg.Name} without being a ghost."); return; @@ -154,7 +150,7 @@ namespace Content.Server.Ghost if (FindLocation(msg.Name) is { } warp) { - ghost.Owner.Transform.Coordinates = warp.Owner.Transform.Coordinates; + EntityManager.GetComponent(ghost.Owner).Coordinates = EntityManager.GetComponent(warp.Owner).Coordinates; } Logger.Warning($"User {args.SenderSession.Name} tried to warp to an invalid warp: {msg.Name}"); @@ -162,32 +158,30 @@ namespace Content.Server.Ghost private void OnGhostWarpToTargetRequest(GhostWarpToTargetRequestEvent msg, EntitySessionEventArgs args) { - if (args.SenderSession.AttachedEntity == null || - !args.SenderSession.AttachedEntity.TryGetComponent(out GhostComponent? ghost)) + if (args.SenderSession.AttachedEntity is not {Valid: true} attached || + !EntityManager.TryGetComponent(attached, out GhostComponent? ghost)) { Logger.Warning($"User {args.SenderSession.Name} tried to warp to {msg.Target} without being a ghost."); return; } - if (!EntityManager.TryGetEntity(msg.Target, out var entity)) + if (!EntityManager.EntityExists(msg.Target)) { Logger.Warning($"User {args.SenderSession.Name} tried to warp to an invalid entity id: {msg.Target}"); return; } - ghost.Owner.Transform.Coordinates = entity.Transform.Coordinates; + EntityManager.GetComponent(ghost.Owner).Coordinates = EntityManager.GetComponent(msg.Target).Coordinates; } private void DeleteEntity(EntityUid uid) { - if (!EntityManager.TryGetEntity(uid, out var entity) - || entity.Deleted - || entity.LifeStage == EntityLifeStage.Terminating) + if (Deleted(uid) || Terminating(uid)) return; - if (entity.TryGetComponent(out var mind)) + if (EntityManager.TryGetComponent(uid, out var mind)) mind.GhostOnShutdown = false; - entity.Delete(); + EntityManager.DeleteEntity(uid); } private IEnumerable GetLocationNames() @@ -220,9 +214,9 @@ namespace Content.Server.Ghost foreach (var player in _playerManager.Sessions) { - if (player.AttachedEntity != null) + if (player.AttachedEntity is {Valid: true} attached) { - players.Add(player.AttachedEntity.Uid, player.AttachedEntity.Name); + players.Add(attached, EntityManager.GetComponent(attached).EntityName); } } diff --git a/Content.Server/Ghost/Roles/Components/GhostRoleMobSpawnerComponent.cs b/Content.Server/Ghost/Roles/Components/GhostRoleMobSpawnerComponent.cs index 27dc5b82a4..fda3a82772 100644 --- a/Content.Server/Ghost/Roles/Components/GhostRoleMobSpawnerComponent.cs +++ b/Content.Server/Ghost/Roles/Components/GhostRoleMobSpawnerComponent.cs @@ -1,12 +1,11 @@ using System; using Content.Server.Mind.Commands; using Content.Server.Mind.Components; -using Content.Server.Players; using JetBrains.Annotations; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; -using Robust.Shared.Utility; using Robust.Shared.ViewVariables; namespace Content.Server.Ghost.Roles.Components @@ -17,6 +16,8 @@ namespace Content.Server.Ghost.Roles.Components [RegisterComponent, ComponentReference(typeof(GhostRoleComponent))] public class GhostRoleMobSpawnerComponent : GhostRoleComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "GhostRoleMobSpawner"; [ViewVariables(VVAccess.ReadWrite)] [DataField("deleteOnSpawn")] @@ -41,15 +42,15 @@ namespace Content.Server.Ghost.Roles.Components if (string.IsNullOrEmpty(Prototype)) throw new NullReferenceException("Prototype string cannot be null or empty!"); - var mob = Owner.EntityManager.SpawnEntity(Prototype, Owner.Transform.Coordinates); + var mob = _entMan.SpawnEntity(Prototype, _entMan.GetComponent(Owner).Coordinates); if (MakeSentient) - MakeSentientCommand.MakeSentient(mob.Uid, Owner.EntityManager); + MakeSentientCommand.MakeSentient(mob, _entMan); mob.EnsureComponent(); var ghostRoleSystem = EntitySystem.Get(); - ghostRoleSystem.GhostRoleInternalCreateMindAndTransfer(session, OwnerUid, mob.Uid, this); + ghostRoleSystem.GhostRoleInternalCreateMindAndTransfer(session, Owner, mob, this); if (++_currentTakeovers < _availableTakeovers) return true; @@ -57,7 +58,7 @@ namespace Content.Server.Ghost.Roles.Components Taken = true; if (_deleteOnSpawn) - Owner.Delete(); + _entMan.DeleteEntity(Owner); return true; } diff --git a/Content.Server/Ghost/Roles/Components/GhostTakeoverAvailableComponent.cs b/Content.Server/Ghost/Roles/Components/GhostTakeoverAvailableComponent.cs index 786ec1fdf7..9c0083849d 100644 --- a/Content.Server/Ghost/Roles/Components/GhostTakeoverAvailableComponent.cs +++ b/Content.Server/Ghost/Roles/Components/GhostTakeoverAvailableComponent.cs @@ -4,6 +4,7 @@ using Content.Server.Mind.Components; using Content.Server.Players; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Utility; namespace Content.Server.Ghost.Roles.Components @@ -29,10 +30,10 @@ namespace Content.Server.Ghost.Roles.Components return false; if (MakeSentient) - MakeSentientCommand.MakeSentient(OwnerUid, Owner.EntityManager); + MakeSentientCommand.MakeSentient(Owner, IoCManager.Resolve()); var ghostRoleSystem = EntitySystem.Get(); - ghostRoleSystem.GhostRoleInternalCreateMindAndTransfer(session, OwnerUid, OwnerUid, this); + ghostRoleSystem.GhostRoleInternalCreateMindAndTransfer(session, Owner, Owner, this); ghostRoleSystem.UnregisterGhostRole(this); diff --git a/Content.Server/Ghost/Roles/GhostRoleSystem.cs b/Content.Server/Ghost/Roles/GhostRoleSystem.cs index 86be3f020d..36c04f748c 100644 --- a/Content.Server/Ghost/Roles/GhostRoleSystem.cs +++ b/Content.Server/Ghost/Roles/GhostRoleSystem.cs @@ -6,17 +6,17 @@ using Content.Server.Ghost.Roles.Components; using Content.Server.Ghost.Roles.UI; using Content.Server.Players; using Content.Shared.GameTicking; -using Content.Shared.Ghost.Roles; using Content.Shared.Ghost; +using Content.Shared.Ghost.Roles; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.Enums; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.ViewVariables; using Robust.Shared.Utility; -using Robust.Shared.Enums; +using Robust.Shared.ViewVariables; namespace Content.Server.Ghost.Roles { @@ -59,7 +59,8 @@ namespace Content.Server.Ghost.Roles public void OpenEui(IPlayerSession session) { - if (session.AttachedEntity == null || !session.AttachedEntity.HasComponent()) + if (session.AttachedEntity is not {Valid: true} attached || + !EntityManager.HasComponent(attached)) return; if(_openUis.ContainsKey(session)) @@ -194,7 +195,7 @@ namespace Content.Server.Ghost.Roles { // 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 (message.Entity.HasComponent()) return; + if (EntityManager.HasComponent(message.Entity)) return; CloseEui(message.Player); } diff --git a/Content.Server/Gravity/EntitySystems/GravityGeneratorSystem.cs b/Content.Server/Gravity/EntitySystems/GravityGeneratorSystem.cs index 6cc53d8137..832cc917a2 100644 --- a/Content.Server/Gravity/EntitySystems/GravityGeneratorSystem.cs +++ b/Content.Server/Gravity/EntitySystems/GravityGeneratorSystem.cs @@ -126,7 +126,7 @@ namespace Content.Server.Gravity.EntitySystems ApcPowerReceiverComponent powerReceiver, float chargeRate) { - if (!_uiSystem.IsUiOpen(component.Owner.Uid, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key)) + if (!_uiSystem.IsUiOpen(component.Owner, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key)) return; var chargeTarget = chargeRate < 0 ? 0 : 1; @@ -162,7 +162,7 @@ namespace Content.Server.Gravity.EntitySystems ); _uiSystem.TrySetUiState( - component.Owner.Uid, + component.Owner, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key, state); @@ -184,7 +184,7 @@ namespace Content.Server.Gravity.EntitySystems private void UpdateGravityActive(GravityGeneratorComponent grav, bool shake) { - var gridId = grav.Owner.Transform.GridID; + var gridId = EntityManager.GetComponent(grav.Owner).GridID; if (gridId == GridId.Invalid) return; @@ -202,7 +202,7 @@ namespace Content.Server.Gravity.EntitySystems private void OnInteractHand(EntityUid uid, GravityGeneratorComponent component, InteractHandEvent args) { - if (!EntityManager.TryGetComponent(args.User.Uid, out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; ApcPowerReceiverComponent? powerReceiver = default!; @@ -219,7 +219,7 @@ namespace Content.Server.Gravity.EntitySystems public void UpdateState(GravityGeneratorComponent grav, ApcPowerReceiverComponent powerReceiver) { - var uid = grav.Owner.Uid; + var uid = grav.Owner; var appearance = EntityManager.GetComponentOrNull(uid); appearance?.SetData(GravityGeneratorVisuals.Charge, grav.Charge); @@ -249,28 +249,28 @@ namespace Content.Server.Gravity.EntitySystems private void MakeBroken(GravityGeneratorComponent component, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner.Uid, false); + _ambientSoundSystem.SetAmbience(component.Owner, false); appearance?.SetData(GravityGeneratorVisuals.State, GravityGeneratorStatus.Broken); } private void MakeUnpowered(GravityGeneratorComponent component, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner.Uid, false); + _ambientSoundSystem.SetAmbience(component.Owner, false); appearance?.SetData(GravityGeneratorVisuals.State, GravityGeneratorStatus.Unpowered); } private void MakeOff(GravityGeneratorComponent component, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner.Uid, false); + _ambientSoundSystem.SetAmbience(component.Owner, false); appearance?.SetData(GravityGeneratorVisuals.State, GravityGeneratorStatus.Off); } private void MakeOn(GravityGeneratorComponent component, AppearanceComponent? appearance) { - _ambientSoundSystem.SetAmbience(component.Owner.Uid, true); + _ambientSoundSystem.SetAmbience(component.Owner, true); appearance?.SetData(GravityGeneratorVisuals.State, GravityGeneratorStatus.On); } diff --git a/Content.Server/Gravity/EntitySystems/GravityShakeSystem.cs b/Content.Server/Gravity/EntitySystems/GravityShakeSystem.cs index a4653cf6e8..04e2902968 100644 --- a/Content.Server/Gravity/EntitySystems/GravityShakeSystem.cs +++ b/Content.Server/Gravity/EntitySystems/GravityShakeSystem.cs @@ -79,9 +79,9 @@ namespace Content.Server.Gravity.EntitySystems { foreach (var player in _playerManager.Sessions) { - if (player.AttachedEntity == null - || player.AttachedEntity.Transform.GridID != gridId - || !player.AttachedEntity.TryGetComponent(out CameraRecoilComponent? recoil)) + if (player.AttachedEntity is not {Valid: true} attached + || EntityManager.GetComponent(attached).GridID != gridId + || !EntityManager.TryGetComponent(attached, out CameraRecoilComponent? recoil)) { continue; } diff --git a/Content.Server/Gravity/EntitySystems/GravitySystem.cs b/Content.Server/Gravity/EntitySystems/GravitySystem.cs index 011ad8f633..1345b70e1f 100644 --- a/Content.Server/Gravity/EntitySystems/GravitySystem.cs +++ b/Content.Server/Gravity/EntitySystems/GravitySystem.cs @@ -1,6 +1,7 @@ using Content.Shared.Gravity; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Gravity.EntitySystems { @@ -16,12 +17,12 @@ namespace Content.Server.Gravity.EntitySystems private void HandleGravityInitialize(EntityUid uid, GravityComponent component, ComponentInit args) { // Incase there's already a generator on the grid we'll just set it now. - var gridId = component.Owner.Transform.GridID; + var gridId = EntityManager.GetComponent(component.Owner).GridID; GravityChangedMessage message; foreach (var generator in EntityManager.EntityQuery()) { - if (generator.Owner.Transform.GridID == gridId && generator.GravityActive) + if (EntityManager.GetComponent(generator.Owner).GridID == gridId && generator.GravityActive) { component.Enabled = true; message = new GravityChangedMessage(gridId, true); @@ -40,7 +41,7 @@ namespace Content.Server.Gravity.EntitySystems if (comp.Enabled) return; comp.Enabled = true; - var gridId = comp.Owner.Transform.GridID; + var gridId = EntityManager.GetComponent(comp.Owner).GridID; var message = new GravityChangedMessage(gridId, true); RaiseLocalEvent(message); } @@ -50,7 +51,7 @@ namespace Content.Server.Gravity.EntitySystems if (!comp.Enabled) return; comp.Enabled = false; - var gridId = comp.Owner.Transform.GridID; + var gridId = EntityManager.GetComponent(comp.Owner).GridID; var message = new GravityChangedMessage(gridId, false); RaiseLocalEvent(message); } diff --git a/Content.Server/Gravity/EntitySystems/WeightlessSystem.cs b/Content.Server/Gravity/EntitySystems/WeightlessSystem.cs index 4c470b7231..6708340cbf 100644 --- a/Content.Server/Gravity/EntitySystems/WeightlessSystem.cs +++ b/Content.Server/Gravity/EntitySystems/WeightlessSystem.cs @@ -34,15 +34,14 @@ namespace Content.Server.Gravity.EntitySystems public void AddAlert(ServerAlertsComponent status) { - var gridId = status.Owner.Transform.GridID; + var gridId = EntityManager.GetComponent(status.Owner).GridID; var alerts = _alerts.GetOrNew(gridId); alerts.Add(status); - if (_mapManager.TryGetGrid(status.Owner.Transform.GridID, out var grid)) + if (_mapManager.TryGetGrid(EntityManager.GetComponent(status.Owner).GridID, out var grid)) { - var gridEntity = EntityManager.GetEntity(grid.GridEntityId); - if (gridEntity.GetComponent().Enabled) + if (EntityManager.GetComponent(grid.GridEntityId).Enabled) { RemoveWeightless(status); } @@ -55,7 +54,7 @@ namespace Content.Server.Gravity.EntitySystems public void RemoveAlert(ServerAlertsComponent status) { - var grid = status.Owner.Transform.GridID; + var grid = EntityManager.GetComponent(status.Owner).GridID; if (!_alerts.TryGetValue(grid, out var statuses)) { return; @@ -99,13 +98,13 @@ namespace Content.Server.Gravity.EntitySystems private void EntParentChanged(ref EntParentChangedMessage ev) { - if (!ev.Entity.TryGetComponent(out ServerAlertsComponent? status)) + if (!EntityManager.TryGetComponent(ev.Entity, out ServerAlertsComponent? status)) { return; } - if (ev.OldParent != null && - ev.OldParent.TryGetComponent(out IMapGridComponent? mapGrid)) + if (ev.OldParent is {Valid: true} old && + EntityManager.TryGetComponent(old, out IMapGridComponent? mapGrid)) { var oldGrid = mapGrid.GridIndex; @@ -115,7 +114,7 @@ namespace Content.Server.Gravity.EntitySystems } } - var newGrid = ev.Entity.Transform.GridID; + var newGrid = EntityManager.GetComponent(ev.Entity).GridID; var newStatuses = _alerts.GetOrNew(newGrid); newStatuses.Add(status); diff --git a/Content.Server/Hands/Components/HandsComponent.cs b/Content.Server/Hands/Components/HandsComponent.cs index 84d7cea30d..ba07419840 100644 --- a/Content.Server/Hands/Components/HandsComponent.cs +++ b/Content.Server/Hands/Components/HandsComponent.cs @@ -31,35 +31,36 @@ namespace Content.Server.Hands.Components #pragma warning restore 618 { [Dependency] private readonly IEntitySystemManager _entitySystemManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; [DataField("disarmedSound")] SoundSpecifier _disarmedSound = new SoundPathSpecifier("/Audio/Effects/thudswoosh.ogg"); int IDisarmedAct.Priority => int.MaxValue; // We want this to be the last disarm act to run. - protected override void OnHeldEntityRemovedFromHand(IEntity heldEntity, HandState handState) + protected override void OnHeldEntityRemovedFromHand(EntityUid heldEntity, HandState handState) { - if (heldEntity.TryGetComponent(out ItemComponent? item)) + if (_entities.TryGetComponent(heldEntity, out ItemComponent? item)) { item.RemovedFromSlot(); _entitySystemManager.GetEntitySystem().UnequippedHandInteraction(Owner, heldEntity, handState); } - if (heldEntity.TryGetComponent(out SpriteComponent? sprite)) + if (_entities.TryGetComponent(heldEntity, out SpriteComponent? sprite)) { - sprite.RenderOrder = heldEntity.EntityManager.CurrentTick.Value; + sprite.RenderOrder = _entities.CurrentTick.Value; } } - protected override void HandlePickupAnimation(IEntity entity) + protected override void HandlePickupAnimation(EntityUid entity) { - var initialPosition = EntityCoordinates.FromMap(Owner.Transform.Parent?.Owner ?? Owner, entity.Transform.MapPosition); + var initialPosition = EntityCoordinates.FromMap(_entities.GetComponent(Owner).Parent?.Owner ?? Owner, _entities.GetComponent(entity).MapPosition); - var finalPosition = Owner.Transform.LocalPosition; + var finalPosition = _entities.GetComponent(Owner).LocalPosition; if (finalPosition.EqualsApprox(initialPosition.Position)) return; - Owner.EntityManager.EntityNetManager!.SendSystemNetworkMessage( - new PickupAnimationMessage(entity.Uid, finalPosition, initialPosition)); + _entities.EntityNetManager!.SendSystemNetworkMessage( + new PickupAnimationMessage(entity, finalPosition, initialPosition)); } #region Pull/Disarm @@ -106,13 +107,13 @@ namespace Content.Server.Hands.Components { if (ActiveHand != null && Drop(ActiveHand, false)) { - source.PopupMessageOtherClients(Loc.GetString("hands-component-disarm-success-others-message", ("disarmer", source.Name), ("disarmed", target.Name))); - source.PopupMessageCursor(Loc.GetString("hands-component-disarm-success-message", ("disarmed", target.Name))); + source.PopupMessageOtherClients(Loc.GetString("hands-component-disarm-success-others-message", ("disarmer", Name: _entities.GetComponent(source).EntityName), ("disarmed", Name: _entities.GetComponent(target).EntityName))); + source.PopupMessageCursor(Loc.GetString("hands-component-disarm-success-message", ("disarmed", Name: _entities.GetComponent(target).EntityName))); } else { - source.PopupMessageOtherClients(Loc.GetString("hands-component-shove-success-others-message", ("shover", source.Name), ("shoved", target.Name))); - source.PopupMessageCursor(Loc.GetString("hands-component-shove-success-message", ("shoved", target.Name))); + source.PopupMessageOtherClients(Loc.GetString("hands-component-shove-success-others-message", ("shover", Name: _entities.GetComponent(source).EntityName), ("shoved", Name: _entities.GetComponent(target).EntityName))); + source.PopupMessageCursor(Loc.GetString("hands-component-shove-success-message", ("shoved", Name: _entities.GetComponent(target).EntityName))); } } } @@ -123,8 +124,8 @@ namespace Content.Server.Hands.Components private bool BreakPulls() { // What is this API?? - if (!Owner.TryGetComponent(out SharedPullerComponent? puller) - || puller.Pulling == null || !puller.Pulling.TryGetComponent(out SharedPullableComponent? pullable)) + if (!_entities.TryGetComponent(Owner, out SharedPullerComponent? puller) + || puller.Pulling is not {Valid: true} pulling || !_entities.TryGetComponent(puller.Pulling.Value, out SharedPullableComponent? pullable)) return false; return _entitySystemManager.GetEntitySystem().TryStopPull(pullable); @@ -163,7 +164,7 @@ namespace Content.Server.Hands.Components if (!TryGetHeldEntity(handName, out var heldEntity)) return null; - heldEntity.TryGetComponent(out ItemComponent? item); + _entities.TryGetComponent(heldEntity, out ItemComponent? item); return item; } @@ -177,7 +178,7 @@ namespace Content.Server.Hands.Components if (!TryGetHeldEntity(handName, out var heldEntity)) return false; - return heldEntity.TryGetComponent(out item); + return _entities.TryGetComponent(heldEntity, out item); } /// @@ -190,7 +191,7 @@ namespace Content.Server.Hands.Components if (!TryGetActiveHeldEntity(out var heldEntity)) return null; - heldEntity.TryGetComponent(out ItemComponent? item); + _entities.TryGetComponent(heldEntity, out ItemComponent? item); return item; } } @@ -199,7 +200,7 @@ namespace Content.Server.Hands.Components { foreach (var entity in GetAllHeldEntities()) { - if (entity.TryGetComponent(out ItemComponent? item)) + if (_entities.TryGetComponent(entity, out ItemComponent? item)) yield return item; } } diff --git a/Content.Server/Hands/Systems/HandVirtualItemSystem.cs b/Content.Server/Hands/Systems/HandVirtualItemSystem.cs index fa9937a6e4..8a56d897f5 100644 --- a/Content.Server/Hands/Systems/HandVirtualItemSystem.cs +++ b/Content.Server/Hands/Systems/HandVirtualItemSystem.cs @@ -1,5 +1,4 @@ using Content.Server.Hands.Components; -using Content.Server.Pulling; using Content.Shared.Hands; using Content.Shared.Hands.Components; using Content.Shared.Interaction; @@ -31,9 +30,9 @@ namespace Content.Server.Hands.Systems if (!hand.IsEmpty) continue; - var pos = hands.Owner.Transform.Coordinates; + var pos = EntityManager.GetComponent(hands.Owner).Coordinates; var virtualItem = EntityManager.SpawnEntity("HandVirtualItem", pos); - var virtualItemComp = virtualItem.GetComponent(); + var virtualItemComp = EntityManager.GetComponent(virtualItem); virtualItemComp.BlockingEntity = blockingEnt; hands.PutEntityIntoHand(hand, virtualItem); return true; @@ -55,7 +54,7 @@ namespace Content.Server.Hands.Systems // If the virtual item gets removed from the hands for any reason, cancel the pull and delete it. private void HandleItemUnequipped(EntityUid uid, HandVirtualItemComponent component, UnequippedHandEvent args) { - Delete(component, args.User.Uid); + Delete(component, args.User); } private void HandleItemDropped(EntityUid uid, HandVirtualItemComponent component, DroppedEvent args) @@ -73,7 +72,7 @@ namespace Content.Server.Hands.Systems var targEv = new VirtualItemDeletedEvent(comp.BlockingEntity, user); RaiseLocalEvent(comp.BlockingEntity, targEv, false); - comp.Owner.QueueDelete(); + EntityManager.QueueDeleteEntity(comp.Owner); } /// @@ -82,23 +81,22 @@ namespace Content.Server.Hands.Systems /// public void DeleteInHandsMatching(EntityUid user, EntityUid matching) { - if (EntityManager.TryGetComponent(user, out var hands)) - { - foreach (var handName in hands.ActivePriorityEnumerable()) - { - var hand = hands.GetHand(handName); - if (hand.IsEmpty) - continue; + if (!EntityManager.TryGetComponent(user, out var hands)) + return; - if (hand.HeldEntity != null) - { - if (EntityManager.TryGetComponent(hand.HeldEntity.Uid, - out var virt) - && virt.BlockingEntity == matching) - { - Delete(virt, user); - } - } + foreach (var handName in hands.ActivePriorityEnumerable()) + { + var hand = hands.GetHand(handName); + if (hand.IsEmpty) + continue; + + if (hand.HeldEntity == default) + continue; + + if (EntityManager.TryGetComponent(hand.HeldEntity, out var virt) + && virt.BlockingEntity == matching) + { + Delete(virt, user); } } } diff --git a/Content.Server/Hands/Systems/HandsSystem.cs b/Content.Server/Hands/Systems/HandsSystem.cs index 640214e96c..e5854da71f 100644 --- a/Content.Server/Hands/Systems/HandsSystem.cs +++ b/Content.Server/Hands/Systems/HandsSystem.cs @@ -72,7 +72,7 @@ namespace Content.Server.Hands.Systems private void HandlePullStarted(EntityUid uid, HandsComponent component, PullStartedMessage args) { - if (!_virtualItemSystem.TrySpawnVirtualItemInHand(args.Pulled.Owner.Uid, uid)) + if (!_virtualItemSystem.TrySpawnVirtualItemInHand(args.Pulled.Owner, uid)) { DebugTools.Assert("Unable to find available hand when starting pulling??"); } @@ -84,12 +84,12 @@ namespace Content.Server.Hands.Systems // and clear it. foreach (var hand in component.Hands) { - if (hand.HeldEntity == null - || !hand.HeldEntity.TryGetComponent(out HandVirtualItemComponent? virtualItem) - || virtualItem.BlockingEntity != args.Pulled.Owner.Uid) + if (hand.HeldEntity == default + || !EntityManager.TryGetComponent(hand.HeldEntity, out HandVirtualItemComponent? virtualItem) + || virtualItem.BlockingEntity != args.Pulled.Owner) continue; - hand.HeldEntity.Delete(); + EntityManager.DeleteEntity(hand.HeldEntity); break; } } @@ -98,10 +98,10 @@ namespace Content.Server.Hands.Systems { var player = session?.AttachedEntity; - if (player == null) + if (!player.HasValue || !player.Value.IsValid()) return; - if (!player.TryGetComponent(out SharedHandsComponent? hands)) + if (!EntityManager.TryGetComponent(player.Value, out SharedHandsComponent? hands)) return; if (!hands.TryGetSwapHandsResult(out var nextHand)) @@ -114,10 +114,10 @@ namespace Content.Server.Hands.Systems { var player = session?.AttachedEntity; - if (player == null) + if (!player.HasValue || !player.Value.IsValid()) return false; - if (!player.TryGetComponent(out SharedHandsComponent? hands)) + if (!EntityManager.TryGetComponent(player.Value, out SharedHandsComponent? hands)) return false; var activeHand = hands.ActiveHand; @@ -173,14 +173,14 @@ namespace Content.Server.Hands.Systems { foreach (var inhand in component.GetAllHeldItems()) { - if (inhand.Owner.HasComponent()) + if (EntityManager.HasComponent(inhand.Owner)) continue; args.PushText(Loc.GetString("comp-hands-examine", ("user", component.Owner), ("item", inhand.Owner))); } } - private static bool TryGetHandsComp( + private bool TryGetHandsComp( ICommonSession? session, [NotNullWhen(true)] out SharedHandsComponent? hands) { @@ -189,12 +189,12 @@ namespace Content.Server.Hands.Systems if (session is not IPlayerSession playerSession) return false; - var playerEnt = playerSession.AttachedEntity; + var player = playerSession.AttachedEntity; - if (playerEnt == null || !playerEnt.IsValid()) + if (player is not {Valid: true}) return false; - return playerEnt.TryGetComponent(out hands); + return EntityManager.TryGetComponent(player, out hands); } private void HandleActivateItem(ICommonSession? session) @@ -218,36 +218,34 @@ namespace Content.Server.Hands.Systems if (session is not IPlayerSession playerSession) return false; - var playerEnt = playerSession.AttachedEntity; - - if (playerEnt == null || - !playerEnt.IsValid() || - playerEnt.IsInContainer() || - !playerEnt.TryGetComponent(out SharedHandsComponent? hands) || + if (playerSession.AttachedEntity is not {Valid: true} player || + !EntityManager.EntityExists(player) || + player.IsInContainer() || + !EntityManager.TryGetComponent(player, out SharedHandsComponent? hands) || !hands.TryGetActiveHeldEntity(out var throwEnt) || - !_actionBlockerSystem.CanThrow(playerEnt.Uid)) + !_actionBlockerSystem.CanThrow(player)) return false; - if (throwEnt.TryGetComponent(out StackComponent? stack) && stack.Count > 1 && stack.ThrowIndividually) + if (EntityManager.TryGetComponent(throwEnt, out StackComponent? stack) && stack.Count > 1 && stack.ThrowIndividually) { - var splitStack = _stackSystem.Split(throwEnt.Uid, 1, playerEnt.Transform.Coordinates, stack); + var splitStack = _stackSystem.Split(throwEnt, 1, EntityManager.GetComponent(player).Coordinates, stack); - if (splitStack == null) + if (splitStack is not {Valid: true}) return false; - throwEnt = EntityManager.GetEntity(splitStack.Value); + throwEnt = splitStack.Value; } else if (!hands.Drop(throwEnt)) return false; - var direction = coords.ToMapPos(EntityManager) - playerEnt.Transform.WorldPosition; + var direction = coords.ToMapPos(EntityManager) - EntityManager.GetComponent(player).WorldPosition; if (direction == Vector2.Zero) return true; direction = direction.Normalized * Math.Min(direction.Length, hands.ThrowRange); var throwStrength = hands.ThrowForceMultiplier; - throwEnt.TryThrow(direction, throwStrength, playerEnt); + throwEnt.TryThrow(direction, throwStrength, player); return true; } @@ -267,17 +265,15 @@ namespace Content.Server.Hands.Systems if (session is not IPlayerSession playerSession) return; - var plyEnt = playerSession.AttachedEntity; - - if (plyEnt == null || !plyEnt.IsValid()) + if (playerSession.AttachedEntity is not {Valid: true} plyEnt || !EntityManager.EntityExists(plyEnt)) return; - if (!plyEnt.TryGetComponent(out SharedHandsComponent? hands) || - !plyEnt.TryGetComponent(out InventoryComponent? inventory)) + if (!EntityManager.TryGetComponent(plyEnt, out SharedHandsComponent? hands) || + !EntityManager.TryGetComponent(plyEnt, out InventoryComponent? inventory)) return; if (!inventory.TryGetSlotItem(equipmentSlot, out ItemComponent? equipmentItem) || - !equipmentItem.Owner.TryGetComponent(out ServerStorageComponent? storageComponent)) + !EntityManager.TryGetComponent(equipmentItem.Owner, out ServerStorageComponent? storageComponent)) { plyEnt.PopupMessage(Loc.GetString("hands-system-missing-equipment-slot", ("slotName", SlotNames[equipmentSlot].ToLower()))); return; @@ -299,7 +295,7 @@ namespace Content.Server.Hands.Systems if (storageComponent.Remove(lastStoredEntity)) { if (!hands.TryPickupEntityToActiveHand(lastStoredEntity)) - lastStoredEntity.Transform.Coordinates = plyEnt.Transform.Coordinates; + EntityManager.GetComponent(lastStoredEntity).Coordinates = EntityManager.GetComponent(plyEnt).Coordinates; } } } diff --git a/Content.Server/Headset/HeadsetComponent.cs b/Content.Server/Headset/HeadsetComponent.cs index 5256d9c8e1..7ebed04056 100644 --- a/Content.Server/Headset/HeadsetComponent.cs +++ b/Content.Server/Headset/HeadsetComponent.cs @@ -22,6 +22,7 @@ namespace Content.Server.Headset public class HeadsetComponent : Component, IListen, IRadio, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IServerNetManager _netManager = default!; public override string Name => "Headset"; @@ -50,16 +51,16 @@ namespace Content.Server.Headset _radioSystem = EntitySystem.Get(); } - public bool CanListen(string message, IEntity source) + public bool CanListen(string message, EntityUid source) { return RadioRequested; } - public void Receive(string message, int channel, IEntity source) + public void Receive(string message, int channel, EntityUid source) { if (Owner.TryGetContainer(out var container)) { - if (!container.Owner.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(container.Owner, out ActorComponent? actor)) return; var playerChannel = actor.PlayerSession.ConnectedClient; @@ -69,17 +70,17 @@ namespace Content.Server.Headset msg.Channel = ChatChannel.Radio; msg.Message = message; //Square brackets are added here to avoid issues with escaping - msg.MessageWrap = Loc.GetString("chat-radio-message-wrap", ("channel", $"\\[{channel}\\]"), ("name", source.Name)); + msg.MessageWrap = Loc.GetString("chat-radio-message-wrap", ("channel", $"\\[{channel}\\]"), ("name", Name: _entMan.GetComponent(source).EntityName)); _netManager.ServerSendMessage(msg, playerChannel); } } - public void Listen(string message, IEntity speaker) + public void Listen(string message, EntityUid speaker) { Broadcast(message, speaker); } - public void Broadcast(string message, IEntity speaker) + public void Broadcast(string message, EntityUid speaker) { _radioSystem.SpreadMessage(this, speaker, message, BroadcastFrequency); RadioRequested = false; diff --git a/Content.Server/Instruments/InstrumentComponent.cs b/Content.Server/Instruments/InstrumentComponent.cs index 67e1b0f3c3..36538a75f7 100644 --- a/Content.Server/Instruments/InstrumentComponent.cs +++ b/Content.Server/Instruments/InstrumentComponent.cs @@ -3,6 +3,7 @@ using Content.Shared.Instruments; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Server.Instruments; @@ -10,6 +11,8 @@ namespace Content.Server.Instruments; [RegisterComponent, ComponentReference(typeof(SharedInstrumentComponent))] public sealed class InstrumentComponent : SharedInstrumentComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables] public float Timer = 0f; @@ -22,9 +25,10 @@ public sealed class InstrumentComponent : SharedInstrumentComponent [ViewVariables] public int MidiEventCount = 0; + // TODO Instruments: Make this ECS public IPlayerSession? InstrumentPlayer => - Owner.GetComponentOrNull()?.CurrentSingleUser - ?? Owner.GetComponentOrNull()?.PlayerSession; + _entMan.GetComponentOrNull(Owner)?.CurrentSingleUser + ?? _entMan.GetComponentOrNull(Owner)?.PlayerSession; [ViewVariables] public BoundUserInterface? UserInterface => Owner.GetUIOrNull(InstrumentUiKey.Key); } diff --git a/Content.Server/Instruments/InstrumentSystem.cs b/Content.Server/Instruments/InstrumentSystem.cs index 317a54378b..ed5161abe3 100644 --- a/Content.Server/Instruments/InstrumentSystem.cs +++ b/Content.Server/Instruments/InstrumentSystem.cs @@ -94,7 +94,10 @@ public sealed partial class InstrumentSystem : SharedInstrumentSystem if (!EntityManager.TryGetComponent(uid, out InstrumentComponent? instrument)) return; - if (!instrument.Playing || args.SenderSession != instrument.InstrumentPlayer || instrument.InstrumentPlayer == null) + if (!instrument.Playing + || args.SenderSession != instrument.InstrumentPlayer + || instrument.InstrumentPlayer == null + || args.SenderSession.AttachedEntity is not {} attached) return; var send = true; @@ -108,11 +111,11 @@ public sealed partial class InstrumentSystem : SharedInstrumentSystem { if (instrument.LaggedBatches == (int) (MaxMidiLaggedBatches * (1 / 3d) + 1)) { - instrument.InstrumentPlayer.AttachedEntity?.PopupMessage( + attached.PopupMessage( Loc.GetString("instrument-component-finger-cramps-light-message")); } else if (instrument.LaggedBatches == (int) (MaxMidiLaggedBatches * (2 / 3d) + 1)) { - instrument.InstrumentPlayer.AttachedEntity?.PopupMessage( + attached.PopupMessage( Loc.GetString("instrument-component-finger-cramps-serious-message")); } } @@ -150,15 +153,13 @@ public sealed partial class InstrumentSystem : SharedInstrumentSystem || instrument.LaggedBatches >= MaxMidiLaggedBatches) && instrument.InstrumentPlayer != null && instrument.RespectMidiLimits) { - var mob = instrument.InstrumentPlayer.AttachedEntity; - // Just in case - Clean(instrument.OwnerUid); + Clean((instrument).Owner); instrument.UserInterface?.CloseAll(); - if (mob != null) + if (instrument.InstrumentPlayer.AttachedEntity is {Valid: true} mob) { - _stunSystem.TryParalyze(mob.Uid, TimeSpan.FromSeconds(1), true); + _stunSystem.TryParalyze(mob, TimeSpan.FromSeconds(1), true); instrument.Owner.PopupMessage(mob, "instrument-component-finger-cramps-max-message"); } diff --git a/Content.Server/Interaction/Components/ClumsyComponent.cs b/Content.Server/Interaction/Components/ClumsyComponent.cs index bba250447d..6fbff2c75f 100644 --- a/Content.Server/Interaction/Components/ClumsyComponent.cs +++ b/Content.Server/Interaction/Components/ClumsyComponent.cs @@ -2,7 +2,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Random; - namespace Content.Server.Interaction.Components { /// @@ -28,9 +27,9 @@ namespace Content.Server.Interaction.Components /// The chance that a "bad action" happens if the user is clumsy, between 0 and 1 inclusive. /// /// True if a "bad action" happened, false if the normal action should happen. - public static bool TryRollClumsy(IEntity entity, float chance) + public static bool TryRollClumsy(EntityUid entity, float chance) { - return entity.TryGetComponent(out ClumsyComponent? clumsy) + return IoCManager.Resolve().TryGetComponent(entity, out ClumsyComponent? clumsy) && clumsy.RollClumsy(chance); } } diff --git a/Content.Server/Interaction/InteractionSystem.cs b/Content.Server/Interaction/InteractionSystem.cs index 5b74ecba43..11c4e4071f 100644 --- a/Content.Server/Interaction/InteractionSystem.cs +++ b/Content.Server/Interaction/InteractionSystem.cs @@ -9,7 +9,6 @@ using Content.Server.Items; using Content.Server.Pulling; using Content.Server.Storage.Components; using Content.Shared.ActionBlocker; -using Content.Shared.Administration.Logs; using Content.Shared.Database; using Content.Shared.DragDrop; using Content.Shared.Input; @@ -71,7 +70,7 @@ namespace Content.Server.Interaction } #region Client Input Validation - private bool ValidateClientInput(ICommonSession? session, EntityCoordinates coords, EntityUid uid, [NotNullWhen(true)] out IEntity? userEntity) + private bool ValidateClientInput(ICommonSession? session, EntityCoordinates coords, EntityUid uid, [NotNullWhen(true)] out EntityUid? userEntity) { userEntity = null; @@ -90,7 +89,7 @@ namespace Content.Server.Interaction userEntity = ((IPlayerSession?) session)?.AttachedEntity; - if (userEntity == null || !userEntity.IsValid()) + if (userEntity == null || !EntityManager.EntityExists(userEntity.Value)) { Logger.WarningS("system.interaction", $"Client sent interaction with no attached entity. Session={session}"); @@ -102,13 +101,13 @@ namespace Content.Server.Interaction public override bool CanAccessViaStorage(EntityUid user, EntityUid target) { - if (!EntityManager.TryGetEntity(target, out var entity)) + if (!EntityManager.EntityExists(target)) return false; - if (!entity.TryGetContainer(out var container)) + if (!target.TryGetContainer(out var container)) return false; - if (!EntityManager.TryGetComponent(container.Owner.Uid, out ServerStorageComponent storage)) + if (!EntityManager.TryGetComponent(container.Owner, out ServerStorageComponent storage)) return false; if (storage.Storage?.ID != container.ID) @@ -128,7 +127,7 @@ namespace Content.Server.Interaction /// private void HandleInteractInventorySlotEvent(InteractInventorySlotEvent msg, EntitySessionEventArgs args) { - if (!EntityManager.TryGetEntity(msg.ItemUid, out var item)) + if (!EntityManager.EntityExists(msg.ItemUid)) { Logger.WarningS("system.interaction", $"Client sent inventory interaction with an invalid target item. Session={args.SenderSession}"); @@ -136,7 +135,7 @@ namespace Content.Server.Interaction } // client sanitization - if (!ValidateClientInput(args.SenderSession, item.Transform.Coordinates, msg.ItemUid, out var userEntity)) + if (!ValidateClientInput(args.SenderSession, EntityManager.GetComponent(msg.ItemUid).Coordinates, msg.ItemUid, out var userEntity)) { Logger.InfoS("system.interaction", $"Inventory interaction validation failed. Session={args.SenderSession}"); return; @@ -144,10 +143,10 @@ namespace Content.Server.Interaction if (msg.AltInteract) // Use 'UserInteraction' function - behaves as if the user alt-clicked the item in the world. - UserInteraction(userEntity, item.Transform.Coordinates, msg.ItemUid, msg.AltInteract); + UserInteraction(userEntity.Value, EntityManager.GetComponent(msg.ItemUid).Coordinates, msg.ItemUid, msg.AltInteract); else // User used 'E'. We want to activate it, not simulate clicking on the item - InteractionActivate(userEntity, item); + InteractionActivate(userEntity.Value, msg.ItemUid); } #region Drag drop @@ -159,15 +158,15 @@ namespace Content.Server.Interaction return; } - if (!_actionBlockerSystem.CanInteract(userEntity.Uid)) + if (!_actionBlockerSystem.CanInteract(userEntity.Value)) return; - if (!EntityManager.TryGetEntity(msg.Dropped, out var dropped)) + if (!EntityManager.EntityExists(msg.Dropped)) return; - if (!EntityManager.TryGetEntity(msg.Target, out var target)) + if (!EntityManager.EntityExists(msg.Target)) return; - var interactionArgs = new DragDropEvent(userEntity, msg.DropLocation, dropped, target); + var interactionArgs = new DragDropEvent(userEntity.Value, msg.DropLocation, msg.Dropped, msg.Target); // must be in range of both the target and the object they are drag / dropping // Client also does this check but ya know we gotta validate it. @@ -175,8 +174,8 @@ namespace Content.Server.Interaction return; // trigger dragdrops on the dropped entity - RaiseLocalEvent(dropped.Uid, interactionArgs); - foreach (var dragDrop in dropped.GetAllComponents()) + RaiseLocalEvent(msg.Dropped, interactionArgs); + foreach (var dragDrop in EntityManager.GetComponents(msg.Dropped)) { if (dragDrop.CanDrop(interactionArgs) && dragDrop.Drop(interactionArgs)) @@ -186,8 +185,8 @@ namespace Content.Server.Interaction } // trigger dragdropons on the targeted entity - RaiseLocalEvent(target.Uid, interactionArgs, false); - foreach (var dragDropOn in target.GetAllComponents()) + RaiseLocalEvent(msg.Target, interactionArgs, false); + foreach (var dragDropOn in EntityManager.GetComponents(msg.Target)) { if (dragDropOn.CanDragDropOn(interactionArgs) && dragDropOn.DragDropOn(interactionArgs)) @@ -207,10 +206,10 @@ namespace Content.Server.Interaction return false; } - if (!EntityManager.TryGetEntity(uid, out var used)) + if (!EntityManager.EntityExists(uid)) return false; - InteractionActivate(user, used); + InteractionActivate(user.Value, uid); return true; } #endregion @@ -224,8 +223,8 @@ namespace Content.Server.Interaction return true; } - if (userEntity.TryGetComponent(out CombatModeComponent? combatMode) && combatMode.IsInCombatMode) - DoAttack(userEntity, coords, true); + if (EntityManager.TryGetComponent(userEntity.Value, out CombatModeComponent? combatMode) && combatMode.IsInCombatMode) + DoAttack(userEntity.Value, coords, true); return true; } @@ -237,9 +236,9 @@ namespace Content.Server.Interaction /// /// /// - internal void AiUseInteraction(IEntity entity, EntityCoordinates coords, EntityUid uid) + internal void AiUseInteraction(EntityUid entity, EntityCoordinates coords, EntityUid uid) { - if (entity.HasComponent()) + if (EntityManager.HasComponent(entity)) throw new InvalidOperationException(); UserInteraction(entity, coords, uid); @@ -254,7 +253,7 @@ namespace Content.Server.Interaction return true; } - UserInteraction(userEntity, coords, uid); + UserInteraction(userEntity.Value, coords, uid); return true; } @@ -268,7 +267,7 @@ namespace Content.Server.Interaction return true; } - UserInteraction(userEntity, coords, uid, altInteract : true ); + UserInteraction(userEntity.Value, coords, uid, altInteract : true ); return true; } @@ -281,19 +280,19 @@ namespace Content.Server.Interaction return true; } - if (userEntity.Uid == uid) + if (userEntity == uid) return false; - if (!EntityManager.TryGetEntity(uid, out var pulledObject)) + if (!EntityManager.EntityExists(uid)) return false; - if (!InRangeUnobstructed(userEntity, pulledObject, popup: true)) + if (!InRangeUnobstructed(userEntity.Value, uid, popup: true)) return false; - if (!pulledObject.TryGetComponent(out SharedPullableComponent? pull)) + if (!EntityManager.TryGetComponent(uid, out SharedPullableComponent? pull)) return false; - return _pullSystem.TogglePull(userEntity, pull); + return _pullSystem.TogglePull(userEntity.Value, pull); } /// @@ -305,47 +304,44 @@ namespace Content.Server.Interaction /// Whether to use default or alternative interactions (usually as a result of /// alt+clicking). If combat mode is enabled, the alternative action is to perform the default non-combat /// interaction. Having an item in the active hand also disables alternative interactions. - public async void UserInteraction(IEntity user, EntityCoordinates coordinates, EntityUid clickedUid, bool altInteract = false) + public async void UserInteraction(EntityUid user, EntityCoordinates coordinates, EntityUid target, bool altInteract = false) { // TODO COMBAT Consider using alt-interact for advanced combat? maybe alt-interact disarms? - if (!altInteract && user.TryGetComponent(out CombatModeComponent? combatMode) && combatMode.IsInCombatMode) + if (!altInteract && EntityManager.TryGetComponent(user, out CombatModeComponent? combatMode) && combatMode.IsInCombatMode) { - DoAttack(user, coordinates, false, clickedUid); + DoAttack(user, coordinates, false, target); return; } if (!ValidateInteractAndFace(user, coordinates)) return; - if (!_actionBlockerSystem.CanInteract(user.Uid)) + if (!_actionBlockerSystem.CanInteract(user)) return; - // Get entity clicked upon from UID if valid UID, if not assume no entity clicked upon and null - EntityManager.TryGetEntity(clickedUid, out var target); - // Check if interacted entity is in the same container, the direct child, or direct parent of the user. // This is bypassed IF the interaction happened through an item slot (e.g., backpack UI) - if (target != null && !user.IsInSameOrParentContainer(target) && !CanAccessViaStorage(user.Uid, target.Uid)) + if (target != default && !user.IsInSameOrParentContainer(target) && !CanAccessViaStorage(user, target)) { Logger.WarningS("system.interaction", - $"User entity named {user.Name} clicked on object {target.Name} that isn't the parent, child, or in the same container"); + $"User entity named {EntityManager.GetComponent(user).EntityName} clicked on object {EntityManager.GetComponent(target).EntityName} that isn't the parent, child, or in the same container"); return; } // Verify user has a hand, and find what object they are currently holding in their active hand - if (!user.TryGetComponent(out var hands)) + if (!EntityManager.TryGetComponent(user, out var hands)) return; var item = hands.GetActiveHand?.Owner; // TODO: Replace with body interaction range when we get something like arm length or telekinesis or something. var inRangeUnobstructed = user.InRangeUnobstructed(coordinates, ignoreInsideBlocker: true); - if (target == null || !inRangeUnobstructed) + if (target == default || !inRangeUnobstructed) { if (item == null) return; - if (!await InteractUsingRanged(user, item, target, coordinates, inRangeUnobstructed) && + if (!await InteractUsingRanged(user, item.Value, target, coordinates, inRangeUnobstructed) && !inRangeUnobstructed) { var message = Loc.GetString("interaction-system-user-interaction-cannot-reach"); @@ -363,20 +359,20 @@ namespace Content.Server.Interaction else if (item != null && item != target) // We are performing a standard interaction with an item, and the target isn't the same as the item // currently in our hand. We will use the item in our hand on the nearby object via InteractUsing - await InteractUsing(user, item, target, coordinates); + await InteractUsing(user, item.Value, target, coordinates); else if (item == null) // Since our hand is empty we will use InteractHand/Activate InteractHand(user, target); } } - private bool ValidateInteractAndFace(IEntity user, EntityCoordinates coordinates) + private bool ValidateInteractAndFace(EntityUid user, EntityCoordinates coordinates) { // Verify user is on the same map as the entity they clicked on - if (coordinates.GetMapId(_entityManager) != user.Transform.MapID) + if (coordinates.GetMapId(_entityManager) != EntityManager.GetComponent(user).MapID) { Logger.WarningS("system.interaction", - $"User entity named {user.Name} clicked on a map they aren't located on"); + $"User entity named {EntityManager.GetComponent(user).EntityName} clicked on a map they aren't located on"); return false; } @@ -390,21 +386,21 @@ namespace Content.Server.Interaction /// Finds components with the InteractHand interface and calls their function /// NOTE: Does not have an InRangeUnobstructed check /// - public void InteractHand(IEntity user, IEntity target) + public void InteractHand(EntityUid user, EntityUid target) { - if (!_actionBlockerSystem.CanInteract(user.Uid)) + if (!_actionBlockerSystem.CanInteract(user)) return; // all interactions should only happen when in range / unobstructed, so no range check is needed var message = new InteractHandEvent(user, target); - RaiseLocalEvent(target.Uid, message); + RaiseLocalEvent(target, message); _adminLogSystem.Add(LogType.InteractHand, LogImpact.Low, $"{user} interacted with {target}"); if (message.Handled) return; var interactHandEventArgs = new InteractHandEventArgs(user, target); - var interactHandComps = target.GetAllComponents().ToList(); + var interactHandComps = EntityManager.GetComponents(target).ToList(); foreach (var interactHandComp in interactHandComps) { // If an InteractHand returns a status completion we finish our interaction @@ -422,19 +418,19 @@ namespace Content.Server.Interaction /// Will have two behaviors, either "uses" the used entity at range on the target entity if it is capable of accepting that action /// Or it will use the used entity itself on the position clicked, regardless of what was there /// - public async Task InteractUsingRanged(IEntity user, IEntity used, IEntity? target, EntityCoordinates clickLocation, bool inRangeUnobstructed) + public async Task InteractUsingRanged(EntityUid user, EntityUid used, EntityUid target, EntityCoordinates clickLocation, bool inRangeUnobstructed) { if (InteractDoBefore(user, used, inRangeUnobstructed ? target : null, clickLocation, false)) return true; - if (target != null) + if (target != default) { - var rangedMsg = new RangedInteractEvent(user.Uid, used.Uid, target.Uid, clickLocation); - RaiseLocalEvent(target.Uid, rangedMsg); + var rangedMsg = new RangedInteractEvent(user, used, target, clickLocation); + RaiseLocalEvent(target, rangedMsg); if (rangedMsg.Handled) return true; - var rangedInteractions = target.GetAllComponents().ToList(); + var rangedInteractions = EntityManager.GetComponents(target).ToList(); var rangedInteractionEventArgs = new RangedInteractEventArgs(user, used, clickLocation); // See if we have a ranged interaction @@ -451,26 +447,21 @@ namespace Content.Server.Interaction return await InteractDoAfter(user, used, inRangeUnobstructed ? target : null, clickLocation, false); } - public void DoAttack(IEntity user, EntityCoordinates coordinates, bool wideAttack, EntityUid targetUid = default) + public void DoAttack(EntityUid user, EntityCoordinates coordinates, bool wideAttack, EntityUid targetUid = default) { if (!ValidateInteractAndFace(user, coordinates)) return; - if (!_actionBlockerSystem.CanAttack(user.Uid)) + if (!_actionBlockerSystem.CanAttack(user)) return; - IEntity? targetEnt = null; - if (!wideAttack) { - // Get entity clicked upon from UID if valid UID, if not assume no entity clicked upon and null - EntityManager.TryGetEntity(targetUid, out targetEnt); - // Check if interacted entity is in the same container, the direct child, or direct parent of the user. - if (targetEnt != null && !user.IsInSameOrParentContainer(targetEnt) && !CanAccessViaStorage(user.Uid, targetEnt.Uid)) + if (targetUid != default && !user.IsInSameOrParentContainer(targetUid) && !CanAccessViaStorage(user, targetUid)) { Logger.WarningS("system.interaction", - $"User entity named {user.Name} clicked on object {targetEnt.Name} that isn't the parent, child, or in the same container"); + $"User entity named {EntityManager.GetComponent(user).EntityName} clicked on object {EntityManager.GetComponent(targetUid).EntityName} that isn't the parent, child, or in the same container"); return; } @@ -480,16 +471,14 @@ namespace Content.Server.Interaction } // Verify user has a hand, and find what object they are currently holding in their active hand - if (user.TryGetComponent(out var hands)) + if (EntityManager.TryGetComponent(user, out var hands)) { - var item = hands.GetActiveHand?.Owner; - - if (item != null) + if (hands.GetActiveHand?.Owner is {Valid: true} item) { if (wideAttack) { var ev = new WideAttackEvent(item, user, coordinates); - RaiseLocalEvent(item.Uid, ev, false); + RaiseLocalEvent(item, ev, false); if (ev.Handled) { @@ -500,14 +489,14 @@ namespace Content.Server.Interaction else { var ev = new ClickAttackEvent(item, user, coordinates, targetUid); - RaiseLocalEvent(item.Uid, ev, false); + RaiseLocalEvent(item, ev, false); if (ev.Handled) { - if (targetEnt != null) + if (targetUid != default) { _adminLogSystem.Add(LogType.AttackArmedClick, LogImpact.Medium, - $"{user} attacked {targetEnt} with {item} at {coordinates}"); + $"{user} attacked {targetUid} with {item} at {coordinates}"); } else { @@ -519,12 +508,10 @@ namespace Content.Server.Interaction } } } - else if (!wideAttack && - (targetEnt != null || EntityManager.TryGetEntity(targetUid, out targetEnt)) && - targetEnt.HasComponent()) + else if (!wideAttack && targetUid != default && _entityManager.HasComponent(targetUid)) { // We pick up items if our hand is empty, even if we're in combat mode. - InteractHand(user, targetEnt); + InteractHand(user, targetUid); return; } } @@ -534,20 +521,20 @@ namespace Content.Server.Interaction if (wideAttack) { var ev = new WideAttackEvent(user, user, coordinates); - RaiseLocalEvent(user.Uid, ev, false); + RaiseLocalEvent(user, ev, false); if (ev.Handled) _adminLogSystem.Add(LogType.AttackUnarmedWide, $"{user} wide attacked at {coordinates}"); } else { var ev = new ClickAttackEvent(user, user, coordinates, targetUid); - RaiseLocalEvent(user.Uid, ev, false); + RaiseLocalEvent(user, ev, false); if (ev.Handled) { - if (targetEnt != null) + if (targetUid != default) { _adminLogSystem.Add(LogType.AttackUnarmedClick, LogImpact.Medium, - $"{user} attacked {targetEnt} at {coordinates}"); + $"{user} attacked {targetUid} at {coordinates}"); } else { diff --git a/Content.Server/Interaction/TilePryCommand.cs b/Content.Server/Interaction/TilePryCommand.cs index 39fa5f8de3..fd5845b669 100644 --- a/Content.Server/Interaction/TilePryCommand.cs +++ b/Content.Server/Interaction/TilePryCommand.cs @@ -4,6 +4,7 @@ using Content.Shared.Administration; using Content.Shared.Maps; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -15,6 +16,8 @@ namespace Content.Server.Interaction [AdminCommand(AdminFlags.Debug)] class TilePryCommand : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "tilepry"; public string Description => "Pries up all tiles in a radius around the user."; public string Help => $"Usage: {Command} "; @@ -22,7 +25,7 @@ namespace Content.Server.Interaction public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; - if (player?.AttachedEntity == null) + if (player?.AttachedEntity is not {} attached) { return; } @@ -46,9 +49,9 @@ namespace Content.Server.Interaction } var mapManager = IoCManager.Resolve(); - var playerGrid = player.AttachedEntity.Transform.GridID; + var playerGrid = _entities.GetComponent(attached).GridID; var mapGrid = mapManager.GetGrid(playerGrid); - var playerPosition = player.AttachedEntity.Transform.Coordinates; + var playerPosition = _entities.GetComponent(attached).Coordinates; var tileDefinitionManager = IoCManager.Resolve(); for (var i = -radius; i <= radius; i++) diff --git a/Content.Server/Inventory/Components/DebugEquipComponent.cs b/Content.Server/Inventory/Components/DebugEquipComponent.cs index e5c375cf3c..9f648aa886 100644 --- a/Content.Server/Inventory/Components/DebugEquipComponent.cs +++ b/Content.Server/Inventory/Components/DebugEquipComponent.cs @@ -2,6 +2,7 @@ using Content.Shared.Inventory; using Content.Shared.Popups; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Inventory.Components { @@ -12,26 +13,28 @@ namespace Content.Server.Inventory.Components [RegisterComponent] public class DebugEquipComponent : Component, IEquipped, IEquippedHand, IUnequipped, IUnequippedHand { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "DebugEquip"; void IEquipped.Equipped(EquippedEventArgs eventArgs) { - eventArgs.User.PopupMessage("equipped " + Owner.Name); + eventArgs.User.PopupMessage("equipped " + _entMan.GetComponent(Owner).EntityName); } void IEquippedHand.EquippedHand(EquippedHandEventArgs eventArgs) { - eventArgs.User.PopupMessage("equipped hand " + Owner.Name); + eventArgs.User.PopupMessage("equipped hand " + _entMan.GetComponent(Owner).EntityName); } void IUnequipped.Unequipped(UnequippedEventArgs eventArgs) { - eventArgs.User.PopupMessage("unequipped " + Owner.Name); + eventArgs.User.PopupMessage("unequipped " + _entMan.GetComponent(Owner).EntityName); } void IUnequippedHand.UnequippedHand(UnequippedHandEventArgs eventArgs) { - eventArgs.User.PopupMessage("unequipped hand" + Owner.Name); + eventArgs.User.PopupMessage("unequipped hand" + _entMan.GetComponent(Owner).EntityName); } } } diff --git a/Content.Server/Inventory/Components/HumanInventoryControllerComponent.cs b/Content.Server/Inventory/Components/HumanInventoryControllerComponent.cs index 9f324f7514..6fc56584b2 100644 --- a/Content.Server/Inventory/Components/HumanInventoryControllerComponent.cs +++ b/Content.Server/Inventory/Components/HumanInventoryControllerComponent.cs @@ -1,8 +1,8 @@ using System.Diagnostics.CodeAnalysis; using Content.Server.Items; using Content.Shared.Item; -using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using static Content.Shared.Inventory.EquipmentSlotDefines; @@ -24,7 +24,7 @@ namespace Content.Server.Inventory.Components _inventory = Owner.EnsureComponent(); } - bool IInventoryController.CanEquip(Slots slot, IEntity entity, bool flagsCheck, [NotNullWhen(false)] out string? reason) + bool IInventoryController.CanEquip(Slots slot, EntityUid entity, bool flagsCheck, [NotNullWhen(false)] out string? reason) { var slotMask = SlotMasks[slot]; reason = null; @@ -42,7 +42,7 @@ namespace Content.Server.Inventory.Components if (slotMask == SlotFlags.POCKET) { - var itemComponent = entity.GetComponent(); + var itemComponent = IoCManager.Resolve().GetComponent(entity); // If this item is small enough then it always fits in pockets. if (itemComponent.Size <= (int) ReferenceSizes.Pocket) diff --git a/Content.Server/Inventory/Components/IInventoryController.cs b/Content.Server/Inventory/Components/IInventoryController.cs index bd980e3b4f..b55db7da67 100644 --- a/Content.Server/Inventory/Components/IInventoryController.cs +++ b/Content.Server/Inventory/Components/IInventoryController.cs @@ -17,12 +17,12 @@ namespace Content.Server.Inventory.Components /// Whether the entity passes default slot masks & flags checks. /// The translated reason why the item cannot be equiped, if this function returns false. Can be null. /// True if the entity can be equipped, false otherwise - bool CanEquip(Slots slot, IEntity entity, bool flagsCheck, [NotNullWhen(false)] out string? reason) + bool CanEquip(Slots slot, EntityUid entity, bool flagsCheck, [NotNullWhen(false)] out string? reason) { reason = null; return flagsCheck; } - bool CanEquip(Slots slot, IEntity entity, bool flagsCheck) => CanEquip(slot, entity, flagsCheck, out _); + bool CanEquip(Slots slot, EntityUid entity, bool flagsCheck) => CanEquip(slot, entity, flagsCheck, out _); } } diff --git a/Content.Server/Inventory/Components/InventoryComponent.cs b/Content.Server/Inventory/Components/InventoryComponent.cs index b8413fbce6..f0aade547d 100644 --- a/Content.Server/Inventory/Components/InventoryComponent.cs +++ b/Content.Server/Inventory/Components/InventoryComponent.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using Content.Server.Administration.Commands; using Content.Server.Clothing.Components; using Content.Server.Hands.Components; using Content.Server.Interaction; @@ -11,15 +10,9 @@ using Content.Server.Storage.Components; using Content.Shared.ActionBlocker; using Content.Shared.Acts; using Content.Shared.Inventory; -using Content.Shared.Movement.Components; using Content.Shared.Movement.EntitySystems; using Content.Shared.Popups; -using Content.Shared.Verbs; -using Robust.Server.Console; -using Robust.Server.GameObjects; -using Robust.Server.Player; using Robust.Shared.Audio; -using Robust.Shared.Console; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -39,6 +32,7 @@ namespace Content.Server.Inventory.Components public class InventoryComponent : SharedInventoryComponent, IExAct { [Dependency] private readonly IEntitySystemManager _entitySystemManager = default!; + [Dependency] private readonly IEntityManager _entities = default!; [ViewVariables] private readonly Dictionary _slotContainers = new(); @@ -69,7 +63,7 @@ namespace Content.Server.Inventory.Components { if (TryGetSlotItem(slot, out ItemComponent? item)) { - item.Owner.Delete(); + _entities.DeleteEntity(item.Owner); } RemoveSlot(slot); @@ -78,7 +72,7 @@ namespace Content.Server.Inventory.Components base.OnRemove(); } - public IEnumerable GetAllHeldItems() + public IEnumerable GetAllHeldItems() { foreach (var (_, container) in _slotContainers) { @@ -112,7 +106,7 @@ namespace Content.Server.Inventory.Components public IEnumerable LookupItems() where T : Component { return _slotContainers.Values - .SelectMany(x => x.ContainedEntities.Select(e => e.GetComponentOrNull())) + .SelectMany(x => x.ContainedEntities.Select(e => _entities.GetComponentOrNull(e))) .Where(x => x != null); } @@ -124,14 +118,14 @@ namespace Content.Server.Inventory.Components } var containedEntity = _slotContainers[slot].ContainedEntity; - if (containedEntity?.Deleted == true) + if (containedEntity != null && _entities.GetComponent(containedEntity.Value).EntityDeleted) { _slotContainers.Remove(slot); containedEntity = null; Dirty(); } - return containedEntity?.GetComponent(); + return containedEntity.HasValue ? _entities.GetComponent(containedEntity.Value) : null; } public bool TryGetSlotItem(Slots slot, [NotNullWhen(true)] out T? itemComponent) where T : ItemComponent @@ -192,8 +186,8 @@ namespace Content.Server.Inventory.Components public bool Equip(Slots slot, ItemComponent item, bool mobCheck = true) => Equip(slot, item, mobCheck, out var _); - public bool Equip(Slots slot, IEntity entity, bool mobCheck = true) => - Equip(slot, entity.GetComponent(), mobCheck); + public bool Equip(Slots slot, EntityUid entity, bool mobCheck = true) => + Equip(slot, _entities.GetComponent(entity), mobCheck); /// /// Checks whether an item can be put in the specified slot. @@ -207,7 +201,7 @@ namespace Content.Server.Inventory.Components var pass = false; reason = null; - if (mobCheck && !EntitySystem.Get().CanEquip(OwnerUid)) + if (mobCheck && !EntitySystem.Get().CanEquip(Owner)) { reason = Loc.GetString("inventory-component-can-equip-cannot"); return false; @@ -225,7 +219,7 @@ namespace Content.Server.Inventory.Components } } - if (Owner.TryGetComponent(out IInventoryController? controller)) + if (_entities.TryGetComponent(Owner, out IInventoryController? controller)) { pass = controller.CanEquip(slot, item.Owner, pass, out var controllerReason); reason = controllerReason ?? reason; @@ -250,8 +244,8 @@ namespace Content.Server.Inventory.Components public bool CanEquip(Slots slot, ItemComponent item, bool mobCheck = true) => CanEquip(slot, item, mobCheck, out var _); - public bool CanEquip(Slots slot, IEntity entity, bool mobCheck = true) => - CanEquip(slot, entity.GetComponent(), mobCheck); + public bool CanEquip(Slots slot, EntityUid entity, bool mobCheck = true) => + CanEquip(slot, _entities.GetComponent(entity), mobCheck); /// /// Drops the item in a slot. @@ -267,9 +261,8 @@ namespace Content.Server.Inventory.Components } var inventorySlot = _slotContainers[slot]; - var entity = inventorySlot.ContainedEntity; - if (entity == null) + if (inventorySlot.ContainedEntity is not {Valid: true} entity) { return false; } @@ -280,7 +273,7 @@ namespace Content.Server.Inventory.Components } // TODO: The item should be dropped to the container our owner is in, if any. - entity.Transform.AttachParentToContainerOrGrid(); + _entities.GetComponent(entity).AttachParentToContainerOrGrid(); _entitySystemManager.GetEntitySystem().UnequippedInteraction(Owner, entity, slot); @@ -295,22 +288,21 @@ namespace Content.Server.Inventory.Components private void UpdateMovementSpeed() { - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); } public void ForceUnequip(Slots slot) { var inventorySlot = _slotContainers[slot]; - var entity = inventorySlot.ContainedEntity; - if (entity == null) + if (inventorySlot.ContainedEntity is not {Valid: true} entity) { return; } - var item = entity.GetComponent(); + var item = _entities.GetComponent(entity); inventorySlot.ForceRemove(entity); - var itemTransform = entity.Transform; + var itemTransform = _entities.GetComponent(entity); itemTransform.AttachParentToContainerOrGrid(); @@ -331,11 +323,11 @@ namespace Content.Server.Inventory.Components /// public bool CanUnequip(Slots slot, bool mobCheck = true) { - if (mobCheck && !EntitySystem.Get().CanUnequip(OwnerUid)) + if (mobCheck && !EntitySystem.Get().CanUnequip(Owner)) return false; var inventorySlot = _slotContainers[slot]; - return inventorySlot.ContainedEntity != null && inventorySlot.CanRemove(inventorySlot.ContainedEntity); + return inventorySlot.ContainedEntity != null && inventorySlot.CanRemove(inventorySlot.ContainedEntity.Value); } /// @@ -403,7 +395,7 @@ namespace Content.Server.Inventory.Components /// The underlying Container System just notified us that an entity was removed from it. /// We need to make sure we process that removed entity as being unequipped from the slot. /// - public void ForceUnequip(IContainer container, IEntity entity) + public void ForceUnequip(IContainer container, EntityUid entity) { // make sure this is one of our containers. // Technically the correct way would be to enumerate the possible slot names @@ -411,7 +403,7 @@ namespace Content.Server.Inventory.Components if (container is not ContainerSlot slot || !_slotContainers.ContainsValue(slot)) return; - if (entity.TryGetComponent(out ItemComponent? itemComp)) + if (_entities.TryGetComponent(entity, out ItemComponent? itemComp)) { itemComp.RemovedFromSlot(); } @@ -431,10 +423,10 @@ namespace Content.Server.Inventory.Components { case ClientInventoryUpdate.Equip: { - var hands = Owner.GetComponent(); + var hands = _entities.GetComponent(Owner); var activeHand = hands.ActiveHand; var activeItem = hands.GetActiveHand; - if (activeHand != null && activeItem != null && activeItem.Owner.TryGetComponent(out ItemComponent? item)) + if (activeHand != null && activeItem != null && _entities.TryGetComponent(activeItem.Owner, out ItemComponent? item)) { hands.TryDropNoInteraction(); if (!Equip(msg.Inventoryslot, item, true, out var reason)) @@ -449,7 +441,7 @@ namespace Content.Server.Inventory.Components case ClientInventoryUpdate.Use: { var interactionSystem = _entitySystemManager.GetEntitySystem(); - var hands = Owner.GetComponent(); + var hands = _entities.GetComponent(Owner); var activeHand = hands.GetActiveHand; var itemContainedInSlot = GetSlotItem(msg.Inventoryslot); if (itemContainedInSlot != null) @@ -469,14 +461,14 @@ namespace Content.Server.Inventory.Components } case ClientInventoryUpdate.Hover: { - var hands = Owner.GetComponent(); + var hands = _entities.GetComponent(Owner); var activeHand = hands.GetActiveHand; if (activeHand != null && GetSlotItem(msg.Inventoryslot) == null) { var canEquip = CanEquip(msg.Inventoryslot, activeHand, true, out var reason); _hoverEntity = new KeyValuePair(msg.Inventoryslot, - (activeHand.Owner.Uid, canEquip)); + (Uid: activeHand.Owner, canEquip)); Dirty(); } @@ -511,7 +503,7 @@ namespace Content.Server.Inventory.Components if (!HasSlot(msg.Slot)) // client input sanitization return; var item = GetSlotItem(msg.Slot); - if (item != null && item.Owner.TryGetComponent(out ServerStorageComponent? storage)) + if (item != null && _entities.TryGetComponent(item.Owner, out ServerStorageComponent? storage)) storage.OpenStorageUI(Owner); break; } @@ -522,9 +514,9 @@ namespace Content.Server.Inventory.Components var list = new List>(); foreach (var (slot, container) in _slotContainers) { - if (container != null && container.ContainedEntity != null) + if (container is {ContainedEntity: { }}) { - list.Add(new KeyValuePair(slot, container.ContainedEntity.Uid)); + list.Add(new KeyValuePair(slot, container.ContainedEntity.Value)); } } @@ -545,7 +537,7 @@ namespace Content.Server.Inventory.Components { foreach (var entity in slot.ContainedEntities) { - var exActs = entity.GetAllComponents().ToList(); + var exActs = _entities.GetComponents(entity).ToList(); foreach (var exAct in exActs) { exAct.OnExplosion(eventArgs); @@ -554,9 +546,9 @@ namespace Content.Server.Inventory.Components } } - public override bool IsEquipped(IEntity item) + public override bool IsEquipped(EntityUid item) { - if (item == null) return false; + if (item == default) return false; foreach (var containerSlot in _slotContainers.Values) { // we don't want a recursive check here diff --git a/Content.Server/Inventory/InventoryHelpers.cs b/Content.Server/Inventory/InventoryHelpers.cs index 30a07de4bc..821fdfdd51 100644 --- a/Content.Server/Inventory/InventoryHelpers.cs +++ b/Content.Server/Inventory/InventoryHelpers.cs @@ -1,5 +1,6 @@ using Content.Server.Inventory.Components; using Content.Server.Items; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Prototypes; using static Content.Shared.Inventory.EquipmentSlotDefines; @@ -10,12 +11,12 @@ namespace Content.Server.Inventory { public static bool SpawnItemInSlot(this InventoryComponent inventory, Slots slot, string prototype, bool mobCheck = false) { - var entityManager = inventory.Owner.EntityManager; + var entityManager = IoCManager.Resolve(); var protoManager = IoCManager.Resolve(); var user = inventory.Owner; // Let's do nothing if the owner of the inventory has been deleted. - if (user.Deleted) + if (entityManager.Deleted(user)) return false; // If we don't have that slot or there's already an item there, we do nothing. @@ -27,17 +28,17 @@ namespace Content.Server.Inventory return false; // Let's spawn this first... - var item = entityManager.SpawnEntity(prototype, user.Transform.MapPosition); + var item = entityManager.SpawnEntity(prototype, entityManager.GetComponent(user).MapPosition); // Helper method that deletes the item and returns false. bool DeleteItem() { - item.Delete(); + entityManager.DeleteEntity(item); return false; } // If this doesn't have an item component, then we can't do anything with it. - if (!item.TryGetComponent(out ItemComponent? itemComp)) + if (!entityManager.TryGetComponent(item, out ItemComponent? itemComp)) return DeleteItem(); // We finally try to equip the item, otherwise we delete it. diff --git a/Content.Server/Inventory/InventorySystem.cs b/Content.Server/Inventory/InventorySystem.cs index 75514455c4..52344adcdd 100644 --- a/Content.Server/Inventory/InventorySystem.cs +++ b/Content.Server/Inventory/InventorySystem.cs @@ -38,7 +38,7 @@ namespace Content.Server.Inventory { if (component.TryGetSlotItem(EquipmentSlotDefines.Slots.SHOES, out ItemComponent? shoes)) { - RaiseLocalEvent(shoes.Owner.Uid, args, false); + RaiseLocalEvent(shoes.Owner, args, false); } } @@ -81,7 +81,7 @@ namespace Content.Server.Inventory { foreach (var equipped in component.GetAllHeldItems()) { - RaiseLocalEvent(equipped.Uid, args, false); + RaiseLocalEvent(equipped, args, false); } } } diff --git a/Content.Server/Items/ItemComponent.cs b/Content.Server/Items/ItemComponent.cs index 63c5fad6a2..d33ab54562 100644 --- a/Content.Server/Items/ItemComponent.cs +++ b/Content.Server/Items/ItemComponent.cs @@ -1,6 +1,8 @@ +using System.Collections.Generic; using Content.Shared.Item; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Items { @@ -10,7 +12,7 @@ namespace Content.Server.Items { public override void RemovedFromSlot() { - foreach (var component in Owner.GetAllComponents()) + foreach (var component in IoCManager.Resolve().GetComponents(Owner)) { component.Visible = true; } @@ -18,7 +20,7 @@ namespace Content.Server.Items public override void EquippedToSlot() { - foreach (var component in Owner.GetAllComponents()) + foreach (var component in IoCManager.Resolve().GetComponents(Owner)) { component.Visible = false; } diff --git a/Content.Server/Jobs/AddComponentSpecial.cs b/Content.Server/Jobs/AddComponentSpecial.cs index a7d9f0eeb7..b154a52c80 100644 --- a/Content.Server/Jobs/AddComponentSpecial.cs +++ b/Content.Server/Jobs/AddComponentSpecial.cs @@ -1,4 +1,3 @@ -using Content.Server.Interaction.Components; using Content.Shared.Roles; using JetBrains.Annotations; using Robust.Shared.GameObjects; @@ -14,7 +13,7 @@ namespace Content.Server.Jobs [DataField("component", required:true)] public string Component { get; } = string.Empty; - public override void AfterEquip(IEntity mob) + public override void AfterEquip(EntityUid mob) { // Yes, this will throw if your component is invalid. var component = (Component)IoCManager.Resolve().GetComponent(Component); diff --git a/Content.Server/Jobs/GiveItemOnHolidaySpecial.cs b/Content.Server/Jobs/GiveItemOnHolidaySpecial.cs index cea9a1df19..59dc087740 100644 --- a/Content.Server/Jobs/GiveItemOnHolidaySpecial.cs +++ b/Content.Server/Jobs/GiveItemOnHolidaySpecial.cs @@ -1,6 +1,5 @@ using Content.Server.Hands.Components; using Content.Server.Holiday; -using Content.Server.Holiday.Interfaces; using Content.Server.Items; using Content.Shared.Roles; using JetBrains.Annotations; @@ -22,7 +21,7 @@ namespace Content.Server.Jobs [DataField("prototype", customTypeSerializer:typeof(PrototypeIdSerializer))] public string Prototype { get; } = string.Empty; - public override void AfterEquip(IEntity mob) + public override void AfterEquip(EntityUid mob) { if (string.IsNullOrEmpty(Holiday) || string.IsNullOrEmpty(Prototype)) return; @@ -30,9 +29,11 @@ namespace Content.Server.Jobs if (!EntitySystem.Get().IsCurrentlyHoliday(Holiday)) return; - var entity = mob.EntityManager.SpawnEntity(Prototype, mob.Transform.Coordinates); + var entMan = IoCManager.Resolve(); - if (!entity.TryGetComponent(out ItemComponent? item) || !mob.TryGetComponent(out HandsComponent? hands)) + var entity = entMan.SpawnEntity(Prototype, entMan.GetComponent(mob).Coordinates); + + if (!entMan.TryGetComponent(entity, out ItemComponent? item) || !entMan.TryGetComponent(mob, out HandsComponent? hands)) return; hands.PutInHand(item, false); diff --git a/Content.Server/Kitchen/Components/KitchenSpikeComponent.cs b/Content.Server/Kitchen/Components/KitchenSpikeComponent.cs index 0b140ff68d..11802518ee 100644 --- a/Content.Server/Kitchen/Components/KitchenSpikeComponent.cs +++ b/Content.Server/Kitchen/Components/KitchenSpikeComponent.cs @@ -12,6 +12,7 @@ using Content.Shared.Nutrition.Components; using Content.Shared.Popups; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; @@ -21,6 +22,8 @@ namespace Content.Server.Kitchen.Components [ComponentReference(typeof(IActivate))] public class KitchenSpikeComponent : SharedKitchenSpikeComponent, IActivate, ISuicideAct { + [Dependency] private readonly IEntityManager _entMan = default!; + private int _meatParts; private string? _meatPrototype; private string _meatSource1p = "?"; @@ -39,8 +42,8 @@ namespace Content.Server.Kitchen.Components if (!string.IsNullOrEmpty(_meatPrototype)) { - var meat = Owner.EntityManager.SpawnEntity(_meatPrototype, Owner.Transform.Coordinates); - meat.Name = _meatName; + var meat = _entMan.SpawnEntity(_meatPrototype, _entMan.GetComponent(Owner).Coordinates); + _entMan.GetComponent(meat).EntityName = _meatName; } if (_meatParts != 0) @@ -66,13 +69,13 @@ namespace Content.Server.Kitchen.Components private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(KitchenSpikeVisuals.Status, (_meatParts > 0) ? KitchenSpikeStatus.Bloody : KitchenSpikeStatus.Empty); } } - private bool Spikeable(IEntity user, IEntity victim, [NotNullWhen(true)] out SharedButcherableComponent? butcherable) + private bool Spikeable(EntityUid user, EntityUid victim, [NotNullWhen(true)] out SharedButcherableComponent? butcherable) { butcherable = null; @@ -82,7 +85,7 @@ namespace Content.Server.Kitchen.Components return false; } - if (!victim.TryGetComponent(out butcherable)) + if (!_entMan.TryGetComponent(victim, out butcherable)) { Owner.PopupMessage(user, Loc.GetString("comp-kitchen-spike-deny-butcher", ("victim", victim), ("this", Owner))); return false; @@ -94,9 +97,9 @@ namespace Content.Server.Kitchen.Components return true; } - public async void TrySpike(IEntity victim, IEntity user) + public async void TrySpike(EntityUid victim, EntityUid user) { - var victimUid = victim.Uid; + var victimUid = (EntityUid) victim; if (_beingButchered.Contains(victimUid)) return; SharedButcherableComponent? butcherable; @@ -105,7 +108,7 @@ namespace Content.Server.Kitchen.Components return; // Prevent dead from being spiked TODO: Maybe remove when rounds can be played and DOT is implemented - if (victim.TryGetComponent(out var state) && + if (_entMan.TryGetComponent(victim, out var state) && !state.IsDead()) { Owner.PopupMessage(user, Loc.GetString("comp-kitchen-spike-deny-not-dead", ("victim", victim))); @@ -153,12 +156,12 @@ namespace Content.Server.Kitchen.Components Owner.PopupMessageEveryone(Loc.GetString("comp-kitchen-spike-kill", ("user", user), ("victim", victim))); // TODO: Need to be able to leave them on the spike to do DoT, see ss13. - victim.Delete(); + _entMan.DeleteEntity((EntityUid) victim); SoundSystem.Play(Filter.Pvs(Owner), SpikeSound.GetSound(), Owner); } - SuicideKind ISuicideAct.Suicide(IEntity victim, IChatManager chat) + SuicideKind ISuicideAct.Suicide(EntityUid victim, IChatManager chat) { var othersMessage = Loc.GetString("comp-kitchen-spike-suicide-other", ("victim", victim)); victim.PopupMessageOtherClients(othersMessage); diff --git a/Content.Server/Kitchen/Components/MicrowaveComponent.cs b/Content.Server/Kitchen/Components/MicrowaveComponent.cs index f86613b5f5..714ce9c912 100644 --- a/Content.Server/Kitchen/Components/MicrowaveComponent.cs +++ b/Content.Server/Kitchen/Components/MicrowaveComponent.cs @@ -14,7 +14,6 @@ using Content.Shared.Acts; using Content.Shared.Body.Components; using Content.Shared.Body.Part; using Content.Shared.Chemistry.Components; -using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Kitchen; @@ -38,6 +37,8 @@ namespace Content.Server.Kitchen.Components [ComponentReference(typeof(IActivate))] public class MicrowaveComponent : SharedMicrowaveComponent, IActivate, IInteractUsing, ISuicideAct, IBreakAct { + [Dependency] private readonly IEntityManager _entities = default!; + [Dependency] private readonly RecipeManager _recipeManager = default!; #region YAMLSERIALIZE @@ -67,10 +68,10 @@ namespace Content.Server.Kitchen.Components /// [ViewVariables] private uint _currentCookTimerTime = 1; - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; private bool HasContents => EntitySystem.Get() - .TryGetSolution(Owner.Uid, SolutionName, out var solution) && + .TryGetSolution(Owner, SolutionName, out var solution) && (solution.Contents.Count > 0 || _storage.ContainedEntities.Count > 0); private bool _uiDirty = true; @@ -93,7 +94,7 @@ namespace Content.Server.Kitchen.Components _currentCookTimerTime = _cookTimeDefault; - EntitySystem.Get().EnsureSolution(Owner.Uid, SolutionName); + EntitySystem.Get().EnsureSolution(Owner, SolutionName); _storage = ContainerHelpers.EnsureContainer(Owner, "microwave_entity_container", out _); @@ -183,12 +184,12 @@ namespace Content.Server.Kitchen.Components } if (_uiDirty && EntitySystem.Get() - .TryGetSolution(Owner.Uid, SolutionName, out var solution)) + .TryGetSolution(Owner, SolutionName, out var solution)) { UserInterface?.SetState(new MicrowaveUpdateUserInterfaceState ( solution.Contents.ToArray(), - _storage.ContainedEntities.Select(item => item.Uid).ToArray(), + _storage.ContainedEntities.Select(item => item).ToArray(), _busy, _currentCookTimeButtonIndex, _currentCookTimerTime @@ -205,7 +206,7 @@ namespace Content.Server.Kitchen.Components finalState = MicrowaveVisualState.Broken; } - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(PowerDeviceVisuals.VisualState, finalState); } @@ -219,7 +220,7 @@ namespace Content.Server.Kitchen.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor) || !Powered) + if (!_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor) || !Powered) { return; } @@ -242,23 +243,21 @@ namespace Content.Server.Kitchen.Components return false; } - var itemEntity = eventArgs.User.GetComponent().GetActiveHand?.Owner; - - if (itemEntity == null) + if (_entities.GetComponent(eventArgs.User).GetActiveHand?.Owner is not {Valid: true} itemEntity) { eventArgs.User.PopupMessage(Loc.GetString("microwave-component-interact-using-no-active-hand")); return false; } - if (itemEntity.TryGetComponent(out var attackPourable)) + if (_entities.TryGetComponent(itemEntity, out var attackPourable)) { var solutionsSystem = EntitySystem.Get(); - if (!solutionsSystem.TryGetDrainableSolution(itemEntity.Uid, out var attackSolution)) + if (!solutionsSystem.TryGetDrainableSolution(itemEntity, out var attackSolution)) { return false; } - if (!solutionsSystem.TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (!solutionsSystem.TryGetSolution(Owner, SolutionName, out var solution)) { return false; } @@ -274,8 +273,8 @@ namespace Content.Server.Kitchen.Components //Move units from attackSolution to targetSolution var removedSolution = EntitySystem.Get() - .Drain(itemEntity.Uid, attackSolution, realTransferAmount); - if (!EntitySystem.Get().TryAddSolution(Owner.Uid, solution, removedSolution)) + .Drain(itemEntity, attackSolution, realTransferAmount); + if (!EntitySystem.Get().TryAddSolution(Owner, solution, removedSolution)) { return false; } @@ -285,7 +284,7 @@ namespace Content.Server.Kitchen.Components return true; } - if (!itemEntity.TryGetComponent(typeof(ItemComponent), out var food)) + if (!_entities.TryGetComponent(itemEntity, typeof(ItemComponent), out var food)) { Owner.PopupMessage(eventArgs.User, "microwave-component-interact-using-transfer-fail"); return false; @@ -311,18 +310,19 @@ namespace Content.Server.Kitchen.Components var solidsDict = new Dictionary(); foreach (var item in _storage.ContainedEntities) { - if (item.Prototype == null) + var metaData = _entities.GetComponent(item); + if (metaData.EntityPrototype == null) { continue; } - if (solidsDict.ContainsKey(item.Prototype.ID)) + if (solidsDict.ContainsKey(metaData.EntityPrototype.ID)) { - solidsDict[item.Prototype.ID]++; + solidsDict[metaData.EntityPrototype.ID]++; } else { - solidsDict.Add(item.Prototype.ID, 1); + solidsDict.Add(metaData.EntityPrototype.ID, 1); } } @@ -365,13 +365,13 @@ namespace Content.Server.Kitchen.Components if (recipeToCook != null) { SubtractContents(recipeToCook); - Owner.EntityManager.SpawnEntity(recipeToCook.Result, Owner.Transform.Coordinates); + _entities.SpawnEntity(recipeToCook.Result, _entities.GetComponent(Owner).Coordinates); } else { VaporizeReagents(); VaporizeSolids(); - Owner.EntityManager.SpawnEntity(_badRecipeName, Owner.Transform.Coordinates); + _entities.SpawnEntity(_badRecipeName, _entities.GetComponent(Owner).Coordinates); } } @@ -389,18 +389,18 @@ namespace Content.Server.Kitchen.Components private void VaporizeReagents() { - if (EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { - EntitySystem.Get().RemoveAllSolution(Owner.Uid, solution); + EntitySystem.Get().RemoveAllSolution(Owner, solution); } } private void VaporizeReagentQuantity(Solution.ReagentQuantity reagentQuantity) { - if (EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { EntitySystem.Get() - .TryRemoveReagent(Owner.Uid, solution, reagentQuantity.ReagentId, reagentQuantity.Quantity); + .TryRemoveReagent(Owner, solution, reagentQuantity.ReagentId, reagentQuantity.Quantity); } } @@ -410,7 +410,7 @@ namespace Content.Server.Kitchen.Components { var item = _storage.ContainedEntities.ElementAt(i); _storage.Remove(item); - item.Delete(); + _entities.DeleteEntity(item); } } @@ -424,16 +424,16 @@ namespace Content.Server.Kitchen.Components private void EjectSolid(EntityUid entityId) { - if (Owner.EntityManager.EntityExists(entityId)) + if (_entities.EntityExists(entityId)) { - _storage.Remove(Owner.EntityManager.GetEntity(entityId)); + _storage.Remove(entityId); } } private void SubtractContents(FoodRecipePrototype recipe) { - var solutionUid = Owner.Uid; - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + var solutionUid = Owner; + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { return; } @@ -450,15 +450,16 @@ namespace Content.Server.Kitchen.Components { foreach (var item in _storage.ContainedEntities) { - if (item.Prototype == null) + var metaData = _entities.GetComponent(item); + if (metaData.EntityPrototype == null) { continue; } - if (item.Prototype.ID == recipeSolid.Key) + if (metaData.EntityPrototype.ID == recipeSolid.Key) { _storage.Remove(item); - item.Delete(); + _entities.DeleteEntity(item); break; } } @@ -468,12 +469,12 @@ namespace Content.Server.Kitchen.Components private MicrowaveSuccessState CanSatisfyRecipe(FoodRecipePrototype recipe, Dictionary solids) { - if (_currentCookTimerTime != (uint) recipe.CookTime) + if (_currentCookTimerTime != recipe.CookTime) { return MicrowaveSuccessState.RecipeFail; } - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { return MicrowaveSuccessState.RecipeFail; } @@ -512,11 +513,11 @@ namespace Content.Server.Kitchen.Components SoundSystem.Play(Filter.Pvs(Owner), _clickSound.GetSound(), Owner, AudioParams.Default.WithVolume(-2f)); } - SuicideKind ISuicideAct.Suicide(IEntity victim, IChatManager chat) + SuicideKind ISuicideAct.Suicide(EntityUid victim, IChatManager chat) { var headCount = 0; - if (victim.TryGetComponent(out var body)) + if (_entities.TryGetComponent(victim, out var body)) { var headSlots = body.GetSlotsOfType(BodyPartType.Head); diff --git a/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs b/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs index 4da12644d6..6062145c5f 100644 --- a/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs +++ b/Content.Server/Kitchen/EntitySystems/ReagentGrinderSystem.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Content.Server.Chemistry.EntitySystems; using Content.Server.Hands.Components; @@ -54,7 +53,7 @@ namespace Content.Server.Kitchen.EntitySystems { if (args.Handled) return; - if (!args.User.HasComponent()) + if (!EntityManager.HasComponent(args.User)) { component.Owner.PopupMessage(args.User, Loc.GetString("reagent-grinder-component-interact-using-no-hands")); @@ -62,18 +61,18 @@ namespace Content.Server.Kitchen.EntitySystems return; } - IEntity heldEnt = args.Used; + var heldEnt = args.Used; // First, check if user is trying to insert a beaker. // No promise it will be a beaker right now, but whatever. // Maybe this should whitelist "beaker" in the prototype id of heldEnt? - if (_solutionsSystem.TryGetFitsInDispenser(heldEnt.Uid, out var beaker)) + if (_solutionsSystem.TryGetFitsInDispenser(heldEnt, out var beaker)) { component.BeakerContainer.Insert(heldEnt); component.HeldBeaker = beaker; EnqueueUiUpdate(component); //We are done, return. Insert the beaker and exit! - if (component.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearance)) { appearance.SetData(SharedReagentGrinderComponent.ReagentGrinderVisualState.BeakerAttached, component.BeakerContainer.ContainedEntity != null); @@ -85,7 +84,7 @@ namespace Content.Server.Kitchen.EntitySystems } //Next, see if the user is trying to insert something they want to be ground/juiced. - if (!heldEnt.TryGetComponent(out ExtractableComponent? juice)) + if (!EntityManager.TryGetComponent(heldEnt, out ExtractableComponent? juice)) { //Entity did NOT pass the whitelist for grind/juice. //Wouldn't want the clown grinding up the Captain's ID card now would you? @@ -113,7 +112,7 @@ namespace Content.Server.Kitchen.EntitySystems { if (args.Handled) return; - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) { return; } @@ -153,7 +152,7 @@ namespace Content.Server.Kitchen.EntitySystems private void OnUIMessageReceived(EntityUid uid, ReagentGrinderComponent component, ServerBoundUserInterfaceMessage message) { - if (component.Busy) + if (component.Busy || message.Session.AttachedEntity is not {} attached) { return; } @@ -161,18 +160,18 @@ namespace Content.Server.Kitchen.EntitySystems switch (message.Message) { case SharedReagentGrinderComponent.ReagentGrinderGrindStartMessage msg: - if (!component.Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || + if (!EntityManager.TryGetComponent(component.Owner, out ApcPowerReceiverComponent? receiver) || !receiver.Powered) break; ClickSound(component); - DoWork(component, message.Session.AttachedEntity!, + DoWork(component, attached, SharedReagentGrinderComponent.GrinderProgram.Grind); break; case SharedReagentGrinderComponent.ReagentGrinderJuiceStartMessage msg: - if (!component.Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver2) || + if (!EntityManager.TryGetComponent(component.Owner, out ApcPowerReceiverComponent? receiver2) || !receiver2.Powered) break; ClickSound(component); - DoWork(component, message.Session.AttachedEntity!, + DoWork(component, attached, SharedReagentGrinderComponent.GrinderProgram.Juice); break; @@ -193,10 +192,10 @@ namespace Content.Server.Kitchen.EntitySystems break; case SharedReagentGrinderComponent.ReagentGrinderEjectChamberContentMessage msg: - if (component.Chamber.ContainedEntities.TryFirstOrDefault(x => x.Uid == msg.EntityID, out var ent)) + if (component.Chamber.ContainedEntities.TryFirstOrNull(x => x == msg.EntityID, out var ent)) { - component.Chamber.Remove(ent); - ent.RandomOffset(0.4f); + component.Chamber.Remove(ent.Value); + SharedEntityExtensions.RandomOffset(ent.Value, 0.4f); EnqueueUiUpdate(component); ClickSound(component); } @@ -226,11 +225,11 @@ namespace Content.Server.Kitchen.EntitySystems { foreach (var entity in comp.Chamber.ContainedEntities) { - if (canJuice || !entity.TryGetComponent(out ExtractableComponent? component)) continue; + if (canJuice || !EntityManager.TryGetComponent(entity, out ExtractableComponent? component)) continue; canJuice = component.JuiceSolution != null; canGrind = component.GrindableSolution != null - && _solutionsSystem.TryGetSolution(entity.Uid, component.GrindableSolution, out _); + && _solutionsSystem.TryGetSolution(entity, component.GrindableSolution, out _); } } @@ -239,10 +238,10 @@ namespace Content.Server.Kitchen.EntitySystems ( comp.Busy, comp.BeakerContainer.ContainedEntity != null, - comp.Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) && receiver.Powered, + EntityManager.TryGetComponent(comp.Owner, out ApcPowerReceiverComponent? receiver) && receiver.Powered, canJuice, canGrind, - comp.Chamber.ContainedEntities.Select(item => item.Uid).ToArray(), + comp.Chamber.ContainedEntities.Select(item => item).ToArray(), //Remember the beaker can be null! comp.HeldBeaker?.Contents.ToArray() )); @@ -253,25 +252,26 @@ namespace Content.Server.Kitchen.EntitySystems /// Tries to eject whatever is in the beaker slot. Puts the item in the user's hands or failing that on top /// of the grinder. /// - private void EjectBeaker(ReagentGrinderComponent component, IEntity? user) + private void EjectBeaker(ReagentGrinderComponent component, EntityUid? user) { if (component.BeakerContainer.ContainedEntity == null || component.HeldBeaker == null || component.Busy) return; - var beaker = component.BeakerContainer.ContainedEntity; - if (beaker is null) + if (component.BeakerContainer.ContainedEntity is not {Valid: true} beaker) return; component.BeakerContainer.Remove(beaker); - if (user == null || !user.TryGetComponent(out var hands) || - !beaker.TryGetComponent(out var item)) + if (user == null || + !EntityManager.TryGetComponent(user.Value, out var hands) || + !EntityManager.TryGetComponent(beaker, out var item)) return; + hands.PutInHandOrDrop(item); component.HeldBeaker = null; EnqueueUiUpdate(component); - if (component.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearance)) { appearance.SetData(SharedReagentGrinderComponent.ReagentGrinderVisualState.BeakerAttached, component.BeakerContainer.ContainedEntity != null); @@ -282,11 +282,11 @@ namespace Content.Server.Kitchen.EntitySystems /// The wzhzhzh of the grinder. Processes the contents of the grinder and puts the output in the beaker. /// /// true for wanting to juice, false for wanting to grind. - private void DoWork(ReagentGrinderComponent component, IEntity user, + private void DoWork(ReagentGrinderComponent component, EntityUid user, SharedReagentGrinderComponent.GrinderProgram program) { //Have power, are we busy, chamber has anything to grind, a beaker for the grounds to go? - if (!component.Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || !receiver.Powered || + if (!EntityManager.TryGetComponent(component.Owner, out ApcPowerReceiverComponent? receiver) || !receiver.Powered || component.Busy || component.Chamber.ContainedEntities.Count <= 0 || component.BeakerContainer.ContainedEntity == null || component.HeldBeaker == null) { @@ -304,60 +304,60 @@ namespace Content.Server.Kitchen.EntitySystems SoundSystem.Play(Filter.Pvs(component.Owner), component.GrindSound.GetSound(), component.Owner, AudioParams.Default); // Get each item inside the chamber and get the reagents it contains. // Transfer those reagents to the beaker, given we have one in. - component.Owner.SpawnTimer(component.WorkTime, (Action) (() => + component.Owner.SpawnTimer(component.WorkTime, () => { foreach (var item in component.Chamber.ContainedEntities.ToList()) { - if (!item.TryGetComponent(out ExtractableComponent? extract) + if (!EntityManager.TryGetComponent(item, out ExtractableComponent? extract) || extract.GrindableSolution == null - || !_solutionsSystem.TryGetSolution(item.Uid, extract.GrindableSolution, out var solution)) continue; + || !_solutionsSystem.TryGetSolution(item, extract.GrindableSolution, out var solution)) continue; var juiceEvent = new ExtractableScalingEvent(); // default of scalar is always 1.0 - RaiseLocalEvent(item.Uid, juiceEvent, false); + RaiseLocalEvent(item, juiceEvent, false); if (component.HeldBeaker.CurrentVolume + solution.CurrentVolume * juiceEvent.Scalar > component.HeldBeaker.MaxVolume) continue; solution.ScaleSolution(juiceEvent.Scalar); - _solutionsSystem.TryAddSolution(beakerEntity.Uid, component.HeldBeaker, solution); - _solutionsSystem.RemoveAllSolution(beakerEntity.Uid, solution); - item.Delete(); + _solutionsSystem.TryAddSolution(beakerEntity.Value, component.HeldBeaker, solution); + _solutionsSystem.RemoveAllSolution(beakerEntity.Value, solution); + EntityManager.DeleteEntity(item); } component.Busy = false; EnqueueUiUpdate(component); bui?.SendMessage(new SharedReagentGrinderComponent.ReagentGrinderWorkCompleteMessage()); - })); + }); break; case SharedReagentGrinderComponent.GrinderProgram.Juice: SoundSystem.Play(Filter.Pvs(component.Owner), component.JuiceSound.GetSound(), component.Owner, AudioParams.Default); - component.Owner.SpawnTimer(component.WorkTime, (Action) (() => + component.Owner.SpawnTimer(component.WorkTime, () => { foreach (var item in component.Chamber.ContainedEntities.ToList()) { - if (!item.TryGetComponent(out var juiceMe) + if (!EntityManager.TryGetComponent(item, out var juiceMe) || juiceMe.JuiceSolution == null) { - Logger.Warning("Couldn't find a juice solution on entityUid:{0}", item.Uid); + Logger.Warning("Couldn't find a juice solution on entityUid:{0}", item); continue; } var juiceEvent = new ExtractableScalingEvent(); // default of scalar is always 1.0 - if (item.HasComponent()) + if (EntityManager.HasComponent(item)) { - RaiseLocalEvent(item.Uid, juiceEvent); + RaiseLocalEvent(item, juiceEvent); } if (component.HeldBeaker.CurrentVolume + juiceMe.JuiceSolution.TotalVolume * juiceEvent.Scalar > component.HeldBeaker.MaxVolume) continue; juiceMe.JuiceSolution.ScaleSolution(juiceEvent.Scalar); - _solutionsSystem.TryAddSolution(beakerEntity.Uid, component.HeldBeaker, juiceMe.JuiceSolution); - item.Delete(); + _solutionsSystem.TryAddSolution(beakerEntity.Value, component.HeldBeaker, juiceMe.JuiceSolution); + EntityManager.DeleteEntity(item); } bui?.SendMessage(new SharedReagentGrinderComponent.ReagentGrinderWorkCompleteMessage()); component.Busy = false; EnqueueUiUpdate(component); - })); + }); break; } } diff --git a/Content.Server/Kudzu/GrowingKudzuSystem.cs b/Content.Server/Kudzu/GrowingKudzuSystem.cs index b582429fcb..53b13c8692 100644 --- a/Content.Server/Kudzu/GrowingKudzuSystem.cs +++ b/Content.Server/Kudzu/GrowingKudzuSystem.cs @@ -44,10 +44,10 @@ public class GrowingKudzuSystem : EntitySystem kudzu.GrowthLevel += 1; if (kudzu.GrowthLevel == 3 && - EntityManager.TryGetComponent(kudzu.OwnerUid, out var spreader)) + EntityManager.TryGetComponent((kudzu).Owner, out var spreader)) { // why cache when you can simply cease to be? Also saves a bit of memory/time. - EntityManager.RemoveComponent(kudzu.OwnerUid); + EntityManager.RemoveComponent((kudzu).Owner); } appearance.SetData(KudzuVisuals.GrowthLevel, kudzu.GrowthLevel); diff --git a/Content.Server/Kudzu/SpreaderSystem.cs b/Content.Server/Kudzu/SpreaderSystem.cs index 0a5ad3e293..d3935484ad 100644 --- a/Content.Server/Kudzu/SpreaderSystem.cs +++ b/Content.Server/Kudzu/SpreaderSystem.cs @@ -35,7 +35,7 @@ public class SpreaderSystem : EntitySystem private void OnAirtightChanged(AirtightChanged e) { - UpdateNearbySpreaders(e.Airtight.OwnerUid, e.Airtight); + UpdateNearbySpreaders((e.Airtight).Owner, e.Airtight); } private void SpreaderAddHandler(EntityUid uid, SpreaderComponent component, ComponentAdd args) diff --git a/Content.Server/Labels/Label/HandLabelerSystem.cs b/Content.Server/Labels/Label/HandLabelerSystem.cs index fcc1a08c0d..cc9293922b 100644 --- a/Content.Server/Labels/Label/HandLabelerSystem.cs +++ b/Content.Server/Labels/Label/HandLabelerSystem.cs @@ -1,16 +1,16 @@ +using System; using Content.Server.Labels.Components; using Content.Server.UserInterface; using Content.Shared.ActionBlocker; -using Content.Shared.Labels; using Content.Shared.Interaction; +using Content.Shared.Labels; +using Content.Shared.Popups; +using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; -using Robust.Shared.Players; using Robust.Shared.IoC; -using JetBrains.Annotations; using Robust.Shared.Localization; -using Content.Shared.Popups; -using System; +using Robust.Shared.Players; namespace Content.Server.Labels { @@ -34,15 +34,15 @@ namespace Content.Server.Labels private void AfterInteractOn(EntityUid uid, HandLabelerComponent handLabeler, AfterInteractEvent args) { - if (args.Target == null || !handLabeler.Whitelist.IsValid(args.Target.Uid)) + if (args.Target is not {Valid: true} target || !handLabeler.Whitelist.IsValid(target)) return; - AddLabelTo(uid, handLabeler, args.Target, out string? result); + AddLabelTo(uid, handLabeler, target, out string? result); if (result != null) handLabeler.Owner.PopupMessage(args.User, result); } - private void AddLabelTo(EntityUid uid, HandLabelerComponent? handLabeler, IEntity target, out string? result) + private void AddLabelTo(EntityUid uid, HandLabelerComponent? handLabeler, EntityUid target, out string? result) { if (!Resolve(uid, ref handLabeler)) { @@ -53,7 +53,7 @@ namespace Content.Server.Labels LabelComponent label = target.EnsureComponent(); if (label.OriginalName != null) - target.Name = label.OriginalName; + EntityManager.GetComponent(target).EntityName = label.OriginalName; label.OriginalName = null; if (handLabeler.AssignedLabel == string.Empty) @@ -63,15 +63,16 @@ namespace Content.Server.Labels return; } - label.OriginalName = target.Name; - target.Name += $" ({handLabeler.AssignedLabel})"; + label.OriginalName = EntityManager.GetComponent(target).EntityName; + string val = EntityManager.GetComponent(target).EntityName + $" ({handLabeler.AssignedLabel})"; + EntityManager.GetComponent(target).EntityName = val; label.CurrentLabel = handLabeler.AssignedLabel; result = Loc.GetString("hand-labeler-successfully-applied"); } private void OnUseInHand(EntityUid uid, HandLabelerComponent handLabeler, UseInHandEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; handLabeler.Owner.GetUIOrNull(HandLabelerUiKey.Key)?.Open(actor.PlayerSession); @@ -80,7 +81,7 @@ namespace Content.Server.Labels private bool CheckInteract(ICommonSession session) { - if (session.AttachedEntityUid is not { } uid + if (session.AttachedEntity is not {Valid: true } uid || !Get().CanInteract(uid) || !Get().CanUse(uid)) return false; diff --git a/Content.Server/Labels/Label/LabelSystem.cs b/Content.Server/Labels/Label/LabelSystem.cs index 9d14a5d92c..d5eb619def 100644 --- a/Content.Server/Labels/Label/LabelSystem.cs +++ b/Content.Server/Labels/Label/LabelSystem.cs @@ -62,7 +62,7 @@ namespace Content.Server.Labels private void OnExamined(EntityUid uid, PaperLabelComponent comp, ExaminedEvent args) { - if (comp.LabelSlot.Item == null) + if (comp.LabelSlot.Item is not {Valid: true} item) return; if (!args.IsInDetailsRange) @@ -71,7 +71,7 @@ namespace Content.Server.Labels return; } - if (!EntityManager.TryGetComponent(comp.LabelSlot.Item.Uid, out PaperComponent paper)) + if (!EntityManager.TryGetComponent(item, out PaperComponent paper)) // Assuming yaml has the correct entity whitelist, this should not happen. return; diff --git a/Content.Server/Lathe/Components/LatheComponent.cs b/Content.Server/Lathe/Components/LatheComponent.cs index df45d4f17f..a1800ce947 100644 --- a/Content.Server/Lathe/Components/LatheComponent.cs +++ b/Content.Server/Lathe/Components/LatheComponent.cs @@ -14,6 +14,7 @@ using Content.Shared.Research.Prototypes; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Server.Lathe.Components @@ -22,6 +23,8 @@ namespace Content.Server.Lathe.Components [ComponentReference(typeof(IActivate))] public class LatheComponent : SharedLatheComponent, IInteractUsing, IActivate { + [Dependency] private readonly IEntityManager _entMan = default!; + public const int VolumePerSheet = 100; [ViewVariables] @@ -41,7 +44,7 @@ namespace Content.Server.Lathe.Components [ViewVariables] private LatheRecipePrototype? _producingRecipe; [ViewVariables] - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; private static readonly TimeSpan InsertionTime = TimeSpan.FromSeconds(0.9f); @@ -74,20 +77,20 @@ namespace Content.Server.Lathe.Components } break; case LatheSyncRequestMessage _: - if (!Owner.HasComponent()) return; + if (!_entMan.HasComponent(Owner)) return; UserInterface?.SendMessage(new LatheFullQueueMessage(GetIdQueue())); if (_producingRecipe != null) UserInterface?.SendMessage(new LatheProducingRecipeMessage(_producingRecipe.ID)); break; case LatheServerSelectionMessage _: - if (!Owner.TryGetComponent(out ResearchClientComponent? researchClient)) return; + if (!_entMan.TryGetComponent(Owner, out ResearchClientComponent? researchClient)) return; researchClient.OpenUserInterface(message.Session); break; case LatheServerSyncMessage _: - if (!Owner.TryGetComponent(out TechnologyDatabaseComponent? database) - || !Owner.TryGetComponent(out ProtolatheDatabaseComponent? protoDatabase)) return; + if (!_entMan.TryGetComponent(Owner, out TechnologyDatabaseComponent? database) + || !_entMan.TryGetComponent(Owner, out ProtolatheDatabaseComponent? protoDatabase)) return; if (database.SyncWithServer()) protoDatabase.Sync(); @@ -100,7 +103,7 @@ namespace Content.Server.Lathe.Components internal bool Produce(LatheRecipePrototype recipe) { - if (Producing || !Powered || !CanProduce(recipe) || !Owner.TryGetComponent(out MaterialStorageComponent? storage)) return false; + if (Producing || !Powered || !CanProduce(recipe) || !_entMan.TryGetComponent(Owner, out MaterialStorageComponent? storage)) return false; UserInterface?.SendMessage(new LatheFullQueueMessage(GetIdQueue())); @@ -122,7 +125,7 @@ namespace Content.Server.Lathe.Components { Producing = false; _producingRecipe = null; - Owner.EntityManager.SpawnEntity(recipe.Result, Owner.Transform.Coordinates); + _entMan.SpawnEntity(recipe.Result, _entMan.GetComponent(Owner).Coordinates); UserInterface?.SendMessage(new LatheStoppedProducingRecipeMessage()); State = LatheState.Base; SetAppearance(LatheVisualState.Idle); @@ -138,7 +141,7 @@ namespace Content.Server.Lathe.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return; if (!Powered) { @@ -150,12 +153,12 @@ namespace Content.Server.Lathe.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (!Owner.TryGetComponent(out MaterialStorageComponent? storage) - || !eventArgs.Using.TryGetComponent(out MaterialComponent? material)) return false; + if (!_entMan.TryGetComponent(Owner, out MaterialStorageComponent? storage) + || !_entMan.TryGetComponent(eventArgs.Using, out MaterialComponent? material)) return false; var multiplier = 1; - if (eventArgs.Using.TryGetComponent(out StackComponent? stack)) multiplier = stack.Count; + if (_entMan.TryGetComponent(eventArgs.Using, out StackComponent? stack)) multiplier = stack.Count; var totalAmount = 0; @@ -201,14 +204,14 @@ namespace Content.Server.Lathe.Components SetAppearance(LatheVisualState.Idle); }); - eventArgs.Using.Delete(); + _entMan.DeleteEntity(eventArgs.Using); return true; } private void SetAppearance(LatheVisualState state) { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(PowerDeviceVisuals.VisualState, state); } diff --git a/Content.Server/Lathe/Components/ProtolatheDatabaseComponent.cs b/Content.Server/Lathe/Components/ProtolatheDatabaseComponent.cs index da8c35cbeb..efd8818994 100644 --- a/Content.Server/Lathe/Components/ProtolatheDatabaseComponent.cs +++ b/Content.Server/Lathe/Components/ProtolatheDatabaseComponent.cs @@ -27,7 +27,7 @@ namespace Content.Server.Lathe.Components /// public void Sync() { - if (!Owner.TryGetComponent(out TechnologyDatabaseComponent? database)) return; + if (!IoCManager.Resolve().TryGetComponent(Owner, out TechnologyDatabaseComponent? database)) return; foreach (var technology in database.Technologies) { diff --git a/Content.Server/Light/Components/EmergencyLightComponent.cs b/Content.Server/Light/Components/EmergencyLightComponent.cs index 9ab0361cdd..23fd78c9eb 100644 --- a/Content.Server/Light/Components/EmergencyLightComponent.cs +++ b/Content.Server/Light/Components/EmergencyLightComponent.cs @@ -5,6 +5,7 @@ using Content.Shared.Examine; using Content.Shared.Light.Component; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -20,6 +21,8 @@ namespace Content.Server.Light.Components public class EmergencyLightComponent : SharedEmergencyLightComponent, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables] private EmergencyLightState State { @@ -30,7 +33,7 @@ namespace Content.Server.Light.Components return; _state = value; - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new EmergencyLightMessage(this, _state)); + _entMan.EventBus.RaiseEvent(EventSource.Local, new EmergencyLightMessage(this, _state)); } } @@ -59,7 +62,7 @@ namespace Content.Server.Light.Components /// public void UpdateState() { - if (!Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver)) + if (!_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver)) { return; } @@ -79,7 +82,7 @@ namespace Content.Server.Light.Components public void OnUpdate(float frameTime) { - if (Owner.Deleted || !Owner.TryGetComponent(out BatteryComponent? battery) || Owner.Paused) + if ((!_entMan.EntityExists(Owner) || !_entMan.TryGetComponent(Owner, out BatteryComponent? battery) || _entMan.GetComponent(Owner).EntityPaused)) { return; } @@ -97,7 +100,7 @@ namespace Content.Server.Light.Components battery.CurrentCharge += _chargingWattage * frameTime * _chargingEfficiency; if (battery.IsFullyCharged) { - if (Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver)) + if (_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver)) { receiver.Load = 1; } @@ -109,23 +112,23 @@ namespace Content.Server.Light.Components private void TurnOff() { - if (Owner.TryGetComponent(out PointLightComponent? light)) + if (_entMan.TryGetComponent(Owner, out PointLightComponent? light)) { light.Enabled = false; } - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) appearance.SetData(EmergencyLightVisuals.On, false); } private void TurnOn() { - if (Owner.TryGetComponent(out PointLightComponent? light)) + if (_entMan.TryGetComponent(Owner, out PointLightComponent? light)) { light.Enabled = true; } - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) appearance.SetData(EmergencyLightVisuals.On, true); } diff --git a/Content.Server/Light/Components/ExpendableLightComponent.cs b/Content.Server/Light/Components/ExpendableLightComponent.cs index 7fbe58c860..2e4b05ddd2 100644 --- a/Content.Server/Light/Components/ExpendableLightComponent.cs +++ b/Content.Server/Light/Components/ExpendableLightComponent.cs @@ -5,6 +5,7 @@ using Content.Shared.Light.Component; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Player; using Robust.Shared.ViewVariables; @@ -16,6 +17,8 @@ namespace Content.Server.Light.Components [RegisterComponent] public class ExpendableLightComponent : SharedExpendableLightComponent, IUse { + [Dependency] private readonly IEntityManager _entMan = default!; + /// /// Status of light, whether or not it is emitting light. /// @@ -35,14 +38,14 @@ namespace Content.Server.Light.Components { base.Initialize(); - if (Owner.TryGetComponent(out var item)) + if (_entMan.TryGetComponent(Owner, out var item)) { item.EquippedPrefix = "unlit"; } CurrentState = ExpendableLightState.BrandNew; Owner.EnsureComponent(); - Owner.TryGetComponent(out _appearance); + _entMan.TryGetComponent(Owner, out _appearance); } /// @@ -52,7 +55,7 @@ namespace Content.Server.Light.Components { if (!Activated && CurrentState == ExpendableLightState.BrandNew) { - if (Owner.TryGetComponent(out var item)) + if (_entMan.TryGetComponent(Owner, out var item)) { item.EquippedPrefix = "lit"; } @@ -91,7 +94,7 @@ namespace Content.Server.Light.Components private void UpdateSpriteAndSounds(bool on) { - if (Owner.TryGetComponent(out SpriteComponent? sprite)) + if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite)) { switch (CurrentState) { @@ -125,7 +128,7 @@ namespace Content.Server.Light.Components } } - if (Owner.TryGetComponent(out ClothingComponent? clothing)) + if (_entMan.TryGetComponent(Owner, out ClothingComponent? clothing)) { clothing.ClothingEquippedPrefix = on ? "Activated" : string.Empty; } @@ -154,13 +157,13 @@ namespace Content.Server.Light.Components case ExpendableLightState.Fading: CurrentState = ExpendableLightState.Dead; - Owner.Name = SpentName; - Owner.Description = SpentDesc; + _entMan.GetComponent(Owner).EntityName = SpentName; + _entMan.GetComponent(Owner).EntityDescription = SpentDesc; UpdateSpriteAndSounds(Activated); UpdateVisualizer(); - if (Owner.TryGetComponent(out var item)) + if (_entMan.TryGetComponent(Owner, out var item)) { item.EquippedPrefix = "unlit"; } diff --git a/Content.Server/Light/Components/HandheldLightComponent.cs b/Content.Server/Light/Components/HandheldLightComponent.cs index b517a67961..dc8b6d7560 100644 --- a/Content.Server/Light/Components/HandheldLightComponent.cs +++ b/Content.Server/Light/Components/HandheldLightComponent.cs @@ -12,15 +12,14 @@ using Content.Shared.Light.Component; using Content.Shared.Popups; using Content.Shared.Rounding; using Content.Shared.Sound; -using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -35,6 +34,8 @@ namespace Content.Server.Light.Components internal sealed class HandheldLightComponent : SharedHandheldLightComponent, IUse, IExamine, IInteractUsing #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables(VVAccess.ReadWrite)] [DataField("wattage")] public float Wattage { get; set; } = 3f; [ViewVariables] private PowerCellSlotComponent _cellSlot = default!; private PowerCellComponent? Cell => _cellSlot.Cell; @@ -71,12 +72,12 @@ namespace Content.Server.Light.Components protected override void OnRemove() { base.OnRemove(); - Owner.EntityManager.EventBus.QueueEvent(EventSource.Local, new DeactivateHandheldLightMessage(this)); + _entMan.EventBus.QueueEvent(EventSource.Local, new DeactivateHandheldLightMessage(this)); } async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) return false; + if (!EntitySystem.Get().CanInteract(eventArgs.User)) return false; if (!_cellSlot.InsertCell(eventArgs.Using)) return false; Dirty(); return true; @@ -103,9 +104,9 @@ namespace Content.Server.Light.Components /// 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(IEntity user) + public bool ToggleStatus(EntityUid user) { - if (!EntitySystem.Get().CanUse(user.Uid)) return false; + if (!EntitySystem.Get().CanUse(user)) return false; return Activated ? TurnOff() : TurnOn(user); } @@ -119,7 +120,7 @@ namespace Content.Server.Light.Components SetState(false); Activated = false; UpdateLightAction(); - Owner.EntityManager.EventBus.QueueEvent(EventSource.Local, new DeactivateHandheldLightMessage(this)); + _entMan.EventBus.QueueEvent(EventSource.Local, new DeactivateHandheldLightMessage(this)); if (makeNoise) { @@ -129,7 +130,7 @@ namespace Content.Server.Light.Components return true; } - public bool TurnOn(IEntity user) + public bool TurnOn(EntityUid user) { if (Activated) { @@ -158,7 +159,7 @@ namespace Content.Server.Light.Components Activated = true; UpdateLightAction(); SetState(true); - Owner.EntityManager.EventBus.QueueEvent(EventSource.Local, new ActivateHandheldLightMessage(this)); + _entMan.EventBus.QueueEvent(EventSource.Local, new ActivateHandheldLightMessage(this)); SoundSystem.Play(Filter.Pvs(Owner), TurnOnSound.GetSound(), Owner); return true; @@ -166,22 +167,22 @@ namespace Content.Server.Light.Components private void SetState(bool on) { - if (Owner.TryGetComponent(out SpriteComponent? sprite)) + if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite)) { sprite.LayerSetVisible(1, on); } - if (Owner.TryGetComponent(out PointLightComponent? light)) + if (_entMan.TryGetComponent(Owner, out PointLightComponent? light)) { light.Enabled = on; } - if (Owner.TryGetComponent(out ClothingComponent? clothing)) + if (_entMan.TryGetComponent(Owner, out ClothingComponent? clothing)) { clothing.ClothingEquippedPrefix = Loc.GetString(on ? "on" : "off"); } - if (Owner.TryGetComponent(out ItemComponent? item)) + if (_entMan.TryGetComponent(Owner, out ItemComponent? item)) { item.EquippedPrefix = Loc.GetString(on ? "on" : "off"); } @@ -200,7 +201,7 @@ namespace Content.Server.Light.Components return; } - var appearanceComponent = Owner.GetComponent(); + var appearanceComponent = _entMan.GetComponent(Owner); if (Cell.MaxCharge - Cell.CurrentCharge < Cell.MaxCharge * 0.70) { @@ -253,7 +254,7 @@ namespace Content.Server.Light.Components { public bool DoToggleAction(ToggleItemActionEventArgs args) { - if (!args.Item.TryGetComponent(out var lightComponent)) return false; + if (!IoCManager.Resolve().TryGetComponent(args.Item, out var lightComponent)) return false; if (lightComponent.Activated == args.ToggledOn) return false; return lightComponent.ToggleStatus(args.Performer); } diff --git a/Content.Server/Light/Components/LightBulbComponent.cs b/Content.Server/Light/Components/LightBulbComponent.cs index a411303691..f632689169 100644 --- a/Content.Server/Light/Components/LightBulbComponent.cs +++ b/Content.Server/Light/Components/LightBulbComponent.cs @@ -39,7 +39,7 @@ namespace Content.Server.Light.Components public void OnBreak(BreakageEventArgs eventArgs) { EntitySystem.Get() - .SetState(Owner.Uid, LightBulbState.Broken, this); + .SetState(Owner, LightBulbState.Broken, this); } } } diff --git a/Content.Server/Light/EntitySystems/LightReplacerSystem.cs b/Content.Server/Light/EntitySystems/LightReplacerSystem.cs index 5c0424a579..77a00db063 100644 --- a/Content.Server/Light/EntitySystems/LightReplacerSystem.cs +++ b/Content.Server/Light/EntitySystems/LightReplacerSystem.cs @@ -1,8 +1,8 @@ +using System.Linq; using Content.Server.Light.Components; using Content.Server.Storage.Components; using Content.Shared.ActionBlocker; using Content.Shared.Interaction; -using Content.Shared.Interaction.Events; using Content.Shared.Light; using Content.Shared.Popups; using JetBrains.Annotations; @@ -12,8 +12,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; -using System; -using System.Linq; namespace Content.Server.Light.EntitySystems { @@ -44,20 +42,20 @@ namespace Content.Server.Light.EntitySystems return; // standard interaction checks - if (!_blocker.CanUse(eventArgs.User.Uid)) return; + if (!_blocker.CanUse(eventArgs.User)) return; if (!eventArgs.CanReach) return; // behaviour will depends on target type if (eventArgs.Target != null) { - var targetUid = eventArgs.Target.Uid; + var targetUid = (EntityUid) eventArgs.Target; // replace broken light in fixture? if (EntityManager.TryGetComponent(targetUid, out PoweredLightComponent? fixture)) - eventArgs.Handled = TryReplaceBulb(uid, targetUid, eventArgs.User.Uid, component, fixture); + eventArgs.Handled = TryReplaceBulb(uid, targetUid, eventArgs.User, component, fixture); // add new bulb to light replacer container? else if (EntityManager.TryGetComponent(targetUid, out LightBulbComponent? bulb)) - eventArgs.Handled = TryInsertBulb(uid, targetUid, eventArgs.User.Uid, true, component, bulb); + eventArgs.Handled = TryInsertBulb(uid, targetUid, eventArgs.User, true, component, bulb); } } @@ -67,18 +65,18 @@ namespace Content.Server.Light.EntitySystems return; // standard interaction checks - if (!_blocker.CanInteract(eventArgs.User.Uid)) return; + if (!_blocker.CanInteract(eventArgs.User)) return; if (eventArgs.Used != null) { - var usedUid = eventArgs.Used.Uid; + var usedUid = eventArgs.Used; // want to insert a new light bulb? if (EntityManager.TryGetComponent(usedUid, out LightBulbComponent ? bulb)) - eventArgs.Handled = TryInsertBulb(uid, usedUid, eventArgs.User.Uid, true, component, bulb); + eventArgs.Handled = TryInsertBulb(uid, usedUid, eventArgs.User, true, component, bulb); // add bulbs from storage? else if (EntityManager.TryGetComponent(usedUid, out ServerStorageComponent? storage)) - eventArgs.Handled = TryInsertBulbsFromStorage(uid, usedUid, eventArgs.User.Uid, component, storage); + eventArgs.Handled = TryInsertBulbsFromStorage(uid, usedUid, eventArgs.User, component, storage); } } @@ -96,7 +94,7 @@ namespace Content.Server.Light.EntitySystems return false; // check if light bulb is broken or missing - var fixtureBulbUid = _poweredLight.GetBulb(fixture.Owner.Uid, fixture); + var fixtureBulbUid = _poweredLight.GetBulb(fixture.Owner, fixture); if (fixtureBulbUid != null) { if (!EntityManager.TryGetComponent(fixtureBulbUid.Value, out LightBulbComponent? fixtureBulb)) @@ -107,7 +105,7 @@ namespace Content.Server.Light.EntitySystems // try get first inserted bulb of the same type as targeted light fixtutre var bulb = replacer.InsertedBulbs.ContainedEntities.FirstOrDefault( - (e) => e.GetComponentOrNull()?.Type == fixture.BulbType); + (e) => EntityManager.GetComponentOrNull(e)?.Type == fixture.BulbType); // found bulb in inserted storage if (bulb != null) @@ -125,7 +123,7 @@ namespace Content.Server.Light.EntitySystems // found right bulb, let's spawn it if (bulbEnt != null) { - bulb = EntityManager.SpawnEntity(bulbEnt.PrototypeName, replacer.Owner.Transform.Coordinates); + bulb = EntityManager.SpawnEntity(bulbEnt.PrototypeName, EntityManager.GetComponent(replacer.Owner).Coordinates); bulbEnt.Amount--; } // not found any light bulbs @@ -142,7 +140,7 @@ namespace Content.Server.Light.EntitySystems } // insert it into fixture - var wasReplaced = _poweredLight.ReplaceBulb(fixtureUid, bulb.Uid, fixture); + var wasReplaced = _poweredLight.ReplaceBulb(fixtureUid, bulb, fixture); if (wasReplaced) { SoundSystem.Play(Filter.Pvs(replacerUid), replacer.Sound.GetSound(), @@ -211,9 +209,9 @@ namespace Content.Server.Light.EntitySystems var storagedEnts = storage.StoredEntities.ToArray(); foreach (var ent in storagedEnts) { - if (EntityManager.TryGetComponent(ent.Uid, out LightBulbComponent? bulb)) + if (EntityManager.TryGetComponent(ent, out LightBulbComponent? bulb)) { - if (TryInsertBulb(replacerUid, ent.Uid, userUid, false, replacer, bulb)) + if (TryInsertBulb(replacerUid, ent, userUid, false, replacer, bulb)) insertedBulbs++; } } diff --git a/Content.Server/Light/EntitySystems/MatchboxSystem.cs b/Content.Server/Light/EntitySystems/MatchboxSystem.cs index df75139a24..434c036898 100644 --- a/Content.Server/Light/EntitySystems/MatchboxSystem.cs +++ b/Content.Server/Light/EntitySystems/MatchboxSystem.cs @@ -2,6 +2,7 @@ using Content.Server.Light.Components; using Content.Shared.Interaction; using Content.Shared.Smoking; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Light.EntitySystems { @@ -16,7 +17,7 @@ namespace Content.Server.Light.EntitySystems private void OnInteractUsing(EntityUid uid, MatchboxComponent component, InteractUsingEvent args) { if (!args.Handled - && args.Used.TryGetComponent(out var matchstick) + && EntityManager.TryGetComponent(args.Used, out var matchstick) && matchstick.CurrentState == SmokableState.Unlit) { Get().Ignite(matchstick, args.User); diff --git a/Content.Server/Light/EntitySystems/MatchstickSystem.cs b/Content.Server/Light/EntitySystems/MatchstickSystem.cs index 33b9bf17a9..67bf4dc3ad 100644 --- a/Content.Server/Light/EntitySystems/MatchstickSystem.cs +++ b/Content.Server/Light/EntitySystems/MatchstickSystem.cs @@ -34,7 +34,7 @@ namespace Content.Server.Light.EntitySystems if (match.CurrentState != SmokableState.Lit) continue; - _atmosphereSystem.HotspotExpose(match.Owner.Transform.Coordinates, 400, 50, true); + _atmosphereSystem.HotspotExpose(EntityManager.GetComponent(match.Owner).Coordinates, 400, 50, true); } } @@ -44,7 +44,7 @@ namespace Content.Server.Light.EntitySystems return; var isHotEvent = new IsHotEvent(); - RaiseLocalEvent(args.Used.Uid, isHotEvent, false); + RaiseLocalEvent(args.Used, isHotEvent, false); if (!isHotEvent.IsHot) return; @@ -58,7 +58,7 @@ namespace Content.Server.Light.EntitySystems args.IsHot = component.CurrentState == SmokableState.Lit; } - public void Ignite(MatchstickComponent component, IEntity user) + public void Ignite(MatchstickComponent component, EntityUid user) { // Play Sound SoundSystem.Play( @@ -84,7 +84,7 @@ namespace Content.Server.Light.EntitySystems component.PointLightComponent.Enabled = component.CurrentState == SmokableState.Lit; } - if (component.Owner.TryGetComponent(out ItemComponent? item)) + if (EntityManager.TryGetComponent(component.Owner, out ItemComponent? item)) { switch (component.CurrentState) { @@ -97,7 +97,7 @@ namespace Content.Server.Light.EntitySystems } } - if (component.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearance)) { appearance.SetData(SmokingVisuals.Smoking, component.CurrentState); } diff --git a/Content.Server/Light/EntitySystems/PoweredLightSystem.cs b/Content.Server/Light/EntitySystems/PoweredLightSystem.cs index 7346382de1..04e2861252 100644 --- a/Content.Server/Light/EntitySystems/PoweredLightSystem.cs +++ b/Content.Server/Light/EntitySystems/PoweredLightSystem.cs @@ -1,30 +1,28 @@ using System; +using Content.Server.Administration.Logs; using Content.Server.DeviceNetwork; using Content.Server.DeviceNetwork.Systems; using Content.Server.Ghost; using Content.Server.Light.Components; using Content.Server.MachineLinking.Events; using Content.Server.Power.Components; -using Content.Server.Power.EntitySystems; -using Content.Shared.Light; +using Content.Server.Temperature.Components; +using Content.Shared.Audio; using Content.Shared.Damage; +using Content.Shared.Database; +using Content.Shared.Hands.Components; +using Content.Shared.Interaction; +using Content.Shared.Light; +using Content.Shared.Popups; using Robust.Server.GameObjects; +using Robust.Shared.Audio; +using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Timing; -using Robust.Shared.Containers; -using Content.Shared.Interaction; -using Content.Shared.Hands.Components; -using Content.Server.Temperature.Components; -using Content.Shared.Popups; using Robust.Shared.Localization; -using Robust.Shared.Audio; -using Robust.Shared.Player; using Robust.Shared.Maths; -using Content.Shared.Audio; -using Content.Server.Administration.Logs; -using Content.Shared.Administration.Logs; -using Content.Shared.Database; +using Robust.Shared.Player; +using Robust.Shared.Timing; namespace Content.Server.Light.EntitySystems { @@ -75,7 +73,7 @@ namespace Content.Server.Light.EntitySystems _ => throw new ArgumentOutOfRangeException() }; - var entity = EntityManager.SpawnEntity(prototype, light.Owner.Transform.Coordinates); + var entity = EntityManager.SpawnEntity(prototype, EntityManager.GetComponent(light.Owner).Coordinates); light.LightBulbContainer.Insert(entity); } @@ -88,7 +86,7 @@ namespace Content.Server.Light.EntitySystems if (args.Handled) return; - args.Handled = InsertBulb(uid, args.Used.Uid, component); + args.Handled = InsertBulb(uid, args.Used, component); } private void OnInteractHand(EntityUid uid, PoweredLightComponent light, InteractHandEvent args) @@ -102,7 +100,7 @@ namespace Content.Server.Light.EntitySystems return; // check if it's possible to apply burn damage to user - var userUid = args.User.Uid; + var userUid = args.User; if (EntityManager.TryGetComponent(userUid, out HeatResistanceComponent? heatResist) && EntityManager.TryGetComponent(bulbUid.Value, out LightBulbComponent? lightBulb)) { @@ -156,7 +154,7 @@ namespace Content.Server.Light.EntitySystems return false; // try to insert bulb in container - if (!light.LightBulbContainer.Insert(EntityManager.GetEntity(bulbUid))) + if (!light.LightBulbContainer.Insert(bulbUid)) return false; UpdateLight(uid, light); @@ -174,24 +172,22 @@ namespace Content.Server.Light.EntitySystems return null; // check if light has bulb - var bulbUid = GetBulb(uid, light); - if (bulbUid == null) + if (GetBulb(uid, light) is not {Valid: true} bulb) return null; // try to remove bulb from container - var bulbEnt = EntityManager.GetEntity(bulbUid.Value); - if (!light.LightBulbContainer.Remove(bulbEnt)) + if (!light.LightBulbContainer.Remove(bulb)) return null; // try to place bulb in hands if (userUid != null) { if (EntityManager.TryGetComponent(userUid.Value, out SharedHandsComponent? hands)) - hands.TryPutInActiveHandOrAny(bulbEnt); + hands.TryPutInActiveHandOrAny(bulb); } UpdateLight(uid, light); - return bulbUid; + return bulb; } /// @@ -213,7 +209,7 @@ namespace Content.Server.Light.EntitySystems if (!Resolve(uid, ref light)) return null; - return light.LightBulbContainer.ContainedEntity?.Uid; + return light.LightBulbContainer.ContainedEntity; } /// @@ -340,7 +336,7 @@ namespace Content.Server.Light.EntitySystems light.IsBlinking = isNowBlinking; - if (!light.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (!EntityManager.TryGetComponent(light.Owner, out AppearanceComponent? appearance)) return; appearance.SetData(PoweredLightVisuals.Blinking, isNowBlinking); } diff --git a/Content.Server/Light/EntitySystems/UnpoweredFlashlightSystem.cs b/Content.Server/Light/EntitySystems/UnpoweredFlashlightSystem.cs index 642676ea41..09201ecaf2 100644 --- a/Content.Server/Light/EntitySystems/UnpoweredFlashlightSystem.cs +++ b/Content.Server/Light/EntitySystems/UnpoweredFlashlightSystem.cs @@ -8,6 +8,7 @@ using Robust.Shared.GameObjects; using Robust.Shared.Localization; using Robust.Shared.Player; using System; +using Robust.Shared.IoC; namespace Content.Server.Light.EntitySystems { @@ -36,18 +37,18 @@ namespace Content.Server.Light.EntitySystems public void ToggleLight(UnpoweredFlashlightComponent flashlight) { - if (!flashlight.Owner.TryGetComponent(out PointLightComponent? light)) + if (!EntityManager.TryGetComponent(flashlight.Owner, out PointLightComponent? light)) return; flashlight.LightOn = !flashlight.LightOn; light.Enabled = flashlight.LightOn; - if (flashlight.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(flashlight.Owner, out AppearanceComponent? appearance)) appearance.SetData(UnpoweredFlashlightVisuals.LightOn, flashlight.LightOn); SoundSystem.Play(Filter.Pvs(light.Owner), flashlight.ToggleSound.GetSound(), flashlight.Owner); - RaiseLocalEvent(flashlight.Owner.Uid, new LightToggleEvent(flashlight.LightOn)); + RaiseLocalEvent(flashlight.Owner, new LightToggleEvent(flashlight.LightOn)); } } diff --git a/Content.Server/Lock/LockSystem.cs b/Content.Server/Lock/LockSystem.cs index 13adfb1466..44948fd3cf 100644 --- a/Content.Server/Lock/LockSystem.cs +++ b/Content.Server/Lock/LockSystem.cs @@ -35,7 +35,7 @@ namespace Content.Server.Lock private void OnStartup(EntityUid uid, LockComponent lockComp, ComponentStartup args) { - if (lockComp.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(lockComp.Owner, out AppearanceComponent? appearance)) { appearance.SetData(StorageVisuals.CanLock, true); } @@ -64,63 +64,63 @@ namespace Content.Server.Lock args.PushText(Loc.GetString(lockComp.Locked ? "lock-comp-on-examined-is-locked" : "lock-comp-on-examined-is-unlocked", - ("entityName", lockComp.Owner.Name))); + ("entityName", Name: EntityManager.GetComponent(lockComp.Owner).EntityName))); } - public bool TryLock(EntityUid uid, IEntity user, LockComponent? lockComp = null) + public bool TryLock(EntityUid uid, EntityUid user, LockComponent? lockComp = null) { if (!Resolve(uid, ref lockComp)) return false; - + if (!CanToggleLock(uid, user, quiet: false)) return false; - + if (!HasUserAccess(uid, user, quiet: false)) return false; - lockComp.Owner.PopupMessage(user, Loc.GetString("lock-comp-do-lock-success", ("entityName",lockComp.Owner.Name))); + lockComp.Owner.PopupMessage(user, Loc.GetString("lock-comp-do-lock-success", ("entityName",Name: EntityManager.GetComponent(lockComp.Owner).EntityName))); lockComp.Locked = true; - + if(lockComp.LockSound != null) { SoundSystem.Play(Filter.Pvs(lockComp.Owner), lockComp.LockSound.GetSound(), lockComp.Owner, AudioParams.Default.WithVolume(-5)); } - if (lockComp.Owner.TryGetComponent(out AppearanceComponent? appearanceComp)) + if (EntityManager.TryGetComponent(lockComp.Owner, out AppearanceComponent? appearanceComp)) { appearanceComp.SetData(StorageVisuals.Locked, true); } - RaiseLocalEvent(lockComp.Owner.Uid, new LockToggledEvent(true)); + RaiseLocalEvent(lockComp.Owner, new LockToggledEvent(true)); return true; } - public bool TryUnlock(EntityUid uid, IEntity user, LockComponent? lockComp = null) + public bool TryUnlock(EntityUid uid, EntityUid user, LockComponent? lockComp = null) { if (!Resolve(uid, ref lockComp)) return false; - + if (!CanToggleLock(uid, user, quiet: false)) return false; - + if (!HasUserAccess(uid, user, quiet: false)) return false; - lockComp.Owner.PopupMessage(user, Loc.GetString("lock-comp-do-unlock-success", ("entityName", lockComp.Owner.Name))); + lockComp.Owner.PopupMessage(user, Loc.GetString("lock-comp-do-unlock-success", ("entityName", Name: EntityManager.GetComponent(lockComp.Owner).EntityName))); lockComp.Locked = false; - + if(lockComp.UnlockSound != null) { SoundSystem.Play(Filter.Pvs(lockComp.Owner), lockComp.UnlockSound.GetSound(), lockComp.Owner, AudioParams.Default.WithVolume(-5)); } - if (lockComp.Owner.TryGetComponent(out AppearanceComponent? appearanceComp)) + if (EntityManager.TryGetComponent(lockComp.Owner, out AppearanceComponent? appearanceComp)) { appearanceComp.SetData(StorageVisuals.Locked, false); } - RaiseLocalEvent(lockComp.Owner.Uid, new LockToggledEvent(false)); + RaiseLocalEvent(lockComp.Owner, new LockToggledEvent(false)); return true; } @@ -128,7 +128,7 @@ namespace Content.Server.Lock /// /// Before locking the entity, check whether it's a locker. If is, prevent it from being locked from the inside or while it is open. /// - public bool CanToggleLock(EntityUid uid, IEntity user, EntityStorageComponent? storage = null, bool quiet = true) + public bool CanToggleLock(EntityUid uid, EntityUid user, EntityStorageComponent? storage = null, bool quiet = true) { if (!Resolve(uid, ref storage, logMissing: false)) return true; @@ -144,13 +144,13 @@ namespace Content.Server.Lock return true; } - private bool HasUserAccess(EntityUid uid, IEntity user, AccessReader? reader = null, bool quiet = true) + private bool HasUserAccess(EntityUid uid, EntityUid user, AccessReader? reader = null, bool quiet = true) { // Not having an AccessComponent means you get free access. woo! if (!Resolve(uid, ref reader)) return true; - if (!_accessReader.IsAllowed(reader, user.Uid)) + if (!_accessReader.IsAllowed(reader, user)) { if (!quiet) reader.Owner.PopupMessage(user, Loc.GetString("lock-comp-has-user-access-fail")); diff --git a/Content.Server/MachineLinking/Events/LinkAttemptEvent.cs b/Content.Server/MachineLinking/Events/LinkAttemptEvent.cs index 0bde20c91e..593311c613 100644 --- a/Content.Server/MachineLinking/Events/LinkAttemptEvent.cs +++ b/Content.Server/MachineLinking/Events/LinkAttemptEvent.cs @@ -5,13 +5,13 @@ namespace Content.Server.MachineLinking.Events { public class LinkAttemptEvent : CancellableEntityEventArgs { - public readonly IEntity Attemptee; + public readonly EntityUid Attemptee; public readonly SignalTransmitterComponent TransmitterComponent; public readonly string TransmitterPort; public readonly SignalReceiverComponent ReceiverComponent; public readonly string ReceiverPort; - public LinkAttemptEvent(IEntity attemptee, SignalTransmitterComponent transmitterComponent, string transmitterPort, SignalReceiverComponent receiverComponent, string receiverPort) + public LinkAttemptEvent(EntityUid attemptee, SignalTransmitterComponent transmitterComponent, string transmitterPort, SignalReceiverComponent receiverComponent, string receiverPort) { TransmitterComponent = transmitterComponent; this.TransmitterPort = transmitterPort; diff --git a/Content.Server/MachineLinking/System/SignalLinkerSystem.cs b/Content.Server/MachineLinking/System/SignalLinkerSystem.cs index 7888a17b84..549731ab9a 100644 --- a/Content.Server/MachineLinking/System/SignalLinkerSystem.cs +++ b/Content.Server/MachineLinking/System/SignalLinkerSystem.cs @@ -71,7 +71,7 @@ namespace Content.Server.MachineLinking.System { if (!IsInRange(component, link.ReceiverComponent)) continue; - RaiseLocalEvent(link.ReceiverComponent.Owner.Uid, + RaiseLocalEvent(link.ReceiverComponent.Owner, new SignalReceivedEvent(link.Receiverport.Name, args.Value), false); } } @@ -80,8 +80,8 @@ namespace Content.Server.MachineLinking.System { if (args.Handled) return; - if (!args.Used.TryGetComponent(out var linker) || !linker.Port.HasValue || - !args.User.TryGetComponent(out ActorComponent? actor) || + if (!EntityManager.TryGetComponent(args.Used, out var linker) || !linker.Port.HasValue || + !EntityManager.TryGetComponent(args.User, out ActorComponent? actor) || !linker.Port.Value.transmitter.Outputs.TryGetPort(linker.Port.Value.port, out var port)) { return; @@ -116,19 +116,21 @@ namespace Content.Server.MachineLinking.System private void OnReceiverUIMessage(EntityUid uid, SignalReceiverComponent component, ServerBoundUserInterfaceMessage msg) { + if (msg.Session.AttachedEntity is not { } attached) return; + switch (msg.Message) { case SignalPortSelected portSelected: - if (msg.Session.AttachedEntity == null || - !msg.Session.AttachedEntity.TryGetComponent(out HandsComponent? hands) || + if (msg.Session.AttachedEntity == default || + !EntityManager.TryGetComponent(msg.Session.AttachedEntity, out HandsComponent? hands) || !hands.TryGetActiveHeldEntity(out var heldEntity) || - !heldEntity.TryGetComponent(out SignalLinkerComponent? signalLinkerComponent) || - !_interaction.InRangeUnobstructed(msg.Session.AttachedEntity, component.Owner, ignoreInsideBlocker: true) || + !EntityManager.TryGetComponent(heldEntity, out SignalLinkerComponent? signalLinkerComponent) || + !_interaction.InRangeUnobstructed(attached, component.Owner, ignoreInsideBlocker: true) || !signalLinkerComponent.Port.HasValue || !signalLinkerComponent.Port.Value.transmitter.Outputs.ContainsPort(signalLinkerComponent.Port .Value.port) || !component.Inputs.ContainsPort(portSelected.Port)) return; - LinkerInteraction(msg.Session.AttachedEntity, signalLinkerComponent.Port.Value.transmitter, + LinkerInteraction(attached, signalLinkerComponent.Port.Value.transmitter, signalLinkerComponent.Port.Value.port, component, portSelected.Port); break; } @@ -156,16 +158,19 @@ namespace Content.Server.MachineLinking.System private void OnTransmitterUIMessage(EntityUid uid, SignalTransmitterComponent component, ServerBoundUserInterfaceMessage msg) { + if (msg.Session.AttachedEntity is not { } attached) + return; + switch (msg.Message) { case SignalPortSelected portSelected: - if (msg.Session.AttachedEntity == null || - !msg.Session.AttachedEntity.TryGetComponent(out HandsComponent? hands) || + if (msg.Session.AttachedEntity == default || + !EntityManager.TryGetComponent(msg.Session.AttachedEntity, out HandsComponent? hands) || !hands.TryGetActiveHeldEntity(out var heldEntity) || - !heldEntity.TryGetComponent(out SignalLinkerComponent? signalLinkerComponent) || - !_interaction.InRangeUnobstructed(msg.Session.AttachedEntity, component.Owner, ignoreInsideBlocker: true)) + !EntityManager.TryGetComponent(heldEntity, out SignalLinkerComponent? signalLinkerComponent) || + !_interaction.InRangeUnobstructed(attached, component.Owner, ignoreInsideBlocker: true)) return; - LinkerSaveInteraction(msg.Session.AttachedEntity, signalLinkerComponent, component, + LinkerSaveInteraction(attached, signalLinkerComponent, component, portSelected.Port); break; } @@ -176,8 +181,8 @@ namespace Content.Server.MachineLinking.System { if (args.Handled) return; - if (!args.Used.TryGetComponent(out var linker) || - !args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.Used, out var linker) || + !EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) { return; } @@ -197,15 +202,15 @@ namespace Content.Server.MachineLinking.System args.Handled = true; } - private void LinkerInteraction(IEntity entity, SignalTransmitterComponent transmitter, string transmitterPort, + private void LinkerInteraction(EntityUid entity, SignalTransmitterComponent transmitter, string transmitterPort, SignalReceiverComponent receiver, string receiverPort) { if (_linkCollection.LinkExists(transmitter, transmitterPort, receiver, receiverPort)) { if (_linkCollection.RemoveLink(transmitter, transmitterPort, receiver, receiverPort)) { - RaiseLocalEvent(receiver.Owner.Uid, new PortDisconnectedEvent(receiverPort)); - RaiseLocalEvent(transmitter.Owner.Uid, new PortDisconnectedEvent(transmitterPort)); + RaiseLocalEvent(receiver.Owner, new PortDisconnectedEvent(receiverPort)); + RaiseLocalEvent(transmitter.Owner, new PortDisconnectedEvent(transmitterPort)); entity.PopupMessageCursor(Loc.GetString("signal-linker-component-unlinked-port", ("port", receiverPort), ("machine", receiver))); } @@ -240,14 +245,14 @@ namespace Content.Server.MachineLinking.System } var linkAttempt = new LinkAttemptEvent(entity, transmitter, transmitterPort, receiver, receiverPort); - RaiseLocalEvent(receiver.Owner.Uid, linkAttempt); - RaiseLocalEvent(transmitter.Owner.Uid, linkAttempt); + RaiseLocalEvent(receiver.Owner, linkAttempt); + RaiseLocalEvent(transmitter.Owner, linkAttempt); if (linkAttempt.Cancelled) return; var link = _linkCollection.AddLink(transmitter, transmitterPort, receiver, receiverPort); if (link.Transmitterport.Signal != null) - RaiseLocalEvent(receiver.Owner.Uid, + RaiseLocalEvent(receiver.Owner, new SignalReceivedEvent(receiverPort, link.Transmitterport.Signal)); entity.PopupMessageCursor(Loc.GetString("signal-linker-component-linked-port", ("port", receiverPort), @@ -255,7 +260,7 @@ namespace Content.Server.MachineLinking.System } } - private void LinkerSaveInteraction(IEntity entity, SignalLinkerComponent linkerComponent, + private void LinkerSaveInteraction(EntityUid entity, SignalLinkerComponent linkerComponent, SignalTransmitterComponent transmitterComponent, string transmitterPort) { if (SavePortInSignalLinker(linkerComponent, transmitterComponent, transmitterPort)) @@ -276,17 +281,15 @@ namespace Content.Server.MachineLinking.System private bool IsInRange(SignalTransmitterComponent transmitterComponent, SignalReceiverComponent receiverComponent) { - if (transmitterComponent.Owner.TryGetComponent( - out var transmitterPowerReceiverComponent) && - receiverComponent.Owner.TryGetComponent( - out var receiverPowerReceiverComponent) + if (EntityManager.TryGetComponent(transmitterComponent.Owner, out var transmitterPowerReceiverComponent) && + EntityManager.TryGetComponent(receiverComponent.Owner, out var receiverPowerReceiverComponent) ) //&& todo are they on the same powernet? { return true; } - return transmitterComponent.Owner.Transform.MapPosition.InRange( - receiverComponent.Owner.Transform.MapPosition, 30f); + return EntityManager.GetComponent(transmitterComponent.Owner).MapPosition.InRange( + EntityManager.GetComponent(receiverComponent.Owner).MapPosition, 30f); } } } diff --git a/Content.Server/MachineLinking/System/TriggerOnSignalReceivedSystem.cs b/Content.Server/MachineLinking/System/TriggerOnSignalReceivedSystem.cs index 17ca92f4b1..de992a855f 100644 --- a/Content.Server/MachineLinking/System/TriggerOnSignalReceivedSystem.cs +++ b/Content.Server/MachineLinking/System/TriggerOnSignalReceivedSystem.cs @@ -19,7 +19,7 @@ namespace Content.Server.MachineLinking.System private void OnSignalReceived(EntityUid uid, TriggerOnSignalReceivedComponent component, SignalReceivedEvent args) { - _trigger.Trigger(EntityManager.GetEntity(uid)); + _trigger.Trigger(uid); } } } diff --git a/Content.Server/Medical/Components/HealingComponent.cs b/Content.Server/Medical/Components/HealingComponent.cs index e3bab68ca9..d3b7ade405 100644 --- a/Content.Server/Medical/Components/HealingComponent.cs +++ b/Content.Server/Medical/Components/HealingComponent.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using Content.Server.Administration.Logs; using Content.Server.Stack; using Content.Shared.ActionBlocker; -using Content.Shared.Administration.Logs; using Content.Shared.Damage; using Content.Shared.Damage.Prototypes; using Content.Shared.Database; @@ -10,6 +9,7 @@ using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using Content.Shared.Stacks; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; using Robust.Shared.ViewVariables; @@ -19,6 +19,8 @@ namespace Content.Server.Medical.Components [RegisterComponent] public class HealingComponent : Component, IAfterInteract { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Healing"; [DataField("damage", required: true)] @@ -40,7 +42,7 @@ namespace Content.Server.Medical.Components return false; } - if (!eventArgs.Target.TryGetComponent(out DamageableComponent? targetDamage)) + if (!_entMan.TryGetComponent(eventArgs.Target.Value, out DamageableComponent? targetDamage)) { return true; } @@ -49,7 +51,7 @@ namespace Content.Server.Medical.Components return true; } - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if (!EntitySystem.Get().CanInteract(eventArgs.User)) { return true; } @@ -60,12 +62,12 @@ namespace Content.Server.Medical.Components return true; } - if (Owner.TryGetComponent(out var stack) && !EntitySystem.Get().Use(Owner.Uid, 1, stack)) + if (_entMan.TryGetComponent(Owner, out var stack) && !EntitySystem.Get().Use(Owner, 1, stack)) { return true; } - var healed = EntitySystem.Get().TryChangeDamage(eventArgs.Target.Uid, Damage, true); + var healed = EntitySystem.Get().TryChangeDamage(eventArgs.Target.Value, Damage, true); if (healed == null) return true; diff --git a/Content.Server/Medical/Components/MedicalScannerComponent.cs b/Content.Server/Medical/Components/MedicalScannerComponent.cs index 413dca3fb8..2ff3235ab9 100644 --- a/Content.Server/Medical/Components/MedicalScannerComponent.cs +++ b/Content.Server/Medical/Components/MedicalScannerComponent.cs @@ -18,7 +18,6 @@ using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using Robust.Shared.Maths; using Robust.Shared.Network; using Robust.Shared.ViewVariables; @@ -29,6 +28,7 @@ namespace Content.Server.Medical.Components [ComponentReference(typeof(SharedMedicalScannerComponent))] public class MedicalScannerComponent : SharedMedicalScannerComponent, IActivate, IDestroyAct { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IServerPreferencesManager _prefsManager = null!; public static readonly TimeSpan InternalOpenAttemptDelay = TimeSpan.FromSeconds(0.5); @@ -37,7 +37,7 @@ namespace Content.Server.Medical.Components private ContainerSlot _bodyContainer = default!; [ViewVariables] - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(MedicalScannerUiKey.Key); @@ -72,7 +72,7 @@ namespace Content.Server.Medical.Components var body = _bodyContainer.ContainedEntity; if (body == null) { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance?.SetData(MedicalScannerVisuals.Status, MedicalScannerStatus.Open); } @@ -80,22 +80,22 @@ namespace Content.Server.Medical.Components return EmptyUIState; } - if (!body.TryGetComponent(out DamageableComponent? damageable)) + if (!_entMan.TryGetComponent(body.Value, out DamageableComponent? damageable)) { return EmptyUIState; } - if (_bodyContainer.ContainedEntity?.Uid == null) + if (_bodyContainer.ContainedEntity == null) { - return new MedicalScannerBoundUserInterfaceState(body.Uid, damageable, true); + return new MedicalScannerBoundUserInterfaceState(body, damageable, true); } var cloningSystem = EntitySystem.Get(); - var scanned = _bodyContainer.ContainedEntity.TryGetComponent(out MindComponent? mindComponent) && + var scanned = _entMan.TryGetComponent(_bodyContainer.ContainedEntity.Value, out MindComponent? mindComponent) && mindComponent.Mind != null && cloningSystem.HasDnaScan(mindComponent.Mind); - return new MedicalScannerBoundUserInterfaceState(body.Uid, damageable, scanned); + return new MedicalScannerBoundUserInterfaceState(body, damageable, scanned); } private void UpdateUserInterface() @@ -134,11 +134,12 @@ namespace Content.Server.Medical.Components if (Powered) { var body = _bodyContainer.ContainedEntity; - var state = body?.GetComponentOrNull(); + if (body == null) + return MedicalScannerStatus.Open; - return state == null - ? MedicalScannerStatus.Open - : GetStatusFromDamageState(state); + var state = _entMan.GetComponentOrNull(body.Value); + + return state == null ? MedicalScannerStatus.Open : GetStatusFromDamageState(state); } return MedicalScannerStatus.Off; @@ -146,7 +147,7 @@ namespace Content.Server.Medical.Components private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(MedicalScannerVisuals.Status, GetStatus()); } @@ -154,7 +155,7 @@ namespace Content.Server.Medical.Components void IActivate.Activate(ActivateEventArgs args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(args.User, out ActorComponent? actor)) { return; } @@ -165,7 +166,7 @@ namespace Content.Server.Medical.Components UserInterface?.Open(actor.PlayerSession); } - public void InsertBody(IEntity user) + public void InsertBody(EntityUid user) { _bodyContainer.Insert(user); UpdateUserInterface(); @@ -174,12 +175,11 @@ namespace Content.Server.Medical.Components public void EjectBody() { - var containedEntity = _bodyContainer.ContainedEntity; - if (containedEntity == null) return; - _bodyContainer.Remove(containedEntity); + if (_bodyContainer.ContainedEntity is not {Valid: true} contained) return; + _bodyContainer.Remove(contained); UpdateUserInterface(); UpdateAppearance(); - EntitySystem.Get().ForciblySetClimbing(containedEntity.Uid); + EntitySystem.Get().ForciblySetClimbing(contained); } public void Update(float frameTime) @@ -190,7 +190,7 @@ namespace Content.Server.Medical.Components private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj) { - if (obj.Message is not UiButtonPressedMessage message) return; + if (obj.Message is not UiButtonPressedMessage message || obj.Session.AttachedEntity == null) return; switch (message.Button) { @@ -199,9 +199,9 @@ namespace Content.Server.Medical.Components { var cloningSystem = EntitySystem.Get(); - if (!_bodyContainer.ContainedEntity.TryGetComponent(out MindComponent? mindComp) || mindComp.Mind == null) + if (!_entMan.TryGetComponent(_bodyContainer.ContainedEntity.Value, out MindComponent? mindComp) || mindComp.Mind == null) { - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("medical-scanner-component-msg-no-soul")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("medical-scanner-component-msg-no-soul")); break; } @@ -216,7 +216,7 @@ namespace Content.Server.Medical.Components if (mindUser == null) { // For now assume this means soul departed - obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("medical-scanner-component-msg-soul-broken")); + obj.Session.AttachedEntity.Value.PopupMessageCursor(Loc.GetString("medical-scanner-component-msg-soul-broken")); break; } diff --git a/Content.Server/Medical/MedicalScannerSystem.cs b/Content.Server/Medical/MedicalScannerSystem.cs index 06cd9eaa12..1e69034e91 100644 --- a/Content.Server/Medical/MedicalScannerSystem.cs +++ b/Content.Server/Medical/MedicalScannerSystem.cs @@ -1,7 +1,7 @@ using Content.Server.Medical.Components; using Content.Shared.ActionBlocker; -using Content.Shared.Verbs; using Content.Shared.Movement; +using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -32,13 +32,13 @@ namespace Content.Server.Medical !args.CanAccess || !args.CanInteract || component.IsOccupied || - !component.CanInsert(args.Using)) + !component.CanInsert(args.Using.Value)) return; Verb verb = new(); - verb.Act = () => component.InsertBody(args.Using); + verb.Act = () => component.InsertBody(args.Using.Value); verb.Category = VerbCategory.Insert; - verb.Text = args.Using.Name; + verb.Text = EntityManager.GetComponent(args.Using.Value).EntityName; args.Verbs.Add(verb); } @@ -60,7 +60,7 @@ namespace Content.Server.Medical // Self-insert verb if (!component.IsOccupied && component.CanInsert(args.User) && - _actionBlockerSystem.CanMove(args.User.Uid)) + _actionBlockerSystem.CanMove(args.User)) { Verb verb = new(); verb.Act = () => component.InsertBody(args.User); @@ -75,7 +75,7 @@ namespace Content.Server.Medical private void OnRelayMovement(EntityUid uid, MedicalScannerComponent component, RelayMovementEntityEvent args) { - if (_blocker.CanInteract(args.Entity.Uid)) + if (_blocker.CanInteract(args.Entity)) { if (_gameTiming.CurTime < component.LastInternalOpenAttempt + MedicalScannerComponent.InternalOpenAttemptDelay) diff --git a/Content.Server/Mind/Commands/MindInfoCommand.cs b/Content.Server/Mind/Commands/MindInfoCommand.cs index d069588a66..c83ef4b3b3 100644 --- a/Content.Server/Mind/Commands/MindInfoCommand.cs +++ b/Content.Server/Mind/Commands/MindInfoCommand.cs @@ -41,7 +41,7 @@ namespace Content.Server.Mind.Commands } var builder = new StringBuilder(); - builder.AppendFormat("player: {0}, mob: {1}\nroles: ", mind.UserId, mind.OwnedComponent?.Owner?.Uid); + builder.AppendFormat("player: {0}, mob: {1}\nroles: ", mind.UserId, mind.OwnedComponent?.Owner); foreach (var role in mind.AllRoles) { builder.AppendFormat("{0} ", role.Name); diff --git a/Content.Server/Mind/Components/MindComponent.cs b/Content.Server/Mind/Components/MindComponent.cs index 3334643a01..386ee396a9 100644 --- a/Content.Server/Mind/Components/MindComponent.cs +++ b/Content.Server/Mind/Components/MindComponent.cs @@ -22,6 +22,8 @@ namespace Content.Server.Mind.Components public class MindComponent : Component, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + /// public override string Name => "Mind"; @@ -53,25 +55,25 @@ namespace Content.Server.Mind.Components /// /// Don't call this unless you know what the hell you're doing. - /// Use instead. + /// Use instead. /// If that doesn't cover it, make something to cover it. /// public void InternalEjectMind() { if (!Deleted) - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new MindRemovedMessage()); + _entMan.EventBus.RaiseLocalEvent(Owner, new MindRemovedMessage()); Mind = null; } /// /// Don't call this unless you know what the hell you're doing. - /// Use instead. + /// Use instead. /// If that doesn't cover it, make something to cover it. /// public void InternalAssignMind(Mind value) { Mind = value; - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new MindAddedMessage()); + _entMan.EventBus.RaiseLocalEvent(Owner, new MindAddedMessage()); } protected override void Shutdown() @@ -84,39 +86,39 @@ namespace Content.Server.Mind.Components if (HasMind) { - var visiting = Mind?.VisitingEntity; - if (visiting != null) + if (Mind?.VisitingEntity is {Valid: true} visiting) { - if (visiting.TryGetComponent(out GhostComponent? ghost)) + if (_entMan.TryGetComponent(visiting, out GhostComponent? ghost)) { EntitySystem.Get().SetCanReturnToBody(ghost, false); } - Mind!.TransferTo(visiting.Uid); + Mind!.TransferTo(visiting); } else if (GhostOnShutdown) { - var spawnPosition = Owner.Transform.Coordinates; + var spawnPosition = _entMan.GetComponent(Owner).Coordinates; // Use a regular timer here because the entity has probably been deleted. Timer.Spawn(0, () => { // Async this so that we don't throw if the grid we're on is being deleted. var mapMan = IoCManager.Resolve(); - var gridId = spawnPosition.GetGridId(Owner.EntityManager); + var gridId = spawnPosition.GetGridId(_entMan); if (gridId == GridId.Invalid || !mapMan.GridExists(gridId)) { spawnPosition = EntitySystem.Get().GetObserverSpawnPoint(); } - var ghost = Owner.EntityManager.SpawnEntity("MobObserver", spawnPosition); - var ghostComponent = ghost.GetComponent(); + var ghost = _entMan.SpawnEntity("MobObserver", spawnPosition); + var ghostComponent = _entMan.GetComponent(ghost); EntitySystem.Get().SetCanReturnToBody(ghostComponent, false); if (Mind != null) { - ghost.Name = Mind.CharacterName ?? string.Empty; - Mind.TransferTo(ghost.Uid); + string? val = Mind.CharacterName ?? string.Empty; + _entMan.GetComponent(ghost).EntityName = val; + Mind.TransferTo(ghost); } }); } @@ -131,7 +133,7 @@ namespace Content.Server.Mind.Components } var dead = - Owner.TryGetComponent(out var state) && + _entMan.TryGetComponent(Owner, out var state) && state.IsDead(); if (!HasMind) diff --git a/Content.Server/Mind/Mind.cs b/Content.Server/Mind/Mind.cs index 3aadd4b2ec..22fb9ea7e9 100644 --- a/Content.Server/Mind/Mind.cs +++ b/Content.Server/Mind/Mind.cs @@ -65,9 +65,9 @@ namespace Content.Server.Mind public bool IsVisitingEntity => VisitingEntity != null; [ViewVariables] - public IEntity? VisitingEntity { get; private set; } + public EntityUid? VisitingEntity { get; private set; } - [ViewVariables] public IEntity? CurrentEntity => VisitingEntity ?? OwnedEntity; + [ViewVariables] public EntityUid? CurrentEntity => VisitingEntity ?? OwnedEntity; [ViewVariables(VVAccess.ReadWrite)] public string? CharacterName { get; set; } @@ -90,7 +90,7 @@ namespace Content.Server.Mind /// Can be null. /// [ViewVariables] - public IEntity? OwnedEntity => OwnedComponent?.Owner; + public EntityUid? OwnedEntity => OwnedComponent?.Owner; /// /// An enumerable over all the roles this mind has. @@ -153,9 +153,7 @@ namespace Content.Server.Mind // (If being a borg or AI counts as dead, then this is highly likely, as it's still the same Mind for practical purposes.) // This can be null if they're deleted (spike / brain nom) - if (OwnedEntity == null) - return true; - var targetMobState = OwnedEntity.GetComponentOrNull(); + var targetMobState = IoCManager.Resolve().GetComponentOrNull(OwnedEntity); // This can be null if it's a brain (this happens very often) // Brains are the result of gibbing so should definitely count as dead if (targetMobState == null) @@ -184,7 +182,10 @@ namespace Content.Server.Mind role.Greet(); var message = new RoleAddedEvent(role); - OwnedEntity?.EntityManager.EventBus.RaiseLocalEvent(OwnedEntity.Uid, message); + if (OwnedEntity != null) + { + IoCManager.Resolve().EventBus.RaiseLocalEvent(OwnedEntity.Value, message); + } return role; } @@ -206,7 +207,11 @@ namespace Content.Server.Mind _roles.Remove(role); var message = new RoleRemovedEvent(role); - OwnedEntity?.EntityManager.EventBus.RaiseLocalEvent(OwnedEntity.Uid, message); + + if (OwnedEntity != null) + { + IoCManager.Resolve().EventBus.RaiseLocalEvent(OwnedEntity.Value, message); + } } public bool HasRole() where T : Role @@ -246,7 +251,7 @@ namespace Content.Server.Mind /// /// Transfer this mind's control over to a new entity. /// - /// + /// /// The entity to control. /// Can be null, in which case it will simply detach the mind from any entity. /// @@ -256,31 +261,30 @@ namespace Content.Server.Mind /// /// Thrown if is already owned by another mind. /// - public void TransferTo(EntityUid? entityUid, bool ghostCheckOverride = false) + public void TransferTo(EntityUid? entity, bool ghostCheckOverride = false) { var entMan = IoCManager.Resolve(); - IEntity? entity = (entityUid != null) ? entMan.GetEntity(entityUid.Value) : null; MindComponent? component = null; var alreadyAttached = false; - if (entityUid != null) + if (entity != null) { - if (!entMan.TryGetComponent(entityUid.Value, out component)) + if (!entMan.TryGetComponent(entity.Value, out component)) { - component = entMan.AddComponent(entityUid.Value); + component = entMan.AddComponent(entity.Value); } else if (component!.HasMind) { EntitySystem.Get().OnGhostAttempt(component.Mind!, false); } - if (entMan.TryGetComponent(entityUid.Value, out var actor)) + if (entMan.TryGetComponent(entity.Value, out var actor)) { // Happens when transferring to your currently visited entity. if (actor.PlayerSession != Session) { - throw new ArgumentException("Visit target already has a session.", nameof(entityUid)); + throw new ArgumentException("Visit target already has a session.", nameof(entity)); } alreadyAttached = true; @@ -292,16 +296,16 @@ namespace Content.Server.Mind OwnedComponent = component; OwnedComponent?.InternalAssignMind(this); - if (IsVisitingEntity + if (VisitingEntity != null && (ghostCheckOverride // to force mind transfer, for example from ControlMobVerb - || !VisitingEntity!.TryGetComponent(out GhostComponent? ghostComponent) // visiting entity is not a Ghost + || !entMan.TryGetComponent(VisitingEntity!, out GhostComponent? ghostComponent) // visiting entity is not a Ghost || !ghostComponent.CanReturnToBody)) // it is a ghost, but cannot return to body anyway, so it's okay { - VisitingEntity = null; + VisitingEntity = default; } // Player is CURRENTLY connected. - if (Session != null && !alreadyAttached && VisitingEntity == null) + if (Session != null && !alreadyAttached && VisitingEntity == default) { Session.AttachToEntity(entity); Logger.Info($"Session {Session.Name} transferred to entity {entity}."); @@ -350,12 +354,12 @@ namespace Content.Server.Mind newOwnerData.UpdateMindFromMindChangeOwningPlayer(this); } - public void Visit(IEntity entity) + public void Visit(EntityUid entity) { Session?.AttachToEntity(entity); VisitingEntity = entity; - var comp = entity.AddComponent(); + var comp = IoCManager.Resolve().AddComponent(entity); comp.Mind = this; Logger.Info($"Session {Session?.Name} visiting entity {entity}."); @@ -363,24 +367,25 @@ namespace Content.Server.Mind public void UnVisit() { - if (!IsVisitingEntity) + if (VisitingEntity == null) { return; } Session?.AttachToEntity(OwnedEntity); - var oldVisitingEnt = VisitingEntity; + var oldVisitingEnt = VisitingEntity.Value; // Null this before removing the component to avoid any infinite loops. - VisitingEntity = null; + VisitingEntity = default; DebugTools.AssertNotNull(oldVisitingEnt); - if (oldVisitingEnt!.HasComponent()) + var entities = IoCManager.Resolve(); + if (entities.HasComponent(oldVisitingEnt)) { - oldVisitingEnt.RemoveComponent(); + entities.RemoveComponent(oldVisitingEnt); } - oldVisitingEnt.EntityManager.EventBus.RaiseLocalEvent(oldVisitingEnt.Uid, new MindUnvisitedMessage()); + entities.EventBus.RaiseLocalEvent(oldVisitingEnt, new MindUnvisitedMessage()); } public bool TryGetSession([NotNullWhen(true)] out IPlayerSession? session) diff --git a/Content.Server/Mining/Components/AsteroidRockComponent.cs b/Content.Server/Mining/Components/AsteroidRockComponent.cs index 10b1bb731c..5d03c68b85 100644 --- a/Content.Server/Mining/Components/AsteroidRockComponent.cs +++ b/Content.Server/Mining/Components/AsteroidRockComponent.cs @@ -17,6 +17,7 @@ namespace Content.Server.Mining.Components [RegisterComponent] public class AsteroidRockComponent : Component, IInteractUsing { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _random = default!; public override string Name => "AsteroidRock"; @@ -25,7 +26,7 @@ namespace Content.Server.Mining.Components protected override void Initialize() { base.Initialize(); - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(AsteroidRockVisuals.State, _random.Pick(SpriteStates)); } @@ -34,12 +35,12 @@ namespace Content.Server.Mining.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { var item = eventArgs.Using; - if (!item.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) + if (!_entMan.TryGetComponent(item, out MeleeWeaponComponent? meleeWeaponComponent)) return false; - EntitySystem.Get().TryChangeDamage(Owner.Uid, meleeWeaponComponent.Damage); + EntitySystem.Get().TryChangeDamage(Owner, meleeWeaponComponent.Damage); - if (!item.TryGetComponent(out PickaxeComponent? pickaxeComponent)) + if (!_entMan.TryGetComponent(item, out PickaxeComponent? pickaxeComponent)) return true; SoundSystem.Play(Filter.Pvs(Owner), pickaxeComponent.MiningSound.GetSound(), Owner, AudioParams.Default); diff --git a/Content.Server/Morgue/Components/BodyBagEntityStorageComponent.cs b/Content.Server/Morgue/Components/BodyBagEntityStorageComponent.cs index 0489e4a2a9..fb21adce49 100644 --- a/Content.Server/Morgue/Components/BodyBagEntityStorageComponent.cs +++ b/Content.Server/Morgue/Components/BodyBagEntityStorageComponent.cs @@ -1,20 +1,9 @@ -using System.Threading.Tasks; -using Content.Server.Hands.Components; -using Content.Server.Items; -using Content.Server.Paper; using Content.Server.Storage.Components; using Content.Shared.Body.Components; -using Content.Shared.Examine; using Content.Shared.Interaction; -using Content.Shared.Morgue; -using Content.Shared.Popups; using Content.Shared.Standing; -using Robust.Server.GameObjects; -using Robust.Shared.Containers; using Robust.Shared.GameObjects; -using Robust.Shared.Localization; -using Robust.Shared.Utility; -using Robust.Shared.ViewVariables; +using Robust.Shared.IoC; namespace Content.Server.Morgue.Components { @@ -26,9 +15,9 @@ namespace Content.Server.Morgue.Components { public override string Name => "BodyBagEntityStorage"; - protected override bool AddToContents(IEntity entity) + protected override bool AddToContents(EntityUid entity) { - if (entity.HasComponent() && !EntitySystem.Get().IsDown(entity.Uid)) return false; + if (IoCManager.Resolve().HasComponent(entity) && !EntitySystem.Get().IsDown(entity)) return false; return base.AddToContents(entity); } } diff --git a/Content.Server/Morgue/Components/CrematoriumEntityStorageComponent.cs b/Content.Server/Morgue/Components/CrematoriumEntityStorageComponent.cs index 384ec59538..807d6e54e8 100644 --- a/Content.Server/Morgue/Components/CrematoriumEntityStorageComponent.cs +++ b/Content.Server/Morgue/Components/CrematoriumEntityStorageComponent.cs @@ -12,9 +12,9 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Content.Shared.Standing; using Robust.Server.GameObjects; -using Robust.Server.Player; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -32,6 +32,8 @@ namespace Content.Server.Morgue.Components public class CrematoriumEntityStorageComponent : MorgueEntityStorageComponent, IExamine, ISuicideAct #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "CrematoriumEntityStorage"; [DataField("cremateStartSound")] private SoundSpecifier _cremateStartSound = new SoundPathSpecifier("/Audio/Items/lighter1.ogg"); @@ -68,7 +70,7 @@ namespace Content.Server.Morgue.Components } } - public override bool CanOpen(IEntity user, bool silent = false) + public override bool CanOpen(EntityUid user, bool silent = false) { if (Cooking) { @@ -104,7 +106,7 @@ namespace Content.Server.Morgue.Components _cremateCancelToken = new CancellationTokenSource(); Owner.SpawnTimer(_burnMilis, () => { - if (Owner.Deleted) + if (_entities.Deleted(Owner)) return; Appearance?.SetData(CrematoriumVisuals.Burning, false); @@ -116,10 +118,10 @@ namespace Content.Server.Morgue.Components { var item = Contents.ContainedEntities[i]; Contents.Remove(item); - item.Delete(); + _entities.DeleteEntity(item); } - var ash = Owner.EntityManager.SpawnEntity("Ash", Owner.Transform.Coordinates); + var ash = _entities.SpawnEntity("Ash", _entities.GetComponent(Owner).Coordinates); Contents.Insert(ash); } @@ -130,12 +132,16 @@ namespace Content.Server.Morgue.Components }, _cremateCancelToken.Token); } - SuicideKind ISuicideAct.Suicide(IEntity victim, IChatManager chat) + SuicideKind ISuicideAct.Suicide(EntityUid victim, IChatManager chat) { - if (victim.TryGetComponent(out ActorComponent? actor) && actor.PlayerSession.ContentData()?.Mind is {} mind) + if (_entities.TryGetComponent(victim, out ActorComponent? actor) && actor.PlayerSession.ContentData()?.Mind is {} mind) { EntitySystem.Get().OnGhostAttempt(mind, false); - mind.OwnedEntity?.PopupMessage(Loc.GetString("crematorium-entity-storage-component-suicide-message")); + + if (mind.OwnedEntity is {Valid: true} entity) + { + entity.PopupMessage(Loc.GetString("crematorium-entity-storage-component-suicide-message")); + } } victim.PopupMessageOtherClients(Loc.GetString("crematorium-entity-storage-component-suicide-message-others", ("victim", victim))); @@ -143,11 +149,11 @@ namespace Content.Server.Morgue.Components if (CanInsert(victim)) { Insert(victim); - EntitySystem.Get().Down(victim.Uid, false); + EntitySystem.Get().Down(victim, false); } else { - victim.Delete(); + _entities.DeleteEntity(victim); } Cremate(); diff --git a/Content.Server/Morgue/Components/MorgueEntityStorageComponent.cs b/Content.Server/Morgue/Components/MorgueEntityStorageComponent.cs index 881f866c58..1900b36a47 100644 --- a/Content.Server/Morgue/Components/MorgueEntityStorageComponent.cs +++ b/Content.Server/Morgue/Components/MorgueEntityStorageComponent.cs @@ -33,6 +33,8 @@ namespace Content.Server.Morgue.Components public class MorgueEntityStorageComponent : EntityStorageComponent, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "MorgueEntityStorage"; [ViewVariables(VVAccess.ReadWrite)] @@ -40,7 +42,7 @@ namespace Content.Server.Morgue.Components private string? _trayPrototypeId; [ViewVariables] - private IEntity? _tray; + private EntityUid _tray; [ViewVariables] public ContainerSlot? TrayContainer { get; private set; } @@ -65,21 +67,21 @@ namespace Content.Server.Morgue.Components public override Vector2 ContentsDumpPosition() { if (_tray != null) - return _tray.Transform.WorldPosition; + return _entMan.GetComponent(_tray).WorldPosition; return base.ContentsDumpPosition(); } - protected override bool AddToContents(IEntity entity) + protected override bool AddToContents(EntityUid entity) { - if (entity.HasComponent() && !EntitySystem.Get().IsDown(entity.Uid)) + if (_entMan.HasComponent(entity) && !EntitySystem.Get().IsDown(entity)) return false; return base.AddToContents(entity); } - public override bool CanOpen(IEntity user, bool silent = false) + public override bool CanOpen(EntityUid user, bool silent = false) { if (!Owner.InRangeUnobstructed( - Owner.Transform.Coordinates.Offset(Owner.Transform.LocalRotation.GetCardinalDir()), + _entMan.GetComponent(Owner).Coordinates.Offset(_entMan.GetComponent(Owner).LocalRotation.GetCardinalDir()), collisionMask: CollisionGroup.Impassable | CollisionGroup.VaultImpassable )) { @@ -100,7 +102,7 @@ namespace Content.Server.Morgue.Components if (_tray == null) { - _tray = Owner.EntityManager.SpawnEntity(_trayPrototypeId, Owner.Transform.Coordinates); + _tray = _entMan.SpawnEntity(_trayPrototypeId, _entMan.GetComponent(Owner).Coordinates); var trayComp = _tray.EnsureComponent(); trayComp.Morgue = Owner; } @@ -109,7 +111,7 @@ namespace Content.Server.Morgue.Components TrayContainer?.Remove(_tray); } - _tray.Transform.Coordinates = new EntityCoordinates(Owner.Uid, 0, -1); + _entMan.GetComponent(_tray).Coordinates = new EntityCoordinates(Owner, 0, -1); base.OpenStorage(); } @@ -122,9 +124,9 @@ namespace Content.Server.Morgue.Components foreach (var entity in Contents.ContainedEntities) { count++; - if (!hasMob && entity.HasComponent()) + if (!hasMob && _entMan.HasComponent(entity)) hasMob = true; - if (!hasSoul && entity.TryGetComponent(out var actor) && actor.PlayerSession != null) + if (!hasSoul && _entMan.TryGetComponent(entity, out var actor) && actor.PlayerSession != null) hasSoul = true; } Appearance?.SetData(MorgueVisuals.HasContents, count > 0); @@ -145,7 +147,7 @@ namespace Content.Server.Morgue.Components } } - protected override IEnumerable DetermineCollidingEntities() + protected override IEnumerable DetermineCollidingEntities() { if (_tray == null) { diff --git a/Content.Server/Morgue/Components/MorgueTrayComponent.cs b/Content.Server/Morgue/Components/MorgueTrayComponent.cs index cedb15a009..9e808adf9e 100644 --- a/Content.Server/Morgue/Components/MorgueTrayComponent.cs +++ b/Content.Server/Morgue/Components/MorgueTrayComponent.cs @@ -1,5 +1,6 @@ using Content.Shared.Interaction; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Server.Morgue.Components @@ -11,11 +12,13 @@ namespace Content.Server.Morgue.Components public override string Name => "MorgueTray"; [ViewVariables] - public IEntity? Morgue { get; set; } + public EntityUid Morgue { get; set; } void IActivate.Activate(ActivateEventArgs eventArgs) { - if (Morgue != null && !Morgue.Deleted && Morgue.TryGetComponent(out var comp)) + var entMan = IoCManager.Resolve(); + + if (Morgue != default && !entMan.Deleted(Morgue) && entMan.TryGetComponent(Morgue, out var comp)) { comp.Activate(new ActivateEventArgs(eventArgs.User, Morgue)); } diff --git a/Content.Server/Movement/Components/FootstepModifierComponent.cs b/Content.Server/Movement/Components/FootstepModifierComponent.cs index fd09533153..fee5f74909 100644 --- a/Content.Server/Movement/Components/FootstepModifierComponent.cs +++ b/Content.Server/Movement/Components/FootstepModifierComponent.cs @@ -2,6 +2,7 @@ using Content.Shared.Audio; using Content.Shared.Sound; using Robust.Shared.Audio; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -24,7 +25,7 @@ namespace Content.Server.Movement.Components public void PlayFootstep() { - SoundSystem.Play(Filter.Pvs(Owner), SoundCollection.GetSound(), Owner.Transform.Coordinates, AudioHelpers.WithVariation(Variation).WithVolume(-2f)); + SoundSystem.Play(Filter.Pvs(Owner), SoundCollection.GetSound(), IoCManager.Resolve().GetComponent(Owner).Coordinates, AudioHelpers.WithVariation(Variation).WithVolume(-2f)); } } } diff --git a/Content.Server/Movement/Components/StressTestMovementComponent.cs b/Content.Server/Movement/Components/StressTestMovementComponent.cs index b6081a3b91..13d3a89081 100644 --- a/Content.Server/Movement/Components/StressTestMovementComponent.cs +++ b/Content.Server/Movement/Components/StressTestMovementComponent.cs @@ -1,4 +1,5 @@ using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Server.Movement.Components @@ -15,7 +16,7 @@ namespace Content.Server.Movement.Components { base.Startup(); - Origin = Owner.Transform.WorldPosition; + Origin = IoCManager.Resolve().GetComponent(Owner).WorldPosition; } } } diff --git a/Content.Server/Movement/StressTestMovementSystem.cs b/Content.Server/Movement/StressTestMovementSystem.cs index 7d48754dfd..317a5bfe97 100644 --- a/Content.Server/Movement/StressTestMovementSystem.cs +++ b/Content.Server/Movement/StressTestMovementSystem.cs @@ -2,6 +2,7 @@ using System; using Content.Server.Movement.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Server.Movement @@ -15,7 +16,7 @@ namespace Content.Server.Movement foreach (var stressTest in EntityManager.EntityQuery(true)) { - var transform = stressTest.Owner.Transform; + var transform = EntityManager.GetComponent(stressTest.Owner); stressTest.Progress += frameTime; diff --git a/Content.Server/NodeContainer/EntitySystems/NodeGroupSystem.cs b/Content.Server/NodeContainer/EntitySystems/NodeGroupSystem.cs index ce19ef09b7..eece6b6a04 100644 --- a/Content.Server/NodeContainer/EntitySystems/NodeGroupSystem.cs +++ b/Content.Server/NodeContainer/EntitySystems/NodeGroupSystem.cs @@ -364,7 +364,7 @@ namespace Content.Server.NodeContainer.EntitySystems Name = n.Name, NetId = n.NetId, Reachable = n.ReachableNodes.Select(r => r.NetId).ToArray(), - Entity = n.Owner.Uid, + Entity = n.Owner, Type = n.GetType().Name }).ToArray() }; diff --git a/Content.Server/NodeContainer/NodeGroups/BaseNodeGroup.cs b/Content.Server/NodeContainer/NodeGroups/BaseNodeGroup.cs index b65700b7e7..cc4f14be4c 100644 --- a/Content.Server/NodeContainer/NodeGroups/BaseNodeGroup.cs +++ b/Content.Server/NodeContainer/NodeGroups/BaseNodeGroup.cs @@ -3,6 +3,7 @@ using System.Linq; using Content.Server.NodeContainer.EntitySystems; using Content.Server.NodeContainer.Nodes; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.ViewVariables; @@ -76,7 +77,7 @@ namespace Content.Server.NodeContainer.NodeGroups public virtual void Initialize(Node sourceNode) { // TODO: Can we get rid of this GridId? - GridId = sourceNode.Owner.Transform.GridID; + GridId = IoCManager.Resolve().GetComponent(sourceNode.Owner).GridID; } /// diff --git a/Content.Server/NodeContainer/Nodes/AdjacentNode.cs b/Content.Server/NodeContainer/Nodes/AdjacentNode.cs index c94206aa44..c3a08ccc13 100644 --- a/Content.Server/NodeContainer/Nodes/AdjacentNode.cs +++ b/Content.Server/NodeContainer/Nodes/AdjacentNode.cs @@ -14,12 +14,12 @@ namespace Content.Server.NodeContainer.Nodes { public override IEnumerable GetReachableNodes() { - if (!Owner.Transform.Anchored) + if (!IoCManager.Resolve().GetComponent(Owner).Anchored) yield break; var entMan = IoCManager.Resolve(); - var grid = IoCManager.Resolve().GetGrid(Owner.Transform.GridID); - var gridIndex = grid.TileIndicesFor(Owner.Transform.Coordinates); + var grid = IoCManager.Resolve().GetGrid(IoCManager.Resolve().GetComponent(Owner).GridID); + var gridIndex = grid.TileIndicesFor(IoCManager.Resolve().GetComponent(Owner).Coordinates); foreach (var (_, node) in NodeHelpers.GetCardinalNeighborNodes(entMan, grid, gridIndex)) { diff --git a/Content.Server/NodeContainer/Nodes/Node.cs b/Content.Server/NodeContainer/Nodes/Node.cs index f544490d7e..2de408c15c 100644 --- a/Content.Server/NodeContainer/Nodes/Node.cs +++ b/Content.Server/NodeContainer/Nodes/Node.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Content.Server.NodeContainer.EntitySystems; using Content.Server.NodeContainer.NodeGroups; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -30,14 +31,14 @@ namespace Content.Server.NodeContainer.Nodes /// /// The entity that owns this node via its . /// - [ViewVariables] public IEntity Owner { get; private set; } = default!; + [ViewVariables] public EntityUid Owner { get; private set; } = default!; /// /// If this node should be considered for connection by other nodes. /// public bool Connectable => !Deleting && Anchored; - protected bool Anchored => !NeedAnchored || Owner.Transform.Anchored; + protected bool Anchored => !NeedAnchored || IoCManager.Resolve().GetComponent(Owner).Anchored; [ViewVariables(VVAccess.ReadWrite)] [DataField("needAnchored")] @@ -68,7 +69,7 @@ namespace Content.Server.NodeContainer.Nodes /// Invoked when the owning is initialized. /// /// The owning entity. - public virtual void Initialize(IEntity owner) + public virtual void Initialize(EntityUid owner) { Owner = owner; } diff --git a/Content.Server/NodeContainer/Nodes/PipeNode.cs b/Content.Server/NodeContainer/Nodes/PipeNode.cs index af13370149..15b30c247c 100644 --- a/Content.Server/NodeContainer/Nodes/PipeNode.cs +++ b/Content.Server/NodeContainer/Nodes/PipeNode.cs @@ -166,14 +166,14 @@ namespace Content.Server.NodeContainer.Nodes /// protected IEnumerable PipesInDirection(PipeDirection pipeDir) { - if (!Owner.Transform.Anchored) + if (!IoCManager.Resolve().GetComponent(Owner).Anchored) yield break; - var grid = IoCManager.Resolve().GetGrid(Owner.Transform.GridID); - var position = Owner.Transform.Coordinates; + var grid = IoCManager.Resolve().GetGrid(IoCManager.Resolve().GetComponent(Owner).GridID); + var position = IoCManager.Resolve().GetComponent(Owner).Coordinates; foreach (var entity in grid.GetInDir(position, pipeDir.ToDirection())) { - if (!Owner.EntityManager.TryGetComponent(entity, out var container)) + if (!IoCManager.Resolve().TryGetComponent(entity, out var container)) continue; foreach (var node in container.Nodes.Values) @@ -189,14 +189,14 @@ namespace Content.Server.NodeContainer.Nodes /// protected IEnumerable PipesInTile() { - if (!Owner.Transform.Anchored) + if (!IoCManager.Resolve().GetComponent(Owner).Anchored) yield break; - var grid = IoCManager.Resolve().GetGrid(Owner.Transform.GridID); - var position = Owner.Transform.Coordinates; + var grid = IoCManager.Resolve().GetGrid(IoCManager.Resolve().GetComponent(Owner).GridID); + var position = IoCManager.Resolve().GetComponent(Owner).Coordinates; foreach (var entity in grid.GetLocal(position)) { - if (!Owner.EntityManager.TryGetComponent(entity, out var container)) + if (!IoCManager.Resolve().TryGetComponent(entity, out var container)) continue; foreach (var node in container.Nodes.Values) @@ -215,7 +215,7 @@ namespace Content.Server.NodeContainer.Nodes { if (RotationsEnabled) { - CurrentPipeDirection = _originalPipeDirection.RotatePipeDirection(Owner.Transform.LocalRotation); + CurrentPipeDirection = _originalPipeDirection.RotatePipeDirection(IoCManager.Resolve().GetComponent(Owner).LocalRotation); } else { @@ -275,8 +275,8 @@ namespace Content.Server.NodeContainer.Nodes /// private void UpdateAppearance() { - if (!Owner.TryGetComponent(out AppearanceComponent? appearance) - || !Owner.TryGetComponent(out NodeContainerComponent? container)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out AppearanceComponent? appearance) + || !IoCManager.Resolve().TryGetComponent(Owner, out NodeContainerComponent? container)) return; var netConnectedDirections = PipeDirection.None; diff --git a/Content.Server/Nuke/Commands/ToggleNukeCommand.cs b/Content.Server/Nuke/Commands/ToggleNukeCommand.cs index 64003964d7..94ba74125b 100644 --- a/Content.Server/Nuke/Commands/ToggleNukeCommand.cs +++ b/Content.Server/Nuke/Commands/ToggleNukeCommand.cs @@ -1,3 +1,4 @@ +using System.Linq; using Content.Server.Administration; using Content.Shared.Administration; using JetBrains.Annotations; @@ -5,7 +6,6 @@ using Robust.Shared.Console; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using System.Linq; namespace Content.Server.Nuke.Commands { @@ -42,7 +42,7 @@ namespace Content.Server.Nuke.Commands return; } - bombUid = bomb.OwnerUid; + bombUid = bomb.Owner; } var nukeSys = EntitySystem.Get(); diff --git a/Content.Server/Nuke/NukeCodeSystem.cs b/Content.Server/Nuke/NukeCodeSystem.cs index 18bd213ce9..b9f38955d6 100644 --- a/Content.Server/Nuke/NukeCodeSystem.cs +++ b/Content.Server/Nuke/NukeCodeSystem.cs @@ -67,7 +67,7 @@ namespace Content.Server.Nuke var consoles = EntityManager.EntityQuery(); foreach (var console in consoles) { - if (!EntityManager.TryGetComponent(console.OwnerUid, out TransformComponent? transform)) + if (!EntityManager.TryGetComponent((console).Owner, out TransformComponent? transform)) continue; var consolePos = transform.MapPosition; diff --git a/Content.Server/Nuke/NukeSystem.cs b/Content.Server/Nuke/NukeSystem.cs index 865c644902..bceb21a134 100644 --- a/Content.Server/Nuke/NukeSystem.cs +++ b/Content.Server/Nuke/NukeSystem.cs @@ -1,25 +1,25 @@ +using System.Collections.Generic; +using Content.Server.Chat.Managers; using Content.Server.Construction.Components; +using Content.Server.Coordinates.Helpers; using Content.Server.Popups; using Content.Server.UserInterface; using Content.Shared.ActionBlocker; +using Content.Shared.Audio; using Content.Shared.Body.Components; using Content.Shared.Containers.ItemSlots; using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using Content.Shared.Nuke; -using Content.Server.Chat.Managers; +using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Server.Player; +using Robust.Shared.Audio; +using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; -using System.Collections.Generic; -using Content.Server.Coordinates.Helpers; -using Content.Shared.Audio; -using Content.Shared.Sound; -using Robust.Shared.Audio; -using Robust.Shared.Containers; namespace Content.Server.Nuke { @@ -116,10 +116,10 @@ namespace Content.Server.Nuke // standard interactions check if (!args.InRangeUnobstructed()) return; - if (!_actionBlocker.CanInteract(args.User.Uid) || !_actionBlocker.CanUse(args.User.Uid)) + if (!_actionBlocker.CanInteract(args.User) || !_actionBlocker.CanUse(args.User)) return; - if (!EntityManager.TryGetComponent(args.User.Uid, out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; ShowUI(uid, actor.PlayerSession, component); @@ -166,7 +166,7 @@ namespace Content.Server.Nuke if (!component.DiskSlot.HasItem) return; - _itemSlots.TryEjectToHands(uid, component.DiskSlot, args.Session.AttachedEntityUid); + _itemSlots.TryEjectToHands(uid, component.DiskSlot, args.Session.AttachedEntity); } private async void OnAnchorButtonPressed(EntityUid uid, NukeComponent component, NukeAnchorMessage args) @@ -413,7 +413,7 @@ namespace Content.Server.Nuke var ents = _lookup.GetEntitiesInRange(pos, component.BlastRadius); foreach (var ent in ents) { - var entUid = ent.Uid; + var entUid = ent; if (!EntityManager.EntityExists(entUid)) continue;; diff --git a/Content.Server/Nutrition/Components/FoodComponent.cs b/Content.Server/Nutrition/Components/FoodComponent.cs index 8d3e1fac19..103bd09a41 100644 --- a/Content.Server/Nutrition/Components/FoodComponent.cs +++ b/Content.Server/Nutrition/Components/FoodComponent.cs @@ -66,7 +66,7 @@ namespace Content.Server.Nutrition.Components { get { - if (!EntitySystem.Get().TryGetSolution(Owner.Uid, SolutionName, out var solution)) + if (!EntitySystem.Get().TryGetSolution(Owner, SolutionName, out var solution)) { return 0; } diff --git a/Content.Server/Nutrition/Components/HungerComponent.cs b/Content.Server/Nutrition/Components/HungerComponent.cs index 599cb7aa3c..743f074459 100644 --- a/Content.Server/Nutrition/Components/HungerComponent.cs +++ b/Content.Server/Nutrition/Components/HungerComponent.cs @@ -23,6 +23,7 @@ namespace Content.Server.Nutrition.Components [RegisterComponent] public sealed class HungerComponent : SharedHungerComponent { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _random = default!; private float _accumulatedFrameTime; @@ -88,13 +89,13 @@ namespace Content.Server.Nutrition.Components { // Revert slow speed if required if (_lastHungerThreshold == HungerThreshold.Starving && _currentHungerThreshold != HungerThreshold.Dead && - Owner.TryGetComponent(out MovementSpeedModifierComponent? movementSlowdownComponent)) + _entMan.TryGetComponent(Owner, out MovementSpeedModifierComponent? movementSlowdownComponent)) { - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); } // Update UI - Owner.TryGetComponent(out ServerAlertsComponent? alertsComponent); + _entMan.TryGetComponent(Owner, out ServerAlertsComponent? alertsComponent); if (HungerThresholdAlertTypes.TryGetValue(_currentHungerThreshold, out var alertId)) { @@ -126,7 +127,7 @@ namespace Content.Server.Nutrition.Components case HungerThreshold.Starving: // TODO: If something else bumps this could cause mega-speed. // If some form of speed update system if multiple things are touching it use that. - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); _lastHungerThreshold = _currentHungerThreshold; _actualDecayRate = _baseDecayRate * 0.6f; return; @@ -185,7 +186,7 @@ namespace Content.Server.Nutrition.Components return; // --> Current Hunger is below dead threshold - if (!Owner.TryGetComponent(out MobStateComponent? mobState)) + if (!_entMan.TryGetComponent(Owner, out MobStateComponent? mobState)) return; if (!mobState.IsDead()) @@ -194,7 +195,7 @@ namespace Content.Server.Nutrition.Components _accumulatedFrameTime += frametime; if (_accumulatedFrameTime >= 1) { - EntitySystem.Get().TryChangeDamage(Owner.Uid, Damage * (int) _accumulatedFrameTime, true); + EntitySystem.Get().TryChangeDamage(Owner, Damage * (int) _accumulatedFrameTime, true); _accumulatedFrameTime -= (int) _accumulatedFrameTime; } } diff --git a/Content.Server/Nutrition/Components/ThirstComponent.cs b/Content.Server/Nutrition/Components/ThirstComponent.cs index 73aee2c905..fadf84772a 100644 --- a/Content.Server/Nutrition/Components/ThirstComponent.cs +++ b/Content.Server/Nutrition/Components/ThirstComponent.cs @@ -23,6 +23,7 @@ namespace Content.Server.Nutrition.Components [RegisterComponent] public sealed class ThirstComponent : SharedThirstComponent { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _random = default!; private float _accumulatedFrameTime; @@ -87,13 +88,13 @@ namespace Content.Server.Nutrition.Components { // Revert slow speed if required if (_lastThirstThreshold == ThirstThreshold.Parched && _currentThirstThreshold != ThirstThreshold.Dead && - Owner.TryGetComponent(out MovementSpeedModifierComponent? movementSlowdownComponent)) + _entMan.TryGetComponent(Owner, out MovementSpeedModifierComponent? movementSlowdownComponent)) { - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); } // Update UI - Owner.TryGetComponent(out ServerAlertsComponent? alertsComponent); + _entMan.TryGetComponent(Owner, out ServerAlertsComponent? alertsComponent); if (ThirstThresholdAlertTypes.TryGetValue(_currentThirstThreshold, out var alertId)) { @@ -123,7 +124,7 @@ namespace Content.Server.Nutrition.Components return; case ThirstThreshold.Parched: - EntitySystem.Get().RefreshMovementSpeedModifiers(OwnerUid); + EntitySystem.Get().RefreshMovementSpeedModifiers(Owner); _lastThirstThreshold = _currentThirstThreshold; _actualDecayRate = _baseDecayRate * 0.6f; return; @@ -182,7 +183,7 @@ namespace Content.Server.Nutrition.Components return; // --> Current Hunger is below dead threshold - if (!Owner.TryGetComponent(out MobStateComponent? mobState)) + if (!_entMan.TryGetComponent(Owner, out MobStateComponent? mobState)) return; if (!mobState.IsDead()) @@ -191,7 +192,7 @@ namespace Content.Server.Nutrition.Components _accumulatedFrameTime += frametime; if (_accumulatedFrameTime >= 1) { - EntitySystem.Get().TryChangeDamage(Owner.Uid, Damage * (int) _accumulatedFrameTime, true); + EntitySystem.Get().TryChangeDamage(Owner, Damage * (int) _accumulatedFrameTime, true); _accumulatedFrameTime -= (int) _accumulatedFrameTime; } } diff --git a/Content.Server/Nutrition/EntitySystems/CreamPieSystem.cs b/Content.Server/Nutrition/EntitySystems/CreamPieSystem.cs index ff0d702838..2d50fef708 100644 --- a/Content.Server/Nutrition/EntitySystems/CreamPieSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/CreamPieSystem.cs @@ -27,9 +27,9 @@ namespace Content.Server.Nutrition.EntitySystems { SoundSystem.Play(Filter.Pvs(creamPie.Owner), creamPie.Sound.GetSound(), creamPie.Owner, AudioHelpers.WithVariation(0.125f)); - if (creamPie.Owner.TryGetComponent(out var foodComp) && _solutionsSystem.TryGetSolution(creamPie.Owner.Uid, foodComp.SolutionName, out var solution)) + if (EntityManager.TryGetComponent(creamPie.Owner, out var foodComp) && _solutionsSystem.TryGetSolution(creamPie.Owner, foodComp.SolutionName, out var solution)) { - _spillableSystem.SpillAt(creamPie.OwnerUid, solution, "PuddleSmear", false); + _spillableSystem.SpillAt(creamPie.Owner, solution, "PuddleSmear", false); } } diff --git a/Content.Server/Nutrition/EntitySystems/DrinkSystem.cs b/Content.Server/Nutrition/EntitySystems/DrinkSystem.cs index c2258c565b..adacaf613a 100644 --- a/Content.Server/Nutrition/EntitySystems/DrinkSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/DrinkSystem.cs @@ -1,4 +1,3 @@ -using System.Linq; using Content.Server.Body.Components; using Content.Server.Body.Systems; using Content.Server.Chemistry.Components.SolutionManager; @@ -131,44 +130,44 @@ namespace Content.Server.Nutrition.EntitySystems private void AfterInteract(EntityUid uid, DrinkComponent component, AfterInteractEvent args) { - if (args.Handled || args.TargetUid == null) + if (args.Handled || args.Target == null) return; - if (!_actionBlockerSystem.CanInteract(args.UserUid) || !_actionBlockerSystem.CanUse(args.UserUid)) + if (!_actionBlockerSystem.CanInteract(args.User) || !_actionBlockerSystem.CanUse(args.User)) return; - if (!args.UserUid.InRangeUnobstructed(uid, popup: true)) - { - args.Handled = true; - return; - } - - if (args.UserUid == args.TargetUid) - { - args.Handled = TryUseDrink(uid, args.UserUid); - return; - } - - if (!args.UserUid.InRangeUnobstructed(args.TargetUid.Value, popup: true)) + if (!args.User.InRangeUnobstructed(uid, popup: true)) { args.Handled = true; return; } if (args.User == args.Target) - args.Handled = TryUseDrink(uid, args.UserUid, component); + { + args.Handled = TryUseDrink(uid, args.User); + return; + } + + if (!args.User.InRangeUnobstructed(args.Target.Value, popup: true)) + { + args.Handled = true; + return; + } + + if (args.User == args.Target) + args.Handled = TryUseDrink(uid, args.User, component); else - args.Handled = TryForceDrink(uid, args.UserUid, args.TargetUid.Value, component); + args.Handled = TryForceDrink(uid, args.User, args.Target.Value, component); } private void OnUse(EntityUid uid, DrinkComponent component, UseInHandEvent args) { if (args.Handled) return; - if (!_actionBlockerSystem.CanInteract(args.UserUid) || !_actionBlockerSystem.CanUse(args.UserUid)) + if (!_actionBlockerSystem.CanInteract(args.User) || !_actionBlockerSystem.CanUse(args.User)) return; - if (!args.UserUid.InRangeUnobstructed(uid, popup: true)) + if (!args.User.InRangeUnobstructed(uid, popup: true)) { args.Handled = true; return; @@ -185,11 +184,11 @@ namespace Content.Server.Nutrition.EntitySystems if (_solutionContainerSystem.DrainAvailable(uid) <= 0) { - args.User.PopupMessage(Loc.GetString("drink-component-on-use-is-empty", ("owner", EntityManager.GetEntity(uid)))); + args.User.PopupMessage(Loc.GetString("drink-component-on-use-is-empty", ("owner", uid))); return; } - args.Handled = TryUseDrink(uid, args.UserUid, component); + args.Handled = TryUseDrink(uid, args.User, component); } private void HandleLand(EntityUid uid, DrinkComponent component, LandEvent args) @@ -202,12 +201,10 @@ namespace Content.Server.Nutrition.EntitySystems component.Opened = true; UpdateAppearance(component); - var entity = EntityManager.GetEntity(uid); - var solution = _solutionContainerSystem.Drain(uid, interactions, interactions.DrainAvailable); - _spillableSystem.SpillAt(entity.Uid, solution, "PuddleSmear"); + _spillableSystem.SpillAt(uid, solution, "PuddleSmear"); - SoundSystem.Play(Filter.Pvs(entity), component.BurstSound.GetSound(), entity, AudioParams.Default.WithVolume(-4)); + SoundSystem.Play(Filter.Pvs(uid), component.BurstSound.GetSound(), uid, AudioParams.Default.WithVolume(-4)); } } @@ -235,13 +232,13 @@ namespace Content.Server.Nutrition.EntitySystems public void UpdateAppearance(DrinkComponent component) { - if (!EntityManager.TryGetComponent(component.OwnerUid, out AppearanceComponent? appearance) || - !EntityManager.HasComponent(component.OwnerUid)) + if (!EntityManager.TryGetComponent((component).Owner, out AppearanceComponent? appearance) || + !EntityManager.HasComponent((component).Owner)) { return; } - var drainAvailable = _solutionContainerSystem.DrainAvailable(component.OwnerUid); + var drainAvailable = _solutionContainerSystem.DrainAvailable((component).Owner); appearance.SetData(FoodVisuals.Visual, drainAvailable.Float()); appearance.SetData(DrinkCanStateVisual.Opened, component.Opened); } @@ -266,18 +263,18 @@ namespace Content.Server.Nutrition.EntitySystems if (!drink.Opened) { _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-not-open", - ("owner", drink.Owner.Name)), uid, Filter.Entities(userUid)); + ("owner", Name: EntityManager.GetComponent(drink.Owner).EntityName)), uid, Filter.Entities(userUid)); return true; } if (!EntityManager.TryGetComponent(userUid, out SharedBodyComponent? body)) return false; - if (!_solutionContainerSystem.TryGetDrainableSolution(drink.OwnerUid, out var drinkSolution) || + if (!_solutionContainerSystem.TryGetDrainableSolution((drink).Owner, out var drinkSolution) || drinkSolution.DrainAvailable <= 0) { _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-is-empty", - ("entity", drink.Owner.Name)), uid, Filter.Entities(userUid)); + ("entity", Name: EntityManager.GetComponent(drink.Owner).EntityName)), uid, Filter.Entities(userUid)); return true; } @@ -294,7 +291,7 @@ namespace Content.Server.Nutrition.EntitySystems var transferAmount = FixedPoint2.Min(drink.TransferAmount, drinkSolution.DrainAvailable); var drain = _solutionContainerSystem.Drain(uid, drinkSolution, transferAmount); var firstStomach = stomachs.FirstOrNull( - stomach => _stomachSystem.CanTransferSolution(stomach.Comp.OwnerUid, drain)); + stomach => _stomachSystem.CanTransferSolution((stomach.Comp).Owner, drain)); // All stomach are full or can't handle whatever solution we have. if (firstStomach == null) @@ -319,7 +316,7 @@ namespace Content.Server.Nutrition.EntitySystems Filter.Pvs(userUid)); drain.DoEntityReaction(userUid, ReactionMethod.Ingestion); - _stomachSystem.TryTransferSolution(firstStomach.Value.Comp.OwnerUid, drain, firstStomach.Value.Comp); + _stomachSystem.TryTransferSolution((firstStomach.Value.Comp).Owner, drain, firstStomach.Value.Comp); return true; } @@ -348,7 +345,7 @@ namespace Content.Server.Nutrition.EntitySystems if (!drink.Opened) { _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-not-open", - ("owner", drink.Owner.Name)), uid, Filter.Entities(userUid)); + ("owner", Name: EntityManager.GetComponent(drink.Owner).EntityName)), uid, Filter.Entities(userUid)); return true; } @@ -356,7 +353,7 @@ namespace Content.Server.Nutrition.EntitySystems drinkSolution.DrainAvailable <= 0) { _popupSystem.PopupEntity(Loc.GetString("drink-component-try-use-drink-is-empty", - ("entity", drink.Owner.Name)), uid, Filter.Entities(userUid)); + ("entity", Name: EntityManager.GetComponent(drink.Owner).EntityName)), uid, Filter.Entities(userUid)); return true; } @@ -382,10 +379,7 @@ namespace Content.Server.Nutrition.EntitySystems }); // logging - var user = EntityManager.GetEntity(userUid); - var target = EntityManager.GetEntity(targetUid); - var drinkable = EntityManager.GetEntity(uid); - _logSystem.Add(LogType.ForceFeed, LogImpact.Medium, $"{user} is forcing {target} to drink {drinkable}"); + _logSystem.Add(LogType.ForceFeed, LogImpact.Medium, $"{userUid} is forcing {targetUid} to drink {uid}"); return true; } @@ -400,7 +394,7 @@ namespace Content.Server.Nutrition.EntitySystems args.Drink.CancelToken = null; var transferAmount = FixedPoint2.Min(args.Drink.TransferAmount, args.DrinkSolution.DrainAvailable); - var drained = _solutionContainerSystem.Drain(args.Drink.OwnerUid, args.DrinkSolution, transferAmount); + var drained = _solutionContainerSystem.Drain((args.Drink).Owner, args.DrinkSolution, transferAmount); if (!_bodySystem.TryGetComponentsOnMechanisms(uid, out var stomachs, body)) { @@ -412,7 +406,7 @@ namespace Content.Server.Nutrition.EntitySystems } var firstStomach = stomachs.FirstOrNull( - stomach => _stomachSystem.CanTransferSolution(stomach.Comp.OwnerUid, drained)); + stomach => _stomachSystem.CanTransferSolution((stomach.Comp).Owner, drained)); // All stomach are full or can't handle whatever solution we have. if (firstStomach == null) @@ -439,7 +433,7 @@ namespace Content.Server.Nutrition.EntitySystems SoundSystem.Play(Filter.Pvs(uid), args.Drink.UseSound.GetSound(), uid, AudioParams.Default.WithVolume(-2f)); drained.DoEntityReaction(uid, ReactionMethod.Ingestion); - _stomachSystem.TryTransferSolution(firstStomach.Value.Comp.OwnerUid, drained, firstStomach.Value.Comp); + _stomachSystem.TryTransferSolution((firstStomach.Value.Comp).Owner, drained, firstStomach.Value.Comp); } private void OnForceDrinkCancelled(ForceDrinkCancelledEvent args) diff --git a/Content.Server/Nutrition/EntitySystems/FoodSystem.cs b/Content.Server/Nutrition/EntitySystems/FoodSystem.cs index 1f872ca1dc..cce1876070 100644 --- a/Content.Server/Nutrition/EntitySystems/FoodSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/FoodSystem.cs @@ -1,8 +1,11 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Content.Server.Body.Components; using Content.Server.Body.Systems; using Content.Server.Chemistry.EntitySystems; using Content.Server.DoAfter; using Content.Server.Hands.Components; +using Content.Server.Inventory.Components; using Content.Server.Items; using Content.Server.Nutrition.Components; using Content.Server.Popups; @@ -14,7 +17,9 @@ using Content.Shared.Database; using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; +using Content.Shared.Inventory; using Content.Shared.MobState.Components; +using Content.Shared.Tag; using Content.Shared.Verbs; using Robust.Shared.Audio; using Robust.Shared.GameObjects; @@ -77,16 +82,16 @@ namespace Content.Server.Nutrition.EntitySystems if (ev.Handled) return; - if (!_actionBlockerSystem.CanInteract(ev.UserUid) || !_actionBlockerSystem.CanUse(ev.UserUid)) + if (!_actionBlockerSystem.CanInteract(ev.User) || !_actionBlockerSystem.CanUse(ev.User)) return; - if (!ev.UserUid.InRangeUnobstructed(uid, popup: true)) + if (!ev.User.InRangeUnobstructed(uid, popup: true)) { ev.Handled = true; return; } - ev.Handled = TryUseFood(uid, ev.UserUid); + ev.Handled = TryUseFood(uid, ev.User); } /// @@ -94,176 +99,40 @@ namespace Content.Server.Nutrition.EntitySystems /// private void OnFeedFood(EntityUid uid, FoodComponent foodComponent, AfterInteractEvent args) { - if (args.Handled || args.TargetUid == null) + if (args.Handled || args.Target == null) return; - if (!_actionBlockerSystem.CanInteract(args.UserUid) || !_actionBlockerSystem.CanUse(args.UserUid)) + if (!_actionBlockerSystem.CanInteract(args.User) || !_actionBlockerSystem.CanUse(args.User)) return; - if (!args.UserUid.InRangeUnobstructed(uid, popup: true)) + if (!args.User.InRangeUnobstructed(uid, popup: true)) { args.Handled = true; return; } - if (args.UserUid == args.TargetUid) + if (args.User == args.Target) { - args.Handled = TryUseFood(uid, args.UserUid); + args.Handled = TryUseFood(uid, args.User); return; } - if (!args.UserUid.InRangeUnobstructed(args.TargetUid.Value, popup: true)) + if (!args.User.InRangeUnobstructed(args.Target.Value, popup: true)) { args.Handled = true; return; } - args.Handled = TryForceFeed(uid, args.UserUid, args.TargetUid.Value); + args.Handled = TryForceFeed(uid, args.User, args.Target.Value); } /// /// Tries to eat some food /// /// Food entity. - /// Feeding initiator. - /// Feeding target. + /// Feeding initiator. /// True if an interaction occurred (i.e., food was consumed, or a pop-up message was created) - public bool TryUseFood(EntityUid uid, EntityUid userUid, FoodComponent? component = null) - { - if (!Resolve(uid, ref component)) - return false; - - // if currently being used to force-feed, cancel that action. - if (component.CancelToken != null) - { - component.CancelToken.Cancel(); - component.CancelToken = null; - return true; - } - - if (uid == userUid || //Suppresses self-eating - EntityManager.TryGetComponent(uid, out var mobState) && mobState.IsAlive()) // Suppresses eating alive mobs - return false; - - if (!_solutionContainerSystem.TryGetSolution(uid, component.SolutionName, out var solution)) - return false; - - if (component.UsesRemaining <= 0) - { - _popupSystem.PopupEntity(Loc.GetString("food-system-try-use-food-is-empty", ("entity", EntityManager.GetEntity(uid))), userUid, Filter.Entities(userUid)); - DeleteAndSpawnTrash(component, userUid); - return true; - } - - if (!EntityManager.TryGetComponent(userUid, out SharedBodyComponent ? body) || - !_bodySystem.TryGetComponentsOnMechanisms(userUid, out var stomachs, body)) - return false; - - if (IsMouthBlocked(userUid, userUid)) - return true; - - var usedUtensils = new List(); - - if (!TryGetRequiredUtensils(userUid, component, out var utensils)) - return true; - - if (!userUid.InRangeUnobstructed(uid, popup: true)) - return true; - - var transferAmount = component.TransferAmount != null ? FixedPoint2.Min((FixedPoint2) component.TransferAmount, solution.CurrentVolume) : solution.CurrentVolume; - var split = _solutionContainerSystem.SplitSolution(uid, solution, transferAmount); - var firstStomach = stomachs.FirstOrNull( - stomach => _stomachSystem.CanTransferSolution(stomach.Comp.OwnerUid, split)); - - if (firstStomach == null) - { - _solutionContainerSystem.TryAddSolution(uid, solution, split); - _popupSystem.PopupEntity(Loc.GetString("food-system-you-cannot-eat-any-more"), userUid, Filter.Entities(userUid)); - return true; - } - - // TODO: Account for partial transfer. - split.DoEntityReaction(userUid, ReactionMethod.Ingestion); - _stomachSystem.TryTransferSolution(firstStomach.Value.Comp.OwnerUid, split, firstStomach.Value.Comp); - - SoundSystem.Play(Filter.Pvs(userUid), component.UseSound.GetSound(), userUid, AudioParams.Default.WithVolume(-1f)); - _popupSystem.PopupEntity(Loc.GetString(component.EatMessage, ("food", component.Owner)), userUid, Filter.Entities(userUid)); - - // Try to break all used utensils - foreach (var utensil in usedUtensils) - { - _utensilSystem.TryBreak(utensil.OwnerUid, userUid); - } - - if (component.UsesRemaining > 0) - { - return true; - } - - if (string.IsNullOrEmpty(component.TrashPrototype)) - EntityManager.QueueDeleteEntity(component.OwnerUid); - else - DeleteAndSpawnTrash(component, userUid); - - return true; - } - - private void DeleteAndSpawnTrash(FoodComponent component, EntityUid? userUid = null) - { - //We're empty. Become trash. - var position = component.Owner.Transform.Coordinates; - var finisher = component.Owner.EntityManager.SpawnEntity(component.TrashPrototype, position); - - // If the user is holding the item - if (userUid != null && - EntityManager.TryGetComponent(userUid.Value, out HandsComponent? handsComponent) && - handsComponent.IsHolding(component.Owner)) - { - EntityManager.DeleteEntity(component.OwnerUid); - - // Put the trash in the user's hand - if (finisher.TryGetComponent(out ItemComponent? item) && - handsComponent.CanPutInHand(item)) - { - handsComponent.PutInHand(item); - } - return; - } - - EntityManager.QueueDeleteEntity(component.OwnerUid); - } - - private void AddEatVerb(EntityUid uid, FoodComponent component, GetInteractionVerbsEvent ev) - { - if (component.CancelToken != null) - return; - - if (uid == ev.UserUid || - !ev.CanInteract || - !ev.CanAccess || - !EntityManager.TryGetComponent(ev.UserUid, out SharedBodyComponent? body) || - !_bodySystem.TryGetComponentsOnMechanisms(ev.UserUid, out var stomachs, body)) - return; - - if (EntityManager.TryGetComponent(uid, out var mobState) && mobState.IsAlive()) - return; - - Verb verb = new(); - verb.Act = () => - { - TryUseFood(uid, ev.UserUid, component); - }; - - verb.Text = Loc.GetString("food-system-verb-eat"); - verb.Priority = -1; - ev.Verbs.Add(verb); - } - - - /// - /// Attempts to force feed a target. Returns true if any interaction occurred, including pop-up generation - /// - public bool TryForceFeed(EntityUid uid, EntityUid userUid, EntityUid targetUid, FoodComponent? food = null) + public bool TryUseFood(EntityUid uid, EntityUid user, FoodComponent? food = null) { if (!Resolve(uid, ref food)) return false; @@ -276,7 +145,146 @@ namespace Content.Server.Nutrition.EntitySystems return true; } - if (!EntityManager.HasComponent(targetUid)) + if (uid == user || //Suppresses self-eating + EntityManager.TryGetComponent(uid, out var mobState) && mobState.IsAlive()) // Suppresses eating alive mobs + return false; + + if (!_solutionContainerSystem.TryGetSolution(uid, food.SolutionName, out var solution)) + return false; + + if (food.UsesRemaining <= 0) + { + _popupSystem.PopupEntity(Loc.GetString("food-system-try-use-food-is-empty", ("entity", uid)), user, Filter.Entities(user)); + DeleteAndSpawnTrash(food, user); + return true; + } + + if (!EntityManager.TryGetComponent(user, out SharedBodyComponent ? body) || + !_bodySystem.TryGetComponentsOnMechanisms(user, out var stomachs, body)) + return false; + + if (IsMouthBlocked(user, user)) + { + return true; + } + + var usedUtensils = new List(); + + if (!TryGetRequiredUtensils(user, food, out var utensils)) + return true; + + if (!user.InRangeUnobstructed(uid, popup: true)) + return true; + + var transferAmount = food.TransferAmount != null ? FixedPoint2.Min((FixedPoint2) food.TransferAmount, solution.CurrentVolume) : solution.CurrentVolume; + var split = _solutionContainerSystem.SplitSolution(uid, solution, transferAmount); + var firstStomach = stomachs.FirstOrNull( + stomach => _stomachSystem.CanTransferSolution((stomach.Comp).Owner, split)); + + if (firstStomach == null) + { + _solutionContainerSystem.TryAddSolution(uid, solution, split); + _popupSystem.PopupEntity(Loc.GetString("food-system-you-cannot-eat-any-more"), user, Filter.Entities(user)); + return true; + } + + // TODO: Account for partial transfer. + split.DoEntityReaction(user, ReactionMethod.Ingestion); + _stomachSystem.TryTransferSolution((firstStomach.Value.Comp).Owner, split, firstStomach.Value.Comp); + + SoundSystem.Play(Filter.Pvs(user), food.UseSound.GetSound(), user, AudioParams.Default.WithVolume(-1f)); + _popupSystem.PopupEntity(Loc.GetString(food.EatMessage, ("food", food.Owner)), user, Filter.Entities(user)); + + // Try to break all used utensils + foreach (var utensil in usedUtensils) + { + _utensilSystem.TryBreak((utensil).Owner, user); + } + + if (food.UsesRemaining > 0) + { + return true; + } + + if (string.IsNullOrEmpty(food.TrashPrototype)) + EntityManager.QueueDeleteEntity((food).Owner); + else + DeleteAndSpawnTrash(food, user); + + return true; + } + + private void DeleteAndSpawnTrash(FoodComponent component, EntityUid? user = null) + { + //We're empty. Become trash. + var position = EntityManager.GetComponent(component.Owner).Coordinates; + var finisher = EntityManager.SpawnEntity(component.TrashPrototype, position); + + // If the user is holding the item + if (user != null && + EntityManager.TryGetComponent(user.Value, out HandsComponent? handsComponent) && + handsComponent.IsHolding(component.Owner)) + { + EntityManager.DeleteEntity((component).Owner); + + // Put the trash in the user's hand + if (EntityManager.TryGetComponent(finisher, out ItemComponent? item) && + handsComponent.CanPutInHand(item)) + { + handsComponent.PutInHand(item); + } + return; + } + + EntityManager.QueueDeleteEntity((component).Owner); + } + + private void AddEatVerb(EntityUid uid, FoodComponent component, GetInteractionVerbsEvent ev) + { + if (component.CancelToken != null) + return; + + if (uid == ev.User || + !ev.CanInteract || + !ev.CanAccess || + !EntityManager.TryGetComponent(ev.User, out SharedBodyComponent? body) || + !_bodySystem.TryGetComponentsOnMechanisms(ev.User, out var stomachs, body)) + return; + + if (EntityManager.TryGetComponent(uid, out var mobState) && mobState.IsAlive()) + return; + + Verb verb = new() + { + Act = () => + { + TryUseFood(uid, ev.User, component); + }, + Text = Loc.GetString("food-system-verb-eat"), + Priority = -1 + }; + + ev.Verbs.Add(verb); + } + + + /// + /// Attempts to force feed a target. Returns true if any interaction occurred, including pop-up generation + /// + public bool TryForceFeed(EntityUid uid, EntityUid user, EntityUid target, FoodComponent? food = null) + { + if (!Resolve(uid, ref food)) + return false; + + // if currently being used to force-feed, cancel that action. + if (food.CancelToken != null) + { + food.CancelToken.Cancel(); + food.CancelToken = null; + return true; + } + + if (!EntityManager.HasComponent(target)) return false; if (!_solutionContainerSystem.TryGetSolution(uid, food.SolutionName, out var foodSolution)) @@ -285,40 +293,39 @@ namespace Content.Server.Nutrition.EntitySystems if (food.UsesRemaining <= 0) { _popupSystem.PopupEntity(Loc.GetString("food-system-try-use-food-is-empty", - ("entity", EntityManager.GetEntity(uid))), userUid, Filter.Entities(userUid)); - DeleteAndSpawnTrash(food, userUid); + ("entity", uid)), user, Filter.Entities(user)); + DeleteAndSpawnTrash(food, user); return true; } - if (IsMouthBlocked(targetUid, userUid)) + if (IsMouthBlocked(target, user)) + { + return true; + } + + if (!TryGetRequiredUtensils(user, food, out var utensils)) return true; - if (!TryGetRequiredUtensils(userUid, food, out var utensils)) - return true; - - EntityManager.TryGetComponent(userUid, out MetaDataComponent? meta); + EntityManager.TryGetComponent(user, out MetaDataComponent? meta); var userName = meta?.EntityName ?? string.Empty; _popupSystem.PopupEntity(Loc.GetString("food-system-force-feed", ("user", userName)), - userUid, Filter.Entities(targetUid)); + user, Filter.Entities(target)); food.CancelToken = new(); - _doAfterSystem.DoAfter(new DoAfterEventArgs(userUid, food.ForceFeedDelay, food.CancelToken.Token, targetUid) + _doAfterSystem.DoAfter(new DoAfterEventArgs(user, food.ForceFeedDelay, food.CancelToken.Token, target) { BreakOnUserMove = true, BreakOnDamage = true, BreakOnStun = true, BreakOnTargetMove = true, MovementThreshold = 1.0f, - TargetFinishedEvent = new ForceFeedEvent(userUid, food, foodSolution, utensils), + TargetFinishedEvent = new ForceFeedEvent(user, food, foodSolution, utensils), BroadcastCancelledEvent = new ForceFeedCancelledEvent(food) }); // logging - var user = EntityManager.GetEntity(userUid); - var target = EntityManager.GetEntity(targetUid); - var edible = EntityManager.GetEntity(uid); - _logSystem.Add(LogType.ForceFeed, LogImpact.Medium, $"{user} is forcing {target} to eat {edible}"); + _logSystem.Add(LogType.ForceFeed, LogImpact.Medium, $"{user} is forcing {target} to eat {uid}"); return true; } @@ -337,9 +344,9 @@ namespace Content.Server.Nutrition.EntitySystems ? FixedPoint2.Min((FixedPoint2) args.Food.TransferAmount, args.FoodSolution.CurrentVolume) : args.FoodSolution.CurrentVolume; - var split = _solutionContainerSystem.SplitSolution(args.Food.OwnerUid, args.FoodSolution, transferAmount); + var split = _solutionContainerSystem.SplitSolution((args.Food).Owner, args.FoodSolution, transferAmount); var firstStomach = stomachs.FirstOrNull( - stomach => _stomachSystem.CanTransferSolution(stomach.Comp.OwnerUid, split)); + stomach => _stomachSystem.CanTransferSolution((stomach.Comp).Owner, split)); if (firstStomach == null) { @@ -349,7 +356,7 @@ namespace Content.Server.Nutrition.EntitySystems } split.DoEntityReaction(uid, ReactionMethod.Ingestion); - _stomachSystem.TryTransferSolution(firstStomach.Value.Comp.OwnerUid, split, firstStomach.Value.Comp); + _stomachSystem.TryTransferSolution((firstStomach.Value.Comp).Owner, split, firstStomach.Value.Comp); EntityManager.TryGetComponent(uid, out MetaDataComponent? targetMeta); var targetName = targetMeta?.EntityName ?? string.Empty; @@ -368,14 +375,14 @@ namespace Content.Server.Nutrition.EntitySystems // Try to break all used utensils foreach (var utensil in args.Utensils) { - _utensilSystem.TryBreak(utensil.OwnerUid, args.User); + _utensilSystem.TryBreak((utensil).Owner, args.User); } if (args.Food.UsesRemaining > 0) return; if (string.IsNullOrEmpty(args.Food.TrashPrototype)) - EntityManager.QueueDeleteEntity(args.Food.OwnerUid); + EntityManager.QueueDeleteEntity((args.Food).Owner); else DeleteAndSpawnTrash(args.Food, args.User); } @@ -401,34 +408,31 @@ namespace Content.Server.Nutrition.EntitySystems DeleteAndSpawnTrash(food); var firstStomach = stomachs.FirstOrNull( - stomach => _stomachSystem.CanTransferSolution(stomach.Comp.OwnerUid, foodSolution)); + stomach => _stomachSystem.CanTransferSolution(((IComponent) stomach.Comp).Owner, foodSolution)); if (firstStomach == null) return; // logging - var userEntity = (user == null) ? null : EntityManager.GetEntity(user.Value); - var targetEntity = EntityManager.GetEntity(target); - var edible = EntityManager.GetEntity(uid); - if (userEntity == null) - _logSystem.Add(LogType.ForceFeed, $"{edible} was thrown into the mouth of {targetEntity}"); + if (user == null) + _logSystem.Add(LogType.ForceFeed, $"{uid} was thrown into the mouth of {target}"); else - _logSystem.Add(LogType.ForceFeed, $"{userEntity} threw {edible} into the mouth of {targetEntity}"); + _logSystem.Add(LogType.ForceFeed, $"{user} threw {uid} into the mouth of {target}"); - var filter = (user == null) ? Filter.Entities(target) : Filter.Entities(target, user.Value); + var filter = user == null ? Filter.Entities(target) : Filter.Entities(target, user.Value); _popupSystem.PopupEntity(Loc.GetString(food.EatMessage), target, filter); foodSolution.DoEntityReaction(uid, ReactionMethod.Ingestion); - _stomachSystem.TryTransferSolution(firstStomach.Value.Comp.OwnerUid, foodSolution, firstStomach.Value.Comp); + _stomachSystem.TryTransferSolution(((IComponent) firstStomach.Value.Comp).Owner, foodSolution, firstStomach.Value.Comp); SoundSystem.Play(Filter.Pvs(target), food.UseSound.GetSound(), target, AudioParams.Default.WithVolume(-1f)); if (string.IsNullOrEmpty(food.TrashPrototype)) - EntityManager.QueueDeleteEntity(food.OwnerUid); + EntityManager.QueueDeleteEntity(((IComponent) food).Owner); else DeleteAndSpawnTrash(food); } - private bool TryGetRequiredUtensils(EntityUid userUid, FoodComponent component, + private bool TryGetRequiredUtensils(EntityUid user, FoodComponent component, out List utensils, HandsComponent? hands = null) { utensils = new(); @@ -436,7 +440,7 @@ namespace Content.Server.Nutrition.EntitySystems if (component.Utensil != UtensilType.None) return true; - if (!Resolve(userUid, ref hands, false)) + if (!Resolve(user, ref hands, false)) return false; var usedTypes = UtensilType.None; @@ -444,7 +448,7 @@ namespace Content.Server.Nutrition.EntitySystems foreach (var item in hands.GetAllHeldItems()) { // Is utensil? - if (!item.Owner.TryGetComponent(out UtensilComponent? utensil)) + if (!EntityManager.TryGetComponent(item.Owner, out UtensilComponent? utensil)) continue; if ((utensil.Types & component.Utensil) != 0 && // Acceptable type? @@ -459,7 +463,7 @@ namespace Content.Server.Nutrition.EntitySystems // If "required" field is set, try to block eating without proper utensils used if (component.UtensilRequired && (usedTypes & component.Utensil) != component.Utensil) { - _popupSystem.PopupEntity(Loc.GetString("food-you-need-to-hold-utensil", ("utensil", component.Utensil ^ usedTypes)), userUid, Filter.Entities(userUid)); + _popupSystem.PopupEntity(Loc.GetString("food-you-need-to-hold-utensil", ("utensil", component.Utensil ^ usedTypes)), user, Filter.Entities(user)); return false; } @@ -482,19 +486,19 @@ namespace Content.Server.Nutrition.EntitySystems IngestionBlockerComponent blocker; if (component.TryGetSlotItem(EquipmentSlotDefines.Slots.MASK, out ItemComponent? mask) && - EntityManager.TryGetComponent(mask.OwnerUid, out blocker) && + EntityManager.TryGetComponent(mask.Owner, out blocker) && blocker.Enabled) { - args.Blocker = mask.OwnerUid; + args.Blocker = mask.Owner; args.Cancel(); return; } if (component.TryGetSlotItem(EquipmentSlotDefines.Slots.HEAD, out ItemComponent? head) && - EntityManager.TryGetComponent(head.OwnerUid, out blocker) && + EntityManager.TryGetComponent(head.Owner, out blocker) && blocker.Enabled) { - args.Blocker = head.OwnerUid; + args.Blocker = head.Owner; args.Cancel(); } } diff --git a/Content.Server/Nutrition/EntitySystems/ForcefeedOnCollideSystem.cs b/Content.Server/Nutrition/EntitySystems/ForcefeedOnCollideSystem.cs index 9c07118667..c2ffa178e5 100644 --- a/Content.Server/Nutrition/EntitySystems/ForcefeedOnCollideSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/ForcefeedOnCollideSystem.cs @@ -19,7 +19,7 @@ namespace Content.Server.Nutrition.EntitySystems private void OnThrowDoHit(EntityUid uid, ForcefeedOnCollideComponent component, ThrowDoHitEvent args) { - _foodSystem.ProjectileForceFeed(uid, args.Target.Uid, args.User?.Uid); + _foodSystem.ProjectileForceFeed(uid, args.Target, args.User); } private void OnLand(EntityUid uid, ForcefeedOnCollideComponent component, LandEvent args) diff --git a/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs b/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs index 396101dbdf..e8ef70d63a 100644 --- a/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/SliceableFoodSystem.cs @@ -34,7 +34,7 @@ namespace Content.Server.Nutrition.EntitySystems if (args.Handled) return; - if (TrySliceFood(uid, args.UserUid, args.UsedUid, component)) + if (TrySliceFood(uid, args.User, args.Used, component)) args.Handled = true; } @@ -57,7 +57,7 @@ namespace Content.Server.Nutrition.EntitySystems return false; } - var sliceUid = EntityManager.SpawnEntity(component.Slice, transform.Coordinates).Uid; + var sliceUid = EntityManager.SpawnEntity(component.Slice, transform.Coordinates); var lostSolution = _solutionContainerSystem.SplitSolution(uid, solution, solution.CurrentVolume / FixedPoint2.New(component.Count)); @@ -86,7 +86,7 @@ namespace Content.Server.Nutrition.EntitySystems // Split last slice if (component.Count == 1) { - var lastSlice = EntityManager.SpawnEntity(component.Slice, transform.Coordinates).Uid; + var lastSlice = EntityManager.SpawnEntity(component.Slice, transform.Coordinates); // Fill last slice with the rest of the solution FillSlice(lastSlice, solution); diff --git a/Content.Server/Nutrition/EntitySystems/SmokingSystem.Cigar.cs b/Content.Server/Nutrition/EntitySystems/SmokingSystem.Cigar.cs index 8a0307159a..0fc638fd2e 100644 --- a/Content.Server/Nutrition/EntitySystems/SmokingSystem.Cigar.cs +++ b/Content.Server/Nutrition/EntitySystems/SmokingSystem.Cigar.cs @@ -42,7 +42,7 @@ namespace Content.Server.Nutrition.EntitySystems return; var isHotEvent = new IsHotEvent(); - RaiseLocalEvent(args.Used.Uid, isHotEvent, false); + RaiseLocalEvent(args.Used, isHotEvent, false); if (!isHotEvent.IsHot) return; diff --git a/Content.Server/Nutrition/EntitySystems/SmokingSystem.cs b/Content.Server/Nutrition/EntitySystems/SmokingSystem.cs index fb364373f7..c3051db172 100644 --- a/Content.Server/Nutrition/EntitySystems/SmokingSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/SmokingSystem.cs @@ -96,11 +96,11 @@ namespace Content.Server.Nutrition.EntitySystems // This is awful. I hate this so much. // TODO: Please, someone refactor containers and free me from this bullshit. if (!smokable.Owner.TryGetContainerMan(out var containerManager) || - !containerManager.Owner.TryGetComponent(out BloodstreamComponent? bloodstream)) + !EntityManager.TryGetComponent(containerManager.Owner, out BloodstreamComponent? bloodstream)) continue; - _reactiveSystem.ReactionEntity(containerManager.OwnerUid, ReactionMethod.Ingestion, inhaledSolution); - _bloodstreamSystem.TryAddToBloodstream(containerManager.OwnerUid, inhaledSolution, bloodstream); + _reactiveSystem.ReactionEntity(containerManager.Owner, ReactionMethod.Ingestion, inhaledSolution); + _bloodstreamSystem.TryAddToBloodstream(containerManager.Owner, inhaledSolution, bloodstream); } _timer -= UpdateTimer; diff --git a/Content.Server/Nutrition/EntitySystems/UtensilSystem.cs b/Content.Server/Nutrition/EntitySystems/UtensilSystem.cs index a129363b00..7ab9b73f48 100644 --- a/Content.Server/Nutrition/EntitySystems/UtensilSystem.cs +++ b/Content.Server/Nutrition/EntitySystems/UtensilSystem.cs @@ -35,33 +35,33 @@ namespace Content.Server.Nutrition.EntitySystems if (ev.Target == null) return; - if (TryUseUtensil(ev.UserUid, ev.Target.Uid, component)) + if (TryUseUtensil(ev.User, ev.Target.Value, component)) ev.Handled = true; } - private bool TryUseUtensil(EntityUid userUid, EntityUid targetUid, UtensilComponent component) + private bool TryUseUtensil(EntityUid user, EntityUid target, UtensilComponent component) { - if (!EntityManager.TryGetComponent(targetUid, out FoodComponent food)) + if (!EntityManager.TryGetComponent(target, out FoodComponent food)) return false; //Prevents food usage with a wrong utensil if ((food.Utensil & component.Types) == 0) { - _popupSystem.PopupEntity(Loc.GetString("food-system-wrong-utensil", ("food", food.Owner), ("utensil", component.Owner)), userUid, Filter.Entities(userUid)); + _popupSystem.PopupEntity(Loc.GetString("food-system-wrong-utensil", ("food", food.Owner), ("utensil", component.Owner)), user, Filter.Entities(user)); return false; } - if (!userUid.InRangeUnobstructed(targetUid, popup: true)) + if (!user.InRangeUnobstructed(target, popup: true)) return false; - return _foodSystem.TryUseFood(targetUid, userUid); + return _foodSystem.TryUseFood(target, user); } /// /// Attempt to break the utensil after interaction. /// /// Utensil. - /// User of the utensil. + /// User of the utensil. public void TryBreak(EntityUid uid, EntityUid userUid, UtensilComponent? component = null) { if (!Resolve(uid, ref component)) @@ -70,7 +70,7 @@ namespace Content.Server.Nutrition.EntitySystems if (_robustRandom.Prob(component.BreakChance)) { SoundSystem.Play(Filter.Pvs(userUid), component.BreakSound.GetSound(), userUid, AudioParams.Default.WithVolume(-2f)); - component.Owner.Delete(); + EntityManager.DeleteEntity(component.Owner); } } } diff --git a/Content.Server/Nutrition/Hungry.cs b/Content.Server/Nutrition/Hungry.cs index c05ca157bb..e36505a9f9 100644 --- a/Content.Server/Nutrition/Hungry.cs +++ b/Content.Server/Nutrition/Hungry.cs @@ -4,12 +4,16 @@ using Content.Shared.Administration; using Content.Shared.Nutrition.Components; using Robust.Server.Player; using Robust.Shared.Console; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Nutrition { [AdminCommand(AdminFlags.Debug)] public class Hungry : IConsoleCommand { + [Dependency] private readonly IEntityManager _entities = default!; + public string Command => "hungry"; public string Description => "Makes you hungry."; public string Help => $"{Command}"; @@ -23,13 +27,13 @@ namespace Content.Server.Nutrition return; } - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {Valid: true} playerEntity) { shell.WriteLine("You cannot use this command without an entity."); return; } - if (!player.AttachedEntity.TryGetComponent(out HungerComponent? hunger)) + if (!_entities.TryGetComponent(playerEntity, out HungerComponent? hunger)) { shell.WriteLine($"Your entity does not have a {nameof(HungerComponent)} component."); return; diff --git a/Content.Server/Objectives/Conditions/KillPersonCondition.cs b/Content.Server/Objectives/Conditions/KillPersonCondition.cs index cbae4d8119..5fe620a2d5 100644 --- a/Content.Server/Objectives/Conditions/KillPersonCondition.cs +++ b/Content.Server/Objectives/Conditions/KillPersonCondition.cs @@ -1,4 +1,6 @@ using Content.Server.Objectives.Interfaces; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Utility; @@ -9,7 +11,23 @@ namespace Content.Server.Objectives.Conditions protected Mind.Mind? Target; public abstract IObjectiveCondition GetAssigned(Mind.Mind mind); - public string Title => Loc.GetString("objective-condition-kill-person-title", ("targetName", Target?.CharacterName ?? Target?.OwnedEntity?.Name ?? string.Empty)); + public string Title + { + get + { + var targetName = string.Empty; + + if (Target == null) + return Loc.GetString("objective-condition-kill-person-title", ("targetName", targetName)); + + if (Target.CharacterName != null) + targetName = Target.CharacterName; + else if (Target.OwnedEntity is {Valid: true} owned) + targetName = IoCManager.Resolve().GetComponent(owned).EntityName; + + return Loc.GetString("objective-condition-kill-person-title", ("targetName", targetName)); + } + } public string Description => Loc.GetString("objective-condition-kill-person-description"); diff --git a/Content.Server/Objectives/Conditions/KillRandomPersonCondition.cs b/Content.Server/Objectives/Conditions/KillRandomPersonCondition.cs index 1a47af4bbc..2d625a6b14 100644 --- a/Content.Server/Objectives/Conditions/KillRandomPersonCondition.cs +++ b/Content.Server/Objectives/Conditions/KillRandomPersonCondition.cs @@ -20,7 +20,13 @@ namespace Content.Server.Objectives.Conditions var allHumans = entityMgr.EntityQuery(true).Where(mc => { var entity = mc.Mind?.OwnedEntity; - return (entity?.GetComponentOrNull()?.IsAlive() ?? false) && mc.Mind != mind; + + if (entity == default) + return false; + + return entityMgr.TryGetComponent(entity, out MobStateComponent mobState) && + mobState.IsAlive() && + mc.Mind != mind; }).Select(mc => mc.Mind).ToList(); return new KillRandomPersonCondition {Target = IoCManager.Resolve().Pick(allHumans)}; } diff --git a/Content.Server/Objectives/Conditions/StealCondition.cs b/Content.Server/Objectives/Conditions/StealCondition.cs index 0f1ec48b77..e4190f96a5 100644 --- a/Content.Server/Objectives/Conditions/StealCondition.cs +++ b/Content.Server/Objectives/Conditions/StealCondition.cs @@ -3,6 +3,7 @@ using Content.Server.Containers; using Content.Server.Objectives.Interfaces; using JetBrains.Annotations; using Robust.Shared.Containers; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Log; @@ -56,8 +57,8 @@ namespace Content.Server.Objectives.Conditions { get { - if (_mind?.OwnedEntity == null) return 0f; - if (!_mind.OwnedEntity.TryGetComponent(out var containerManagerComponent)) return 0f; + if (_mind?.OwnedEntity is not {Valid: true} owned) return 0f; + if (!IoCManager.Resolve().TryGetComponent(owned, out var containerManagerComponent)) return 0f; float count = containerManagerComponent.CountPrototypeOccurencesRecursive(_prototypeId); return count/_amount; diff --git a/Content.Server/PAI/PAISystem.cs b/Content.Server/PAI/PAISystem.cs index b7429ba162..0908fa117e 100644 --- a/Content.Server/PAI/PAISystem.cs +++ b/Content.Server/PAI/PAISystem.cs @@ -63,24 +63,25 @@ namespace Content.Server.PAI // Check for pAI activation if (EntityManager.TryGetComponent(uid, out var mind) && mind.HasMind) { - _popupSystem.PopupEntity(Loc.GetString("pai-system-pai-installed"), uid, Filter.Entities(args.User.Uid)); + _popupSystem.PopupEntity(Loc.GetString("pai-system-pai-installed"), uid, Filter.Entities(args.User)); return; } else if (EntityManager.HasComponent(uid)) { - _popupSystem.PopupEntity(Loc.GetString("pai-system-still-searching"), uid, Filter.Entities(args.User.Uid)); + _popupSystem.PopupEntity(Loc.GetString("pai-system-still-searching"), uid, Filter.Entities(args.User)); return; } // Ownership tag - component.Owner.Name = Loc.GetString("pai-system-pai-name", ("owner", args.User)); + string val = Loc.GetString("pai-system-pai-name", ("owner", args.User)); + EntityManager.GetComponent(component.Owner).EntityName = val; var ghostFinder = EntityManager.EnsureComponent(uid); ghostFinder.RoleName = Loc.GetString("pai-system-role-name"); ghostFinder.RoleDescription = Loc.GetString("pai-system-role-description"); - _popupSystem.PopupEntity(Loc.GetString("pai-system-searching"), uid, Filter.Entities(args.User.Uid)); + _popupSystem.PopupEntity(Loc.GetString("pai-system-searching"), uid, Filter.Entities(args.User)); UpdatePAIAppearance(uid, PAIStatus.Searching); } @@ -144,7 +145,7 @@ namespace Content.Server.PAI if (EntityManager.HasComponent(uid)) { EntityManager.RemoveComponent(uid); - _popupSystem.PopupEntity(Loc.GetString("pai-system-wiped-device"), uid, Filter.Entities(args.User.Uid)); + _popupSystem.PopupEntity(Loc.GetString("pai-system-wiped-device"), uid, Filter.Entities(args.User)); PAITurningOff(uid); } }; @@ -160,7 +161,7 @@ namespace Content.Server.PAI if (EntityManager.HasComponent(uid)) { EntityManager.RemoveComponent(uid); - _popupSystem.PopupEntity(Loc.GetString("pai-system-stopped-searching"), uid, Filter.Entities(args.User.Uid)); + _popupSystem.PopupEntity(Loc.GetString("pai-system-stopped-searching"), uid, Filter.Entities(args.User)); PAITurningOff(uid); } }; diff --git a/Content.Server/PDA/PDAExtensions.cs b/Content.Server/PDA/PDAExtensions.cs index a944d3a712..8787dc5165 100644 --- a/Content.Server/PDA/PDAExtensions.cs +++ b/Content.Server/PDA/PDAExtensions.cs @@ -3,6 +3,7 @@ using Content.Server.Access.Components; using Content.Server.Hands.Components; using Content.Server.Inventory.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.PDA { @@ -14,22 +15,24 @@ namespace Content.Server.PDA /// /// The player to check in. /// The id card component. - public static IdCardComponent? GetHeldId(this IEntity player) + public static IdCardComponent? GetHeldId(this EntityUid player) { IdCardComponent? firstIdInPda = null; - if (player.TryGetComponent(out HandsComponent? hands)) + var entMan = IoCManager.Resolve(); + + if (entMan.TryGetComponent(player, out HandsComponent? hands)) { foreach (var item in hands.GetAllHeldItems()) { if (firstIdInPda == null && - item.Owner.TryGetComponent(out PDAComponent? pda) && + entMan.TryGetComponent(item.Owner, out PDAComponent? pda) && pda.ContainedID != null) { firstIdInPda = pda.ContainedID; } - if (item.Owner.TryGetComponent(out IdCardComponent? card)) + if (entMan.TryGetComponent(item.Owner, out IdCardComponent? card)) { return card; } @@ -43,18 +46,18 @@ namespace Content.Server.PDA IdCardComponent? firstIdInInventory = null; - if (player.TryGetComponent(out InventoryComponent? inventory)) + if (entMan.TryGetComponent(player, out InventoryComponent? inventory)) { foreach (var item in inventory.GetAllHeldItems()) { if (firstIdInInventory == null && - item.TryGetComponent(out PDAComponent? pda) && + entMan.TryGetComponent(item, out PDAComponent? pda) && pda.ContainedID != null) { firstIdInInventory = pda.ContainedID; } - if (item.TryGetComponent(out IdCardComponent? card)) + if (entMan.TryGetComponent(item, out IdCardComponent? card)) { return card; } @@ -71,7 +74,7 @@ namespace Content.Server.PDA /// The player to check in. /// The id card component. /// true if found, false otherwise. - public static bool TryGetHeldId(this IEntity player, [NotNullWhen(true)] out IdCardComponent? id) + public static bool TryGetHeldId(this EntityUid player, [NotNullWhen(true)] out IdCardComponent? id) { return (id = player.GetHeldId()) != null; } diff --git a/Content.Server/PDA/PDASystem.cs b/Content.Server/PDA/PDASystem.cs index 391d2ce00b..5c95c183d3 100644 --- a/Content.Server/PDA/PDASystem.cs +++ b/Content.Server/PDA/PDASystem.cs @@ -73,7 +73,7 @@ namespace Content.Server.PDA private void OnItemInserted(EntityUid uid, PDAComponent pda, EntInsertedIntoContainerMessage args) { if (args.Container.ID == pda.IdSlot.ID) - pda.ContainedID = args.Entity.GetComponentOrNull(); + pda.ContainedID = EntityManager.GetComponentOrNull(args.Entity); UpdatePDAAppearance(pda); UpdatePDAUserInterface(pda); @@ -110,9 +110,9 @@ namespace Content.Server.PDA UpdatePDAUserInterface(pda); } - private bool OpenUI(PDAComponent pda, IEntity user) + private bool OpenUI(PDAComponent pda, EntityUid user) { - if (!user.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(user, out ActorComponent? actor)) return false; var ui = pda.Owner.GetUIOrNull(PDAUiKey.Key); @@ -123,7 +123,7 @@ namespace Content.Server.PDA private void UpdatePDAAppearance(PDAComponent pda) { - if (pda.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(pda.Owner, out AppearanceComponent? appearance)) appearance.SetData(PDAVisuals.IDCardInserted, pda.ContainedID != null); } @@ -136,7 +136,7 @@ namespace Content.Server.PDA JobTitle = pda.ContainedID?.JobTitle }; - var hasUplink = pda.Owner.HasComponent(); + var hasUplink = EntityManager.HasComponent(pda.Owner); var ui = pda.Owner.GetUIOrNull(PDAUiKey.Key); ui?.SetState(new PDAUpdateState(pda.FlashlightOn, pda.PenSlot.HasItem, ownerInfo, hasUplink)); @@ -145,7 +145,7 @@ namespace Content.Server.PDA private void OnUIMessage(PDAComponent pda, ServerBoundUserInterfaceMessage msg) { // cast EntityUid? to EntityUid - if (msg.Session.AttachedEntityUid is not EntityUid playerUid) + if (msg.Session.AttachedEntity is not {Valid: true} playerUid) return; switch (msg.Message) @@ -155,24 +155,24 @@ namespace Content.Server.PDA break; case PDAToggleFlashlightMessage _: { - if (pda.Owner.TryGetComponent(out UnpoweredFlashlightComponent? flashlight)) + if (EntityManager.TryGetComponent(pda.Owner, out UnpoweredFlashlightComponent? flashlight)) _unpoweredFlashlight.ToggleLight(flashlight); break; } case PDAEjectIDMessage _: { - _itemSlotsSystem.TryEjectToHands(pda.Owner.Uid, pda.IdSlot, playerUid); + _itemSlotsSystem.TryEjectToHands(pda.Owner, pda.IdSlot, playerUid); break; } case PDAEjectPenMessage _: { - _itemSlotsSystem.TryEjectToHands(pda.Owner.Uid, pda.PenSlot, playerUid); + _itemSlotsSystem.TryEjectToHands(pda.Owner, pda.PenSlot, playerUid); break; } case PDAShowUplinkMessage _: { - if (pda.Owner.TryGetComponent(out UplinkComponent? uplink)) + if (EntityManager.TryGetComponent(pda.Owner, out UplinkComponent? uplink)) _uplinkSystem.ToggleUplinkUI(uplink, msg.Session); break; } diff --git a/Content.Server/Paper/PaperComponent.cs b/Content.Server/Paper/PaperComponent.cs index 35729d9c9b..e99520c72e 100644 --- a/Content.Server/Paper/PaperComponent.cs +++ b/Content.Server/Paper/PaperComponent.cs @@ -6,6 +6,7 @@ using Content.Shared.Paper; using Content.Shared.Tag; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -18,6 +19,8 @@ namespace Content.Server.Paper public class PaperComponent : SharedPaperComponent, IExamine, IInteractUsing, IUse #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + private PaperAction _mode; [DataField("content")] public string Content { get; set; } = ""; @@ -42,7 +45,7 @@ namespace Content.Server.Paper Content = content + '\n'; UpdateUserInterface(); - if (!Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (!_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) return; var status = string.IsNullOrWhiteSpace(content) @@ -73,7 +76,7 @@ namespace Content.Server.Paper bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return false; _mode = PaperAction.Read; @@ -90,12 +93,12 @@ namespace Content.Server.Paper Content += msg.Text + '\n'; - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(PaperVisuals.Status, PaperStatus.Written); } - Owner.Description = ""; + _entMan.GetComponent(Owner).EntityDescription = ""; UpdateUserInterface(); } @@ -103,7 +106,7 @@ namespace Content.Server.Paper { if (!eventArgs.Using.HasTag("Write")) return false; - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return false; _mode = PaperAction.Write; diff --git a/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorControlBoxComponent.cs b/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorControlBoxComponent.cs index d890de6857..d4d757127b 100644 --- a/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorControlBoxComponent.cs +++ b/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorControlBoxComponent.cs @@ -11,7 +11,6 @@ using Content.Server.VendingMachines; using Content.Server.WireHacking; using Content.Shared.ActionBlocker; using Content.Shared.Interaction; -using Content.Shared.Interaction.Events; using Content.Shared.Singularity.Components; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; @@ -37,6 +36,7 @@ namespace Content.Server.ParticleAccelerator.Components [RegisterComponent] public class ParticleAcceleratorControlBoxComponent : ParticleAcceleratorPartComponent, IActivate, IWires { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IMapManager _mapManager = default!; public override string Name => "ParticleAcceleratorControlBox"; @@ -153,8 +153,8 @@ namespace Content.Server.ParticleAccelerator.Components } - if (obj.Session.AttachedEntityUid == null || - !EntitySystem.Get().CanInteract(obj.Session.AttachedEntityUid.Value)) + if (obj.Session.AttachedEntity is not {Valid: true} attached || + !EntitySystem.Get().CanInteract(attached)) { return; } @@ -222,12 +222,12 @@ namespace Content.Server.ParticleAccelerator.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { return; } - if (Owner.TryGetComponent(out var wires) && wires.IsPanelOpen) + if (_entMan.TryGetComponent(Owner, out var wires) && wires.IsPanelOpen) { wires.OpenInterface(actor.PlayerSession); } @@ -334,7 +334,7 @@ namespace Content.Server.ParticleAccelerator.Components private void UpdateWireStatus() { - if (!Owner.TryGetComponent(out WiresComponent? wires)) + if (!_entMan.TryGetComponent(Owner, out WiresComponent? wires)) { return; } @@ -384,13 +384,13 @@ namespace Content.Server.ParticleAccelerator.Components _partEmitterRight = null; // Find fuel chamber first by scanning cardinals. - if (Owner.Transform.Anchored) + if (_entMan.GetComponent(Owner).Anchored) { - var grid = _mapManager.GetGrid(Owner.Transform.GridID); - var coords = Owner.Transform.Coordinates; + var grid = _mapManager.GetGrid(_entMan.GetComponent(Owner).GridID); + var coords = _entMan.GetComponent(Owner).Coordinates; foreach (var maybeFuel in grid.GetCardinalNeighborCells(coords)) { - if (Owner.EntityManager.TryGetComponent(maybeFuel, out _partFuelChamber)) + if (_entMan.TryGetComponent(maybeFuel, out _partFuelChamber)) { break; } @@ -406,7 +406,7 @@ namespace Content.Server.ParticleAccelerator.Components // Align ourselves to match fuel chamber orientation. // This means that if you mess up the orientation of the control box it's not a big deal, // because the sprite is far from obvious about the orientation. - Owner.Transform.LocalRotation = _partFuelChamber.Owner.Transform.LocalRotation; + _entMan.GetComponent(Owner).LocalRotation = _entMan.GetComponent(_partFuelChamber.Owner).LocalRotation; var offsetEndCap = RotateOffset((1, 1)); var offsetPowerBox = RotateOffset((1, -1)); @@ -452,7 +452,7 @@ namespace Content.Server.ParticleAccelerator.Components Vector2i RotateOffset(in Vector2i vec) { - var rot = new Angle(Owner.Transform.LocalRotation); + var rot = new Angle(_entMan.GetComponent(Owner).LocalRotation); return (Vector2i) rot.RotateVec(vec); } } @@ -460,11 +460,11 @@ namespace Content.Server.ParticleAccelerator.Components private bool ScanPart(Vector2i offset, [NotNullWhen(true)] out T? part) where T : ParticleAcceleratorPartComponent { - var grid = _mapManager.GetGrid(Owner.Transform.GridID); - var coords = Owner.Transform.Coordinates; + var grid = _mapManager.GetGrid(_entMan.GetComponent(Owner).GridID); + var coords = _entMan.GetComponent(Owner).Coordinates; foreach (var ent in grid.GetOffset(coords, offset)) { - if (Owner.EntityManager.TryGetComponent(ent, out part) && !part.Deleted) + if (_entMan.TryGetComponent(ent, out part) && !part.Deleted) { return true; } @@ -577,7 +577,7 @@ namespace Content.Server.ParticleAccelerator.Components private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(ParticleAcceleratorVisuals.VisualState, _apcPowerReceiverComponent!.Powered @@ -683,7 +683,7 @@ namespace Content.Server.ParticleAccelerator.Components private void UpdatePartVisualState(ParticleAcceleratorPartComponent? component) { - if (component == null || !component.Owner.TryGetComponent(out var appearanceComponent)) + if (component == null || !_entMan.TryGetComponent(component.Owner, out var appearanceComponent)) { return; } diff --git a/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorEmitterComponent.cs b/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorEmitterComponent.cs index da09283cd0..b4053089df 100644 --- a/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorEmitterComponent.cs +++ b/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorEmitterComponent.cs @@ -1,5 +1,6 @@ using Content.Shared.Singularity.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; @@ -15,14 +16,15 @@ namespace Content.Server.ParticleAccelerator.Components public void Fire(ParticleAcceleratorPowerState strength) { - var projectile = Owner.EntityManager.SpawnEntity("ParticlesProjectile", Owner.Transform.Coordinates); + var entities = IoCManager.Resolve(); + var projectile = entities.SpawnEntity("ParticlesProjectile", entities.GetComponent(Owner).Coordinates); - if (!projectile.TryGetComponent(out var particleProjectileComponent)) + if (!entities.TryGetComponent(projectile, out var particleProjectileComponent)) { Logger.Error("ParticleAcceleratorEmitter tried firing particles, but they was spawned without a ParticleProjectileComponent"); return; } - particleProjectileComponent.Fire(strength, Owner.Transform.WorldRotation, Owner); + particleProjectileComponent.Fire(strength, entities.GetComponent(Owner).WorldRotation, Owner); } public override string ToString() diff --git a/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorPartComponent.cs b/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorPartComponent.cs index 17c9a53035..0d52dc89d7 100644 --- a/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorPartComponent.cs +++ b/Content.Server/ParticleAccelerator/Components/ParticleAcceleratorPartComponent.cs @@ -1,4 +1,5 @@ using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.ViewVariables; namespace Content.Server.ParticleAccelerator.Components @@ -12,7 +13,7 @@ namespace Content.Server.ParticleAccelerator.Components base.Initialize(); // FIXME: this has to be an entity system, full stop. - Owner.Transform.Anchored = true; + IoCManager.Resolve().GetComponent(Owner).Anchored = true; } public void OnAnchorChanged() diff --git a/Content.Server/ParticleAccelerator/Components/ParticleProjectileComponent.cs b/Content.Server/ParticleAccelerator/Components/ParticleProjectileComponent.cs index b49a0f2b2a..6fabcf499f 100644 --- a/Content.Server/ParticleAccelerator/Components/ParticleProjectileComponent.cs +++ b/Content.Server/ParticleAccelerator/Components/ParticleProjectileComponent.cs @@ -3,10 +3,9 @@ using Content.Server.Singularity.Components; using Content.Shared.Singularity.Components; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; -using Robust.Shared.Physics.Collision; -using Robust.Shared.Physics.Dynamics; using Robust.Shared.Timing; namespace Content.Server.ParticleAccelerator.Components @@ -14,28 +13,30 @@ namespace Content.Server.ParticleAccelerator.Components [RegisterComponent] public class ParticleProjectileComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "ParticleProjectile"; public ParticleAcceleratorPowerState State; - public void Fire(ParticleAcceleratorPowerState state, Angle angle, IEntity firer) + public void Fire(ParticleAcceleratorPowerState state, Angle angle, EntityUid firer) { State = state; - if (!Owner.TryGetComponent(out var physicsComponent)) + if (!_entMan.TryGetComponent(Owner, out var physicsComponent)) { Logger.Error("ParticleProjectile tried firing, but it was spawned without a CollidableComponent"); return; } physicsComponent.BodyStatus = BodyStatus.InAir; - if (!Owner.TryGetComponent(out var projectileComponent)) + if (!_entMan.TryGetComponent(Owner, out var projectileComponent)) { Logger.Error("ParticleProjectile tried firing, but it was spawned without a ProjectileComponent"); return; } projectileComponent.IgnoreEntity(firer); - if (!Owner.TryGetComponent(out var singuloFoodComponent)) + if (!_entMan.TryGetComponent(Owner, out var singuloFoodComponent)) { Logger.Error("ParticleProjectile tried firing, but it was spawned without a SinguloFoodComponent"); return; @@ -60,7 +61,7 @@ namespace Content.Server.ParticleAccelerator.Components _ => "0" }; - if (!Owner.TryGetComponent(out var spriteComponent)) + if (!_entMan.TryGetComponent(Owner, out var spriteComponent)) { Logger.Error("ParticleProjectile tried firing, but it was spawned without a SpriteComponent"); return; @@ -70,8 +71,8 @@ namespace Content.Server.ParticleAccelerator.Components physicsComponent .LinearVelocity = angle.ToWorldVec() * 20f; - Owner.Transform.LocalRotation = angle; - Timer.Spawn(3000, () => Owner.Delete()); + _entMan.GetComponent(Owner).LocalRotation = angle; + Timer.Spawn(3000, () => _entMan.DeleteEntity(Owner)); } } } diff --git a/Content.Server/ParticleAccelerator/EntitySystems/ParticleAcceleratorPartSystem.cs b/Content.Server/ParticleAccelerator/EntitySystems/ParticleAcceleratorPartSystem.cs index 0b5709402d..7505a783ba 100644 --- a/Content.Server/ParticleAccelerator/EntitySystems/ParticleAcceleratorPartSystem.cs +++ b/Content.Server/ParticleAccelerator/EntitySystems/ParticleAcceleratorPartSystem.cs @@ -1,6 +1,7 @@ using Content.Server.ParticleAccelerator.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.ParticleAccelerator.EntitySystems { @@ -23,9 +24,9 @@ namespace Content.Server.ParticleAccelerator.EntitySystems component.OnAnchorChanged(); } - private static void RotateEvent(ref RotateEvent ev) + private void RotateEvent(ref RotateEvent ev) { - if (ev.Sender.TryGetComponent(out ParticleAcceleratorPartComponent? part)) + if (EntityManager.TryGetComponent(ev.Sender, out ParticleAcceleratorPartComponent? part)) { part.Rotated(); } diff --git a/Content.Server/Physics/Controllers/ConveyorController.cs b/Content.Server/Physics/Controllers/ConveyorController.cs index ca7d695349..146a2985ed 100644 --- a/Content.Server/Physics/Controllers/ConveyorController.cs +++ b/Content.Server/Physics/Controllers/ConveyorController.cs @@ -41,11 +41,12 @@ namespace Content.Server.Physics.Controllers } var direction = system.GetAngle(comp).ToVec(); - var ownerPos = comp.Owner.Transform.WorldPosition; + var entMan = IoCManager.Resolve(); + var ownerPos = entMan.GetComponent(comp.Owner).WorldPosition; foreach (var (entity, physics) in EntitySystem.Get().GetEntitiesToMove(comp)) { - var itemRelativeToConveyor = entity.Transform.WorldPosition - ownerPos; + var itemRelativeToConveyor = entMan.GetComponent(entity).WorldPosition - ownerPos; physics.LinearVelocity += Convey(direction, comp.Speed, frameTime, itemRelativeToConveyor); } } diff --git a/Content.Server/Physics/Controllers/MoverController.cs b/Content.Server/Physics/Controllers/MoverController.cs index 1dfb49bdd2..21ee487a22 100644 --- a/Content.Server/Physics/Controllers/MoverController.cs +++ b/Content.Server/Physics/Controllers/MoverController.cs @@ -10,7 +10,6 @@ using Content.Shared.Inventory; using Content.Shared.Maps; using Content.Shared.Movement; using Content.Shared.Movement.Components; -using Content.Shared.Shuttles; using Content.Shared.Shuttles.Components; using Content.Shared.Tag; using Robust.Shared.Audio; @@ -53,7 +52,7 @@ namespace Content.Server.Physics.Controllers foreach (var (mobMover, mover, physics) in EntityManager.EntityQuery()) { - _excludedMobs.Add(mover.Owner.Uid); + _excludedMobs.Add(mover.Owner); HandleMobMovement(mover, physics, mobMover); } @@ -61,7 +60,7 @@ namespace Content.Server.Physics.Controllers foreach (var (mover, physics) in EntityManager.EntityQuery(true)) { - if (_excludedMobs.Contains(mover.Owner.Uid)) continue; + if (_excludedMobs.Contains(mover.Owner)) continue; HandleKinematicMovement(mover, physics); } @@ -75,7 +74,7 @@ namespace Content.Server.Physics.Controllers foreach (var (pilot, mover, xform) in EntityManager.EntityQuery()) { if (pilot.Console == null) continue; - _excludedMobs.Add(mover.Owner.Uid); + _excludedMobs.Add(mover.Owner); var gridId = xform.GridID; @@ -108,7 +107,7 @@ namespace Content.Server.Physics.Controllers // then do the movement input once for it. foreach (var (shuttle, pilots) in _shuttlePilots) { - if (shuttle.Paused || !EntityManager.TryGetComponent(shuttle.OwnerUid, out PhysicsComponent? body)) continue; + if (shuttle.Paused || !EntityManager.TryGetComponent((shuttle).Owner, out PhysicsComponent? body)) continue; // Collate movement linear and angular inputs together var linearInput = Vector2.Zero; @@ -131,7 +130,7 @@ namespace Content.Server.Physics.Controllers if (sprint.Equals(Vector2.Zero)) continue; - var offsetRotation = EntityManager.GetComponent(console.OwnerUid).LocalRotation; + var offsetRotation = EntityManager.GetComponent((console).Owner).LocalRotation; linearInput += offsetRotation.RotateVec(new Vector2(0f, sprint.Y)); angularInput += sprint.X; @@ -153,7 +152,7 @@ namespace Content.Server.Physics.Controllers if (sprint.Equals(Vector2.Zero)) continue; - var offsetRotation = EntityManager.GetComponent(console.OwnerUid).LocalRotation; + var offsetRotation = EntityManager.GetComponent((console).Owner).LocalRotation; sprint = offsetRotation.RotateVec(sprint); linearInput += sprint; @@ -180,7 +179,7 @@ namespace Content.Server.Physics.Controllers var angle = linearInput.ToWorldAngle(); var linearDir = angle.GetDir(); var dockFlag = linearDir.AsFlag(); - var shuttleNorth = EntityManager.GetComponent(body.OwnerUid).WorldRotation.ToWorldVec(); + var shuttleNorth = EntityManager.GetComponent((body).Owner).WorldRotation.ToWorldVec(); // Won't just do cardinal directions. foreach (DirectionFlag dir in Enum.GetValues(typeof(DirectionFlag))) @@ -271,7 +270,7 @@ namespace Content.Server.Physics.Controllers { if (!mover.Owner.HasTag("FootstepSound")) return; - var transform = mover.Owner.Transform; + var transform = EntityManager.GetComponent(mover.Owner); var coordinates = transform.Coordinates; var gridId = coordinates.GetGridId(EntityManager); var distanceNeeded = mover.Sprinting ? StepSoundMoveDistanceRunning : StepSoundMoveDistanceWalking; @@ -303,9 +302,9 @@ namespace Content.Server.Physics.Controllers mobMover.StepSoundDistance -= distanceNeeded; - if (mover.Owner.TryGetComponent(out var inventory) + if (EntityManager.TryGetComponent(mover.Owner, out var inventory) && inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.SHOES, out var item) - && item.Owner.TryGetComponent(out var modifier)) + && EntityManager.TryGetComponent(item.Owner, out var modifier)) { modifier.PlayFootstep(); } @@ -315,7 +314,7 @@ namespace Content.Server.Physics.Controllers } } - private void PlayFootstepSound(IEntity mover, GridId gridId, EntityCoordinates coordinates, bool sprinting) + private void PlayFootstepSound(EntityUid mover, GridId gridId, EntityCoordinates coordinates, bool sprinting) { var grid = _mapManager.GetGrid(gridId); var tile = grid.GetTileRef(coordinates); @@ -352,7 +351,7 @@ namespace Content.Server.Physics.Controllers SoundSystem.Play( Filter.Pvs(coordinates), soundToPlay, - mover.Transform.Coordinates, + EntityManager.GetComponent(mover).Coordinates, sprinting ? AudioParams.Default.WithVolume(0.75f) : null); } } diff --git a/Content.Server/Physics/Controllers/PullController.cs b/Content.Server/Physics/Controllers/PullController.cs index 1978036cfa..3625850847 100644 --- a/Content.Server/Physics/Controllers/PullController.cs +++ b/Content.Server/Physics/Controllers/PullController.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using Content.Shared.Pulling; using Robust.Shared.GameObjects; +using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Physics.Controllers; -using Robust.Shared.Maths; -using Robust.Shared.Utility; namespace Content.Server.Physics.Controllers { @@ -65,32 +64,31 @@ namespace Content.Server.Physics.Controllers continue; } - var puller = pullable.Puller; - if (puller == null) + if (pullable.Puller is not {Valid: true} puller) { continue; } // Now that's over with... - var pullerPosition = puller.Transform.MapPosition; - var movingTo = pullable.MovingTo.Value.ToMap(pullable.Owner.EntityManager); + var pullerPosition = EntityManager.GetComponent(puller).MapPosition; + var movingTo = pullable.MovingTo.Value.ToMap(EntityManager); if (movingTo.MapId != pullerPosition.MapId) { _pullableSystem.StopMoveTo(pullable); continue; } - if (!pullable.Owner.TryGetComponent(out var physics) || + if (!EntityManager.TryGetComponent(pullable.Owner, out var physics) || physics.BodyType == BodyType.Static || - movingTo.MapId != pullable.Owner.Transform.MapID) + movingTo.MapId != EntityManager.GetComponent(pullable.Owner).MapID) { _pullableSystem.StopMoveTo(pullable); continue; } var movingPosition = movingTo.Position; - var ownerPosition = pullable.Owner.Transform.MapPosition.Position; + var ownerPosition = EntityManager.GetComponent(pullable.Owner).MapPosition.Position; var diff = movingPosition - ownerPosition; var diffLength = diff.Length; @@ -118,7 +116,7 @@ namespace Content.Server.Physics.Controllers var impulse = accel * physics.Mass * frameTime; physics.ApplyLinearImpulse(impulse); - if (puller.TryGetComponent(out var pullerPhysics)) + if (EntityManager.TryGetComponent(puller, out var pullerPhysics)) { pullerPhysics.WakeBody(); pullerPhysics.ApplyLinearImpulse(-impulse); diff --git a/Content.Server/Physics/Controllers/SingularityController.cs b/Content.Server/Physics/Controllers/SingularityController.cs index 4c64b5ee9c..eb905f468d 100644 --- a/Content.Server/Physics/Controllers/SingularityController.cs +++ b/Content.Server/Physics/Controllers/SingularityController.cs @@ -21,7 +21,7 @@ namespace Content.Server.Physics.Controllers foreach (var (singularity, physics) in EntityManager.EntityQuery()) { - if (singularity.Owner.HasComponent() || + if (EntityManager.HasComponent(singularity.Owner) || singularity.BeingDeletedByAnotherSingularity) continue; singularity.MoveAccumulator -= frameTime; diff --git a/Content.Server/Pinpointer/ServerPinpointerSystem.cs b/Content.Server/Pinpointer/ServerPinpointerSystem.cs index 15d5a1ecaa..2ed782176e 100644 --- a/Content.Server/Pinpointer/ServerPinpointerSystem.cs +++ b/Content.Server/Pinpointer/ServerPinpointerSystem.cs @@ -60,10 +60,10 @@ namespace Content.Server.Pinpointer var l = new SortedList(); foreach (var e in ents) { - if (whitelist.IsValid(e.Uid)) + if (whitelist.IsValid(e)) { - var dist = (e.Transform.WorldPosition - transform.WorldPosition).LengthSquared; - l.TryAdd(dist, e.Uid); + var dist = (EntityManager.GetComponent(e).WorldPosition - transform.WorldPosition).LengthSquared; + l.TryAdd(dist, e); } } diff --git a/Content.Server/Plants/Components/RandomPottedPlantComponent.cs b/Content.Server/Plants/Components/RandomPottedPlantComponent.cs index b5b830e432..d3e2a42f57 100644 --- a/Content.Server/Plants/Components/RandomPottedPlantComponent.cs +++ b/Content.Server/Plants/Components/RandomPottedPlantComponent.cs @@ -11,6 +11,8 @@ namespace Content.Server.Plants.Components [RegisterComponent] public class RandomPottedPlantComponent : Component, IMapInit { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "RandomPottedPlant"; private static readonly string[] RegularPlantStates; @@ -61,7 +63,7 @@ namespace Content.Server.Plants.Components if (_selectedState != null) { - Owner.GetComponent().LayerSetState(0, _selectedState); + _entMan.GetComponent(Owner).LayerSetState(0, _selectedState); } } @@ -72,7 +74,7 @@ namespace Content.Server.Plants.Components var list = _plastic ? PlasticPlantStates : RegularPlantStates; _selectedState = random.Pick(list); - Owner.GetComponent().LayerSetState(0, _selectedState); + _entMan.GetComponent(Owner).LayerSetState(0, _selectedState); } } } diff --git a/Content.Server/PneumaticCannon/PneumaticCannonComponent.cs b/Content.Server/PneumaticCannon/PneumaticCannonComponent.cs index 319b16170c..3272486ad9 100644 --- a/Content.Server/PneumaticCannon/PneumaticCannonComponent.cs +++ b/Content.Server/PneumaticCannon/PneumaticCannonComponent.cs @@ -1,11 +1,9 @@ using System.Collections.Generic; using Content.Shared.Sound; using Content.Shared.Tools; -using Content.Shared.Verbs; using Robust.Shared.Analyzers; using Robust.Shared.Containers; using Robust.Shared.GameObjects; -using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; @@ -80,7 +78,7 @@ namespace Content.Server.PneumaticCannon public struct FireData { - public IEntity User; + public EntityUid User; public float Strength; public Vector2 Direction; } diff --git a/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs b/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs index 367ad583d6..6784c555eb 100644 --- a/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs +++ b/Content.Server/PneumaticCannon/PneumaticCannonSystem.cs @@ -4,30 +4,25 @@ using System.Linq; using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; using Content.Server.Camera; -using Content.Server.CombatMode; using Content.Server.Hands.Components; using Content.Server.Items; using Content.Server.Nutrition.Components; using Content.Server.Storage.Components; using Content.Server.Stunnable; -using Content.Server.Stunnable.Components; -using Content.Shared.Interaction; -using Content.Shared.PneumaticCannon; -using Robust.Shared.Containers; -using Robust.Shared.GameObjects; -using Robust.Shared.Map; using Content.Server.Throwing; -using Content.Server.Tools; using Content.Server.Tools.Components; using Content.Shared.CombatMode; +using Content.Shared.Interaction; +using Content.Shared.PneumaticCannon; using Content.Shared.Popups; -using Content.Shared.Sound; using Content.Shared.StatusEffect; using Content.Shared.Verbs; -using Content.Shared.Weapons.Melee; using Robust.Shared.Audio; +using Robust.Shared.Containers; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; +using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Player; using Robust.Shared.Random; @@ -98,7 +93,7 @@ namespace Content.Server.PneumaticCannon private void OnInteractUsing(EntityUid uid, PneumaticCannonComponent component, InteractUsingEvent args) { args.Handled = true; - if (args.Used.HasComponent() + if (EntityManager.HasComponent(args.Used) && component.GasTankSlot.CanInsert(args.Used) && component.GasTankRequired) { @@ -109,7 +104,7 @@ namespace Content.Server.PneumaticCannon return; } - if (args.Used.TryGetComponent(out var tool)) + if (EntityManager.TryGetComponent(args.Used, out var tool)) { if (tool.Qualities.Contains(component.ToolModifyMode)) { @@ -138,8 +133,8 @@ namespace Content.Server.PneumaticCannon // this overrides the ServerStorageComponent's insertion stuff because // it's not event-based yet and I can't cancel it, so tools and stuff // will modify mode/power then get put in anyway - if (args.Used.TryGetComponent(out var item) - && component.Owner.TryGetComponent(out var storage)) + if (EntityManager.TryGetComponent(args.Used, out var item) + && EntityManager.TryGetComponent(component.Owner, out var storage)) { if (storage.CanInsert(args.Used)) { @@ -167,20 +162,20 @@ namespace Content.Server.PneumaticCannon { args.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-fire-no-gas", ("cannon", component.Owner))); - SoundSystem.Play(Filter.Pvs(args.Used.Uid), "/Audio/Items/hiss.ogg", args.Used.Uid, AudioParams.Default); + SoundSystem.Play(Filter.Pvs(args.Used), "/Audio/Items/hiss.ogg", args.Used, AudioParams.Default); return; } AddToQueue(component, args.User, args.ClickLocation); } - public void AddToQueue(PneumaticCannonComponent comp, IEntity user, EntityCoordinates click) + public void AddToQueue(PneumaticCannonComponent comp, EntityUid user, EntityCoordinates click) { - if (!comp.Owner.TryGetComponent(out var storage)) + if (!EntityManager.TryGetComponent(comp.Owner, out var storage)) return; if (storage.StoredEntities == null) return; if (storage.StoredEntities.Count == 0) { - SoundSystem.Play(Filter.Pvs(comp.OwnerUid), "/Audio/Weapons/click.ogg", comp.OwnerUid, AudioParams.Default); + SoundSystem.Play(Filter.Pvs((comp).Owner), "/Audio/Weapons/click.ogg", ((IComponent) comp).Owner, AudioParams.Default); return; } @@ -195,7 +190,7 @@ namespace Content.Server.PneumaticCannon for (int i = 0; i < entCounts; i++) { - var dir = (click.ToMapPos(EntityManager) - user.Transform.WorldPosition).Normalized; + var dir = (click.ToMapPos(EntityManager) - EntityManager.GetComponent(user).WorldPosition).Normalized; var randomAngle = GetRandomFireAngleFromPower(comp.Power).RotateVec(dir); var randomStrengthMult = _random.NextFloat(0.75f, 1.25f); @@ -217,24 +212,24 @@ namespace Content.Server.PneumaticCannon { data.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-fire-no-gas", ("cannon", comp.Owner))); - SoundSystem.Play(Filter.Pvs(comp.OwnerUid), "/Audio/Items/hiss.ogg", comp.OwnerUid, AudioParams.Default); + SoundSystem.Play(Filter.Pvs(((IComponent) comp).Owner), "/Audio/Items/hiss.ogg", ((IComponent) comp).Owner, AudioParams.Default); return; } - if (!comp.Owner.TryGetComponent(out var storage)) + if (!EntityManager.TryGetComponent(comp.Owner, out var storage)) return; - if (data.User.Deleted) + if (Deleted(data.User)) return; if (storage.StoredEntities == null) return; if (storage.StoredEntities.Count == 0) return; // click sound? - IEntity ent = _random.Pick(storage.StoredEntities); + var ent = _random.Pick(storage.StoredEntities); storage.Remove(ent); - SoundSystem.Play(Filter.Pvs(data.User), comp.FireSound.GetSound(), comp.OwnerUid, AudioParams.Default); - if (data.User.TryGetComponent(out var recoil)) + SoundSystem.Play(Filter.Pvs(data.User), comp.FireSound.GetSound(), ((IComponent) comp).Owner, AudioParams.Default); + if (EntityManager.TryGetComponent(data.User, out var recoil)) { recoil.Kick(Vector2.One * data.Strength); } @@ -244,19 +239,20 @@ namespace Content.Server.PneumaticCannon // lasagna, anybody? ent.EnsureComponent(); - if(data.User.TryGetComponent(out var status) + if(EntityManager.TryGetComponent(data.User, out var status) && comp.Power == PneumaticCannonPower.High) { - _stun.TryParalyze(data.User.Uid, TimeSpan.FromSeconds(comp.HighPowerStunTime), true, status); + _stun.TryParalyze(data.User, TimeSpan.FromSeconds(comp.HighPowerStunTime), true, status); + data.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-power-stun", ("cannon", comp.Owner))); } - if (comp.GasTankSlot.ContainedEntity != null && comp.GasTankRequired) + if (comp.GasTankSlot.ContainedEntity is {Valid: true} contained && comp.GasTankRequired) { // we checked for this earlier in HasGas so a GetComp is okay - var gas = comp.GasTankSlot.ContainedEntity.GetComponent(); - var environment = _atmos.GetTileMixture(comp.Owner.Transform.Coordinates, true); + var gas = EntityManager.GetComponent(contained); + var environment = _atmos.GetTileMixture(EntityManager.GetComponent(comp.Owner).Coordinates, true); var removed = gas.RemoveAir(GetMoleUsageFromPower(comp.Power)); if (environment != null && removed != null) { @@ -272,11 +268,11 @@ namespace Content.Server.PneumaticCannon { var usage = GetMoleUsageFromPower(component.Power); - if (component.GasTankSlot.ContainedEntity == null) + if (component.GasTankSlot.ContainedEntity is not {Valid: true } contained) return false; // not sure how it wouldnt, but it might not! who knows - if (component.GasTankSlot.ContainedEntity.TryGetComponent(out var tank)) + if (EntityManager.TryGetComponent(contained, out var tank)) { if (tank.Air.TotalMoles < usage) return false; @@ -311,32 +307,31 @@ namespace Content.Server.PneumaticCannon args.Verbs.Add(ejectItems); } - public void TryRemoveGasTank(PneumaticCannonComponent component, IEntity user) + public void TryRemoveGasTank(PneumaticCannonComponent component, EntityUid user) { - if (component.GasTankSlot.ContainedEntity == null) + if (component.GasTankSlot.ContainedEntity is not {Valid: true} contained) { user.PopupMessage(Loc.GetString("pneumatic-cannon-component-gas-tank-none", ("cannon", component.Owner))); return; } - var ent = component.GasTankSlot.ContainedEntity; - if (component.GasTankSlot.Remove(ent)) + if (component.GasTankSlot.Remove(contained)) { - if (user.TryGetComponent(out var hands)) + if (EntityManager.TryGetComponent(user, out var hands)) { - hands.TryPutInActiveHandOrAny(ent); + hands.TryPutInActiveHandOrAny(contained); } user.PopupMessage(Loc.GetString("pneumatic-cannon-component-gas-tank-remove", - ("tank", ent), ("cannon", component.Owner))); + ("tank", contained), ("cannon", component.Owner))); UpdateAppearance(component); } } - public void TryEjectAllItems(PneumaticCannonComponent component, IEntity user) + public void TryEjectAllItems(PneumaticCannonComponent component, EntityUid user) { - if (component.Owner.TryGetComponent(out var storage)) + if (EntityManager.TryGetComponent(component.Owner, out var storage)) { if (storage.StoredEntities == null) return; foreach (var entity in storage.StoredEntities.ToArray()) @@ -351,7 +346,7 @@ namespace Content.Server.PneumaticCannon private void UpdateAppearance(PneumaticCannonComponent component) { - if (component.Owner.TryGetComponent(out var appearance)) + if (EntityManager.TryGetComponent(component.Owner, out var appearance)) { appearance.SetData(PneumaticCannonVisuals.Tank, component.GasTankSlot.ContainedEntities.Count != 0); diff --git a/Content.Server/Pointing/Components/PointingArrowComponent.cs b/Content.Server/Pointing/Components/PointingArrowComponent.cs index 832a23bb3b..f914ba684c 100644 --- a/Content.Server/Pointing/Components/PointingArrowComponent.cs +++ b/Content.Server/Pointing/Components/PointingArrowComponent.cs @@ -1,6 +1,7 @@ using Content.Shared.Pointing.Components; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; using DrawDepth = Content.Shared.DrawDepth.DrawDepth; @@ -10,6 +11,8 @@ namespace Content.Server.Pointing.Components [RegisterComponent] public class PointingArrowComponent : SharedPointingArrowComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + /// /// The current amount of seconds left on this arrow. /// @@ -57,7 +60,7 @@ namespace Content.Server.Pointing.Components { base.Startup(); - if (Owner.TryGetComponent(out SpriteComponent? sprite)) + if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite)) { sprite.DrawDepth = (int) DrawDepth.Overlays; } @@ -66,7 +69,7 @@ namespace Content.Server.Pointing.Components public void Update(float frameTime) { var movement = _speed * frameTime * (_up ? 1 : -1); - Owner.Transform.LocalPosition += (0, movement); + _entMan.GetComponent(Owner).LocalPosition += (0, movement); _duration -= frameTime; _currentStep -= frameTime; @@ -75,12 +78,12 @@ namespace Content.Server.Pointing.Components { if (_rogue) { - Owner.RemoveComponent(); - Owner.AddComponent(); + _entMan.RemoveComponent(Owner); + _entMan.AddComponent(Owner); return; } - Owner.Delete(); + _entMan.DeleteEntity(Owner); return; } diff --git a/Content.Server/Pointing/Components/RoguePointingArrowComponent.cs b/Content.Server/Pointing/Components/RoguePointingArrowComponent.cs index 35c813283c..3c8b8914db 100644 --- a/Content.Server/Pointing/Components/RoguePointingArrowComponent.cs +++ b/Content.Server/Pointing/Components/RoguePointingArrowComponent.cs @@ -13,7 +13,7 @@ namespace Content.Server.Pointing.Components public class RoguePointingArrowComponent : SharedRoguePointingArrowComponent { [ViewVariables] - public IEntity? Chasing; + public EntityUid? Chasing; [ViewVariables(VVAccess.ReadWrite)] [DataField("turningDelay")] diff --git a/Content.Server/Pointing/EntitySystems/PointingSystem.cs b/Content.Server/Pointing/EntitySystems/PointingSystem.cs index c299e55fb9..adc23667bc 100644 --- a/Content.Server/Pointing/EntitySystems/PointingSystem.cs +++ b/Content.Server/Pointing/EntitySystems/PointingSystem.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; -using System.Linq; using Content.Server.Ghost.Components; using Content.Server.Players; using Content.Server.Pointing.Components; using Content.Server.Visible; -using Content.Shared.ActionBlocker; using Content.Shared.Input; using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; @@ -20,7 +18,6 @@ using Robust.Shared.Input.Binding; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; -using Robust.Shared.Maths; using Robust.Shared.Player; using Robust.Shared.Players; using Robust.Shared.Timing; @@ -57,13 +54,12 @@ namespace Content.Server.Pointing.EntitySystems } // TODO: FOV - private void SendMessage(IEntity source, IEnumerable viewers, IEntity? pointed, string selfMessage, + private void SendMessage(EntityUid source, IEnumerable viewers, EntityUid pointed, string selfMessage, string viewerMessage, string? viewerPointedAtMessage = null) { foreach (var viewer in viewers) { - var viewerEntity = viewer.AttachedEntity; - if (viewerEntity == null) + if (viewer.AttachedEntity is not {Valid: true} viewerEntity) { continue; } @@ -78,11 +74,11 @@ namespace Content.Server.Pointing.EntitySystems } } - public bool InRange(IEntity pointer, EntityCoordinates coordinates) + public bool InRange(EntityUid pointer, EntityCoordinates coordinates) { - if (pointer.HasComponent()) + if (EntityManager.HasComponent(pointer)) { - return pointer.Transform.Coordinates.InRange(EntityManager, coordinates, 15); + return EntityManager.GetComponent(pointer).Coordinates.InRange(EntityManager, coordinates, 15); } else { @@ -90,11 +86,10 @@ namespace Content.Server.Pointing.EntitySystems } } - public bool TryPoint(ICommonSession? session, EntityCoordinates coords, EntityUid uid) + public bool TryPoint(ICommonSession? session, EntityCoordinates coords, EntityUid pointed) { var mapCoords = coords.ToMap(EntityManager); - var player = (session as IPlayerSession)?.ContentData()?.Mind?.CurrentEntity; - if (player == null) + if ((session as IPlayerSession)?.ContentData()?.Mind?.CurrentEntity is not { } player) { return false; } @@ -105,7 +100,7 @@ namespace Content.Server.Pointing.EntitySystems return false; } - if (EntityManager.TryGetEntity(uid, out var entity) && entity.HasComponent()) + if (EntityManager.EntityExists(pointed)) { // this is a pointing arrow. no pointing here... return false; @@ -122,7 +117,7 @@ namespace Content.Server.Pointing.EntitySystems var arrow = EntityManager.SpawnEntity("pointingarrow", mapCoords); var layer = (int) VisibilityFlags.Normal; - if (player.TryGetComponent(out VisibilityComponent? playerVisibility)) + if (EntityManager.TryGetComponent(player, out VisibilityComponent? playerVisibility)) { var arrowVisibility = arrow.EnsureComponent(); layer = arrowVisibility.Layer = playerVisibility.Layer; @@ -131,11 +126,12 @@ namespace Content.Server.Pointing.EntitySystems // Get players that are in range and whose visibility layer matches the arrow's. bool ViewerPredicate(IPlayerSession playerSession) { - var ent = playerSession.ContentData()?.Mind?.CurrentEntity; + if (playerSession.ContentData()?.Mind?.CurrentEntity is not {Valid: true} ent || + !EntityManager.TryGetComponent(ent, out var eyeComp) || + (eyeComp.VisibilityMask & layer) == 0) + return false; - if (ent is null || (!ent.TryGetComponent(out var eyeComp) || (eyeComp.VisibilityMask & layer) == 0)) return false; - - return ent.Transform.MapPosition.InRange(player.Transform.MapPosition, PointingRange); + return EntityManager.GetComponent(ent).MapPosition.InRange(EntityManager.GetComponent(player).MapPosition, PointingRange); } var viewers = Filter.Empty() @@ -146,17 +142,17 @@ namespace Content.Server.Pointing.EntitySystems string viewerMessage; string? viewerPointedAtMessage = null; - if (EntityManager.TryGetEntity(uid, out var pointed)) + if (EntityManager.EntityExists(pointed)) { selfMessage = player == pointed ? Loc.GetString("pointing-system-point-at-self") : Loc.GetString("pointing-system-point-at-other", ("other", pointed)); viewerMessage = player == pointed - ? Loc.GetString("pointing-system-point-at-self-others", ("otherName", player.Name), ("other", player)) - : Loc.GetString("pointing-system-point-at-other-others", ("otherName", player.Name), ("other", pointed)); + ? Loc.GetString("pointing-system-point-at-self-others", ("otherName", Name: EntityManager.GetComponent(player).EntityName), ("other", player)) + : Loc.GetString("pointing-system-point-at-other-others", ("otherName", Name: EntityManager.GetComponent(player).EntityName), ("other", pointed)); - viewerPointedAtMessage = Loc.GetString("pointing-system-point-at-you-other", ("otherName", player.Name)); + viewerPointedAtMessage = Loc.GetString("pointing-system-point-at-you-other", ("otherName", Name: EntityManager.GetComponent(player).EntityName)); } else { @@ -171,10 +167,10 @@ namespace Content.Server.Pointing.EntitySystems selfMessage = Loc.GetString("pointing-system-point-at-tile", ("tileName", tileDef.DisplayName)); - viewerMessage = Loc.GetString("pointing-system-other-point-at-tile", ("otherName", player.Name), ("tileName", tileDef.DisplayName)); + viewerMessage = Loc.GetString("pointing-system-other-point-at-tile", ("otherName", Name: EntityManager.GetComponent(player).EntityName), ("tileName", tileDef.DisplayName)); } - _pointers[session!] = _gameTiming.CurTime; + _pointers[session] = _gameTiming.CurTime; SendMessage(player, viewers, pointed, selfMessage, viewerMessage, viewerPointedAtMessage); @@ -200,17 +196,17 @@ namespace Content.Server.Pointing.EntitySystems return; //Check if the object is already being pointed at - if (args.Target.HasComponent()) + if (EntityManager.HasComponent(args.Target)) return; - if (!args.User.TryGetComponent(out var actor) || - !InRange(args.User, args.Target.Transform.Coordinates)) + if (!EntityManager.TryGetComponent(args.User, out var actor) || + !InRange(args.User, EntityManager.GetComponent(args.Target).Coordinates)) return; Verb verb = new(); verb.Text = Loc.GetString("pointing-verb-get-data-text"); verb.IconTexture = "/Textures/Interface/VerbIcons/point.svg.192dpi.png"; - verb.Act = () => TryPoint(actor.PlayerSession, args.Target.Transform.Coordinates, args.Target.Uid); ; + verb.Act = () => TryPoint(actor.PlayerSession, EntityManager.GetComponent(args.Target).Coordinates, args.Target); ; args.Verbs.Add(verb); } diff --git a/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs b/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs index c8706537d9..3bfea1b949 100644 --- a/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs +++ b/Content.Server/Pointing/EntitySystems/RoguePointingSystem.cs @@ -37,7 +37,7 @@ namespace Content.Server.Pointing.EntitySystems } } - private IEntity? RandomNearbyPlayer(EntityUid uid, RoguePointingArrowComponent? component = null, TransformComponent? transform = null) + private EntityUid? RandomNearbyPlayer(EntityUid uid, RoguePointingArrowComponent? component = null, TransformComponent? transform = null) { if (!Resolve(uid, ref component, ref transform)) return null; @@ -65,10 +65,10 @@ namespace Content.Server.Pointing.EntitySystems { foreach (var (component, transform) in EntityManager.EntityQuery()) { - var uid = component.Owner.Uid; + var uid = component.Owner; component.Chasing ??= RandomNearbyPlayer(uid, component, transform); - if (component.Chasing == null) + if (component.Chasing is not {Valid: true} chasing) { EntityManager.QueueDeleteEntity(uid); return; @@ -78,7 +78,7 @@ namespace Content.Server.Pointing.EntitySystems if (component.TurningDelay > 0) { - var difference = component.Chasing.Transform.WorldPosition - transform.WorldPosition; + var difference = EntityManager.GetComponent(chasing).WorldPosition - transform.WorldPosition; var angle = difference.ToAngle(); var adjusted = angle.Degrees + 90; var newAngle = Angle.FromDegrees(adjusted); @@ -93,7 +93,7 @@ namespace Content.Server.Pointing.EntitySystems UpdateAppearance(uid, component, transform); - var toChased = component.Chasing.Transform.WorldPosition - transform.WorldPosition; + var toChased = EntityManager.GetComponent(chasing).WorldPosition - transform.WorldPosition; transform.WorldPosition += toChased * frameTime * component.ChasingSpeed; diff --git a/Content.Server/Popups/PopupExtensions.cs b/Content.Server/Popups/PopupExtensions.cs index 12aa0afe96..a10414556f 100644 --- a/Content.Server/Popups/PopupExtensions.cs +++ b/Content.Server/Popups/PopupExtensions.cs @@ -1,10 +1,6 @@ -using System.Collections.Generic; -using System.Linq; using Content.Shared.Popups; using Robust.Server.Player; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; -using Robust.Shared.Map; using Robust.Shared.Player; namespace Content.Server.Popups @@ -17,7 +13,7 @@ namespace Content.Server.Popups /// /// The entity on which to popup the message. /// The message to show. - public static void PopupMessageOtherClients(this IEntity source, string message) + public static void PopupMessageOtherClients(this EntityUid source, string message) { var viewers = Filter.Empty() .AddPlayersByPvs(source) @@ -25,14 +21,12 @@ namespace Content.Server.Popups foreach (var viewer in viewers) { - var viewerEntity = viewer.AttachedEntity; - - if (viewerEntity == null || source == viewerEntity || viewer.AttachedEntity == null) + if (viewer.AttachedEntity is not {Valid: true} viewerEntity || source == viewerEntity || viewer.AttachedEntity == null) { continue; } - source.PopupMessage(viewer.AttachedEntity, message); + source.PopupMessage(viewerEntity, message); } } @@ -49,7 +43,7 @@ namespace Content.Server.Popups /// /// The range in which to search for players, defaulting to one screen. /// - public static void PopupMessageEveryone(this IEntity source, string message, IPlayerManager? playerManager = null, int range = 15) + public static void PopupMessageEveryone(this EntityUid source, string message, IPlayerManager? playerManager = null, int range = 15) { source.PopupMessage(message); source.PopupMessageOtherClients(message); diff --git a/Content.Server/Popups/PopupMsgCommand.cs b/Content.Server/Popups/PopupMsgCommand.cs index 85392bc712..499522f4e5 100644 --- a/Content.Server/Popups/PopupMsgCommand.cs +++ b/Content.Server/Popups/PopupMsgCommand.cs @@ -3,7 +3,6 @@ using Content.Shared.Administration; using Content.Shared.Popups; using Robust.Shared.Console; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; namespace Content.Server.Popups { @@ -16,13 +15,11 @@ namespace Content.Server.Popups public void Execute(IConsoleShell shell, string argStr, string[] args) { - var entityMgr = IoCManager.Resolve(); - var source = EntityUid.Parse(args[0]); var viewer = EntityUid.Parse(args[1]); var msg = args[2]; - entityMgr.GetEntity(source).PopupMessage(entityMgr.GetEntity(viewer), msg); + source.PopupMessage(viewer, msg); } } } diff --git a/Content.Server/Power/Components/ApcComponent.cs b/Content.Server/Power/Components/ApcComponent.cs index 91281a4b98..dd8b3bf215 100644 --- a/Content.Server/Power/Components/ApcComponent.cs +++ b/Content.Server/Power/Components/ApcComponent.cs @@ -24,6 +24,7 @@ namespace Content.Server.Power.Components [ComponentReference(typeof(IActivate))] public class ApcComponent : BaseApcNetComponent, IActivate { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; public override string Name => "Apc"; @@ -56,7 +57,7 @@ namespace Content.Server.Power.Components [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(ApcUiKey.Key); - public BatteryComponent? Battery => Owner.TryGetComponent(out BatteryComponent? batteryComponent) ? batteryComponent : null; + public BatteryComponent? Battery => _entMan.TryGetComponent(Owner, out BatteryComponent? batteryComponent) ? batteryComponent : null; [ComponentDependency] private AccessReader? _accessReader = null; @@ -87,25 +88,21 @@ namespace Content.Server.Power.Components private void UserInterfaceOnReceiveMessage(ServerBoundUserInterfaceMessage serverMsg) { - if (serverMsg.Message is ApcToggleMainBreakerMessage) + if (serverMsg.Message is not ApcToggleMainBreakerMessage || serverMsg.Session.AttachedEntity is not {} attached) + return; + + var accessSystem = EntitySystem.Get(); + if (_accessReader == null || accessSystem.IsAllowed(_accessReader, attached)) { - var user = serverMsg.Session.AttachedEntity; - if (user == null) return; - - var accessSystem = EntitySystem.Get(); - if (_accessReader == null || accessSystem.IsAllowed(_accessReader, user.Uid)) - { - MainBreakerEnabled = !MainBreakerEnabled; - Owner.GetComponent().CanDischarge = MainBreakerEnabled; - - _uiDirty = true; - SoundSystem.Play(Filter.Pvs(Owner), _onReceiveMessageSound.GetSound(), Owner, AudioParams.Default.WithVolume(-2f)); - } - else - { - user.PopupMessageCursor(Loc.GetString("apc-component-insufficient-access")); - } + MainBreakerEnabled = !MainBreakerEnabled; + _entMan.GetComponent(Owner).CanDischarge = MainBreakerEnabled; + _uiDirty = true; + SoundSystem.Play(Filter.Pvs(Owner), _onReceiveMessageSound.GetSound(), Owner, AudioParams.Default.WithVolume(-2f)); + } + else + { + attached.PopupMessageCursor(Loc.GetString("apc-component-insufficient-access")); } } @@ -117,12 +114,12 @@ namespace Content.Server.Power.Components _lastChargeState = newState; _lastChargeStateChange = _gameTiming.CurTime; - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(ApcVisuals.ChargeState, newState); } - if (Owner.TryGetComponent(out SharedPointLightComponent? light)) + if (_entMan.TryGetComponent(Owner, out SharedPointLightComponent? light)) { light.Color = newState switch { @@ -135,7 +132,7 @@ namespace Content.Server.Power.Components } } - Owner.TryGetComponent(out BatteryComponent? battery); + _entMan.TryGetComponent(Owner, out BatteryComponent? battery); var newCharge = battery?.CurrentCharge; if (newCharge != null && newCharge != _lastCharge && _lastChargeChange + TimeSpan.FromSeconds(VisualsChangeDelay) < _gameTiming.CurTime) @@ -162,7 +159,7 @@ namespace Content.Server.Power.Components private ApcChargeState CalcChargeState() { - if (!Owner.TryGetComponent(out BatteryComponent? battery)) + if (!_entMan.TryGetComponent(Owner, out BatteryComponent? battery)) { return ApcChargeState.Lack; } @@ -174,7 +171,7 @@ namespace Content.Server.Power.Components return ApcChargeState.Full; } - var netBattery = Owner.GetComponent(); + var netBattery = _entMan.GetComponent(Owner); var delta = netBattery.CurrentSupply - netBattery.CurrentReceiving; return delta < 0 ? ApcChargeState.Charging : ApcChargeState.Lack; @@ -186,7 +183,7 @@ namespace Content.Server.Power.Components if (bat == null) return ApcExternalPowerState.None; - var netBat = Owner.GetComponent(); + var netBat = _entMan.GetComponent(Owner); if (netBat.CurrentReceiving == 0 && netBat.LoadingNetworkDemand != 0) { return ApcExternalPowerState.None; @@ -203,7 +200,7 @@ namespace Content.Server.Power.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { return; } diff --git a/Content.Server/Power/Components/ApcPowerReceiverComponent.cs b/Content.Server/Power/Components/ApcPowerReceiverComponent.cs index 6e36108e5f..4a0ae9a80a 100644 --- a/Content.Server/Power/Components/ApcPowerReceiverComponent.cs +++ b/Content.Server/Power/Components/ApcPowerReceiverComponent.cs @@ -24,6 +24,8 @@ namespace Content.Server.Power.Components public class ApcPowerReceiverComponent : Component, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "ApcPowerReceiver"; [ViewVariables] @@ -85,9 +87,9 @@ namespace Content.Server.Power.Components #pragma warning disable 618 SendMessage(new PowerChangedMessage(Powered)); #pragma warning restore 618 - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new PowerChangedEvent(Powered, NetworkLoad.ReceivingPower)); + _entMan.EventBus.RaiseLocalEvent(Owner, new PowerChangedEvent(Powered, NetworkLoad.ReceivingPower)); - if (Owner.TryGetComponent(out var appearance)) + if (_entMan.TryGetComponent(Owner, out var appearance)) { appearance.SetData(PowerDeviceVisuals.Powered, Powered); } diff --git a/Content.Server/Power/Components/BaseCharger.cs b/Content.Server/Power/Components/BaseCharger.cs index 55f14c121e..e874bf6b07 100644 --- a/Content.Server/Power/Components/BaseCharger.cs +++ b/Content.Server/Power/Components/BaseCharger.cs @@ -8,6 +8,7 @@ using Content.Shared.Popups; using Content.Shared.Power; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -18,6 +19,8 @@ namespace Content.Server.Power.Components [ComponentReference(typeof(IInteractUsing))] public abstract class BaseCharger : Component, IActivate, IInteractUsing { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables] private BatteryComponent? _heldBattery; @@ -87,22 +90,21 @@ namespace Content.Server.Power.Components /// This will remove the item directly into the user's hand / floor /// /// - public void RemoveItem(IEntity user) + public void RemoveItem(EntityUid user) { - var heldItem = Container.ContainedEntity; - if (heldItem == null) + if (Container.ContainedEntity is not {Valid: true} heldItem) { return; } Container.Remove(heldItem); _heldBattery = null; - if (user.TryGetComponent(out HandsComponent? handsComponent)) + if (_entMan.TryGetComponent(user, out HandsComponent? handsComponent)) { - handsComponent.PutInHandOrDrop(heldItem.GetComponent()); + handsComponent.PutInHandOrDrop(_entMan.GetComponent(heldItem)); } - if (heldItem.TryGetComponent(out ServerBatteryBarrelComponent? batteryBarrelComponent)) + if (_entMan.TryGetComponent(heldItem, out ServerBatteryBarrelComponent? batteryBarrelComponent)) { batteryBarrelComponent.UpdateAppearance(); } @@ -117,7 +119,7 @@ namespace Content.Server.Power.Components private CellChargerStatus GetStatus() { - if (Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) && + if (_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) && !receiver.Powered) { return CellChargerStatus.Off; @@ -133,7 +135,7 @@ namespace Content.Server.Power.Components return CellChargerStatus.Charging; } - public bool TryInsertItem(IEntity entity) + public bool TryInsertItem(EntityUid entity) { if (!IsEntityCompatible(entity) || HasCell) { @@ -151,22 +153,22 @@ namespace Content.Server.Power.Components /// /// If the supplied entity should fit into the charger. /// - public abstract bool IsEntityCompatible(IEntity entity); + public abstract bool IsEntityCompatible(EntityUid entity); - protected abstract BatteryComponent? GetBatteryFrom(IEntity entity); + protected abstract BatteryComponent? GetBatteryFrom(EntityUid entity); private void UpdateStatus() { // Not called UpdateAppearance just because it messes with the load var status = GetStatus(); if (_status == status || - !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver)) + !_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver)) { return; } _status = status; - Owner.TryGetComponent(out AppearanceComponent? appearance); + _entMan.TryGetComponent(Owner, out AppearanceComponent? appearance); switch (_status) { @@ -205,7 +207,7 @@ namespace Content.Server.Power.Components private void TransferPower(float frameTime) { - if (Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) && + if (_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) && !receiver.Powered) { return; diff --git a/Content.Server/Power/Components/BaseNetConnectorComponent.cs b/Content.Server/Power/Components/BaseNetConnectorComponent.cs index beea86d6d5..cbf232abc2 100644 --- a/Content.Server/Power/Components/BaseNetConnectorComponent.cs +++ b/Content.Server/Power/Components/BaseNetConnectorComponent.cs @@ -3,6 +3,7 @@ using System.Linq; using Content.Server.NodeContainer; using Content.Server.NodeContainer.NodeGroups; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -17,6 +18,8 @@ namespace Content.Server.Power.Components public abstract class BaseNetConnectorComponent : Component, IBaseNetConnectorComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + [ViewVariables(VVAccess.ReadWrite)] public Voltage Voltage { get => _voltage; set => SetVoltage(value); } [DataField("voltage")] @@ -67,7 +70,7 @@ namespace Content.Server.Power.Components private bool TryFindNet([NotNullWhen(true)] out TNetType? foundNet) { - if (Owner.TryGetComponent(out var container)) + if (_entMan.TryGetComponent(Owner, out var container)) { var compatibleNet = container.Nodes.Values .Where(node => (NodeId == null || NodeId == node.Name) && node.NodeGroupID == (NodeGroupID) Voltage) diff --git a/Content.Server/Power/Components/CableComponent.cs b/Content.Server/Power/Components/CableComponent.cs index e74fbcc8b2..3260c81a1a 100644 --- a/Content.Server/Power/Components/CableComponent.cs +++ b/Content.Server/Power/Components/CableComponent.cs @@ -2,11 +2,10 @@ using System.Threading.Tasks; using Content.Server.Electrocution; using Content.Server.Stack; using Content.Server.Tools; -using Content.Server.Tools.Components; using Content.Shared.Interaction; using Content.Shared.Tools; -using Content.Shared.Tools.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; using Robust.Shared.ViewVariables; @@ -19,6 +18,8 @@ namespace Content.Server.Power.Components [RegisterComponent] public class CableComponent : Component, IInteractUsing { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Cable"; [ViewVariables] @@ -42,16 +43,16 @@ namespace Content.Server.Power.Components if (_cableDroppedOnCutPrototype == null) return false; - if (!await EntitySystem.Get().UseTool(eventArgs.Using.Uid, eventArgs.User.Uid, Owner.Uid, 0f, 0.25f, _cuttingQuality)) return false; + if (!await EntitySystem.Get().UseTool(eventArgs.Using, eventArgs.User, Owner, 0f, 0.25f, _cuttingQuality)) return false; - if (EntitySystem.Get().TryDoElectrifiedAct(Owner.Uid, eventArgs.User.Uid)) return false; + if (EntitySystem.Get().TryDoElectrifiedAct(Owner, eventArgs.User)) return false; - Owner.Delete(); - var droppedEnt = Owner.EntityManager.SpawnEntity(_cableDroppedOnCutPrototype, eventArgs.ClickLocation); + _entMan.DeleteEntity(Owner); + var droppedEnt = _entMan.SpawnEntity(_cableDroppedOnCutPrototype, eventArgs.ClickLocation); // TODO: Literally just use a prototype that has a single thing in the stack, it's not that complicated... - if (droppedEnt.TryGetComponent(out var stack)) - EntitySystem.Get().SetCount(droppedEnt.Uid, 1, stack); + if (_entMan.TryGetComponent(droppedEnt, out var stack)) + EntitySystem.Get().SetCount(droppedEnt, 1, stack); return true; } diff --git a/Content.Server/Power/Components/CablePlacerComponent.cs b/Content.Server/Power/Components/CablePlacerComponent.cs index 62bc4ec85a..d054654692 100644 --- a/Content.Server/Power/Components/CablePlacerComponent.cs +++ b/Content.Server/Power/Components/CablePlacerComponent.cs @@ -15,6 +15,7 @@ namespace Content.Server.Power.Components [RegisterComponent] internal class CablePlacerComponent : Component, IAfterInteract { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IMapManager _mapManager = default!; /// @@ -31,7 +32,7 @@ namespace Content.Server.Power.Components /// async Task IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs) { - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if (!EntitySystem.Get().CanInteract(eventArgs.User)) return false; if (_cablePrototypeID == null) @@ -40,7 +41,7 @@ namespace Content.Server.Power.Components if (!eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true)) return false; - if(!_mapManager.TryGetGrid(eventArgs.ClickLocation.GetGridId(Owner.EntityManager), out var grid)) + if(!_mapManager.TryGetGrid(eventArgs.ClickLocation.GetGridId(_entMan), out var grid)) return false; var snapPos = grid.TileIndicesFor(eventArgs.ClickLocation); @@ -51,17 +52,17 @@ namespace Content.Server.Power.Components foreach (var anchored in grid.GetAnchoredEntities(snapPos)) { - if (Owner.EntityManager.TryGetComponent(anchored, out var wire) && wire.CableType == _blockingCableType) + if (_entMan.TryGetComponent(anchored, out var wire) && wire.CableType == _blockingCableType) { return false; } } - if (Owner.TryGetComponent(out var stack) - && !EntitySystem.Get().Use(Owner.Uid, 1, stack)) + if (_entMan.TryGetComponent(Owner, out var stack) + && !EntitySystem.Get().Use(Owner, 1, stack)) return false; - Owner.EntityManager.SpawnEntity(_cablePrototypeID, grid.GridTileToLocal(snapPos)); + _entMan.SpawnEntity(_cablePrototypeID, grid.GridTileToLocal(snapPos)); return true; } } diff --git a/Content.Server/Power/EntitySystems/BaseChargerSystem.cs b/Content.Server/Power/EntitySystems/BaseChargerSystem.cs index 649c5ca71c..a7aafce0e4 100644 --- a/Content.Server/Power/EntitySystems/BaseChargerSystem.cs +++ b/Content.Server/Power/EntitySystems/BaseChargerSystem.cs @@ -39,11 +39,11 @@ namespace Content.Server.Power.EntitySystems !args.CanAccess || !args.CanInteract || !component.HasCell || - !_actionBlockerSystem.CanPickup(args.User.Uid)) + !_actionBlockerSystem.CanPickup(args.User)) return; Verb verb = new(); - verb.Text = component.Container.ContainedEntity!.Name; + verb.Text = EntityManager.GetComponent(component.Container.ContainedEntity!.Value).EntityName; verb.Category = VerbCategory.Eject; verb.Act = () => component.RemoveItem(args.User); args.Verbs.Add(verb); @@ -51,18 +51,18 @@ namespace Content.Server.Power.EntitySystems private void AddInsertVerb(EntityUid uid, BaseCharger component, GetInteractionVerbsEvent args) { - if (args.Using == null || + if (args.Using is not {Valid: true} @using || !args.CanAccess || !args.CanInteract || component.HasCell || - !component.IsEntityCompatible(args.Using) || - !_actionBlockerSystem.CanDrop(args.User.Uid)) + !component.IsEntityCompatible(@using) || + !_actionBlockerSystem.CanDrop(args.User)) return; Verb verb = new(); - verb.Text = args.Using.Name; + verb.Text = EntityManager.GetComponent(@using).EntityName; verb.Category = VerbCategory.Insert; - verb.Act = () => component.TryInsertItem(args.Using); + verb.Act = () => component.TryInsertItem(@using); args.Verbs.Add(verb); } } diff --git a/Content.Server/Power/EntitySystems/CableMultitoolSystem.cs b/Content.Server/Power/EntitySystems/CableMultitoolSystem.cs index c14982af77..bbcc87d782 100644 --- a/Content.Server/Power/EntitySystems/CableMultitoolSystem.cs +++ b/Content.Server/Power/EntitySystems/CableMultitoolSystem.cs @@ -43,12 +43,12 @@ namespace Content.Server.Power.EntitySystems if (args.IsInDetailsRange) { // Determine if they are holding a multitool. - if (args.Examiner.TryGetComponent(out var hands) && hands.TryGetActiveHand(out var hand)) + if (EntityManager.TryGetComponent(args.Examiner, out var hands) && hands.TryGetActiveHand(out var hand)) { var held = hand.HeldEntity; // Pulsing is hardcoded here because I don't think it needs to be more complex than that right now. // Update if I'm wrong. - if ((held != null) && _toolSystem.HasQuality(held.Uid, "Pulsing")) + if ((held != null) && _toolSystem.HasQuality(held, "Pulsing")) { args.PushMarkup(GenerateCableMarkup(uid)); // args.PushFancyUpdatingPowerGraphs(uid); diff --git a/Content.Server/Power/EntitySystems/CableVisSystem.cs b/Content.Server/Power/EntitySystems/CableVisSystem.cs index 65bfdeeebc..5ed4866f76 100644 --- a/Content.Server/Power/EntitySystems/CableVisSystem.cs +++ b/Content.Server/Power/EntitySystems/CableVisSystem.cs @@ -63,7 +63,7 @@ namespace Content.Server.Power.EntitySystems if (reachable is not CableNode) continue; - var otherTransform = reachable.Owner.Transform; + var otherTransform = EntityManager.GetComponent(reachable.Owner); if (otherTransform.GridID != grid.Index) continue; diff --git a/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs b/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs index c1ec5db65e..567bea92fd 100644 --- a/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs +++ b/Content.Server/Power/EntitySystems/ExtensionCableSystem.cs @@ -42,7 +42,7 @@ namespace Content.Server.Power.EntitySystems receiver.Provider?.LinkedReceivers.Remove(receiver); receiver.Provider = provider; provider.LinkedReceivers.Add(receiver); - RaiseLocalEvent(receiver.Owner.Uid, new ProviderConnectedEvent(provider), broadcast: false); + RaiseLocalEvent(receiver.Owner, new ProviderConnectedEvent(provider), broadcast: false); RaiseLocalEvent(uid, new ReceiverConnectedEvent(receiver), broadcast: false); } } @@ -60,34 +60,32 @@ namespace Content.Server.Power.EntitySystems foreach (var receiver in receivers) { receiver.Provider = null; - RaiseLocalEvent(receiver.Owner.Uid, new ProviderDisconnectedEvent(provider), broadcast: false); - RaiseLocalEvent(provider.Owner.Uid, new ReceiverDisconnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(receiver.Owner, new ProviderDisconnectedEvent(provider), broadcast: false); + RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent(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.GetComponent(receiver.OwnerUid).EntityLifeStage > + if (EntityManager.GetComponent((receiver).Owner).EntityLifeStage > EntityLifeStage.MapInitialized) continue; TryFindAndSetProvider(receiver); } } - private IEnumerable FindAvailableReceivers(EntityUid uid, float range) + private IEnumerable FindAvailableReceivers(EntityUid owner, float range) { - var owner = EntityManager.GetEntity(uid); - var nearbyEntities = IoCManager.Resolve() .GetEntitiesInRange(owner, range); foreach (var entity in nearbyEntities) { - if (EntityManager.TryGetComponent(entity.Uid, out var receiver) && + if (EntityManager.TryGetComponent(entity, out var receiver) && receiver.Connectable && receiver.Provider == null && - entity.Transform.Coordinates.TryDistance(owner.EntityManager, owner.Transform.Coordinates, out var distance) && + EntityManager.GetComponent(entity).Coordinates.TryDistance(EntityManager, EntityManager.GetComponent(owner).Coordinates, out var distance) && distance < Math.Min(range, receiver.ReceptionRange)) { yield return receiver; @@ -110,7 +108,7 @@ namespace Content.Server.Power.EntitySystems if (provider != null) { - RaiseLocalEvent(provider.Owner.Uid, new ReceiverDisconnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false); provider.LinkedReceivers.Remove(receiver); } @@ -120,7 +118,7 @@ namespace Content.Server.Power.EntitySystems private void OnReceiverStarted(EntityUid uid, ExtensionCableReceiverComponent receiver, ComponentStartup args) { - if (receiver.Owner.TryGetComponent(out PhysicsComponent? physicsComponent)) + if (EntityManager.TryGetComponent(receiver.Owner, out PhysicsComponent? physicsComponent)) { receiver.Connectable = physicsComponent.BodyType == BodyType.Static; } @@ -137,7 +135,7 @@ namespace Content.Server.Power.EntitySystems receiver.Provider.LinkedReceivers.Remove(receiver); RaiseLocalEvent(uid, new ProviderDisconnectedEvent(receiver.Provider), broadcast: false); - RaiseLocalEvent(receiver.Provider.Owner.Uid, new ReceiverDisconnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(receiver.Provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false); } private void AnchorStateChanged(EntityUid uid, ExtensionCableReceiverComponent receiver, ref AnchorStateChangedEvent args) @@ -156,7 +154,7 @@ namespace Content.Server.Power.EntitySystems RaiseLocalEvent(uid, new ProviderDisconnectedEvent(receiver.Provider), broadcast: false); if (receiver.Provider != null) { - RaiseLocalEvent(receiver.Provider.Owner.Uid, new ReceiverDisconnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(receiver.Provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false); receiver.Provider.LinkedReceivers.Remove(receiver); } @@ -170,22 +168,22 @@ namespace Content.Server.Power.EntitySystems receiver.Provider = provider; provider.LinkedReceivers.Add(receiver); - RaiseLocalEvent(receiver.Owner.Uid, new ProviderConnectedEvent(provider), broadcast: false); - RaiseLocalEvent(provider.Owner.Uid, new ReceiverConnectedEvent(receiver), broadcast: false); + RaiseLocalEvent(receiver.Owner, new ProviderConnectedEvent(provider), broadcast: false); + RaiseLocalEvent(provider.Owner, new ReceiverConnectedEvent(receiver), broadcast: false); } - private static bool TryFindAvailableProvider(IEntity owner, float range, [NotNullWhen(true)] out ExtensionCableProviderComponent? foundProvider) + private bool TryFindAvailableProvider(EntityUid owner, float range, [NotNullWhen(true)] out ExtensionCableProviderComponent? foundProvider) { var nearbyEntities = IoCManager.Resolve() .GetEntitiesInRange(owner, range); foreach (var entity in nearbyEntities) { - if (!entity.TryGetComponent(out var provider)) continue; + if (!EntityManager.TryGetComponent(entity, out var provider)) continue; if (!provider.Connectable) continue; - if (!entity.Transform.Coordinates.TryDistance(owner.EntityManager, owner.Transform.Coordinates, out var distance)) continue; + if (!EntityManager.GetComponent(entity).Coordinates.TryDistance(EntityManager, EntityManager.GetComponent(owner).Coordinates, out var distance)) continue; if (!(distance < Math.Min(range, provider.TransferRange))) continue; diff --git a/Content.Server/Power/EntitySystems/PowerNetSystem.cs b/Content.Server/Power/EntitySystems/PowerNetSystem.cs index 867a915593..a9db544d01 100644 --- a/Content.Server/Power/EntitySystems/PowerNetSystem.cs +++ b/Content.Server/Power/EntitySystems/PowerNetSystem.cs @@ -6,6 +6,7 @@ using Content.Server.Power.NodeGroups; using Content.Server.Power.Pow3r; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Server.Power.EntitySystems @@ -269,7 +270,7 @@ namespace Content.Server.Power.EntitySystems { lastRecv = newRecv; var msg = new PowerConsumerReceivedChanged(newRecv, consumer.DrawRate); - RaiseLocalEvent(consumer.Owner.Uid, msg); + RaiseLocalEvent(consumer.Owner, msg); } } @@ -284,11 +285,11 @@ namespace Content.Server.Power.EntitySystems if (lastPowerSupply == 0f && currentSupply != 0f) { - RaiseLocalEvent(powerNetBattery.Owner.Uid, new PowerNetBatterySupplyEvent {Supply = true}); + RaiseLocalEvent(powerNetBattery.Owner, new PowerNetBatterySupplyEvent {Supply = true}); } else if (lastPowerSupply > 0f && currentSupply == 0f) { - RaiseLocalEvent(powerNetBattery.Owner.Uid, new PowerNetBatterySupplyEvent {Supply = false}); + RaiseLocalEvent(powerNetBattery.Owner, new PowerNetBatterySupplyEvent {Supply = false}); } } @@ -316,7 +317,7 @@ namespace Content.Server.Power.EntitySystems _powerState.Networks.Allocate(out network.Id) = network; } - private static void DoReconnectApcNet(ApcNet net) + private void DoReconnectApcNet(ApcNet net) { var netNode = net.NetworkNode; @@ -342,13 +343,13 @@ namespace Content.Server.Power.EntitySystems foreach (var apc in net.Apcs) { - var netBattery = apc.Owner.GetComponent(); + var netBattery = EntityManager.GetComponent(apc.Owner); netNode.BatteriesDischarging.Add(netBattery.NetworkBattery.Id); netBattery.NetworkBattery.LinkedNetworkDischarging = netNode.Id; } } - private static void DoReconnectPowerNet(PowerNet net) + private void DoReconnectPowerNet(PowerNet net) { var netNode = net.NetworkNode; @@ -371,14 +372,14 @@ namespace Content.Server.Power.EntitySystems foreach (var charger in net.Chargers) { - var battery = charger.Owner.GetComponent(); + var battery = EntityManager.GetComponent(charger.Owner); netNode.BatteriesCharging.Add(battery.NetworkBattery.Id); battery.NetworkBattery.LinkedNetworkCharging = netNode.Id; } foreach (var discharger in net.Dischargers) { - var battery = discharger.Owner.GetComponent(); + var battery = EntityManager.GetComponent(discharger.Owner); netNode.BatteriesDischarging.Add(battery.NetworkBattery.Id); battery.NetworkBattery.LinkedNetworkDischarging = netNode.Id; } diff --git a/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs b/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs index 8a77441cf0..d2004f084e 100644 --- a/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs +++ b/Content.Server/Power/EntitySystems/PowerReceiverSystem.cs @@ -30,7 +30,7 @@ namespace Content.Server.Power.EntitySystems private void OnProviderConnected(EntityUid uid, ApcPowerReceiverComponent receiver, ExtensionCableSystem.ProviderConnectedEvent args) { - var providerUid = args.Provider.Owner.Uid; + var providerUid = args.Provider.Owner; if (!EntityManager.TryGetComponent(providerUid, out var provider)) return; @@ -48,7 +48,7 @@ namespace Content.Server.Power.EntitySystems private void OnReceiverConnected(EntityUid uid, ApcPowerProviderComponent provider, ExtensionCableSystem.ReceiverConnectedEvent args) { - if (EntityManager.TryGetComponent(args.Receiver.Owner.Uid, out ApcPowerReceiverComponent receiver)) + if (EntityManager.TryGetComponent(args.Receiver.Owner, out ApcPowerReceiverComponent receiver)) { provider.AddReceiver(receiver); } @@ -56,7 +56,7 @@ namespace Content.Server.Power.EntitySystems private void OnReceiverDisconnected(EntityUid uid, ApcPowerProviderComponent provider, ExtensionCableSystem.ReceiverDisconnectedEvent args) { - if (EntityManager.TryGetComponent(args.Receiver.Owner.Uid, out ApcPowerReceiverComponent receiver)) + if (EntityManager.TryGetComponent(args.Receiver.Owner, out ApcPowerReceiverComponent receiver)) { provider.RemoveReceiver(receiver); } diff --git a/Content.Server/Power/NodeGroups/ApcNet.cs b/Content.Server/Power/NodeGroups/ApcNet.cs index 3043e4dd03..2dc7bd53bc 100644 --- a/Content.Server/Power/NodeGroups/ApcNet.cs +++ b/Content.Server/Power/NodeGroups/ApcNet.cs @@ -7,6 +7,7 @@ using Content.Server.Power.EntitySystems; using Content.Server.Power.Pow3r; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.ViewVariables; @@ -66,7 +67,7 @@ namespace Content.Server.Power.NodeGroups public void AddApc(ApcComponent apc) { - if (apc.Owner.TryGetComponent(out PowerNetworkBatteryComponent? netBattery)) + if (IoCManager.Resolve().TryGetComponent(apc.Owner, out PowerNetworkBatteryComponent? netBattery)) netBattery.NetworkBattery.LinkedNetworkDischarging = default; QueueNetworkReconnect(); @@ -75,7 +76,7 @@ namespace Content.Server.Power.NodeGroups public void RemoveApc(ApcComponent apc) { - if (apc.Owner.TryGetComponent(out PowerNetworkBatteryComponent? netBattery)) + if (IoCManager.Resolve().TryGetComponent(apc.Owner, out PowerNetworkBatteryComponent? netBattery)) netBattery.NetworkBattery.LinkedNetworkDischarging = default; QueueNetworkReconnect(); diff --git a/Content.Server/Power/NodeGroups/BaseNetConnectorNodeGroup.cs b/Content.Server/Power/NodeGroups/BaseNetConnectorNodeGroup.cs index 9bdee30633..46c7540ec3 100644 --- a/Content.Server/Power/NodeGroups/BaseNetConnectorNodeGroup.cs +++ b/Content.Server/Power/NodeGroups/BaseNetConnectorNodeGroup.cs @@ -3,6 +3,8 @@ using System.Linq; using Content.Server.NodeContainer.NodeGroups; using Content.Server.NodeContainer.Nodes; using Content.Server.Power.Components; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Power.NodeGroups { @@ -14,8 +16,7 @@ namespace Content.Server.Power.NodeGroups foreach (var node in groupNodes) { - var newNetConnectorComponents = node.Owner - .GetAllComponents>() + var newNetConnectorComponents = IoCManager.Resolve().GetComponents>(node.Owner) .Where(powerComp => (powerComp.NodeId == null || powerComp.NodeId == node.Name) && (NodeGroupID) powerComp.Voltage == node.NodeGroupID) .ToList(); diff --git a/Content.Server/Power/NodeGroups/PowerNet.cs b/Content.Server/Power/NodeGroups/PowerNet.cs index c3fee34dfd..b49d251186 100644 --- a/Content.Server/Power/NodeGroups/PowerNet.cs +++ b/Content.Server/Power/NodeGroups/PowerNet.cs @@ -7,6 +7,7 @@ using Content.Server.Power.EntitySystems; using Content.Server.Power.Pow3r; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.ViewVariables; @@ -90,7 +91,7 @@ namespace Content.Server.Power.NodeGroups public void AddDischarger(BatteryDischargerComponent discharger) { - var battery = discharger.Owner.GetComponent(); + var battery = IoCManager.Resolve().GetComponent(discharger.Owner); battery.NetworkBattery.LinkedNetworkCharging = default; Dischargers.Add(discharger); _powerNetSystem.QueueReconnectPowerNet(this); @@ -99,7 +100,7 @@ namespace Content.Server.Power.NodeGroups public void RemoveDischarger(BatteryDischargerComponent discharger) { // Can be missing if the entity is being deleted, not a big deal. - if (discharger.Owner.TryGetComponent(out PowerNetworkBatteryComponent? battery)) + if (IoCManager.Resolve().TryGetComponent(discharger.Owner, out PowerNetworkBatteryComponent? battery)) battery.NetworkBattery.LinkedNetworkCharging = default; Dischargers.Remove(discharger); @@ -108,7 +109,7 @@ namespace Content.Server.Power.NodeGroups public void AddCharger(BatteryChargerComponent charger) { - var battery = charger.Owner.GetComponent(); + var battery = IoCManager.Resolve().GetComponent(charger.Owner); battery.NetworkBattery.LinkedNetworkCharging = default; Chargers.Add(charger); _powerNetSystem.QueueReconnectPowerNet(this); @@ -117,7 +118,7 @@ namespace Content.Server.Power.NodeGroups public void RemoveCharger(BatteryChargerComponent charger) { // Can be missing if the entity is being deleted, not a big deal. - if (charger.Owner.TryGetComponent(out PowerNetworkBatteryComponent? battery)) + if (IoCManager.Resolve().TryGetComponent(charger.Owner, out PowerNetworkBatteryComponent? battery)) battery.NetworkBattery.LinkedNetworkCharging = default; Chargers.Remove(charger); diff --git a/Content.Server/Power/Nodes/CableDeviceNode.cs b/Content.Server/Power/Nodes/CableDeviceNode.cs index 96ccdc8d1a..d8c4c217ef 100644 --- a/Content.Server/Power/Nodes/CableDeviceNode.cs +++ b/Content.Server/Power/Nodes/CableDeviceNode.cs @@ -18,10 +18,10 @@ namespace Content.Server.Power.Nodes var entMan = IoCManager.Resolve(); // If we're in an invalid grid, such as grid 0, we cannot connect to anything. - if(!IoCManager.Resolve().TryGetGrid(Owner.Transform.GridID, out var grid)) + if(!IoCManager.Resolve().TryGetGrid(IoCManager.Resolve().GetComponent(Owner).GridID, out var grid)) yield break; - var gridIndex = grid.TileIndicesFor(Owner.Transform.Coordinates); + var gridIndex = grid.TileIndicesFor(IoCManager.Resolve().GetComponent(Owner).Coordinates); foreach (var node in NodeHelpers.GetNodesInTile(entMan, grid, gridIndex)) { diff --git a/Content.Server/Power/Nodes/CableNode.cs b/Content.Server/Power/Nodes/CableNode.cs index bfb0c44629..9d1143b2a9 100644 --- a/Content.Server/Power/Nodes/CableNode.cs +++ b/Content.Server/Power/Nodes/CableNode.cs @@ -18,8 +18,8 @@ namespace Content.Server.Power.Nodes yield break; var entMan = IoCManager.Resolve(); - var grid = IoCManager.Resolve().GetGrid(Owner.Transform.GridID); - var gridIndex = grid.TileIndicesFor(Owner.Transform.Coordinates); + var grid = IoCManager.Resolve().GetGrid(IoCManager.Resolve().GetComponent(Owner).GridID); + var gridIndex = grid.TileIndicesFor(IoCManager.Resolve().GetComponent(Owner).Coordinates); // While we go over adjacent nodes, we build a list of blocked directions due to // incoming or outgoing wire terminals. @@ -44,11 +44,11 @@ namespace Content.Server.Power.Nodes if (dir == Direction.Invalid) { // On own tile, block direction it faces - terminalDirs |= 1 << (int) node.Owner.Transform.LocalRotation.GetCardinalDir(); + terminalDirs |= 1 << (int) IoCManager.Resolve().GetComponent(node.Owner).LocalRotation.GetCardinalDir(); } else { - var terminalDir = node.Owner.Transform.LocalRotation.GetCardinalDir(); + var terminalDir = IoCManager.Resolve().GetComponent(node.Owner).LocalRotation.GetCardinalDir(); if (terminalDir.GetOpposite() == dir) { // Target tile has a terminal towards us, block the direction. @@ -73,7 +73,7 @@ namespace Content.Server.Power.Nodes { base.OnPostRebuild(); - EntitySystem.Get().QueueUpdate(Owner.Uid); + EntitySystem.Get().QueueUpdate(Owner); } } } diff --git a/Content.Server/Power/Nodes/CableTerminalNode.cs b/Content.Server/Power/Nodes/CableTerminalNode.cs index eeb63c670b..17351ec7eb 100644 --- a/Content.Server/Power/Nodes/CableTerminalNode.cs +++ b/Content.Server/Power/Nodes/CableTerminalNode.cs @@ -12,15 +12,15 @@ namespace Content.Server.Power.Nodes { public override IEnumerable GetReachableNodes() { - if (Owner.Transform.GridID == GridId.Invalid) + if (IoCManager.Resolve().GetComponent(Owner).GridID == GridId.Invalid) yield break; // No funny nodes in spess. var entMan = IoCManager.Resolve(); - var grid = IoCManager.Resolve().GetGrid(Owner.Transform.GridID); - var gridIndex = grid.TileIndicesFor(Owner.Transform.Coordinates); + var grid = IoCManager.Resolve().GetGrid(IoCManager.Resolve().GetComponent(Owner).GridID); + var gridIndex = grid.TileIndicesFor(IoCManager.Resolve().GetComponent(Owner).Coordinates); - var dir = Owner.Transform.LocalRotation.GetDir(); + var dir = IoCManager.Resolve().GetComponent(Owner).LocalRotation.GetDir(); var targetIdx = gridIndex + NodeHelpers.TileOffsetForDir(dir); foreach (var node in NodeHelpers.GetNodesInTile(entMan, grid, targetIdx)) diff --git a/Content.Server/Power/Nodes/CableTerminalPortNode.cs b/Content.Server/Power/Nodes/CableTerminalPortNode.cs index ba7cda71d5..e1cf189f11 100644 --- a/Content.Server/Power/Nodes/CableTerminalPortNode.cs +++ b/Content.Server/Power/Nodes/CableTerminalPortNode.cs @@ -12,12 +12,12 @@ namespace Content.Server.Power.Nodes { public override IEnumerable GetReachableNodes() { - if (Owner.Transform.GridID == GridId.Invalid) + if (IoCManager.Resolve().GetComponent(Owner).GridID == GridId.Invalid) yield break; // No funny nodes in spess. var entMan = IoCManager.Resolve(); - var grid = IoCManager.Resolve().GetGrid(Owner.Transform.GridID); - var gridIndex = grid.TileIndicesFor(Owner.Transform.Coordinates); + var grid = IoCManager.Resolve().GetGrid(IoCManager.Resolve().GetComponent(Owner).GridID); + var gridIndex = grid.TileIndicesFor(IoCManager.Resolve().GetComponent(Owner).Coordinates); var nodes = NodeHelpers.GetCardinalNeighborNodes(entMan, grid, gridIndex, includeSameTile: false); foreach (var (_, node) in nodes) diff --git a/Content.Server/Power/SMES/SmesComponent.cs b/Content.Server/Power/SMES/SmesComponent.cs index 8115975b50..9b606f6759 100644 --- a/Content.Server/Power/SMES/SmesComponent.cs +++ b/Content.Server/Power/SMES/SmesComponent.cs @@ -18,6 +18,7 @@ namespace Content.Server.Power.SMES [RegisterComponent] public class SmesComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; public override string Name => "Smes"; @@ -47,7 +48,7 @@ namespace Content.Server.Power.SMES _lastChargeLevel = newLevel; _lastChargeLevelChange = _gameTiming.CurTime; - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(SmesVisuals.LastChargeLevel, newLevel); } @@ -59,7 +60,7 @@ namespace Content.Server.Power.SMES _lastChargeState = newChargeState; _lastChargeStateChange = _gameTiming.CurTime; - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(SmesVisuals.LastChargeState, newChargeState); } @@ -68,7 +69,7 @@ namespace Content.Server.Power.SMES private int GetNewChargeLevel() { - if (!Owner.TryGetComponent(out BatteryComponent? battery)) + if (!_entMan.TryGetComponent(Owner, out BatteryComponent? battery)) { return 0; } @@ -78,7 +79,7 @@ namespace Content.Server.Power.SMES private ChargeState GetNewChargeState() { - var battery = Owner.GetComponent(); + var battery = _entMan.GetComponent(Owner); return (battery.CurrentSupply - battery.CurrentReceiving) switch { > 0 => ChargeState.Discharging, diff --git a/Content.Server/PowerCell/Components/PowerCellChargerComponent.cs b/Content.Server/PowerCell/Components/PowerCellChargerComponent.cs index 3b5d7b78cc..69b52d42c7 100644 --- a/Content.Server/PowerCell/Components/PowerCellChargerComponent.cs +++ b/Content.Server/PowerCell/Components/PowerCellChargerComponent.cs @@ -1,6 +1,7 @@ using Content.Server.Power.Components; using Content.Shared.Interaction; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.PowerCell.Components { @@ -14,14 +15,14 @@ namespace Content.Server.PowerCell.Components { public override string Name => "PowerCellCharger"; - public override bool IsEntityCompatible(IEntity entity) + public override bool IsEntityCompatible(EntityUid entity) { - return entity.HasComponent(); + return IoCManager.Resolve().HasComponent(entity); } - protected override BatteryComponent GetBatteryFrom(IEntity entity) + protected override BatteryComponent GetBatteryFrom(EntityUid entity) { - return entity.GetComponent(); + return IoCManager.Resolve().GetComponent(entity); } } } diff --git a/Content.Server/PowerCell/Components/PowerCellComponent.cs b/Content.Server/PowerCell/Components/PowerCellComponent.cs index 4603d11b68..c0cda8d0ff 100644 --- a/Content.Server/PowerCell/Components/PowerCellComponent.cs +++ b/Content.Server/PowerCell/Components/PowerCellComponent.cs @@ -5,6 +5,7 @@ using Content.Shared.Examine; using Content.Shared.PowerCell; using Content.Shared.Rounding; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -72,13 +73,13 @@ namespace Content.Server.PowerCell.Components var light = (int) Math.Ceiling(Math.Sqrt(CurrentCharge) / 30); CurrentCharge = 0; - EntitySystem.Get().SpawnExplosion(OwnerUid, 0, heavy, light, light*2); - Owner.Delete(); + EntitySystem.Get().SpawnExplosion(Owner, 0, heavy, light, light*2); + IoCManager.Resolve().DeleteEntity(Owner); } private void UpdateVisuals() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (IoCManager.Resolve().TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(PowerCellVisuals.ChargeLevel, GetLevel(CurrentCharge / MaxCharge)); } diff --git a/Content.Server/PowerCell/Components/PowerCellSlotComponent.cs b/Content.Server/PowerCell/Components/PowerCellSlotComponent.cs index 37263243ba..d5138ef1bc 100644 --- a/Content.Server/PowerCell/Components/PowerCellSlotComponent.cs +++ b/Content.Server/PowerCell/Components/PowerCellSlotComponent.cs @@ -7,6 +7,7 @@ using Content.Shared.Sound; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Serialization.Manager.Attributes; @@ -24,6 +25,8 @@ namespace Content.Server.PowerCell.Components public class PowerCellSlotComponent : Component, IExamine, IMapInit #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "PowerCellSlot"; /// @@ -80,7 +83,7 @@ namespace Content.Server.PowerCell.Components get { if (_cellContainer.ContainedEntity == null) return null; - return _cellContainer.ContainedEntity.TryGetComponent(out PowerCellComponent? cell) ? cell : null; + return _entities.TryGetComponent(_cellContainer.ContainedEntity.Value, out PowerCellComponent? cell) ? cell : null; } } @@ -125,7 +128,7 @@ namespace Content.Server.PowerCell.Components /// (optional) the user to give the removed cell to. /// Should be played upon removal? /// The cell component of the entity that was removed, or null if removal failed. - public PowerCellComponent? EjectCell(IEntity? user, bool playSound = true) + public PowerCellComponent? EjectCell(EntityUid user, bool playSound = true) { var cell = Cell; if (cell == null || !CanRemoveCell) return null; @@ -133,14 +136,14 @@ namespace Content.Server.PowerCell.Components //Dirty(); if (user != null) { - if (!user.TryGetComponent(out HandsComponent? hands) || !hands.PutInHand(cell.Owner.GetComponent())) + if (!_entities.TryGetComponent(user, out HandsComponent? hands) || !hands.PutInHand(_entities.GetComponent(cell.Owner))) { - cell.Owner.Transform.Coordinates = user.Transform.Coordinates; + _entities.GetComponent(cell.Owner).Coordinates = _entities.GetComponent(user).Coordinates; } } else { - cell.Owner.Transform.Coordinates = Owner.Transform.Coordinates; + _entities.GetComponent(cell.Owner).Coordinates = _entities.GetComponent(Owner).Coordinates; } if (playSound) @@ -148,7 +151,7 @@ namespace Content.Server.PowerCell.Components SoundSystem.Play(Filter.Pvs(Owner), CellRemoveSound.GetSound(), Owner, AudioHelpers.WithVariation(0.125f)); } - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new PowerCellChangedEvent(true), false); + _entities.EventBus.RaiseLocalEvent(Owner, new PowerCellChangedEvent(true), false); return cell; } @@ -158,11 +161,11 @@ namespace Content.Server.PowerCell.Components /// The cell to insert. /// Should be played upon insertion? /// True if insertion succeeded; false otherwise. - public bool InsertCell(IEntity cell, bool playSound = true) + public bool InsertCell(EntityUid cell, bool playSound = true) { if (Cell != null) return false; - if (!cell.TryGetComponent(out var _)) return false; - if (!cell.TryGetComponent(out var cellComponent)) return false; + if (!_entities.HasComponent(cell)) return false; + if (!_entities.TryGetComponent(cell, out var cellComponent)) return false; if (cellComponent.CellSize != SlotSize) return false; if (!_cellContainer.Insert(cell)) return false; //Dirty(); @@ -171,7 +174,7 @@ namespace Content.Server.PowerCell.Components SoundSystem.Play(Filter.Pvs(Owner), CellInsertSound.GetSound(), Owner, AudioHelpers.WithVariation(0.125f)); } - Owner.EntityManager.EventBus.RaiseLocalEvent(Owner.Uid, new PowerCellChangedEvent(false), false); + _entities.EventBus.RaiseLocalEvent(Owner, new PowerCellChangedEvent(false), false); return true; } @@ -198,7 +201,7 @@ namespace Content.Server.PowerCell.Components }; } - var cell = Owner.EntityManager.SpawnEntity(type, Owner.Transform.Coordinates); + var cell = _entities.SpawnEntity(type, _entities.GetComponent(Owner).Coordinates); _cellContainer.Insert(cell); } } diff --git a/Content.Server/PowerCell/PowerCellSystem.cs b/Content.Server/PowerCell/PowerCellSystem.cs index 02595812ce..422025d370 100644 --- a/Content.Server/PowerCell/PowerCellSystem.cs +++ b/Content.Server/PowerCell/PowerCellSystem.cs @@ -31,7 +31,7 @@ namespace Content.Server.PowerCell !args.CanInteract || !component.ShowVerb || !component.HasCell || - !_actionBlockerSystem.CanPickup(args.User.Uid)) + !_actionBlockerSystem.CanPickup(args.User)) return; Verb verb = new(); @@ -43,18 +43,18 @@ namespace Content.Server.PowerCell private void AddInsertVerb(EntityUid uid, PowerCellSlotComponent component, GetInteractionVerbsEvent args) { - if (args.Using == null || + if (args.Using is not {Valid: true} @using || !args.CanAccess || !args.CanInteract || component.HasCell || - !args.Using.HasComponent() || - !_actionBlockerSystem.CanDrop(args.User.Uid)) + !EntityManager.HasComponent(@using) || + !_actionBlockerSystem.CanDrop(args.User)) return; Verb verb = new(); - verb.Text = args.Using.Name; + verb.Text = EntityManager.GetComponent(@using).EntityName; verb.Category = VerbCategory.Insert; - verb.Act = () => component.InsertCell(args.Using); + verb.Act = () => component.InsertCell(@using); args.Verbs.Add(verb); } diff --git a/Content.Server/Projectiles/Components/HitscanComponent.cs b/Content.Server/Projectiles/Components/HitscanComponent.cs index b2fd403f6e..b6aae157ef 100644 --- a/Content.Server/Projectiles/Components/HitscanComponent.cs +++ b/Content.Server/Projectiles/Components/HitscanComponent.cs @@ -21,6 +21,7 @@ namespace Content.Server.Projectiles.Components [RegisterComponent] public class HitscanComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; public override string Name => "Hitscan"; @@ -47,7 +48,7 @@ namespace Content.Server.Projectiles.Components [DataField("soundHitWall")] private SoundSpecifier _soundHitWall = new SoundPathSpecifier("/Audio/Weapons/Guns/Hits/laser_sear_wall.ogg"); - public void FireEffects(IEntity user, float distance, Angle angle, IEntity? hitEntity = null) + public void FireEffects(EntityUid user, float distance, Angle angle, EntityUid? hitEntity = null) { var effectSystem = EntitySystem.Get(); _startTime = _gameTiming.CurTime; @@ -56,12 +57,12 @@ namespace Content.Server.Projectiles.Components var mapManager = IoCManager.Resolve(); // We'll get the effects relative to the grid / map of the firer - var gridOrMap = user.Transform.GridID == GridId.Invalid ? mapManager.GetMapEntityId(user.Transform.MapID) : - mapManager.GetGrid(user.Transform.GridID).GridEntityId; + var gridOrMap = _entMan.GetComponent(user).GridID == GridId.Invalid ? mapManager.GetMapEntityId(_entMan.GetComponent(user).MapID) : + mapManager.GetGrid(_entMan.GetComponent(user).GridID).GridEntityId; - var parentXform = Owner.EntityManager.GetComponent(gridOrMap); + var parentXform = _entMan.GetComponent(gridOrMap); - var localCoordinates = new EntityCoordinates(gridOrMap, parentXform.InvWorldMatrix.Transform(user.Transform.WorldPosition)); + var localCoordinates = new EntityCoordinates(gridOrMap, parentXform.InvWorldMatrix.Transform(_entMan.GetComponent(user).WorldPosition)); var localAngle = angle - parentXform.WorldRotation; var afterEffect = AfterEffects(localCoordinates, localAngle, distance, 1.0f); @@ -96,9 +97,9 @@ namespace Content.Server.Projectiles.Components Owner.SpawnTimer((int) _deathTime.TotalMilliseconds, () => { - if (!Owner.Deleted) + if (!_entMan.Deleted(Owner)) { - Owner.Delete(); + _entMan.DeleteEntity(Owner); } }); } @@ -161,7 +162,7 @@ namespace Content.Server.Projectiles.Components EffectSprite = _impactFlash, Born = _startTime, DeathTime = _deathTime, - Coordinates = Owner.Transform.Coordinates.Offset(angle.ToVec() * distance), + Coordinates = _entMan.GetComponent(Owner).Coordinates.Offset(angle.ToVec() * distance), //Rotated from east facing Rotation = (float) angle.FlipPositive(), Color = Vector4.Multiply(new Vector4(255, 255, 255, 750), ColorModifier), diff --git a/Content.Server/Projectiles/Components/ProjectileComponent.cs b/Content.Server/Projectiles/Components/ProjectileComponent.cs index d7aeeb3cc5..24f9555182 100644 --- a/Content.Server/Projectiles/Components/ProjectileComponent.cs +++ b/Content.Server/Projectiles/Components/ProjectileComponent.cs @@ -1,9 +1,7 @@ -using System.Collections.Generic; using Content.Shared.Damage; using Content.Shared.Projectiles; using Content.Shared.Sound; using Robust.Shared.GameObjects; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -32,9 +30,9 @@ namespace Content.Server.Projectiles.Components /// Function that makes the collision of this object ignore a specific entity so we don't collide with ourselves /// /// - public void IgnoreEntity(IEntity shooter) + public void IgnoreEntity(EntityUid shooter) { - Shooter = shooter.Uid; + Shooter = shooter; Dirty(); } diff --git a/Content.Server/Projectiles/ProjectileSystem.cs b/Content.Server/Projectiles/ProjectileSystem.cs index 77a3d8a1ea..8ae66eaca5 100644 --- a/Content.Server/Projectiles/ProjectileSystem.cs +++ b/Content.Server/Projectiles/ProjectileSystem.cs @@ -1,7 +1,6 @@ using Content.Server.Administration.Logs; using Content.Server.Camera; using Content.Server.Projectiles.Components; -using Content.Shared.Administration.Logs; using Content.Shared.Body.Components; using Content.Shared.Damage; using Content.Shared.Database; @@ -36,11 +35,11 @@ namespace Content.Server.Projectiles var otherEntity = args.OtherFixture.Body.Owner; - var coordinates = args.OtherFixture.Body.Owner.Transform.Coordinates; + var coordinates = EntityManager.GetComponent(args.OtherFixture.Body.Owner).Coordinates; var playerFilter = Filter.Pvs(coordinates); - if (!otherEntity.Deleted && component.SoundHitSpecies != null && - otherEntity.HasComponent()) + if (!EntityManager.GetComponent(otherEntity).EntityDeleted && component.SoundHitSpecies != null && + EntityManager.HasComponent(otherEntity)) { SoundSystem.Play(playerFilter, component.SoundHitSpecies.GetSound(), coordinates); } @@ -52,18 +51,19 @@ namespace Content.Server.Projectiles SoundSystem.Play(playerFilter, soundHit, coordinates); } - if (!otherEntity.Deleted) + if (!EntityManager.GetComponent(otherEntity).EntityDeleted) { - var dmg = _damageableSystem.TryChangeDamage(otherEntity.Uid, component.Damage); + var dmg = _damageableSystem.TryChangeDamage(otherEntity, component.Damage); component.DamagedEntity = true; - if (dmg is not null && EntityManager.TryGetEntity(component.Shooter, out var shooter)) + if (dmg is not null && EntityManager.EntityExists(component.Shooter)) _adminLogSystem.Add(LogType.BulletHit, LogImpact.Low, - $"Projectile {component.Owner} shot by {shooter} hit {otherEntity} and dealt {dmg.Total} damage"); + $"Projectile {component.Owner} shot by {component.Shooter:shooter} hit {otherEntity} and dealt {dmg.Total} damage"); } // Damaging it can delete it - if (!otherEntity.Deleted && otherEntity.TryGetComponent(out CameraRecoilComponent? recoilComponent)) + if (!EntityManager.GetComponent(otherEntity).EntityDeleted && + EntityManager.TryGetComponent(otherEntity, out CameraRecoilComponent? recoilComponent)) { var direction = args.OurFixture.Body.LinearVelocity.Normalized; recoilComponent.Kick(direction); @@ -83,7 +83,7 @@ namespace Content.Server.Projectiles if (component.TimeLeft <= 0) { - component.Owner.Delete(); + EntityManager.DeleteEntity(component.Owner); } } } diff --git a/Content.Server/Pulling/PullingSystem.cs b/Content.Server/Pulling/PullingSystem.cs index eb3eabe508..7cb76f9d24 100644 --- a/Content.Server/Pulling/PullingSystem.cs +++ b/Content.Server/Pulling/PullingSystem.cs @@ -27,9 +27,7 @@ namespace Content.Server.Pulling private void HandleReleasePulledObject(ICommonSession? session) { - var player = session?.AttachedEntity; - - if (player == null) + if (session?.AttachedEntity is not {Valid: true} player) { return; } @@ -39,7 +37,7 @@ namespace Content.Server.Pulling return; } - if (!pulled.TryGetComponent(out SharedPullableComponent? pullable)) + if (!EntityManager.TryGetComponent(pulled.Value, out SharedPullableComponent? pullable)) { return; } diff --git a/Content.Server/RCD/Systems/RCDAmmoSystem.cs b/Content.Server/RCD/Systems/RCDAmmoSystem.cs index 897bde1805..d88754c105 100644 --- a/Content.Server/RCD/Systems/RCDAmmoSystem.cs +++ b/Content.Server/RCD/Systems/RCDAmmoSystem.cs @@ -1,11 +1,10 @@ +using System; using Content.Server.RCD.Components; using Content.Shared.Examine; -using Content.Shared.Hands.Components; using Content.Shared.Interaction; using Content.Shared.Popups; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using System; namespace Content.Server.RCD.Systems { @@ -29,7 +28,8 @@ namespace Content.Server.RCD.Systems if (args.Handled || !args.CanReach) return; - if (args.Target == null || !EntityManager.TryGetComponent(args.Target.Uid, out RCDComponent? rcdComponent)) + if (args.Target is not {Valid: true} target || + !EntityManager.TryGetComponent(target, out RCDComponent? rcdComponent)) return; if (rcdComponent.MaxAmmo - rcdComponent.CurrentAmmo < component.RefillAmmo) diff --git a/Content.Server/RCD/Systems/RCDSystem.cs b/Content.Server/RCD/Systems/RCDSystem.cs index 02a8ca6c18..a26afd0556 100644 --- a/Content.Server/RCD/Systems/RCDSystem.cs +++ b/Content.Server/RCD/Systems/RCDSystem.cs @@ -1,3 +1,5 @@ +using System; +using System.Threading; using Content.Server.DoAfter; using Content.Server.RCD.Components; using Content.Shared.Coordinates; @@ -14,8 +16,6 @@ using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Player; -using System; -using System.Threading; namespace Content.Server.RCD.Systems { @@ -118,18 +118,21 @@ namespace Content.Server.RCD.Systems } else //Delete what the user targeted { - args.Target?.Delete(); + if (args.Target is {Valid: true} target) + { + EntityManager.DeleteEntity(target); + } } break; //Walls are a special behaviour, and require us to build a new object with a transform rather than setting a grid tile, // thus we early return to avoid the tile set code. case RcdMode.Walls: var ent = EntityManager.SpawnEntity("WallSolid", mapGrid.GridTileToLocal(snapPos)); - ent.Transform.LocalRotation = Angle.Zero; // Walls always need to point south. + EntityManager.GetComponent(ent).LocalRotation = Angle.Zero; // Walls always need to point south. break; case RcdMode.Airlock: var airlock = EntityManager.SpawnEntity("Airlock", mapGrid.GridTileToLocal(snapPos)); - airlock.Transform.LocalRotation = rcd.Owner.Transform.LocalRotation; //Now apply icon smoothing. + EntityManager.GetComponent(airlock).LocalRotation = EntityManager.GetComponent(rcd.Owner).LocalRotation; //Now apply icon smoothing. break; default: args.Handled = true; @@ -186,7 +189,7 @@ namespace Content.Server.RCD.Systems return false; } //They tried to decon a non-turf but it's not in the whitelist - if (eventArgs.Target != null && !eventArgs.Target.HasTag("RCDDeconstructWhitelist")) + if (eventArgs.Target != null && !eventArgs.Target.Value.HasTag("RCDDeconstructWhitelist")) { rcd.Owner.PopupMessage(eventArgs.User, Loc.GetString("rcd-component-deconstruct-target-not-on-whitelist-message")); return false; @@ -224,7 +227,7 @@ namespace Content.Server.RCD.Systems } } - private void NextMode(EntityUid uid, RCDComponent rcd, IEntity? user) + private void NextMode(EntityUid uid, RCDComponent rcd, EntityUid user) { SoundSystem.Play(Filter.Pvs(uid), rcd.SwapModeSound.GetSound(), uid); diff --git a/Content.Server/Radiation/RadiationPulseComponent.cs b/Content.Server/Radiation/RadiationPulseComponent.cs index 7c1828bdf0..58ba2c6cef 100644 --- a/Content.Server/Radiation/RadiationPulseComponent.cs +++ b/Content.Server/Radiation/RadiationPulseComponent.cs @@ -5,7 +5,6 @@ using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Timing; @@ -16,6 +15,7 @@ namespace Content.Server.Radiation [ComponentReference(typeof(SharedRadiationPulseComponent))] public sealed class RadiationPulseComponent : SharedRadiationPulseComponent { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly IRobustRandom _random = default!; @@ -108,11 +108,11 @@ namespace Content.Server.Radiation public void Update(float frameTime) { - if (!Decay || Owner.Deleted) + if (!Decay || _entMan.Deleted(Owner)) return; if (_duration <= 0f) - Owner.QueueDelete(); + _entMan.QueueDeleteEntity(Owner); _duration -= frameTime; } diff --git a/Content.Server/Radiation/RadiationPulseSystem.cs b/Content.Server/Radiation/RadiationPulseSystem.cs index 7142952880..e7a2ba599a 100644 --- a/Content.Server/Radiation/RadiationPulseSystem.cs +++ b/Content.Server/Radiation/RadiationPulseSystem.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Linq; using Content.Shared.Radiation; using Content.Shared.Sound; @@ -11,6 +12,7 @@ namespace Content.Server.Radiation [UsedImplicitly] public sealed class RadiationPulseSystem : EntitySystem { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IEntityLookup _lookup = default!; private const float RadiationCooldown = 0.5f; @@ -32,16 +34,16 @@ namespace Content.Server.Radiation comp.Update(RadiationCooldown); var ent = comp.Owner; - if (ent.Deleted) continue; + if (Deleted(ent)) continue; - foreach (var entity in _lookup.GetEntitiesInRange(ent.Transform.Coordinates, comp.Range)) + foreach (var entity in _lookup.GetEntitiesInRange(_entMan.GetComponent(ent).Coordinates, comp.Range)) { // For now at least still need this because it uses a list internally then returns and this may be deleted before we get to it. - if (entity.Deleted) continue; + if ((!_entMan.EntityExists(entity) ? EntityLifeStage.Deleted : _entMan.GetComponent(entity).EntityLifeStage) >= EntityLifeStage.Deleted) continue; // Note: Radiation is liable for a refactor (stinky Sloth coding a basic version when he did StationEvents) // so this ToArray doesn't really matter. - foreach (var radiation in entity.GetAllComponents().ToArray()) + foreach (var radiation in _entMan.GetComponents(entity).ToArray()) { radiation.RadiationAct(RadiationCooldown, comp); } diff --git a/Content.Server/Radio/Components/HandheldRadioComponent.cs b/Content.Server/Radio/Components/HandheldRadioComponent.cs index 412909ad55..f05181d5b4 100644 --- a/Content.Server/Radio/Components/HandheldRadioComponent.cs +++ b/Content.Server/Radio/Components/HandheldRadioComponent.cs @@ -63,7 +63,7 @@ namespace Content.Server.Radio.Components _chatManager.EntitySay(Owner, message); } - public bool Use(IEntity user) + public bool Use(EntityUid user) { RadioOn = !RadioOn; @@ -79,13 +79,13 @@ namespace Content.Server.Radio.Components return Use(eventArgs.User); } - public bool CanListen(string message, IEntity source) + public bool CanListen(string message, EntityUid source) { return RadioOn && - Owner.InRangeUnobstructed(source.Transform.Coordinates, range: ListenRange); + Owner.InRangeUnobstructed(IoCManager.Resolve().GetComponent(source).Coordinates, range: ListenRange); } - public void Receive(string message, int channel, IEntity speaker) + public void Receive(string message, int channel, EntityUid speaker) { if (RadioOn) { @@ -93,12 +93,12 @@ namespace Content.Server.Radio.Components } } - public void Listen(string message, IEntity speaker) + public void Listen(string message, EntityUid speaker) { Broadcast(message, speaker); } - public void Broadcast(string message, IEntity speaker) + public void Broadcast(string message, EntityUid speaker) { _radioSystem.SpreadMessage(this, speaker, message, BroadcastFrequency); } diff --git a/Content.Server/Radio/Components/IListen.cs b/Content.Server/Radio/Components/IListen.cs index 77ee15a8f2..daeb227d3b 100644 --- a/Content.Server/Radio/Components/IListen.cs +++ b/Content.Server/Radio/Components/IListen.cs @@ -1,4 +1,4 @@ -using Robust.Shared.GameObjects; +using Robust.Shared.GameObjects; namespace Content.Server.Radio.Components { @@ -10,8 +10,8 @@ namespace Content.Server.Radio.Components { int ListenRange { get; } - bool CanListen(string message, IEntity source); + bool CanListen(string message, EntityUid source); - void Listen(string message, IEntity speaker); + void Listen(string message, EntityUid speaker); } } diff --git a/Content.Server/Radio/Components/IRadio.cs b/Content.Server/Radio/Components/IRadio.cs index f93bf4877b..4025956762 100644 --- a/Content.Server/Radio/Components/IRadio.cs +++ b/Content.Server/Radio/Components/IRadio.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using Robust.Shared.GameObjects; +using System.Collections.Generic; using Robust.Shared.GameObjects; namespace Content.Server.Radio.Components @@ -7,8 +8,8 @@ namespace Content.Server.Radio.Components { IReadOnlyList Channels { get; } - void Receive(string message, int channel, IEntity speaker); + void Receive(string message, int channel, EntityUid speaker); - void Broadcast(string message, IEntity speaker); + void Broadcast(string message, EntityUid speaker); } } diff --git a/Content.Server/Radio/EntitySystems/ListeningSystem.cs b/Content.Server/Radio/EntitySystems/ListeningSystem.cs index 7bc4dc93c1..1c4b2b5763 100644 --- a/Content.Server/Radio/EntitySystems/ListeningSystem.cs +++ b/Content.Server/Radio/EntitySystems/ListeningSystem.cs @@ -7,7 +7,7 @@ namespace Content.Server.Radio.EntitySystems [UsedImplicitly] public class ListeningSystem : EntitySystem { - public void PingListeners(IEntity source, string message) + public void PingListeners(EntityUid source, string message) { foreach (var listener in EntityManager.EntityQuery(true)) { diff --git a/Content.Server/Radio/EntitySystems/RadioSystem.cs b/Content.Server/Radio/EntitySystems/RadioSystem.cs index ee2e749585..350590f6a4 100644 --- a/Content.Server/Radio/EntitySystems/RadioSystem.cs +++ b/Content.Server/Radio/EntitySystems/RadioSystem.cs @@ -11,7 +11,7 @@ namespace Content.Server.Radio.EntitySystems { private readonly List _messages = new(); - public void SpreadMessage(IRadio source, IEntity speaker, string message, int channel) + public void SpreadMessage(IRadio source, EntityUid speaker, string message, int channel) { if (_messages.Contains(message)) return; diff --git a/Content.Server/Recycling/Components/RecyclableComponent.cs b/Content.Server/Recycling/Components/RecyclableComponent.cs index 5e5f3c661b..df546fe876 100644 --- a/Content.Server/Recycling/Components/RecyclableComponent.cs +++ b/Content.Server/Recycling/Components/RecyclableComponent.cs @@ -1,5 +1,6 @@ using System; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Recycling.Components @@ -7,6 +8,8 @@ namespace Content.Server.Recycling.Components [RegisterComponent] public class RecyclableComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Recyclable"; /// @@ -32,12 +35,12 @@ namespace Content.Server.Recycling.Components { for (var i = 0; i < Math.Max(_amount * efficiency, 1); i++) { - Owner.EntityManager.SpawnEntity(_prototype, Owner.Transform.Coordinates); + _entMan.SpawnEntity(_prototype, _entMan.GetComponent(Owner).Coordinates); } } - Owner.QueueDelete(); + _entMan.QueueDeleteEntity(Owner); } } } diff --git a/Content.Server/Recycling/Components/RecyclerComponent.cs b/Content.Server/Recycling/Components/RecyclerComponent.cs index d1cd624b4b..bc01f03034 100644 --- a/Content.Server/Recycling/Components/RecyclerComponent.cs +++ b/Content.Server/Recycling/Components/RecyclerComponent.cs @@ -1,16 +1,15 @@ using Content.Server.Act; using Content.Server.Chat.Managers; using Content.Server.GameTicking; -using Content.Server.Mind.Components; using Content.Server.Players; using Content.Server.Popups; using Content.Shared.Body.Components; using Content.Shared.Popups; using Content.Shared.Recycling; using Robust.Server.GameObjects; -using Robust.Server.Player; using Robust.Shared.Analyzers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -22,6 +21,8 @@ namespace Content.Server.Recycling.Components [Friend(typeof(RecyclerSystem))] public class RecyclerComponent : Component, ISuicideAct { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Recycler"; /// @@ -40,15 +41,15 @@ namespace Content.Server.Recycling.Components private void Clean() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(RecyclerVisuals.Bloody, false); } } - SuicideKind ISuicideAct.Suicide(IEntity victim, IChatManager chat) + SuicideKind ISuicideAct.Suicide(EntityUid victim, IChatManager chat) { - if (victim.TryGetComponent(out ActorComponent? actor) && actor.PlayerSession.ContentData()?.Mind is {} mind) + if (_entMan.TryGetComponent(victim, out ActorComponent? actor) && actor.PlayerSession.ContentData()?.Mind is {} mind) { EntitySystem.Get().OnGhostAttempt(mind, false); mind.OwnedEntity?.PopupMessage(Loc.GetString("recycler-component-suicide-message")); @@ -56,7 +57,7 @@ namespace Content.Server.Recycling.Components victim.PopupMessageOtherClients(Loc.GetString("recycler-component-suicide-message-others", ("victim",victim))); - if (victim.TryGetComponent(out var body)) + if (_entMan.TryGetComponent(victim, out var body)) { body.Gib(true); } diff --git a/Content.Server/Recycling/RecyclerSystem.cs b/Content.Server/Recycling/RecyclerSystem.cs index a57e8f4538..58424d91ba 100644 --- a/Content.Server/Recycling/RecyclerSystem.cs +++ b/Content.Server/Recycling/RecyclerSystem.cs @@ -1,13 +1,10 @@ -using System.Collections.Generic; using Content.Server.Power.Components; using Content.Server.Recycling.Components; using Content.Shared.Body.Components; using Content.Shared.Recycling; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Physics; using Robust.Shared.Physics.Dynamics; -using Robust.Shared.Utility; namespace Content.Server.Recycling { @@ -24,17 +21,17 @@ namespace Content.Server.Recycling Recycle(component, args.OtherFixture.Body.Owner); } - private void Recycle(RecyclerComponent component, IEntity entity) + private void Recycle(RecyclerComponent component, EntityUid entity) { // TODO: Prevent collision with recycled items // Can only recycle things that are recyclable... And also check the safety of the thing to recycle. - if (!entity.TryGetComponent(out RecyclableComponent? recyclable) || !recyclable.Safe && component.Safe) return; + if (!EntityManager.TryGetComponent(entity, out RecyclableComponent? recyclable) || !recyclable.Safe && component.Safe) return; // Mobs are a special case! if (CanGib(component, entity)) { - entity.GetComponent().Gib(true); + EntityManager.GetComponent(entity).Gib(true); Bloodstain(component); return; } @@ -42,16 +39,16 @@ namespace Content.Server.Recycling recyclable.Recycle(component.Efficiency); } - private bool CanGib(RecyclerComponent component, IEntity entity) + private bool CanGib(RecyclerComponent component, EntityUid entity) { // We suppose this entity has a Recyclable component. - return entity.HasComponent() && !component.Safe && - component.Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) && receiver.Powered; + return EntityManager.HasComponent(entity) && !component.Safe && + EntityManager.TryGetComponent(component.Owner, out ApcPowerReceiverComponent? receiver) && receiver.Powered; } public void Bloodstain(RecyclerComponent component) { - if (component.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearance)) { appearance.SetData(RecyclerVisuals.Bloody, true); } diff --git a/Content.Server/Repairable/RepairableSystem.cs b/Content.Server/Repairable/RepairableSystem.cs index b8296d9bca..f331280403 100644 --- a/Content.Server/Repairable/RepairableSystem.cs +++ b/Content.Server/Repairable/RepairableSystem.cs @@ -27,11 +27,11 @@ namespace Content.Server.Repairable public async void Repair(EntityUid uid, RepairableComponent component, InteractUsingEvent args) { // Only try repair the target if it is damaged - if (!component.Owner.TryGetComponent(out DamageableComponent? damageable) || damageable.TotalDamage == 0) + if (!EntityManager.TryGetComponent(component.Owner, out DamageableComponent? damageable) || damageable.TotalDamage == 0) return; // Can the tool actually repair this, does it have enough fuel? - if (!await _toolSystem.UseTool(args.Used.Uid, args.User.Uid, uid, component.FuelCost, component.DoAfterDelay, component.QualityNeeded)) + if (!await _toolSystem.UseTool(args.Used, args.User, uid, component.FuelCost, component.DoAfterDelay, component.QualityNeeded)) return; // Repair all damage diff --git a/Content.Server/Research/Components/ResearchClientComponent.cs b/Content.Server/Research/Components/ResearchClientComponent.cs index cad05ed8f2..376725c5ec 100644 --- a/Content.Server/Research/Components/ResearchClientComponent.cs +++ b/Content.Server/Research/Components/ResearchClientComponent.cs @@ -57,7 +57,7 @@ namespace Content.Server.Research.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!IoCManager.Resolve().TryGetComponent(eventArgs.User, out ActorComponent? actor)) return; OpenUserInterface(actor.PlayerSession); diff --git a/Content.Server/Research/Components/ResearchConsoleComponent.cs b/Content.Server/Research/Components/ResearchConsoleComponent.cs index 3ec7adf925..ef9c6a35b8 100644 --- a/Content.Server/Research/Components/ResearchConsoleComponent.cs +++ b/Content.Server/Research/Components/ResearchConsoleComponent.cs @@ -22,12 +22,13 @@ namespace Content.Server.Research.Components [ComponentReference(typeof(IActivate))] public class ResearchConsoleComponent : SharedResearchConsoleComponent, IActivate { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [DataField("sound")] private SoundSpecifier _soundCollectionName = new SoundCollectionSpecifier("keyboard"); - [ViewVariables] private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + [ViewVariables] private bool Powered => !_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(ResearchConsoleUiKey.Key); @@ -47,9 +48,9 @@ namespace Content.Server.Research.Components private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage message) { - if (!Owner.TryGetComponent(out TechnologyDatabaseComponent? database)) + if (!_entMan.TryGetComponent(Owner, out TechnologyDatabaseComponent? database)) return; - if (!Owner.TryGetComponent(out ResearchClientComponent? client)) + if (!_entMan.TryGetComponent(Owner, out ResearchClientComponent? client)) return; if (!Powered) return; @@ -90,7 +91,7 @@ namespace Content.Server.Research.Components private ResearchConsoleBoundInterfaceState GetNewUiState() { - if (!Owner.TryGetComponent(out ResearchClientComponent? client) || + if (!_entMan.TryGetComponent(Owner, out ResearchClientComponent? client) || client.Server == null) return new ResearchConsoleBoundInterfaceState(default, default); @@ -111,7 +112,7 @@ namespace Content.Server.Research.Components void IActivate.Activate(ActivateEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return; if (!Powered) { diff --git a/Content.Server/Research/Components/ResearchPointSourceComponent.cs b/Content.Server/Research/Components/ResearchPointSourceComponent.cs index 39d95fe36d..bb32eadb66 100644 --- a/Content.Server/Research/Components/ResearchPointSourceComponent.cs +++ b/Content.Server/Research/Components/ResearchPointSourceComponent.cs @@ -1,6 +1,7 @@ using Content.Server.Power.Components; using Content.Shared.Interaction; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -42,7 +43,7 @@ namespace Content.Server.Research.Components protected override void Initialize() { base.Initialize(); - Owner.TryGetComponent(out _powerReceiver); + IoCManager.Resolve().TryGetComponent(Owner, out _powerReceiver); } } } diff --git a/Content.Server/Research/Components/ResearchServerComponent.cs b/Content.Server/Research/Components/ResearchServerComponent.cs index fada87fc84..5f37de70c5 100644 --- a/Content.Server/Research/Components/ResearchServerComponent.cs +++ b/Content.Server/Research/Components/ResearchServerComponent.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Content.Server.Power.Components; using Content.Shared.Research.Prototypes; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -73,7 +74,7 @@ namespace Content.Server.Research.Components Id = ServerCount++; EntitySystem.Get()?.RegisterServer(this); Database = Owner.EnsureComponent(); - Owner.TryGetComponent(out _powerReceiver); + IoCManager.Resolve().TryGetComponent(Owner, out _powerReceiver); } /// diff --git a/Content.Server/Research/Components/TechnologyDatabaseComponent.cs b/Content.Server/Research/Components/TechnologyDatabaseComponent.cs index ebfbcdd62e..00ac1ad2e6 100644 --- a/Content.Server/Research/Components/TechnologyDatabaseComponent.cs +++ b/Content.Server/Research/Components/TechnologyDatabaseComponent.cs @@ -1,6 +1,7 @@ using Content.Shared.Research.Components; using Content.Shared.Research.Prototypes; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Players; namespace Content.Server.Research.Components @@ -41,7 +42,7 @@ namespace Content.Server.Research.Components /// Whether it could sync or not public bool SyncWithServer() { - if (!Owner.TryGetComponent(out ResearchClientComponent? client)) return false; + if (!IoCManager.Resolve().TryGetComponent(Owner, out ResearchClientComponent? client)) return false; if (client.Server?.Database == null) return false; Sync(client.Server.Database); diff --git a/Content.Server/Rotatable/RotatableSystem.cs b/Content.Server/Rotatable/RotatableSystem.cs index 1d7e3db164..5f64d88cc1 100644 --- a/Content.Server/Rotatable/RotatableSystem.cs +++ b/Content.Server/Rotatable/RotatableSystem.cs @@ -2,6 +2,7 @@ using Content.Shared.Popups; using Content.Shared.Rotatable; using Content.Shared.Verbs; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Physics; @@ -38,12 +39,12 @@ namespace Content.Server.Rotatable // Check if the object is anchored, and whether we are still allowed to rotate it. if (!component.RotateWhileAnchored && - component.Owner.TryGetComponent(out IPhysBody? physics) && + EntityManager.TryGetComponent(component.Owner, out IPhysBody? physics) && physics.BodyType == BodyType.Static) return; Verb resetRotation = new(); - resetRotation.Act = () => component.Owner.Transform.LocalRotation = Angle.Zero; + resetRotation.Act = () => EntityManager.GetComponent(component.Owner).LocalRotation = Angle.Zero; resetRotation.Category = VerbCategory.Rotate; resetRotation.IconTexture = "/Textures/Interface/VerbIcons/refresh.svg.192dpi.png"; resetRotation.Text = "Reset"; @@ -53,7 +54,7 @@ namespace Content.Server.Rotatable // rotate clockwise Verb rotateCW = new(); - rotateCW.Act = () => component.Owner.Transform.LocalRotation += Angle.FromDegrees(-90); + rotateCW.Act = () => EntityManager.GetComponent(component.Owner).LocalRotation += Angle.FromDegrees(-90); rotateCW.Category = VerbCategory.Rotate; rotateCW.IconTexture = "/Textures/Interface/VerbIcons/rotate_cw.svg.192dpi.png"; rotateCW.Priority = -1; @@ -62,7 +63,7 @@ namespace Content.Server.Rotatable // rotate counter-clockwise Verb rotateCCW = new(); - rotateCCW.Act = () => component.Owner.Transform.LocalRotation += Angle.FromDegrees(90); + rotateCCW.Act = () => EntityManager.GetComponent(component.Owner).LocalRotation += Angle.FromDegrees(90); rotateCCW.Category = VerbCategory.Rotate; rotateCCW.IconTexture = "/Textures/Interface/VerbIcons/rotate_ccw.svg.192dpi.png"; rotateCCW.Priority = 0; @@ -73,21 +74,21 @@ namespace Content.Server.Rotatable /// /// Replace a flippable entity with it's flipped / mirror-symmetric entity. /// - public static void TryFlip(FlippableComponent component, IEntity user) + public void TryFlip(FlippableComponent component, EntityUid user) { - if (component.Owner.TryGetComponent(out IPhysBody? physics) && + if (EntityManager.TryGetComponent(component.Owner, out IPhysBody? physics) && physics.BodyType == BodyType.Static) { component.Owner.PopupMessage(user, Loc.GetString("flippable-component-try-flip-is-stuck")); return; } - var oldTransform = component.Owner.Transform; - var entity = component.Owner.EntityManager.SpawnEntity(component.MirrorEntity, oldTransform.Coordinates); - var newTransform = entity.Transform; + var oldTransform = EntityManager.GetComponent(component.Owner); + var entity = EntityManager.SpawnEntity(component.MirrorEntity, oldTransform.Coordinates); + var newTransform = EntityManager.GetComponent(entity); newTransform.LocalRotation = oldTransform.LocalRotation; newTransform.Anchored = false; - component.Owner.Delete(); + EntityManager.DeleteEntity(component.Owner); } } } diff --git a/Content.Server/RoundEnd/RoundEndSystem.cs b/Content.Server/RoundEnd/RoundEndSystem.cs index 2dc92158d2..6584bb362a 100644 --- a/Content.Server/RoundEnd/RoundEndSystem.cs +++ b/Content.Server/RoundEnd/RoundEndSystem.cs @@ -3,10 +3,8 @@ using System.Threading; using Content.Server.Administration.Logs; using Content.Server.Chat.Managers; using Content.Server.GameTicking; -using Content.Shared.Administration.Logs; using Content.Shared.Database; using Content.Shared.GameTicking; -using Robust.Server.Player; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -80,12 +78,12 @@ namespace Content.Server.RoundEnd Timer.Spawn(CallCooldown, () => OnCallCooldownEnded?.Invoke(), _callCooldownEndedTokenSource.Token); } - public void RequestRoundEnd(IEntity? requester = null, bool checkCooldown = true) + public void RequestRoundEnd(EntityUid? requester = null, bool checkCooldown = true) { RequestRoundEnd(RoundEndCountdownTime, requester, checkCooldown); } - public void RequestRoundEnd(TimeSpan countdownTime, IEntity? requester = null, bool checkCooldown = true) + public void RequestRoundEnd(TimeSpan countdownTime, EntityUid? requester = null, bool checkCooldown = true) { if (IsRoundEndCountdownStarted) return; @@ -95,7 +93,7 @@ namespace Content.Server.RoundEnd return; } - if (requester != null) + if (requester != default) { _adminLog.Add(LogType.ShuttleCalled, LogImpact.High, $"Shuttle called by {requester}"); } @@ -118,7 +116,7 @@ namespace Content.Server.RoundEnd OnRoundEndCountdownStarted?.Invoke(); } - public void CancelRoundEndCountdown(IEntity? requester = null, bool checkCooldown = true) + public void CancelRoundEndCountdown(EntityUid? requester = null, bool checkCooldown = true) { if (!IsRoundEndCountdownStarted) return; @@ -128,7 +126,7 @@ namespace Content.Server.RoundEnd return; } - if (requester != null) + if (requester != default) { _adminLog.Add(LogType.ShuttleRecalled, LogImpact.High, $"Shuttle recalled by {requester}"); } diff --git a/Content.Server/Sandbox/Commands/ColorNetworkCommand.cs b/Content.Server/Sandbox/Commands/ColorNetworkCommand.cs index 621399f4fa..80d511a27a 100644 --- a/Content.Server/Sandbox/Commands/ColorNetworkCommand.cs +++ b/Content.Server/Sandbox/Commands/ColorNetworkCommand.cs @@ -6,7 +6,6 @@ using Content.Server.Atmos.Piping.EntitySystems; using Content.Server.NodeContainer; using Content.Server.NodeContainer.NodeGroups; using Content.Shared.Administration; -using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.GameObjects; @@ -56,8 +55,7 @@ namespace Content.Server.Sandbox.Commands return; } - var target = entityManager.GetEntity(eUid); - if (!target.TryGetComponent(out NodeContainerComponent? nodeContainerComponent)) + if (!entityManager.TryGetComponent(eUid, out NodeContainerComponent? nodeContainerComponent)) { shell.WriteLine(Loc.GetString("shell-entity-is-not-node-container")); return; @@ -87,9 +85,9 @@ namespace Content.Server.Sandbox.Commands foreach (var x in group.Nodes) { - if (!x.Owner.TryGetComponent(out var atmosPipeColorComponent)) continue; + if (!IoCManager.Resolve().TryGetComponent(x.Owner, out var atmosPipeColorComponent)) continue; - EntitySystem.Get().SetColor(x.Owner.Uid, atmosPipeColorComponent, color); + EntitySystem.Get().SetColor(x.Owner, atmosPipeColorComponent, color); } } } diff --git a/Content.Server/Sandbox/SandboxManager.cs b/Content.Server/Sandbox/SandboxManager.cs index a85ad94cb0..572dc5f4cb 100644 --- a/Content.Server/Sandbox/SandboxManager.cs +++ b/Content.Server/Sandbox/SandboxManager.cs @@ -1,12 +1,13 @@ using System.Linq; using Content.Server.Access.Components; -using Content.Shared.Containers.ItemSlots; +using Content.Server.Access.Systems; using Content.Server.GameTicking; using Content.Server.Hands.Components; using Content.Server.Inventory.Components; using Content.Server.Items; using Content.Server.PDA; using Content.Shared.Access; +using Content.Shared.Containers.ItemSlots; using Content.Shared.Sandbox; using Robust.Server.Console; using Robust.Server.GameObjects; @@ -19,7 +20,6 @@ using Robust.Shared.Network; using Robust.Shared.Prototypes; using Robust.Shared.ViewVariables; using static Content.Shared.Inventory.EquipmentSlotDefines; -using Content.Server.Access.Systems; namespace Content.Server.Sandbox { @@ -115,7 +115,7 @@ namespace Content.Server.Sandbox } var player = _playerManager.GetSessionByChannel(message.MsgChannel); - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {} attached) { return; } @@ -124,22 +124,22 @@ namespace Content.Server.Sandbox .EnumeratePrototypes() .Select(p => p.ID).ToArray(); - if (player.AttachedEntity.TryGetComponent(out InventoryComponent? inv) + if (_entityManager.TryGetComponent(attached, out InventoryComponent? inv) && inv.TryGetSlotItem(Slots.IDCARD, out ItemComponent? wornItem)) { - if (wornItem.Owner.HasComponent()) + if (_entityManager.HasComponent(wornItem.Owner)) { UpgradeId(wornItem.Owner); } - else if (wornItem.Owner.TryGetComponent(out PDAComponent? pda)) + else if (_entityManager.TryGetComponent(wornItem.Owner, out PDAComponent? pda)) { if (pda.ContainedID == null) { var newID = CreateFreshId(); - if (pda.Owner.TryGetComponent(out ItemSlotsComponent? itemSlots)) + if (_entityManager.TryGetComponent(pda.Owner, out ItemSlotsComponent? itemSlots)) { _entityManager.EntitySysManager.GetEntitySystem(). - TryInsert(wornItem.Owner.Uid, pda.IdSlot, newID); + TryInsert(wornItem.Owner, pda.IdSlot, newID); } } else @@ -148,32 +148,32 @@ namespace Content.Server.Sandbox } } } - else if (player.AttachedEntity.TryGetComponent(out var hands)) + else if (_entityManager.TryGetComponent(attached, out var hands)) { var card = CreateFreshId(); - if (!player.AttachedEntity.TryGetComponent(out inv) || !inv.Equip(Slots.IDCARD, card)) + if (!_entityManager.TryGetComponent(attached, out inv) || !inv.Equip(Slots.IDCARD, card)) { - hands.PutInHandOrDrop(card.GetComponent()); + hands.PutInHandOrDrop(_entityManager.GetComponent(card)); } } - void UpgradeId(IEntity id) + void UpgradeId(EntityUid id) { var accessSystem = EntitySystem.Get(); - accessSystem.TrySetTags(id.Uid, allAccess); + accessSystem.TrySetTags(id, allAccess); - if (id.TryGetComponent(out SpriteComponent? sprite)) + if (_entityManager.TryGetComponent(id, out SpriteComponent? sprite)) { sprite.LayerSetState(0, "gold"); } } - IEntity CreateFreshId() + EntityUid CreateFreshId() { - var card = _entityManager.SpawnEntity("CaptainIDCard", player.AttachedEntity.Transform.Coordinates); + var card = _entityManager.SpawnEntity("CaptainIDCard", _entityManager.GetComponent(attached).Coordinates); UpgradeId(card); - card.GetComponent().FullName = player.AttachedEntity.Name; + _entityManager.GetComponent(card).FullName = _entityManager.GetComponent(attached).EntityName; return card; } } diff --git a/Content.Server/Security/Systems/DeployableBarrierSystem.cs b/Content.Server/Security/Systems/DeployableBarrierSystem.cs index b67bbc1f67..2420b66f91 100644 --- a/Content.Server/Security/Systems/DeployableBarrierSystem.cs +++ b/Content.Server/Security/Systems/DeployableBarrierSystem.cs @@ -4,6 +4,7 @@ using Content.Shared.Security; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using System; +using Robust.Shared.IoC; namespace Content.Server.Security.Systems { @@ -18,7 +19,7 @@ namespace Content.Server.Security.Systems private void OnStartup(EntityUid uid, DeployableBarrierComponent component, ComponentStartup args) { - if (!component.Owner.TryGetComponent(out LockComponent? lockComponent)) + if (!EntityManager.TryGetComponent(component.Owner, out LockComponent? lockComponent)) return; ToggleBarrierDeploy(component, lockComponent.Locked); @@ -31,15 +32,15 @@ namespace Content.Server.Security.Systems private void ToggleBarrierDeploy(DeployableBarrierComponent component, bool isDeployed) { - component.Owner.Transform.Anchored = isDeployed; + EntityManager.GetComponent(component.Owner).Anchored = isDeployed; - if (!component.Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (!EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearanceComponent)) return; var state = isDeployed ? DeployableBarrierState.Deployed : DeployableBarrierState.Idle; appearanceComponent.SetData(DeployableBarrierVisuals.State, state); - if (component.Owner.TryGetComponent(out PointLightComponent? light)) + if (EntityManager.TryGetComponent(component.Owner, out PointLightComponent? light)) light.Enabled = isDeployed; } } diff --git a/Content.Server/Shuttles/Components/ThrusterComponent.cs b/Content.Server/Shuttles/Components/ThrusterComponent.cs index c91828d0da..44be1f4b43 100644 --- a/Content.Server/Shuttles/Components/ThrusterComponent.cs +++ b/Content.Server/Shuttles/Components/ThrusterComponent.cs @@ -33,11 +33,11 @@ namespace Content.Server.Shuttles.Components if (!_enabled) { - system.DisableThruster(OwnerUid, this); + system.DisableThruster(Owner, this); } - else if (system.CanEnable(OwnerUid, this)) + else if (system.CanEnable(Owner, this)) { - system.EnableThruster(OwnerUid, this); + system.EnableThruster(Owner, this); } } } diff --git a/Content.Server/Shuttles/EntitySystems/DockingSystem.cs b/Content.Server/Shuttles/EntitySystems/DockingSystem.cs index 56cea164f9..771e833db1 100644 --- a/Content.Server/Shuttles/EntitySystems/DockingSystem.cs +++ b/Content.Server/Shuttles/EntitySystems/DockingSystem.cs @@ -1,5 +1,3 @@ -using Content.Server.Atmos.Components; -using Content.Server.Atmos.EntitySystems; using Content.Server.Doors.Components; using Content.Server.Power.Components; using Content.Server.Shuttles.Components; @@ -112,7 +110,7 @@ namespace Content.Server.Shuttles.EntitySystems if (dockingFixture == null) { DebugTools.Assert(false); - Logger.ErrorS("docking", $"Found null fixture on {EntityManager.GetEntity(body.OwnerUid)}"); + Logger.ErrorS("docking", $"Found null fixture on {(body).Owner}"); return null; } @@ -146,7 +144,7 @@ namespace Content.Server.Shuttles.EntitySystems if (otherDockingFixture == null) { DebugTools.Assert(false); - Logger.ErrorS("docking", $"Found null docking fixture on {EntityManager.GetEntity(ent)}"); + Logger.ErrorS("docking", $"Found null docking fixture on {ent}"); continue; } @@ -183,7 +181,7 @@ namespace Content.Server.Shuttles.EntitySystems if (dockB == null || dockA.DockJoint == null) { DebugTools.Assert(false); - Logger.Error("docking", $"Tried to cleanup {dockA.OwnerUid} but not docked?"); + Logger.Error("docking", $"Tried to cleanup {(dockA).Owner} but not docked?"); dockA.DockedWith = null; if (dockA.DockJoint != null) @@ -202,8 +200,8 @@ namespace Content.Server.Shuttles.EntitySystems dockA.DockedWith = null; // If these grids are ever invalid then need to look at fixing ordering for unanchored events elsewhere. - var gridAUid = _mapManager.GetGrid(EntityManager.GetComponent(dockA.OwnerUid).GridID).GridEntityId; - var gridBUid = _mapManager.GetGrid(EntityManager.GetComponent(dockB.OwnerUid).GridID).GridEntityId; + var gridAUid = _mapManager.GetGrid(EntityManager.GetComponent((dockA).Owner).GridID).GridEntityId; + var gridBUid = _mapManager.GetGrid(EntityManager.GetComponent((dockB).Owner).GridID).GridEntityId; var msg = new UndockEvent { @@ -213,8 +211,8 @@ namespace Content.Server.Shuttles.EntitySystems GridBUid = gridBUid, }; - EntityManager.EventBus.RaiseLocalEvent(dockA.OwnerUid, msg, false); - EntityManager.EventBus.RaiseLocalEvent(dockB.OwnerUid, msg, false); + EntityManager.EventBus.RaiseLocalEvent((dockA).Owner, msg, false); + EntityManager.EventBus.RaiseLocalEvent((dockB).Owner, msg, false); EntityManager.EventBus.RaiseEvent(EventSource.Local, msg); } @@ -310,8 +308,8 @@ namespace Content.Server.Shuttles.EntitySystems // We could also potentially use a prismatic joint? Depending if we want clamps that can extend or whatever - var dockAXform = EntityManager.GetComponent(dockA.OwnerUid); - var dockBXform = EntityManager.GetComponent(dockB.OwnerUid); + var dockAXform = EntityManager.GetComponent((dockA).Owner); + var dockBXform = EntityManager.GetComponent((dockB).Owner); var gridA = _mapManager.GetGrid(dockAXform.GridID).GridEntityId; var gridB = _mapManager.GetGrid(dockBXform.GridID).GridEntityId; @@ -326,7 +324,7 @@ namespace Content.Server.Shuttles.EntitySystems // These need playing around with // Could also potentially have collideconnected false and stiffness 0 but it was a bit more suss??? - var joint = _jointSystem.CreateWeldJoint(gridA, gridB, DockingJoint + dockA.OwnerUid); + var joint = _jointSystem.CreateWeldJoint(gridA, gridB, DockingJoint + (dockA).Owner); var gridAXform = EntityManager.GetComponent(gridA); var gridBXform = EntityManager.GetComponent(gridB); @@ -346,13 +344,13 @@ namespace Content.Server.Shuttles.EntitySystems dockA.DockJoint = joint; dockB.DockJoint = joint; - if (EntityManager.TryGetComponent(dockA.OwnerUid, out ServerDoorComponent? doorA)) + if (EntityManager.TryGetComponent((dockA).Owner, out ServerDoorComponent? doorA)) { doorA.ChangeAirtight = false; doorA.Open(); } - if (EntityManager.TryGetComponent(dockB.OwnerUid, out ServerDoorComponent? doorB)) + if (EntityManager.TryGetComponent((dockB).Owner, out ServerDoorComponent? doorB)) { doorB.ChangeAirtight = false; doorB.Open(); @@ -366,8 +364,8 @@ namespace Content.Server.Shuttles.EntitySystems GridBUid = gridB, }; - EntityManager.EventBus.RaiseLocalEvent(dockA.OwnerUid, msg, false); - EntityManager.EventBus.RaiseLocalEvent(dockB.OwnerUid, msg, false); + EntityManager.EventBus.RaiseLocalEvent((dockA).Owner, msg, false); + EntityManager.EventBus.RaiseLocalEvent((dockB).Owner, msg, false); EntityManager.EventBus.RaiseEvent(EventSource.Local, msg); } @@ -376,8 +374,8 @@ namespace Content.Server.Shuttles.EntitySystems /// private void TryDock(DockingComponent dockA, DockingComponent dockB) { - if (!EntityManager.TryGetComponent(dockA.OwnerUid, out PhysicsComponent? bodyA) || - !EntityManager.TryGetComponent(dockB.OwnerUid, out PhysicsComponent? bodyB) || + if (!EntityManager.TryGetComponent((dockA).Owner, out PhysicsComponent? bodyA) || + !EntityManager.TryGetComponent((dockB).Owner, out PhysicsComponent? bodyB) || !dockA.Enabled || !dockB.Enabled) { @@ -423,17 +421,17 @@ namespace Content.Server.Shuttles.EntitySystems if (dock.DockedWith == null) { DebugTools.Assert(false); - Logger.ErrorS("docking", $"Tried to undock {dock.OwnerUid} but not docked with anything?"); + Logger.ErrorS("docking", $"Tried to undock {(dock).Owner} but not docked with anything?"); return; } - if (EntityManager.TryGetComponent(dock.OwnerUid, out ServerDoorComponent? doorA)) + if (EntityManager.TryGetComponent((dock).Owner, out ServerDoorComponent? doorA)) { doorA.ChangeAirtight = true; doorA.Close(); } - if (EntityManager.TryGetComponent(dock.DockedWith.OwnerUid, out ServerDoorComponent? doorB)) + if (EntityManager.TryGetComponent((dock.DockedWith).Owner, out ServerDoorComponent? doorB)) { doorB.ChangeAirtight = true; doorB.Close(); diff --git a/Content.Server/Shuttles/EntitySystems/ShuttleConsoleSystem.cs b/Content.Server/Shuttles/EntitySystems/ShuttleConsoleSystem.cs index e028546819..5e879cdbc7 100644 --- a/Content.Server/Shuttles/EntitySystems/ShuttleConsoleSystem.cs +++ b/Content.Server/Shuttles/EntitySystems/ShuttleConsoleSystem.cs @@ -39,7 +39,7 @@ namespace Content.Server.Shuttles.EntitySystems { if (comp.Console == null) continue; - if (!_blocker.CanInteract(comp.OwnerUid)) + if (!_blocker.CanInteract((comp).Owner)) { toRemove.Add(comp); } @@ -96,7 +96,7 @@ namespace Content.Server.Shuttles.EntitySystems return; } - var pilotComponent = EntityManager.EnsureComponent(args.User.Uid); + var pilotComponent = EntityManager.EnsureComponent(args.User); if (!component.Enabled) { @@ -130,10 +130,10 @@ namespace Content.Server.Shuttles.EntitySystems ClearPilots(component); } - public void AddPilot(IEntity entity, ShuttleConsoleComponent component) + public void AddPilot(EntityUid entity, ShuttleConsoleComponent component) { - if (!_blocker.CanInteract(entity.Uid) || - !entity.TryGetComponent(out PilotComponent? pilotComponent) || + if (!_blocker.CanInteract(entity) || + !EntityManager.TryGetComponent(entity, out PilotComponent? pilotComponent) || component.SubscribedPilots.Contains(pilotComponent)) { return; @@ -141,14 +141,14 @@ namespace Content.Server.Shuttles.EntitySystems component.SubscribedPilots.Add(pilotComponent); - if (entity.TryGetComponent(out ServerAlertsComponent? alertsComponent)) + if (EntityManager.TryGetComponent(entity, out ServerAlertsComponent? alertsComponent)) { alertsComponent.ShowAlert(AlertType.PilotingShuttle); } entity.PopupMessage(Loc.GetString("shuttle-pilot-start")); pilotComponent.Console = component; - pilotComponent.Position = EntityManager.GetComponent(entity.Uid).Coordinates; + pilotComponent.Position = EntityManager.GetComponent(entity).Coordinates; pilotComponent.Dirty(); } @@ -163,7 +163,7 @@ namespace Content.Server.Shuttles.EntitySystems if (!helmsman.SubscribedPilots.Remove(pilotComponent)) return; - if (pilotComponent.Owner.TryGetComponent(out ServerAlertsComponent? alertsComponent)) + if (EntityManager.TryGetComponent(pilotComponent.Owner, out ServerAlertsComponent? alertsComponent)) { alertsComponent.ClearAlert(AlertType.PilotingShuttle); } @@ -171,12 +171,12 @@ namespace Content.Server.Shuttles.EntitySystems pilotComponent.Owner.PopupMessage(Loc.GetString("shuttle-pilot-end")); if (pilotComponent.LifeStage < ComponentLifeStage.Stopping) - EntityManager.RemoveComponent(pilotComponent.Owner.Uid); + EntityManager.RemoveComponent(pilotComponent.Owner); } - public void RemovePilot(IEntity entity) + public void RemovePilot(EntityUid entity) { - if (!entity.TryGetComponent(out PilotComponent? pilotComponent)) return; + if (!EntityManager.TryGetComponent(entity, out PilotComponent? pilotComponent)) return; RemovePilot(pilotComponent); } diff --git a/Content.Server/Shuttles/EntitySystems/ShuttleSystem.cs b/Content.Server/Shuttles/EntitySystems/ShuttleSystem.cs index d7052f2851..d88cb99cee 100644 --- a/Content.Server/Shuttles/EntitySystems/ShuttleSystem.cs +++ b/Content.Server/Shuttles/EntitySystems/ShuttleSystem.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Content.Server.Shuttles.Components; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Physics; namespace Content.Server.Shuttles.EntitySystems @@ -51,17 +52,17 @@ namespace Content.Server.Shuttles.EntitySystems private void OnGridInit(GridInitializeEvent ev) { - EntityManager.GetEntity(ev.EntityUid).EnsureComponent(); + EntityManager.EnsureComponent(ev.EntityUid); } private void OnShuttleStartup(EntityUid uid, ShuttleComponent component, ComponentStartup args) { - if (!component.Owner.HasComponent()) + if (!EntityManager.HasComponent(component.Owner)) { return; } - if (!component.Owner.TryGetComponent(out PhysicsComponent? physicsComponent)) + if (!EntityManager.TryGetComponent(component.Owner, out PhysicsComponent? physicsComponent)) { return; } @@ -74,7 +75,7 @@ namespace Content.Server.Shuttles.EntitySystems public void Toggle(ShuttleComponent component) { - if (!component.Owner.TryGetComponent(out PhysicsComponent? physicsComponent)) return; + if (!EntityManager.TryGetComponent(component.Owner, out PhysicsComponent? physicsComponent)) return; component.Enabled = !component.Enabled; @@ -110,7 +111,7 @@ namespace Content.Server.Shuttles.EntitySystems // None of the below is necessary for any cleanup if we're just deleting. if (EntityManager.GetComponent(uid).EntityLifeStage >= EntityLifeStage.Terminating) return; - if (!component.Owner.TryGetComponent(out PhysicsComponent? physicsComponent)) + if (!EntityManager.TryGetComponent(component.Owner, out PhysicsComponent? physicsComponent)) { return; } diff --git a/Content.Server/Shuttles/EntitySystems/ThrusterSystem.cs b/Content.Server/Shuttles/EntitySystems/ThrusterSystem.cs index 698e7322de..347e863e4f 100644 --- a/Content.Server/Shuttles/EntitySystems/ThrusterSystem.cs +++ b/Content.Server/Shuttles/EntitySystems/ThrusterSystem.cs @@ -397,14 +397,14 @@ namespace Content.Server.Shuttles.EntitySystems if (args.OurFixture.ID != BurnFixture) return; _activeThrusters.Add(component); - component.Colliding.Add(args.OtherFixture.Body.OwnerUid); + component.Colliding.Add((args.OtherFixture.Body).Owner); } private void OnEndCollide(EntityUid uid, ThrusterComponent component, EndCollideEvent args) { if (args.OurFixture.ID != BurnFixture) return; - component.Colliding.Remove(args.OtherFixture.Body.OwnerUid); + component.Colliding.Remove((args.OtherFixture.Body).Owner); if (component.Colliding.Count == 0) { @@ -425,7 +425,7 @@ namespace Content.Server.Shuttles.EntitySystems foreach (var comp in component.LinearThrusters[index]) { - if (!EntityManager.TryGetComponent(comp.OwnerUid, out AppearanceComponent? appearanceComponent)) + if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent)) continue; comp.Firing = true; @@ -446,7 +446,7 @@ namespace Content.Server.Shuttles.EntitySystems foreach (var comp in component.LinearThrusters[index]) { - if (!EntityManager.TryGetComponent(comp.OwnerUid, out AppearanceComponent? appearanceComponent)) + if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent)) continue; comp.Firing = false; @@ -470,7 +470,7 @@ namespace Content.Server.Shuttles.EntitySystems { foreach (var comp in component.AngularThrusters) { - if (!EntityManager.TryGetComponent(comp.OwnerUid, out AppearanceComponent? appearanceComponent)) + if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent)) continue; comp.Firing = true; @@ -481,7 +481,7 @@ namespace Content.Server.Shuttles.EntitySystems { foreach (var comp in component.AngularThrusters) { - if (!EntityManager.TryGetComponent(comp.OwnerUid, out AppearanceComponent? appearanceComponent)) + if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent)) continue; comp.Firing = false; diff --git a/Content.Server/Singularity/Components/ContainmentFieldConnection.cs b/Content.Server/Singularity/Components/ContainmentFieldConnection.cs index ece1ad6c8f..f2f6a26eae 100644 --- a/Content.Server/Singularity/Components/ContainmentFieldConnection.cs +++ b/Content.Server/Singularity/Components/ContainmentFieldConnection.cs @@ -1,11 +1,10 @@ -using System; +using System; using System.Collections.Generic; using System.Threading; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; -using Robust.Shared.Physics; using Timer = Robust.Shared.Timing.Timer; namespace Content.Server.Singularity.Components @@ -14,7 +13,7 @@ namespace Content.Server.Singularity.Components { public readonly ContainmentFieldGeneratorComponent Generator1; public readonly ContainmentFieldGeneratorComponent Generator2; - private readonly List _fields = new(); + private readonly List _fields = new(); private int _sharedEnergyPool; private readonly CancellationTokenSource _powerDecreaseCancellationTokenSource = new(); public int SharedEnergyPool @@ -36,8 +35,8 @@ namespace Content.Server.Singularity.Components Generator2 = generator2; //generateFields - var pos1 = generator1.Owner.Transform.Coordinates; - var pos2 = generator2.Owner.Transform.Coordinates; + var pos1 = IoCManager.Resolve().GetComponent(generator1.Owner).Coordinates; + var pos2 = IoCManager.Resolve().GetComponent(generator2.Owner).Coordinates; if (pos1 == pos2) { Dispose(); @@ -54,15 +53,15 @@ namespace Content.Server.Singularity.Components { var currentCoords = pos1.Offset(currentOffset); var newEnt = entityManager.SpawnEntity("ContainmentField", currentCoords); - if (!newEnt.TryGetComponent(out var containmentFieldComponent)) + if (!IoCManager.Resolve().TryGetComponent(newEnt, out var containmentFieldComponent)) { Logger.Error("While creating Fields in ContainmentFieldConnection, a ContainmentField without a ContainmentFieldComponent was created. Deleting newly spawned ContainmentField..."); - newEnt.Delete(); + IoCManager.Resolve().DeleteEntity(newEnt); continue; } containmentFieldComponent.Parent = this; - newEnt.Transform.WorldRotation = generator1.Owner.Transform.WorldRotation + dirVec.ToWorldAngle(); + IoCManager.Resolve().GetComponent(newEnt).WorldRotation = IoCManager.Resolve().GetComponent(generator1.Owner).WorldRotation + dirVec.ToWorldAngle(); _fields.Add(newEnt); currentOffset += dirVec; @@ -72,10 +71,10 @@ namespace Content.Server.Singularity.Components Timer.SpawnRepeating(1000, () => { SharedEnergyPool--;}, _powerDecreaseCancellationTokenSource.Token); } - public bool CanRepell(IEntity toRepell) + public bool CanRepell(EntityUid toRepell) { var powerNeeded = 1; - if (toRepell.TryGetComponent(out var singularityComponent)) + if (IoCManager.Resolve().TryGetComponent(toRepell, out var singularityComponent)) { powerNeeded += 2*singularityComponent.Level; } @@ -88,7 +87,7 @@ namespace Content.Server.Singularity.Components _powerDecreaseCancellationTokenSource.Cancel(); foreach (var field in _fields) { - field.Delete(); + IoCManager.Resolve().DeleteEntity(field); } _fields.Clear(); diff --git a/Content.Server/Singularity/Components/ContainmentFieldGeneratorComponent.cs b/Content.Server/Singularity/Components/ContainmentFieldGeneratorComponent.cs index e28cde993b..bbe9a0a190 100644 --- a/Content.Server/Singularity/Components/ContainmentFieldGeneratorComponent.cs +++ b/Content.Server/Singularity/Components/ContainmentFieldGeneratorComponent.cs @@ -5,10 +5,10 @@ using Content.Shared.Physics; using Content.Shared.Singularity.Components; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Physics; -using Robust.Shared.Physics.Broadphase; using Robust.Shared.ViewVariables; namespace Content.Server.Singularity.Components @@ -17,6 +17,8 @@ namespace Content.Server.Singularity.Components [ComponentReference(typeof(SharedContainmentFieldGeneratorComponent))] public class ContainmentFieldGeneratorComponent : SharedContainmentFieldGeneratorComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + private int _powerBuffer; [ViewVariables] @@ -62,7 +64,7 @@ namespace Content.Server.Singularity.Components private Tuple? _connection1; private Tuple? _connection2; - public bool CanRepell(IEntity toRepell) => _connection1?.Item2?.CanRepell(toRepell) == true || + public bool CanRepell(EntityUid toRepell) => _connection1?.Item2?.CanRepell(toRepell) == true || _connection2?.Item2?.CanRepell(toRepell) == true; public void OnAnchoredChanged() @@ -95,9 +97,9 @@ namespace Content.Server.Singularity.Components { if (_connection1?.Item1 == direction || _connection2?.Item1 == direction) continue; - var dirVec = Owner.Transform.WorldRotation.RotateVec(direction.ToVec()); - var ray = new CollisionRay(Owner.Transform.WorldPosition, dirVec, (int) CollisionGroup.MobMask); - var rawRayCastResults = EntitySystem.Get().IntersectRay(Owner.Transform.MapID, ray, 4.5f, Owner, false); + var dirVec = _entMan.GetComponent(Owner).WorldRotation.RotateVec(direction.ToVec()); + var ray = new CollisionRay(_entMan.GetComponent(Owner).WorldPosition, dirVec, (int) CollisionGroup.MobMask); + var rawRayCastResults = EntitySystem.Get().IntersectRay(_entMan.GetComponent(Owner).MapID, ray, 4.5f, Owner, false); var rayCastResults = rawRayCastResults as RayCastResults[] ?? rawRayCastResults.ToArray(); if(!rayCastResults.Any()) continue; @@ -113,11 +115,11 @@ namespace Content.Server.Singularity.Components } if(closestResult == null) continue; var ent = closestResult.Value.HitEntity; - if (!ent.TryGetComponent(out var fieldGeneratorComponent) || + if (!_entMan.TryGetComponent(ent, out var fieldGeneratorComponent) || fieldGeneratorComponent.Owner == Owner || !fieldGeneratorComponent.HasFreeConnections() || IsConnectedWith(fieldGeneratorComponent) || - !ent.TryGetComponent(out var collidableComponent) || + !_entMan.TryGetComponent(ent, out var collidableComponent) || collidableComponent.BodyType != BodyType.Static) { continue; diff --git a/Content.Server/Singularity/Components/RadiationCollectorComponent.cs b/Content.Server/Singularity/Components/RadiationCollectorComponent.cs index a1f0e2642a..b1c70ea84d 100644 --- a/Content.Server/Singularity/Components/RadiationCollectorComponent.cs +++ b/Content.Server/Singularity/Components/RadiationCollectorComponent.cs @@ -74,7 +74,7 @@ namespace Content.Server.Singularity.Components protected void SetAppearance(RadiationCollectorVisualState state) { - if (Owner.TryGetComponent(out var appearance)) + if (IoCManager.Resolve().TryGetComponent(Owner, out var appearance)) { appearance.SetData(RadiationCollectorVisuals.VisualState, state); } diff --git a/Content.Server/Singularity/Components/ServerSingularityComponent.cs b/Content.Server/Singularity/Components/ServerSingularityComponent.cs index 21f8e4def8..1fa0a855bf 100644 --- a/Content.Server/Singularity/Components/ServerSingularityComponent.cs +++ b/Content.Server/Singularity/Components/ServerSingularityComponent.cs @@ -2,14 +2,10 @@ using Content.Shared.Singularity; using Content.Shared.Singularity.Components; using Content.Shared.Sound; using Robust.Shared.Audio; -using Robust.Shared.Containers; using Robust.Shared.GameObjects; -using Robust.Shared.Physics.Collision; -using Robust.Shared.Physics.Dynamics; +using Robust.Shared.IoC; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; -using Robust.Shared.Timing; using Robust.Shared.ViewVariables; namespace Content.Server.Singularity.Components @@ -18,6 +14,8 @@ namespace Content.Server.Singularity.Components [ComponentReference(typeof(SharedSingularityComponent))] public class ServerSingularityComponent : SharedSingularityComponent { + [Dependency] private readonly IEntityManager _entMan = default!; + private SharedSingularitySystem _singularitySystem = default!; [ViewVariables(VVAccess.ReadWrite)] @@ -31,7 +29,7 @@ namespace Content.Server.Singularity.Components _energy = value; if (_energy <= 0) { - Owner.Delete(); + _entMan.DeleteEntity(Owner); return; } @@ -96,7 +94,7 @@ namespace Content.Server.Singularity.Components protected override void Shutdown() { base.Shutdown(); - SoundSystem.Play(Filter.Pvs(Owner), _singularityCollapsingSound.GetSound(), Owner.Transform.Coordinates); + SoundSystem.Play(Filter.Pvs(Owner), _singularityCollapsingSound.GetSound(), _entMan.GetComponent(Owner).Coordinates); } } } diff --git a/Content.Server/Singularity/Components/SingularityGenerator.cs b/Content.Server/Singularity/Components/SingularityGenerator.cs index c9bf0bb192..fbf93e7ba7 100644 --- a/Content.Server/Singularity/Components/SingularityGenerator.cs +++ b/Content.Server/Singularity/Components/SingularityGenerator.cs @@ -7,6 +7,8 @@ namespace Content.Server.Singularity.Components [RegisterComponent] public class SingularityGeneratorComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "SingularityGenerator"; [ViewVariables] private int _power; @@ -21,8 +23,7 @@ namespace Content.Server.Singularity.Components _power = value; if (_power > 15) { - var entityManager = IoCManager.Resolve(); - entityManager.SpawnEntity("Singularity", Owner.Transform.Coordinates); + _entMan.SpawnEntity("Singularity", _entMan.GetComponent(Owner).Coordinates); //dont delete ourselves, just wait to get eaten } } diff --git a/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs b/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs index 3873c57cf7..373d44dfbf 100644 --- a/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs +++ b/Content.Server/Singularity/EntitySystems/ContainmentFieldGeneratorSystem.cs @@ -3,6 +3,7 @@ using Content.Server.Singularity.Components; using Content.Shared.Singularity.Components; using Content.Shared.Tag; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Physics.Dynamics; namespace Content.Server.Singularity.EntitySystems @@ -21,7 +22,7 @@ namespace Content.Server.Singularity.EntitySystems private void HandleParticleCollide(EntityUid uid, ParticleProjectileComponent component, StartCollideEvent args) { - if (args.OtherFixture.Body.Owner.TryGetComponent(out var singularityGeneratorComponent)) + if (EntityManager.TryGetComponent(args.OtherFixture.Body.Owner, out var singularityGeneratorComponent)) { singularityGeneratorComponent.Power += component.State switch { diff --git a/Content.Server/Singularity/EntitySystems/EmitterSystem.cs b/Content.Server/Singularity/EntitySystems/EmitterSystem.cs index 77dd0b3d05..e68c227a1a 100644 --- a/Content.Server/Singularity/EntitySystems/EmitterSystem.cs +++ b/Content.Server/Singularity/EntitySystems/EmitterSystem.cs @@ -44,7 +44,7 @@ namespace Content.Server.Singularity.EntitySystems return; } - if (component.Owner.TryGetComponent(out PhysicsComponent? phys) && phys.BodyType == BodyType.Static) + if (EntityManager.TryGetComponent(component.Owner, out PhysicsComponent? phys) && phys.BodyType == BodyType.Static) { if (!component.IsOn) { @@ -166,9 +166,9 @@ namespace Content.Server.Singularity.EntitySystems private void Fire(EmitterComponent component) { - var projectile = component.Owner.EntityManager.SpawnEntity(component.BoltType, component.Owner.Transform.Coordinates); + var projectile = EntityManager.SpawnEntity(component.BoltType, EntityManager.GetComponent(component.Owner).Coordinates); - if (!projectile.TryGetComponent(out var physicsComponent)) + if (!EntityManager.TryGetComponent(projectile, out var physicsComponent)) { Logger.Error("Emitter tried firing a bolt, but it was spawned without a PhysicsComponent"); return; @@ -176,7 +176,7 @@ namespace Content.Server.Singularity.EntitySystems physicsComponent.BodyStatus = BodyStatus.InAir; - if (!projectile.TryGetComponent(out var projectileComponent)) + if (!EntityManager.TryGetComponent(projectile, out var projectileComponent)) { Logger.Error("Emitter tried firing a bolt, but it was spawned without a ProjectileComponent"); return; @@ -185,11 +185,11 @@ namespace Content.Server.Singularity.EntitySystems projectileComponent.IgnoreEntity(component.Owner); physicsComponent - .LinearVelocity = component.Owner.Transform.WorldRotation.ToWorldVec() * 20f; - projectile.Transform.WorldRotation = component.Owner.Transform.WorldRotation; + .LinearVelocity = EntityManager.GetComponent(component.Owner).WorldRotation.ToWorldVec() * 20f; + EntityManager.GetComponent(projectile).WorldRotation = EntityManager.GetComponent(component.Owner).WorldRotation; // TODO: Move to projectile's code. - Timer.Spawn(3000, () => projectile.Delete()); + Timer.Spawn(3000, () => EntityManager.DeleteEntity(projectile)); SoundSystem.Play(Filter.Pvs(component.Owner), component.FireSound.GetSound(), component.Owner, AudioHelpers.WithVariation(EmitterComponent.Variation).WithVolume(EmitterComponent.Volume).WithMaxDistance(EmitterComponent.Distance)); diff --git a/Content.Server/Singularity/EntitySystems/SingularitySystem.cs b/Content.Server/Singularity/EntitySystems/SingularitySystem.cs index 4665461bbe..ed128475d6 100644 --- a/Content.Server/Singularity/EntitySystems/SingularitySystem.cs +++ b/Content.Server/Singularity/EntitySystems/SingularitySystem.cs @@ -82,7 +82,7 @@ namespace Content.Server.Singularity.EntitySystems { if (component.BeingDeletedByAnotherSingularity) return; - var worldPos = component.Owner.Transform.WorldPosition; + var worldPos = EntityManager.GetComponent(component.Owner).WorldPosition; DestroyEntities(component, worldPos); DestroyTiles(component, worldPos); PullEntities(component, worldPos); @@ -99,22 +99,22 @@ namespace Content.Server.Singularity.EntitySystems return component.Level - 0.5f; } - private bool CanDestroy(SharedSingularityComponent component, IEntity entity) + private bool CanDestroy(SharedSingularityComponent component, EntityUid entity) { return entity == component.Owner || - entity.HasComponent() || - entity.HasComponent() || - entity.HasComponent() || - entity.HasComponent(); + EntityManager.HasComponent(entity) || + EntityManager.HasComponent(entity) || + EntityManager.HasComponent(entity) || + EntityManager.HasComponent(entity); } - private void HandleDestroy(ServerSingularityComponent component, IEntity entity) + private void HandleDestroy(ServerSingularityComponent component, EntityUid entity) { // TODO: Need singuloimmune tag if (CanDestroy(component, entity)) return; // Singularity priority management / etc. - if (entity.TryGetComponent(out var otherSingulo)) + if (EntityManager.TryGetComponent(entity, out var otherSingulo)) { // MERGE if (!otherSingulo.BeingDeletedByAnotherSingularity) @@ -125,9 +125,9 @@ namespace Content.Server.Singularity.EntitySystems otherSingulo.BeingDeletedByAnotherSingularity = true; } - entity.QueueDelete(); + EntityManager.QueueDeleteEntity(entity); - if (entity.TryGetComponent(out var singuloFood)) + if (EntityManager.TryGetComponent(entity, out var singuloFood)) component.Energy += singuloFood.Energy; else component.Energy++; @@ -141,17 +141,17 @@ namespace Content.Server.Singularity.EntitySystems // The reason we don't /just/ use collision is because we'll be deleting stuff that may not necessarily have physics (e.g. carpets). var destroyRange = DestroyTileRange(component); - foreach (var entity in _lookup.GetEntitiesInRange(component.Owner.Transform.MapID, worldPos, destroyRange)) + foreach (var entity in _lookup.GetEntitiesInRange(EntityManager.GetComponent(component.Owner).MapID, worldPos, destroyRange)) { HandleDestroy(component, entity); } } - private bool CanPull(IEntity entity) + private bool CanPull(EntityUid entity) { - return !(entity.HasComponent() || - entity.HasComponent() || - entity.HasComponent() || + return !(EntityManager.HasComponent(entity) || + EntityManager.HasComponent(entity) || + EntityManager.HasComponent(entity) || entity.IsInContainer()); } @@ -162,16 +162,16 @@ namespace Content.Server.Singularity.EntitySystems var pullRange = PullRange(component); var destroyRange = DestroyTileRange(component); - foreach (var entity in _lookup.GetEntitiesInRange(component.Owner.Transform.MapID, worldPos, pullRange)) + foreach (var entity in _lookup.GetEntitiesInRange(EntityManager.GetComponent(component.Owner).MapID, worldPos, pullRange)) { // I tried having it so level 6 can de-anchor. BAD IDEA, MASSIVE LAG. if (entity == component.Owner || - !entity.TryGetComponent(out var collidableComponent) || + !EntityManager.TryGetComponent(entity, out var collidableComponent) || collidableComponent.BodyType == BodyType.Static) continue; if (!CanPull(entity)) continue; - var vec = worldPos - entity.Transform.WorldPosition; + var vec = worldPos - EntityManager.GetComponent(entity).WorldPosition; if (vec.Length < destroyRange - 0.01f) continue; @@ -192,7 +192,7 @@ namespace Content.Server.Singularity.EntitySystems var circle = new Circle(worldPos, radius); var box = new Box2(worldPos - radius, worldPos + radius); - foreach (var grid in _mapManager.FindGridsIntersecting(component.Owner.Transform.MapID, box)) + foreach (var grid in _mapManager.FindGridsIntersecting(EntityManager.GetComponent(component.Owner).MapID, box)) { foreach (var tile in grid.GetTilesIntersecting(circle)) { diff --git a/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs b/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs index bef808674a..4030f057e6 100644 --- a/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs +++ b/Content.Server/Solar/EntitySystems/PowerSolarSystem.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using System.Linq; using Content.Server.Power.Components; using Content.Server.Solar.Components; -using Content.Shared.Physics; using Content.Shared.GameTicking; +using Content.Shared.Physics; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -112,17 +112,19 @@ namespace Content.Server.Solar.EntitySystems else { TotalPanelPower = 0; - foreach (var panel in EntityManager.EntityQuery()) + foreach (var (panel, xform) in EntityManager.EntityQuery()) { TotalPanelPower += panel.MaxSupply * panel.Coverage; - panel.Owner.Transform.WorldRotation = TargetPanelRotation; + xform.WorldRotation = TargetPanelRotation; _updateQueue.Enqueue(panel); } } } - private void UpdatePanelCoverage(SolarPanelComponent panel) { - IEntity entity = panel.Owner; + private void UpdatePanelCoverage(SolarPanelComponent panel) + { + EntityUid entity = panel.Owner; + var xform = EntityManager.GetComponent(entity); // So apparently, and yes, I *did* only find this out later, // this is just a really fancy way of saying "Lambert's law of cosines". @@ -136,7 +138,7 @@ namespace Content.Server.Solar.EntitySystems // directly downwards (abs(theta) = pi) = coverage -1 // as TowardsSun + = CCW, // panelRelativeToSun should - = CW - var panelRelativeToSun = entity.Transform.WorldRotation - TowardsSun; + var panelRelativeToSun = xform.WorldRotation - TowardsSun; // essentially, given cos = X & sin = Y & Y is 'downwards', // then for the first 90 degrees of rotation in either direction, // this plots the lower-right quadrant of a circle. @@ -154,19 +156,19 @@ namespace Content.Server.Solar.EntitySystems if (coverage > 0) { // Determine if the solar panel is occluded, and zero out coverage if so. - var ray = new CollisionRay(entity.Transform.WorldPosition, TowardsSun.ToWorldVec(), (int) CollisionGroup.Opaque); + var ray = new CollisionRay(xform.WorldPosition, TowardsSun.ToWorldVec(), (int) CollisionGroup.Opaque); var rayCastResults = _physicsSystem.IntersectRayWithPredicate( - entity.Transform.MapID, + xform.MapID, ray, SunOcclusionCheckDistance, - e => !e.Transform.Anchored || e == entity); + e => !xform.Anchored || e == entity); if (rayCastResults.Any()) coverage = 0; } // Total coverage calculated; apply it to the panel. panel.Coverage = coverage; - UpdateSupply(panel.OwnerUid, panel); + UpdateSupply((panel).Owner, panel); } public void UpdateSupply( diff --git a/Content.Server/Spawners/Components/ConditionalSpawnerComponent.cs b/Content.Server/Spawners/Components/ConditionalSpawnerComponent.cs index 4c9936494c..31a1b566be 100644 --- a/Content.Server/Spawners/Components/ConditionalSpawnerComponent.cs +++ b/Content.Server/Spawners/Components/ConditionalSpawnerComponent.cs @@ -12,6 +12,7 @@ namespace Content.Server.Spawners.Components [RegisterComponent] public class ConditionalSpawnerComponent : Component, IMapInit { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _robustRandom = default!; public override string Name => "ConditionalSpawner"; @@ -61,8 +62,8 @@ namespace Content.Server.Spawners.Components return; } - if(!Owner.Deleted) - Owner.EntityManager.SpawnEntity(_robustRandom.Pick(Prototypes), Owner.Transform.Coordinates); + if(_entMan.Deleted(Owner)) + _entMan.SpawnEntity(_robustRandom.Pick(Prototypes), _entMan.GetComponent(Owner).Coordinates); } public virtual void MapInit() diff --git a/Content.Server/Spawners/Components/RandomSpawnerComponent.cs b/Content.Server/Spawners/Components/RandomSpawnerComponent.cs index 8aba08a4f2..bae54820e9 100644 --- a/Content.Server/Spawners/Components/RandomSpawnerComponent.cs +++ b/Content.Server/Spawners/Components/RandomSpawnerComponent.cs @@ -12,6 +12,7 @@ namespace Content.Server.Spawners.Components [RegisterComponent] public class RandomSpawnerComponent : ConditionalSpawnerComponent { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _robustRandom = default!; public override string Name => "RandomSpawner"; @@ -32,7 +33,7 @@ namespace Content.Server.Spawners.Components { if (RarePrototypes.Count > 0 && (RareChance == 1.0f || _robustRandom.Prob(RareChance))) { - Owner.EntityManager.SpawnEntity(_robustRandom.Pick(RarePrototypes), Owner.Transform.Coordinates); + _entMan.SpawnEntity(_robustRandom.Pick(RarePrototypes), _entMan.GetComponent(Owner).Coordinates); return; } @@ -47,15 +48,15 @@ namespace Content.Server.Spawners.Components return; } - if(!Owner.Deleted) + if(!_entMan.Deleted(Owner)) { var random = IoCManager.Resolve(); var x_negative = random.Prob(0.5f) ? -1 : 1; var y_negative = random.Prob(0.5f) ? -1 : 1; - var entity = Owner.EntityManager.SpawnEntity(_robustRandom.Pick(Prototypes), Owner.Transform.Coordinates); - entity.Transform.LocalPosition += new Vector2(random.NextFloat() * Offset * x_negative, random.NextFloat() * Offset * y_negative); + var entity = _entMan.SpawnEntity(_robustRandom.Pick(Prototypes), _entMan.GetComponent(Owner).Coordinates); + _entMan.GetComponent(entity).LocalPosition += new Vector2(random.NextFloat() * Offset * x_negative, random.NextFloat() * Offset * y_negative); } } @@ -63,7 +64,7 @@ namespace Content.Server.Spawners.Components public override void MapInit() { Spawn(); - Owner.Delete(); + _entMan.DeleteEntity(Owner); } } } diff --git a/Content.Server/Spawners/Components/TimedSpawnerComponent.cs b/Content.Server/Spawners/Components/TimedSpawnerComponent.cs index ff804342d5..64296fb7dc 100644 --- a/Content.Server/Spawners/Components/TimedSpawnerComponent.cs +++ b/Content.Server/Spawners/Components/TimedSpawnerComponent.cs @@ -76,7 +76,7 @@ namespace Content.Server.Spawners.Components for (int i = 0; i < number; i++) { var entity = _robustRandom.Pick(Prototypes); - Owner.EntityManager.SpawnEntity(entity, Owner.Transform.Coordinates); + IoCManager.Resolve().SpawnEntity(entity, IoCManager.Resolve().GetComponent(Owner).Coordinates); } } } diff --git a/Content.Server/Sprite/Components/RandomSpriteColorComponent.cs b/Content.Server/Sprite/Components/RandomSpriteColorComponent.cs index 13db3ca25c..4dca98070b 100644 --- a/Content.Server/Sprite/Components/RandomSpriteColorComponent.cs +++ b/Content.Server/Sprite/Components/RandomSpriteColorComponent.cs @@ -36,7 +36,7 @@ namespace Content.Server.Sprite.Components private void UpdateColor() { - if (Owner.TryGetComponent(out SpriteComponent? spriteComponent) && _selectedColor != null) + if (IoCManager.Resolve().TryGetComponent(Owner, out SpriteComponent? spriteComponent) && _selectedColor != null) { spriteComponent.LayerSetState(0, _baseState); spriteComponent.LayerSetColor(0, _colors[_selectedColor]); diff --git a/Content.Server/Sprite/Components/RandomSpriteStateComponent.cs b/Content.Server/Sprite/Components/RandomSpriteStateComponent.cs index 6dcfd5c86c..eafeede655 100644 --- a/Content.Server/Sprite/Components/RandomSpriteStateComponent.cs +++ b/Content.Server/Sprite/Components/RandomSpriteStateComponent.cs @@ -23,7 +23,7 @@ namespace Content.Server.Sprite.Components { base.Initialize(); if (_spriteStates == null) return; - if (!Owner.TryGetComponent(out SpriteComponent? spriteComponent)) return; + if (!IoCManager.Resolve().TryGetComponent(Owner, out SpriteComponent? spriteComponent)) return; spriteComponent.LayerSetState(_spriteLayer, _random.Pick(_spriteStates)); } } diff --git a/Content.Server/Stack/StackSystem.cs b/Content.Server/Stack/StackSystem.cs index 1caafeb1cc..1b4bb1b028 100644 --- a/Content.Server/Stack/StackSystem.cs +++ b/Content.Server/Stack/StackSystem.cs @@ -1,11 +1,8 @@ using System; -using System.Collections.Generic; -using System.Collections.Immutable; using Content.Server.Hands.Components; using Content.Server.Items; using Content.Server.Popups; using Content.Shared.Interaction; -using Content.Shared.Popups; using Content.Shared.Stacks; using Content.Shared.Verbs; using JetBrains.Annotations; @@ -40,24 +37,24 @@ namespace Content.Server.Stack } /// - /// Try to split this stack into two. Returns a non-null if successful. + /// Try to split this stack into two. Returns a non-null if successful. /// public EntityUid? Split(EntityUid uid, int amount, EntityCoordinates spawnPosition, SharedStackComponent? stack = null) { if (!Resolve(uid, ref stack)) - return null; + return default; // Get a prototype ID to spawn the new entity. Null is also valid, although it should rarely be picked... var prototype = _prototypeManager.TryIndex(stack.StackTypeId, out var stackType) ? stackType.Spawn - : stack.Owner.Prototype?.ID; + : EntityManager.GetComponent(stack.Owner).EntityPrototype?.ID; // Try to remove the amount of things we want to split from the original stack... if (!Use(uid, amount, stack)) - return null; + return default; // Set the output parameter in the event instance to the newly split stack. - var entity = EntityManager.SpawnEntity(prototype, spawnPosition).Uid; + var entity = EntityManager.SpawnEntity(prototype, spawnPosition); if (EntityManager.TryGetComponent(entity, out SharedStackComponent? stackComp)) { @@ -76,7 +73,7 @@ namespace Content.Server.Stack public EntityUid Spawn(int amount, StackPrototype prototype, EntityCoordinates spawnPosition) { // Set the output result parameter to the new stack entity... - var entity = EntityManager.SpawnEntity(prototype.Spawn, spawnPosition).Uid; + var entity = EntityManager.SpawnEntity(prototype.Spawn, spawnPosition); var stack = EntityManager.GetComponent(entity); // And finally, set the correct amount! @@ -89,7 +86,7 @@ namespace Content.Server.Stack if (args.Handled) return; - if (!args.Used.TryGetComponent(out var otherStack)) + if (!EntityManager.TryGetComponent(args.Used, out var otherStack)) return; if (!otherStack.StackTypeId.Equals(stack.StackTypeId)) @@ -97,16 +94,16 @@ namespace Content.Server.Stack var toTransfer = Math.Min(stack.Count, otherStack.AvailableSpace); SetCount(uid, stack.Count - toTransfer, stack); - SetCount(args.Used.Uid, otherStack.Count + toTransfer, otherStack); + SetCount(args.Used, otherStack.Count + toTransfer, otherStack); var popupPos = args.ClickLocation; if (!popupPos.IsValid(EntityManager)) { - popupPos = args.User.Transform.Coordinates; + popupPos = EntityManager.GetComponent(args.User).Coordinates; } - var filter = Filter.Entities(args.User.Uid); + var filter = Filter.Entities(args.User); switch (toTransfer) { @@ -137,7 +134,7 @@ namespace Content.Server.Stack Verb halve = new(); halve.Text = Loc.GetString("comp-stack-split-halve"); halve.Category = VerbCategory.Split; - halve.Act = () => UserSplit(uid, args.User.Uid, stack.Count / 2, stack); + halve.Act = () => UserSplit(uid, args.User, stack.Count / 2, stack); halve.Priority = 1; args.Verbs.Add(halve); @@ -150,7 +147,7 @@ namespace Content.Server.Stack Verb verb = new(); verb.Text = amount.ToString(); verb.Category = VerbCategory.Split; - verb.Act = () => UserSplit(uid, args.User.Uid, amount, stack); + verb.Act = () => UserSplit(uid, args.User, amount, stack); // we want to sort by size, not alphabetically by the verb text. verb.Priority = priority; @@ -188,10 +185,10 @@ namespace Content.Server.Stack return; } - if(Split(uid, amount, userTransform.Coordinates, stack) is not {} splitStack) + if (Split(uid, amount, userTransform.Coordinates, stack) is not {Valid: true} split) return; - if (EntityManager.TryGetComponent(splitStack, out var item)) + if (EntityManager.TryGetComponent(split, out var item)) { hands.PutInHandOrDrop(item); } diff --git a/Content.Server/Standing/StandingStateSystem.cs b/Content.Server/Standing/StandingStateSystem.cs index d92da48a8a..3db2003236 100644 --- a/Content.Server/Standing/StandingStateSystem.cs +++ b/Content.Server/Standing/StandingStateSystem.cs @@ -16,19 +16,19 @@ public class StandingStateSystem : EntitySystem var direction = EntityManager.TryGetComponent(uid, out PhysicsComponent? comp) ? comp.LinearVelocity / 50 : Vector2.Zero; var dropAngle = _random.NextFloat(0.8f, 1.2f); - if (EntityManager.TryGetComponent(uid, out HandsComponent? hands)) + if (!EntityManager.TryGetComponent(uid, out HandsComponent? hands)) + return; + + foreach (var heldItem in hands.GetAllHeldItems()) { - foreach (var heldItem in hands.GetAllHeldItems()) - { - if (hands.Drop(heldItem.Owner)) - { - Throwing.ThrowHelper.TryThrow(heldItem.Owner, - _random.NextAngle().RotateVec(direction / dropAngle + - EntityManager.GetEntity(uid).Transform.WorldRotation.ToVec() / 50), - 0.5f * dropAngle * _random.NextFloat(-0.9f, 1.1f), - EntityManager.GetEntity(uid), 0); - } - } + if (!hands.Drop(heldItem.Owner)) + continue; + + var worldRotation = EntityManager.GetComponent(uid).WorldRotation.ToVec(); + Throwing.ThrowHelper.TryThrow(heldItem.Owner, + _random.NextAngle().RotateVec(direction / dropAngle + worldRotation / 50), + 0.5f * dropAngle * _random.NextFloat(-0.9f, 1.1f), + uid, 0); } } diff --git a/Content.Server/StationEvents/Events/GasLeak.cs b/Content.Server/StationEvents/Events/GasLeak.cs index 8f306e1c49..56151e4692 100644 --- a/Content.Server/StationEvents/Events/GasLeak.cs +++ b/Content.Server/StationEvents/Events/GasLeak.cs @@ -1,6 +1,4 @@ -using System.Linq; using Content.Server.Atmos.EntitySystems; -using Content.Server.Station; using Content.Shared.Atmos; using Content.Shared.Station; using Robust.Shared.Audio; @@ -16,18 +14,18 @@ namespace Content.Server.StationEvents.Events { internal sealed class GasLeak : StationEvent { - [Dependency] private IRobustRandom _robustRandom = default!; - [Dependency] private IEntityManager _entityManager = default!; + [Dependency] private readonly IRobustRandom _robustRandom = default!; + [Dependency] private readonly IEntityManager _entityManager = default!; public override string Name => "GasLeak"; - public override string? StartAnnouncement => + public override string StartAnnouncement => "Attention crew, there is a gas leak on the station. We advise you to avoid the area and wear suit internals in the meantime."; // Sourced from https://github.com/vgstation-coders/vgstation13/blob/2c5a491446ab824a8fbbf39bcf656b590e0228df/sound/misc/bloblarm.ogg - public override string? StartAudio => "/Audio/Announcements/bloblarm.ogg"; + public override string StartAudio => "/Audio/Announcements/bloblarm.ogg"; - protected override string? EndAnnouncement => "The source of the gas leak has been fixed. Please be cautious around areas with gas remaining."; + protected override string EndAnnouncement => "The source of the gas leak has been fixed. Please be cautious around areas with gas remaining."; private static readonly Gas[] LeakableGases = { Gas.Plasma, @@ -62,7 +60,7 @@ namespace Content.Server.StationEvents.Events private StationId _targetStation; - private IEntity? _targetGrid; + private EntityUid _targetGrid; private Vector2i _targetTile; @@ -122,15 +120,15 @@ namespace Content.Server.StationEvents.Events var atmosphereSystem = EntitySystem.Get(); if (!_foundTile || - _targetGrid == null || - _targetGrid.Deleted || - !atmosphereSystem.IsSimulatedGrid(_targetGrid.Transform.GridID)) + _targetGrid == default || + _entityManager.Deleted(_targetGrid) || + !atmosphereSystem.IsSimulatedGrid(_entityManager.GetComponent(_targetGrid).GridID)) { Running = false; return; } - var environment = atmosphereSystem.GetTileMixture(_targetGrid.Transform.GridID, _targetTile, true); + var environment = atmosphereSystem.GetTileMixture(_entityManager.GetComponent(_targetGrid).GridID, _targetTile, true); environment?.AdjustMoles(_leakGas, LeakCooldown * _molesPerSecond); } @@ -142,7 +140,7 @@ namespace Content.Server.StationEvents.Events Spark(); _foundTile = false; - _targetGrid = null; + _targetGrid = default; _targetTile = default; _targetCoords = default; _leakGas = Gas.Oxygen; @@ -155,16 +153,16 @@ namespace Content.Server.StationEvents.Events if (_robustRandom.NextFloat() <= SparkChance) { if (!_foundTile || - _targetGrid == null || - _targetGrid.Deleted || - !atmosphereSystem.IsSimulatedGrid(_targetGrid.Transform.GridID)) + _targetGrid == default || + (!_entityManager.EntityExists(_targetGrid) ? EntityLifeStage.Deleted : _entityManager.GetComponent(_targetGrid).EntityLifeStage) >= EntityLifeStage.Deleted || + !atmosphereSystem.IsSimulatedGrid(_entityManager.GetComponent(_targetGrid).GridID)) { return; } // Don't want it to be so obnoxious as to instantly murder anyone in the area but enough that // it COULD start potentially start a bigger fire. - atmosphereSystem.HotspotExpose(_targetGrid.Transform.GridID, _targetTile, 700f, 50f, true); + atmosphereSystem.HotspotExpose(_entityManager.GetComponent(_targetGrid).GridID, _targetTile, 700f, 50f, true); SoundSystem.Play(Filter.Pvs(_targetCoords), "/Audio/Effects/sparks4.ogg", _targetCoords); } } diff --git a/Content.Server/StationEvents/Events/KudzuGrowth.cs b/Content.Server/StationEvents/Events/KudzuGrowth.cs index 2b3b730693..edc89abff4 100644 --- a/Content.Server/StationEvents/Events/KudzuGrowth.cs +++ b/Content.Server/StationEvents/Events/KudzuGrowth.cs @@ -1,4 +1,3 @@ -using Content.Shared.Station; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; @@ -31,7 +30,7 @@ public class KudzuGrowth : StationEvent // Give crew at least 9 minutes to either have it gone, or to suffer another event. Kudzu is not actually required to be dead for another event to roll. protected override float EndAfter => 60*4; - private IEntity? _targetGrid; + private EntityUid _targetGrid; private Vector2i _targetTile; diff --git a/Content.Server/StationEvents/Events/MeteorSwarm.cs b/Content.Server/StationEvents/Events/MeteorSwarm.cs index d1efd54eec..6ff7124c49 100644 --- a/Content.Server/StationEvents/Events/MeteorSwarm.cs +++ b/Content.Server/StationEvents/Events/MeteorSwarm.cs @@ -111,7 +111,7 @@ namespace Content.Server.StationEvents.Events var offset = angle.RotateVec(new Vector2((maximumDistance - minimumDistance) * _robustRandom.NextFloat() + minimumDistance, 0)); var spawnPosition = new MapCoordinates(center + offset, mapId); var meteor = _entityManager.SpawnEntity("MeteorLarge", spawnPosition); - var physics = _entityManager.GetComponent(meteor.Uid); + var physics = _entityManager.GetComponent(meteor); physics.BodyStatus = BodyStatus.InAir; physics.LinearDamping = 0f; physics.AngularDamping = 0f; @@ -121,7 +121,7 @@ namespace Content.Server.StationEvents.Events physics.Mass * ((MaxAngularVelocity - MinAngularVelocity) * _robustRandom.NextFloat() + MinAngularVelocity)); // TODO: God this disgusts me but projectile needs a refactor. - meteor.GetComponent().TimeLeft = 120f; + IoCManager.Resolve().GetComponent(meteor).TimeLeft = 120f; } } } diff --git a/Content.Server/StationEvents/Events/PowerGridCheck.cs b/Content.Server/StationEvents/Events/PowerGridCheck.cs index 43e632b975..b9e65a5bbe 100644 --- a/Content.Server/StationEvents/Events/PowerGridCheck.cs +++ b/Content.Server/StationEvents/Events/PowerGridCheck.cs @@ -28,7 +28,7 @@ namespace Content.Server.StationEvents.Events private CancellationTokenSource? _announceCancelToken; - private readonly List _powered = new(); + private readonly List _powered = new(); public override void Announce() { @@ -51,11 +51,13 @@ namespace Content.Server.StationEvents.Events public override void Shutdown() { + var entMan = IoCManager.Resolve(); + foreach (var entity in _powered) { - if (entity.Deleted) continue; + if (entMan.Deleted(entity)) continue; - if (entity.TryGetComponent(out ApcPowerReceiverComponent? powerReceiverComponent)) + if (entMan.TryGetComponent(entity, out ApcPowerReceiverComponent? powerReceiverComponent)) { powerReceiverComponent.PowerDisabled = false; } diff --git a/Content.Server/StationEvents/Events/RadiationStorm.cs b/Content.Server/StationEvents/Events/RadiationStorm.cs index 725df773a3..fc4dc173a4 100644 --- a/Content.Server/StationEvents/Events/RadiationStorm.cs +++ b/Content.Server/StationEvents/Events/RadiationStorm.cs @@ -70,7 +70,8 @@ namespace Content.Server.StationEvents.Events // Account for split stations by just randomly picking a piece of it. var possibleTargets = _entityManager.EntityQuery() .Where(x => x.Station == _target).ToArray(); - var stationEnt = _robustRandom.Pick(possibleTargets).OwnerUid; + StationComponent tempQualifier = _robustRandom.Pick(possibleTargets); + var stationEnt = (tempQualifier).Owner; if (!_entityManager.TryGetComponent(stationEnt, out var grid)) return; @@ -88,15 +89,15 @@ namespace Content.Server.StationEvents.Events return; var pulse = _entityManager.SpawnEntity("RadiationPulse", coordinates); - pulse.GetComponent().DoPulse(); + _entityManager.GetComponent(pulse).DoPulse(); ResetTimeUntilPulse(); } - public static void SpawnPulseAt(EntityCoordinates at) + public void SpawnPulseAt(EntityCoordinates at) { var pulse = IoCManager.Resolve() .SpawnEntity("RadiationPulse", at); - pulse.GetComponent().DoPulse(); + _entityManager.GetComponent(pulse).DoPulse(); } private bool TryFindRandomGrid(IMapGrid mapGrid, out EntityCoordinates coordinates) diff --git a/Content.Server/StationEvents/Events/StationEvent.cs b/Content.Server/StationEvents/Events/StationEvent.cs index edd085d499..95303fdffa 100644 --- a/Content.Server/StationEvents/Events/StationEvent.cs +++ b/Content.Server/StationEvents/Events/StationEvent.cs @@ -3,9 +3,8 @@ using Content.Server.Administration.Logs; using Content.Server.Atmos.EntitySystems; using Content.Server.Chat.Managers; using Content.Server.Station; -using Content.Shared.Administration.Logs; -using Content.Shared.Station; using Content.Shared.Database; +using Content.Shared.Station; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -187,7 +186,7 @@ namespace Content.Server.StationEvents.Events } - public static bool TryFindRandomTile(out Vector2i tile, out StationId targetStation, out IEntity? targetGrid, out EntityCoordinates targetCoords, IRobustRandom? robustRandom = null, IEntityManager? entityManager = null) + public static bool TryFindRandomTile(out Vector2i tile, out StationId targetStation, out EntityUid targetGrid, out EntityCoordinates targetCoords, IRobustRandom? robustRandom = null, IEntityManager? entityManager = null) { tile = default; robustRandom ??= IoCManager.Resolve(); @@ -200,7 +199,7 @@ namespace Content.Server.StationEvents.Events .Where(x => x.Station == t).ToArray(); targetGrid = robustRandom.Pick(possibleTargets).Owner; - if (!entityManager.TryGetComponent(targetGrid!.Uid, out var gridComp)) + if (!entityManager.TryGetComponent(targetGrid!, out var gridComp)) return false; var grid = gridComp.Grid; diff --git a/Content.Server/Storage/Components/CursedEntityStorageComponent.cs b/Content.Server/Storage/Components/CursedEntityStorageComponent.cs index cd51d95045..061e471b28 100644 --- a/Content.Server/Storage/Components/CursedEntityStorageComponent.cs +++ b/Content.Server/Storage/Components/CursedEntityStorageComponent.cs @@ -17,6 +17,7 @@ namespace Content.Server.Storage.Components [RegisterComponent] public class CursedEntityStorageComponent : EntityStorageComponent { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _robustRandom = default!; public override string Name => "CursedEntityStorage"; @@ -31,7 +32,7 @@ namespace Content.Server.Storage.Components // No contents, we do nothing if (Contents.ContainedEntities.Count == 0) return; - var lockers = Owner.EntityManager.EntityQuery().Select(c => c.Owner).ToList(); + var lockers = _entMan.EntityQuery().Select(c => c.Owner).ToList(); if (lockers.Contains(Owner)) lockers.Remove(Owner); @@ -40,7 +41,7 @@ namespace Content.Server.Storage.Components if (lockerEnt == null) return; // No valid lockers anywhere. - var locker = lockerEnt.GetComponent(); + var locker = _entMan.GetComponent(lockerEnt); if (locker.Open) locker.TryCloseStorage(Owner); diff --git a/Content.Server/Storage/Components/EntityStorageComponent.cs b/Content.Server/Storage/Components/EntityStorageComponent.cs index edba41b62c..3bdd3cf325 100644 --- a/Content.Server/Storage/Components/EntityStorageComponent.cs +++ b/Content.Server/Storage/Components/EntityStorageComponent.cs @@ -2,10 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Content.Server.Tools; using Content.Server.Ghost.Components; -using Content.Server.Tools.Components; -using Content.Shared.ActionBlocker; +using Content.Server.Tools; using Content.Shared.Acts; using Content.Shared.Body.Components; using Content.Shared.Interaction; @@ -16,8 +14,6 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Content.Shared.Storage; using Content.Shared.Tools; -using Content.Shared.Tools.Components; -using Content.Shared.Verbs; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; @@ -37,6 +33,8 @@ namespace Content.Server.Storage.Components [ComponentReference(typeof(IStorageComponent))] public class EntityStorageComponent : Component, IActivate, IStorageComponent, IInteractUsing, IDestroyAct, IExAct { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "EntityStorage"; private const float MaxSize = 1.0f; // maximum width or height of an entity allowed inside the storage. @@ -152,9 +150,9 @@ namespace Content.Server.Storage.Components Contents.ShowContents = _showContents; Contents.OccludesLight = _occludesLight; - if (Owner.TryGetComponent(out var surface)) + if (_entMan.TryGetComponent(Owner, out var surface)) { - EntitySystem.Get().SetPlaceable(Owner.Uid, Open, surface); + EntitySystem.Get().SetPlaceable(Owner, Open, surface); } UpdateAppearance(); @@ -165,7 +163,7 @@ namespace Content.Server.Storage.Components ToggleOpen(eventArgs.User); } - public virtual bool CanOpen(IEntity user, bool silent = false) + public virtual bool CanOpen(EntityUid user, bool silent = false) { if (IsWeldedShut) { @@ -173,7 +171,7 @@ namespace Content.Server.Storage.Components return false; } - if (Owner.TryGetComponent(out var @lock) && @lock.Locked) + if (_entMan.TryGetComponent(Owner, out var @lock) && @lock.Locked) { if (!silent) Owner.PopupMessage(user, Loc.GetString("entity-storage-component-locked-message")); return false; @@ -182,12 +180,12 @@ namespace Content.Server.Storage.Components return true; } - public virtual bool CanClose(IEntity user, bool silent = false) + public virtual bool CanClose(EntityUid user, bool silent = false) { return true; } - public void ToggleOpen(IEntity user) + public void ToggleOpen(EntityUid user) { if (Open) { @@ -218,14 +216,14 @@ namespace Content.Server.Storage.Components // 5. if this is NOT AN ITEM, then mobs can always be eaten unless unless a previous law prevents it // Let's not insert admin ghosts, yeah? This is really a a hack and should be replaced by attempt events - if (Owner.EntityManager.HasComponent(entity.Uid)) + if (_entMan.HasComponent(entity)) continue; // checks - var targetIsItem = Owner.EntityManager.HasComponent(entity.Uid); - var targetIsMob = Owner.EntityManager.HasComponent(entity.Uid); - var storageIsItem = Owner.EntityManager.HasComponent(OwnerUid); + var targetIsItem = _entMan.HasComponent(entity); + var targetIsMob = _entMan.HasComponent(entity); + var storageIsItem = _entMan.HasComponent(Owner); var allowedToEat = false; @@ -270,7 +268,7 @@ namespace Content.Server.Storage.Components private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(StorageVisuals.CanWeld, _canWeldShut); appearance.SetData(StorageVisuals.Welded, _isWeldedShut); @@ -279,7 +277,7 @@ namespace Content.Server.Storage.Components private void ModifyComponents() { - if (!_isCollidableWhenOpen && Owner.TryGetComponent(out var manager)) + if (!_isCollidableWhenOpen && _entMan.TryGetComponent(Owner, out var manager)) { if (Open) { @@ -297,21 +295,21 @@ namespace Content.Server.Storage.Components } } - if (Owner.TryGetComponent(out var surface)) + if (_entMan.TryGetComponent(Owner, out var surface)) { - EntitySystem.Get().SetPlaceable(Owner.Uid, Open, surface); + EntitySystem.Get().SetPlaceable(Owner, Open, surface); } - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(StorageVisuals.Open, Open); } } - protected virtual bool AddToContents(IEntity entity) + protected virtual bool AddToContents(EntityUid entity) { if (entity == Owner) return false; - if (entity.TryGetComponent(out IPhysBody? entityPhysicsComponent)) + if (_entMan.TryGetComponent(entity, out IPhysBody? entityPhysicsComponent)) { if (MaxSize < entityPhysicsComponent.GetWorldAABB().Size.X || MaxSize < entityPhysicsComponent.GetWorldAABB().Size.Y) @@ -325,7 +323,7 @@ namespace Content.Server.Storage.Components public virtual Vector2 ContentsDumpPosition() { - return Owner.Transform.WorldPosition; + return _entMan.GetComponent(Owner).WorldPosition; } private void EmptyContents() @@ -334,8 +332,8 @@ namespace Content.Server.Storage.Components { if (Contents.Remove(contained)) { - contained.Transform.WorldPosition = ContentsDumpPosition(); - if (contained.TryGetComponent(out var physics)) + _entMan.GetComponent(contained).WorldPosition = ContentsDumpPosition(); + if (_entMan.TryGetComponent(contained, out var physics)) { physics.CanCollide = true; } @@ -343,14 +341,14 @@ namespace Content.Server.Storage.Components } } - public virtual bool TryOpenStorage(IEntity user) + public virtual bool TryOpenStorage(EntityUid user) { if (!CanOpen(user)) return false; OpenStorage(); return true; } - public virtual bool TryCloseStorage(IEntity user) + public virtual bool TryCloseStorage(EntityUid user) { if (!CanClose(user)) return false; CloseStorage(); @@ -358,18 +356,19 @@ namespace Content.Server.Storage.Components } /// - public bool Remove(IEntity entity) + public bool Remove(EntityUid entity) { return Contents.CanRemove(entity); } /// - public bool Insert(IEntity entity) + public bool Insert(EntityUid entity) { // Trying to add while open just dumps it on the ground below us. if (Open) { - entity.Transform.WorldPosition = Owner.Transform.WorldPosition; + var entMan = _entMan; + entMan.GetComponent(entity).WorldPosition = entMan.GetComponent(Owner).WorldPosition; return true; } @@ -377,7 +376,7 @@ namespace Content.Server.Storage.Components } /// - public bool CanInsert(IEntity entity) + public bool CanInsert(EntityUid entity) { if (Open) { @@ -423,7 +422,7 @@ namespace Content.Server.Storage.Components var toolSystem = EntitySystem.Get(); - if (!await toolSystem.UseTool(eventArgs.Using.Uid, eventArgs.User.Uid, Owner.Uid, 1f, 1f, _weldingQuality)) + if (!await toolSystem.UseTool(eventArgs.Using, eventArgs.User, Owner, 1f, 1f, _weldingQuality)) { _beingWelded = false; return false; @@ -440,7 +439,7 @@ namespace Content.Server.Storage.Components EmptyContents(); } - protected virtual IEnumerable DetermineCollidingEntities() + protected virtual IEnumerable DetermineCollidingEntities() { var entityLookup = IoCManager.Resolve(); return entityLookup.GetEntitiesIntersecting(Owner, -0.015f, LookupFlags.Approximate); @@ -456,7 +455,7 @@ namespace Content.Server.Storage.Components var containedEntities = Contents.ContainedEntities.ToList(); foreach (var entity in containedEntities) { - var exActs = entity.GetAllComponents().ToArray(); + var exActs = _entMan.GetComponents(entity).ToArray(); foreach (var exAct in exActs) { exAct.OnExplosion(eventArgs); diff --git a/Content.Server/Storage/Components/IStorageComponent.cs b/Content.Server/Storage/Components/IStorageComponent.cs index c2169695c5..52f0388479 100644 --- a/Content.Server/Storage/Components/IStorageComponent.cs +++ b/Content.Server/Storage/Components/IStorageComponent.cs @@ -4,8 +4,8 @@ namespace Content.Server.Storage.Components { public interface IStorageComponent : IComponent { - bool Remove(IEntity entity); - bool Insert(IEntity entity); - bool CanInsert(IEntity entity); + bool Remove(EntityUid entity); + bool Insert(EntityUid entity); + bool CanInsert(EntityUid entity); } } diff --git a/Content.Server/Storage/Components/SecretStashComponent.cs b/Content.Server/Storage/Components/SecretStashComponent.cs index 4b3c705755..30e8992a59 100644 --- a/Content.Server/Storage/Components/SecretStashComponent.cs +++ b/Content.Server/Storage/Components/SecretStashComponent.cs @@ -5,6 +5,7 @@ using Content.Shared.Item; using Content.Shared.Popups; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -17,6 +18,8 @@ namespace Content.Server.Storage.Components [RegisterComponent] public class SecretStashComponent : Component, IDestroyAct { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "SecretStash"; [ViewVariables] [DataField("maxItemSize")] @@ -27,7 +30,7 @@ namespace Content.Server.Storage.Components [ViewVariables] private ContainerSlot _itemContainer = default!; - public string SecretPartName => _secretPartNameOverride ?? Loc.GetString("comp-secret-stash-secret-part-name", ("name", Owner.Name)); + public string SecretPartName => _secretPartNameOverride ?? Loc.GetString("comp-secret-stash-secret-part-name", ("name", _entMan.GetComponent(Owner).EntityName)); protected override void Initialize() { @@ -41,7 +44,7 @@ namespace Content.Server.Storage.Components /// /// /// True if item was hidden inside stash - public bool TryHideItem(IEntity user, IEntity itemToHide) + public bool TryHideItem(EntityUid user, EntityUid itemToHide) { if (_itemContainer.ContainedEntity != null) { @@ -49,7 +52,7 @@ namespace Content.Server.Storage.Components return false; } - if (!itemToHide.TryGetComponent(out ItemComponent? item)) + if (!_entMan.TryGetComponent(itemToHide, out ItemComponent? item)) return false; if (item.Size > _maxItemSize) @@ -59,7 +62,7 @@ namespace Content.Server.Storage.Components return false; } - if (!user.TryGetComponent(out HandsComponent? hands)) + if (!_entMan.TryGetComponent(user, out HandsComponent? hands)) return false; if (!hands.Drop(itemToHide, _itemContainer)) @@ -75,22 +78,22 @@ namespace Content.Server.Storage.Components /// /// /// True if user recieved item - public bool TryGetItem(IEntity user) + public bool TryGetItem(EntityUid user) { - if (_itemContainer.ContainedEntity == null) + if (_itemContainer.ContainedEntity is not {Valid: true} contained) return false; Owner.PopupMessage(user, Loc.GetString("comp-secret-stash-action-get-item-found-something", ("stash", SecretPartName))); - if (user.TryGetComponent(out HandsComponent? hands)) + if (_entMan.TryGetComponent(user, out HandsComponent? hands)) { - if (!_itemContainer.ContainedEntity.TryGetComponent(out ItemComponent? item)) + if (!_entMan.TryGetComponent(contained, out ItemComponent? item)) return false; hands.PutInHandOrDrop(item); } - else if (_itemContainer.Remove(_itemContainer.ContainedEntity)) + else if (_itemContainer.Remove(contained)) { - _itemContainer.ContainedEntity.Transform.Coordinates = Owner.Transform.Coordinates; + _entMan.GetComponent(contained).Coordinates = _entMan.GetComponent(Owner).Coordinates; } return true; @@ -108,9 +111,9 @@ namespace Content.Server.Storage.Components public void OnDestroy(DestructionEventArgs eventArgs) { // drop item inside - if (_itemContainer.ContainedEntity != null) + if (_itemContainer.ContainedEntity is {Valid: true} contained) { - _itemContainer.ContainedEntity.Transform.Coordinates = Owner.Transform.Coordinates; + _entMan.GetComponent(contained).Coordinates = _entMan.GetComponent(Owner).Coordinates; } } } diff --git a/Content.Server/Storage/Components/ServerStorageComponent.cs b/Content.Server/Storage/Components/ServerStorageComponent.cs index 11fe60b80a..12ec21c6d6 100644 --- a/Content.Server/Storage/Components/ServerStorageComponent.cs +++ b/Content.Server/Storage/Components/ServerStorageComponent.cs @@ -49,8 +49,8 @@ namespace Content.Server.Storage.Components private const string LoggerName = "Storage"; public Container? Storage; - - private readonly Dictionary _sizeCache = new(); + + private readonly Dictionary _sizeCache = new(); [DataField("occludesLight")] private bool _occludesLight = true; @@ -79,7 +79,7 @@ namespace Content.Server.Storage.Components public SoundSpecifier StorageSoundCollection { get; set; } = new SoundCollectionSpecifier("storageRustle"); [ViewVariables] - public override IReadOnlyList? StoredEntities => Storage?.ContainedEntities; + public override IReadOnlyList? StoredEntities => Storage?.ContainedEntities; [ViewVariables(VVAccess.ReadWrite)] public bool OccludesLight @@ -94,7 +94,7 @@ namespace Content.Server.Storage.Components private void UpdateStorageVisualization() { - if (!_entityManager.TryGetComponent(OwnerUid, out AppearanceComponent appearance)) + if (!_entityManager.TryGetComponent(Owner, out AppearanceComponent appearance)) return; bool open = SubscribedSessions.Count != 0; @@ -102,7 +102,7 @@ namespace Content.Server.Storage.Components appearance.SetData(StorageVisuals.Open, open); appearance.SetData(SharedBagOpenVisuals.BagState, open ? SharedBagState.Open : SharedBagState.Closed); - if (_entityManager.HasComponent(OwnerUid)) + if (_entityManager.HasComponent(Owner)) appearance.SetData(StackVisuals.Hide, !open); } @@ -129,7 +129,7 @@ namespace Content.Server.Storage.Components foreach (var entity in Storage.ContainedEntities) { - var item = entity.GetComponent(); + var item = _entityManager.GetComponent(entity); _storageUsed += item.Size; } } @@ -139,28 +139,28 @@ namespace Content.Server.Storage.Components /// /// The entity to check /// true if it can be inserted, false otherwise - public bool CanInsert(IEntity entity) + public bool CanInsert(EntityUid entity) { EnsureInitialCalculated(); - if (entity.TryGetComponent(out ServerStorageComponent? storage) && + if (_entityManager.TryGetComponent(entity, out ServerStorageComponent? storage) && storage._storageCapacityMax >= _storageCapacityMax) { return false; } - if (entity.TryGetComponent(out SharedItemComponent? store) && + if (_entityManager.TryGetComponent(entity, out SharedItemComponent? store) && store.Size > _storageCapacityMax - _storageUsed) { return false; } - if (_whitelist != null && !_whitelist.IsValid(entity.Uid)) + if (_whitelist != null && !_whitelist.IsValid(entity)) { return false; } - if (entity.Transform.Anchored) + if (_entityManager.GetComponent(entity).Anchored) { return false; } @@ -173,12 +173,12 @@ namespace Content.Server.Storage.Components /// /// The entity to insert /// true if the entity was inserted, false otherwise - public bool Insert(IEntity entity) + public bool Insert(EntityUid entity) { return CanInsert(entity) && Storage?.Insert(entity) == true; } - public override bool Remove(IEntity entity) + public override bool Remove(EntityUid entity) { EnsureInitialCalculated(); return Storage?.Remove(entity) == true; @@ -194,10 +194,10 @@ namespace Content.Server.Storage.Components PlaySoundCollection(); EnsureInitialCalculated(); - Logger.DebugS(LoggerName, $"Storage (UID {Owner.Uid}) had entity (UID {message.Entity.Uid}) inserted into it."); + Logger.DebugS(LoggerName, $"Storage (UID {Owner}) had entity (UID {message.Entity}) inserted into it."); var size = 0; - if (message.Entity.TryGetComponent(out SharedItemComponent? storable)) + if (_entityManager.TryGetComponent(message.Entity, out SharedItemComponent? storable)) size = storable.Size; _storageUsed += size; @@ -219,7 +219,7 @@ namespace Content.Server.Storage.Components if (!_sizeCache.TryGetValue(message.Entity, out var size)) { - Logger.WarningS(LoggerName, $"Removed entity {message.Entity} without a cached size from storage {Owner} at {Owner.Transform.MapPosition}"); + Logger.WarningS(LoggerName, $"Removed entity {message.Entity} without a cached size from storage {Owner} at {_entityManager.GetComponent(Owner).MapPosition}"); RecalculateStorageUsed(); return; @@ -235,11 +235,11 @@ namespace Content.Server.Storage.Components /// /// The player to insert an entity from /// true if inserted, false otherwise - public bool PlayerInsertHeldEntity(IEntity player) + public bool PlayerInsertHeldEntity(EntityUid player) { EnsureInitialCalculated(); - if (!player.TryGetComponent(out HandsComponent? hands) || + if (!_entityManager.TryGetComponent(player, out HandsComponent? hands) || hands.GetActiveHand == null) { return false; @@ -265,11 +265,11 @@ namespace Content.Server.Storage.Components /// /// Inserts an Entity () in the world into storage, informing if it fails. - /// is *NOT* held, see . + /// is *NOT* held, see . /// /// The player to insert an entity with /// true if inserted, false otherwise - public bool PlayerInsertEntityInWorld(IEntity player, IEntity toInsert) + public bool PlayerInsertEntityInWorld(EntityUid player, EntityUid toInsert) { EnsureInitialCalculated(); @@ -285,14 +285,14 @@ namespace Content.Server.Storage.Components /// Opens the storage UI for an entity /// /// The entity to open the UI for - public void OpenStorageUI(IEntity entity) + public void OpenStorageUI(EntityUid entity) { PlaySoundCollection(); EnsureInitialCalculated(); - var userSession = entity.GetComponent().PlayerSession; + var userSession = _entityManager.GetComponent(entity).PlayerSession; - Logger.DebugS(LoggerName, $"Storage (UID {Owner.Uid}) \"used\" by player session (UID {userSession.AttachedEntityUid})."); + Logger.DebugS(LoggerName, $"Storage (UID {Owner}) \"used\" by player session (UID {userSession.AttachedEntity})."); SubscribeSession(userSession); #pragma warning disable 618 @@ -320,7 +320,7 @@ namespace Content.Server.Storage.Components { if (session.AttachedEntity == null) { - Logger.DebugS(LoggerName, $"Storage (UID {Owner.Uid}) detected no attached entity in player session (UID {session.AttachedEntityUid})."); + Logger.DebugS(LoggerName, $"Storage (UID {Owner}) detected no attached entity in player session (UID {session.AttachedEntity})."); UnsubscribeSession(session); return; @@ -340,7 +340,7 @@ namespace Content.Server.Storage.Components return; } - var stored = StoredEntities.Select(e => e.Uid).ToArray(); + var stored = StoredEntities.Select(e => e).ToArray(); #pragma warning disable 618 SendNetworkMessage(new StorageHeldItemsMessage(stored, _storageUsed, _storageCapacityMax), session.ConnectedClient); @@ -357,7 +357,7 @@ namespace Content.Server.Storage.Components if (!SubscribedSessions.Contains(session)) { - Logger.DebugS(LoggerName, $"Storage (UID {Owner.Uid}) subscribed player session (UID {session.AttachedEntityUid})."); + Logger.DebugS(LoggerName, $"Storage (UID {Owner}) subscribed player session (UID {session.AttachedEntity})."); session.PlayerStatusChanged += HandlePlayerSessionChangeEvent; SubscribedSessions.Add(session); @@ -375,7 +375,7 @@ namespace Content.Server.Storage.Components { if (SubscribedSessions.Contains(session)) { - Logger.DebugS(LoggerName, $"Storage (UID {Owner.Uid}) unsubscribed player session (UID {session.AttachedEntityUid})."); + Logger.DebugS(LoggerName, $"Storage (UID {Owner}) unsubscribed player session (UID {session.AttachedEntity})."); SubscribedSessions.Remove(session); #pragma warning disable 618 @@ -400,13 +400,13 @@ namespace Content.Server.Storage.Components foreach (var entity in StoredEntities) { - if (_entityManager.TryGetComponent(entity.Uid, out ServerStorageComponent storageComponent)) + if (_entityManager.TryGetComponent(entity, out ServerStorageComponent storageComponent)) { - DebugTools.Assert(storageComponent != this, $"Storage component contains itself!? Entity: {OwnerUid}"); + DebugTools.Assert(storageComponent != this, $"Storage component contains itself!? Entity: {Owner}"); storageComponent.UnsubscribeSession(session); } - if (_entityManager.TryGetComponent(entity.Uid, out ServerUserInterfaceComponent uiComponent)) + if (_entityManager.TryGetComponent(entity, out ServerUserInterfaceComponent uiComponent)) { foreach (var ui in uiComponent.Interfaces) { @@ -418,7 +418,7 @@ namespace Content.Server.Storage.Components private void HandlePlayerSessionChangeEvent(object? obj, SessionStatusEventArgs sessionStatus) { - Logger.DebugS(LoggerName, $"Storage (UID {Owner.Uid}) handled a status change in player session (UID {sessionStatus.Session.AttachedEntityUid})."); + Logger.DebugS(LoggerName, $"Storage (UID {Owner}) handled a status change in player session (UID {sessionStatus.Session.AttachedEntity})."); if (sessionStatus.NewStatus != SessionStatus.InGame) { @@ -452,28 +452,26 @@ namespace Content.Server.Storage.Components { EnsureInitialCalculated(); - var player = session.AttachedEntity; - - if (player == null) + if (session.AttachedEntity is not {Valid: true} player) { break; } - var ownerTransform = Owner.Transform; - var playerTransform = player.Transform; + var ownerTransform = _entityManager.GetComponent(Owner); + var playerTransform = _entityManager.GetComponent(player); - if (!playerTransform.Coordinates.InRange(Owner.EntityManager, ownerTransform.Coordinates, 2) || + if (!playerTransform.Coordinates.InRange(_entityManager, ownerTransform.Coordinates, 2) || Owner.IsInContainer() && !playerTransform.ContainsEntity(ownerTransform)) { break; } - if (!Owner.EntityManager.TryGetEntity(remove.EntityUid, out var entity) || Storage?.Contains(entity) == false) + if (!remove.EntityUid.Valid || Storage?.Contains(remove.EntityUid) == false) { break; } - if (!entity.TryGetComponent(out ItemComponent? item) || !player.TryGetComponent(out HandsComponent? hands)) + if (!_entityManager.TryGetComponent(remove.EntityUid, out ItemComponent? item) || !_entityManager.TryGetComponent(player, out HandsComponent? hands)) { break; } @@ -491,9 +489,7 @@ namespace Content.Server.Storage.Components { EnsureInitialCalculated(); - var player = session.AttachedEntity; - - if (player == null) + if (session.AttachedEntity is not {Valid: true} player) { break; } @@ -529,9 +525,9 @@ namespace Content.Server.Storage.Components { if (!_clickInsert) return false; - Logger.DebugS(LoggerName, $"Storage (UID {Owner.Uid}) attacked by user (UID {eventArgs.User.Uid}) with entity (UID {eventArgs.Using.Uid})."); + Logger.DebugS(LoggerName, $"Storage (UID {Owner}) attacked by user (UID {eventArgs.User}) with entity (UID {eventArgs.Using})."); - if (Owner.HasComponent()) + if (_entityManager.HasComponent(Owner)) { return false; } @@ -570,14 +566,14 @@ namespace Content.Server.Storage.Components // Pick up all entities in a radius around the clicked location. // The last half of the if is because carpets exist and this is terrible - if (_areaInsert && (eventArgs.Target == null || !eventArgs.Target.HasComponent())) + if (_areaInsert && (eventArgs.Target == null || !_entityManager.HasComponent(eventArgs.Target.Value))) { - var validStorables = new List(); + var validStorables = new List(); foreach (var entity in IoCManager.Resolve().GetEntitiesInRange(eventArgs.ClickLocation, _areaInsertRadius, LookupFlags.None)) { if (entity.IsInContainer() || entity == eventArgs.User - || !entity.HasComponent() + || !_entityManager.HasComponent(entity) || !EntitySystem.Get().InRangeUnobstructed(eventArgs.User, entity)) continue; validStorables.Add(entity); @@ -605,12 +601,12 @@ namespace Content.Server.Storage.Components // Check again, situation may have changed for some entities, but we'll still pick up any that are valid if (entity.IsInContainer() || entity == eventArgs.User - || !entity.HasComponent()) + || !_entityManager.HasComponent(entity)) continue; - var position = EntityCoordinates.FromMap(Owner.Transform.Parent?.Owner ?? Owner, entity.Transform.MapPosition); + var position = EntityCoordinates.FromMap(_entityManager.GetComponent(Owner).Parent?.Owner ?? Owner, _entityManager.GetComponent(entity).MapPosition); if (PlayerInsertEntityInWorld(eventArgs.User, entity)) { - successfullyInserted.Add(entity.Uid); + successfullyInserted.Add(entity); successfullyInsertedPositions.Add(position); } } @@ -633,19 +629,25 @@ namespace Content.Server.Storage.Components // Pick up the clicked entity else if (_quickInsert) { - if (eventArgs.Target == null - || eventArgs.Target.IsInContainer() - || eventArgs.Target == eventArgs.User - || !eventArgs.Target.HasComponent()) + if (eventArgs.Target is not {Valid: true} target) + { return false; - var position = EntityCoordinates.FromMap(Owner.Transform.Parent?.Owner ?? Owner, eventArgs.Target.Transform.MapPosition); - if (PlayerInsertEntityInWorld(eventArgs.User, eventArgs.Target)) + } + + if (target.IsInContainer() + || target == eventArgs.User + || !_entityManager.HasComponent(target)) + return false; + var position = EntityCoordinates.FromMap( + _entityManager.GetComponent(Owner).Parent?.Owner ?? Owner, + _entityManager.GetComponent(target).MapPosition); + if (PlayerInsertEntityInWorld(eventArgs.User, target)) { #pragma warning disable 618 SendNetworkMessage(new AnimateInsertingEntitiesMessage( #pragma warning restore 618 - new List() { eventArgs.Target.Uid }, - new List() { position } + new List {target}, + new List {position} )); return true; } @@ -685,7 +687,7 @@ namespace Content.Server.Storage.Components foreach (var entity in storedEntities) { - var exActs = entity.GetAllComponents().ToArray(); + var exActs = _entityManager.GetComponents(entity).ToArray(); foreach (var exAct in exActs) { exAct.OnExplosion(eventArgs); diff --git a/Content.Server/Storage/Components/StorageFillComponent.cs b/Content.Server/Storage/Components/StorageFillComponent.cs index 2af21ed610..84c1823ca3 100644 --- a/Content.Server/Storage/Components/StorageFillComponent.cs +++ b/Content.Server/Storage/Components/StorageFillComponent.cs @@ -15,6 +15,8 @@ namespace Content.Server.Storage.Components [RegisterComponent] public sealed class StorageFillComponent : Component, IMapInit { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "StorageFill"; [DataField("contents")] private List _contents = new(); @@ -28,7 +30,7 @@ namespace Content.Server.Storage.Components return; } - if (!Owner.TryGetComponent(out IStorageComponent? storage)) + if (!_entMan.TryGetComponent(Owner, out IStorageComponent? storage)) { Logger.Error($"StorageFillComponent couldn't find any StorageComponent ({Owner})"); return; @@ -48,14 +50,18 @@ namespace Content.Server.Storage.Components continue; } + var entMan = _entMan; + var transform = entMan.GetComponent(Owner); + for (var i = 0; i < storageItem.Amount; i++) { - var ent = Owner.EntityManager.SpawnEntity(storageItem.PrototypeId, Owner.Transform.Coordinates); + + var ent = entMan.SpawnEntity(storageItem.PrototypeId, transform.Coordinates); if (storage.Insert(ent)) continue; Logger.ErrorS("storage", $"Tried to StorageFill {storageItem.PrototypeId} inside {Owner} but can't."); - Owner.EntityManager.DeleteEntity(ent); + entMan.DeleteEntity(ent); } if (!string.IsNullOrEmpty(storageItem.GroupId)) alreadySpawnedGroups.Add(storageItem.GroupId); diff --git a/Content.Server/Storage/EntitySystems/ItemCounterSystem.cs b/Content.Server/Storage/EntitySystems/ItemCounterSystem.cs index 43f76c7b68..5b697eeb22 100644 --- a/Content.Server/Storage/EntitySystems/ItemCounterSystem.cs +++ b/Content.Server/Storage/EntitySystems/ItemCounterSystem.cs @@ -3,6 +3,8 @@ using Content.Shared.Storage.Components; using Content.Shared.Storage.EntitySystems; using JetBrains.Annotations; using Robust.Shared.Containers; +using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Storage.EntitySystems { @@ -11,7 +13,7 @@ namespace Content.Server.Storage.EntitySystems { protected override int? GetCount(ContainerModifiedMessage msg, ItemCounterComponent itemCounter) { - if (!msg.Container.Owner.TryGetComponent(out ServerStorageComponent? component) + if (!EntityManager.TryGetComponent(msg.Container.Owner, out ServerStorageComponent? component) || component.StoredEntities == null) { return null; @@ -20,7 +22,7 @@ namespace Content.Server.Storage.EntitySystems var count = 0; foreach (var entity in component.StoredEntities) { - if (itemCounter.Count.IsValid(entity.Uid)) count++; + if (itemCounter.Count.IsValid(entity)) count++; } return count; diff --git a/Content.Server/Storage/EntitySystems/ItemMapperSystem.cs b/Content.Server/Storage/EntitySystems/ItemMapperSystem.cs index 84ba80ab5d..5ffebc1088 100644 --- a/Content.Server/Storage/EntitySystems/ItemMapperSystem.cs +++ b/Content.Server/Storage/EntitySystems/ItemMapperSystem.cs @@ -3,9 +3,9 @@ using Content.Server.Storage.Components; using Content.Shared.Storage.Components; using Content.Shared.Storage.EntitySystems; using JetBrains.Annotations; -using Robust.Shared.Analyzers; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Storage.EntitySystems { @@ -16,15 +16,15 @@ namespace Content.Server.Storage.EntitySystems ItemMapperComponent itemMapper, out IReadOnlyList showLayers) { - if (msg.Container.Owner.TryGetComponent(out ServerStorageComponent? component)) + if (EntityManager.TryGetComponent(msg.Container.Owner, out ServerStorageComponent? component)) { - var containedLayers = component.StoredEntities ?? new List(); + var containedLayers = component.StoredEntities ?? new List(); var list = new List(); foreach (var mapLayerData in itemMapper.MapLayers.Values) { foreach (var entity in containedLayers) { - if (mapLayerData.Whitelist.IsValid(entity.Uid)) + if (mapLayerData.Whitelist.IsValid(entity)) { list.Add(mapLayerData.Layer); break; diff --git a/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs b/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs index e694aa237a..929d9bd084 100644 --- a/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs +++ b/Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs @@ -26,9 +26,8 @@ namespace Content.Server.Storage.EntitySystems if (args.Handled) return; - var owner = EntityManager.GetEntity(uid); var alreadySpawnedGroups = new List(); - IEntity? entityToPlaceInHands = null; + EntityUid entityToPlaceInHands = default; foreach (var storageItem in component.Items) { if (!string.IsNullOrEmpty(storageItem.GroupId) && @@ -42,24 +41,24 @@ namespace Content.Server.Storage.EntitySystems for (var i = 0; i < storageItem.Amount; i++) { - entityToPlaceInHands = EntityManager.SpawnEntity(storageItem.PrototypeId, args.User.Transform.Coordinates); + entityToPlaceInHands = EntityManager.SpawnEntity(storageItem.PrototypeId, EntityManager.GetComponent(args.User).Coordinates); } if (!string.IsNullOrEmpty(storageItem.GroupId)) alreadySpawnedGroups.Add(storageItem.GroupId); } if (component.Sound != null) - SoundSystem.Play(Filter.Pvs(owner), component.Sound.GetSound()); + SoundSystem.Play(Filter.Pvs(uid), component.Sound.GetSound()); component.Uses--; if (component.Uses == 0) { args.Handled = true; - owner.Delete(); + EntityManager.DeleteEntity(uid); } - if (entityToPlaceInHands != null - && args.User.TryGetComponent(out var hands)) + if (entityToPlaceInHands != default + && EntityManager.TryGetComponent(args.User, out var hands)) { hands.TryPutInAnyHand(entityToPlaceInHands); } diff --git a/Content.Server/Storage/EntitySystems/StorageSystem.cs b/Content.Server/Storage/EntitySystems/StorageSystem.cs index 6ffe397bcd..e3b4a473e0 100644 --- a/Content.Server/Storage/EntitySystems/StorageSystem.cs +++ b/Content.Server/Storage/EntitySystems/StorageSystem.cs @@ -2,16 +2,17 @@ using System.Collections.Generic; using Content.Server.Hands.Components; using Content.Server.Interaction; using Content.Server.Storage.Components; -using Content.Shared.Verbs; +using Content.Shared.Interaction; using Content.Shared.Movement; +using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Timing; using Robust.Shared.Localization; +using Robust.Shared.Timing; namespace Content.Server.Storage.EntitySystems { @@ -37,17 +38,17 @@ namespace Content.Server.Storage.EntitySystems private void OnRelayMovement(EntityUid uid, EntityStorageComponent component, RelayMovementEntityEvent args) { - if (EntityManager.HasComponent(args.Entity.Uid)) - { - if (_gameTiming.CurTime < - component.LastInternalOpenAttempt + EntityStorageComponent.InternalOpenAttemptDelay) - { - return; - } + if (!EntityManager.HasComponent(args.Entity)) + return; - component.LastInternalOpenAttempt = _gameTiming.CurTime; - component.TryOpenStorage(args.Entity); + if (_gameTiming.CurTime < + component.LastInternalOpenAttempt + EntityStorageComponent.InternalOpenAttemptDelay) + { + return; } + + component.LastInternalOpenAttempt = _gameTiming.CurTime; + component.TryOpenStorage(args.Entity); } /// @@ -91,7 +92,7 @@ namespace Content.Server.Storage.EntitySystems return; // Get the session for the user - var session = args.User.GetComponentOrNull()?.PlayerSession; + var session = EntityManager.GetComponentOrNull(args.User)?.PlayerSession; if (session == null) return; @@ -113,21 +114,21 @@ namespace Content.Server.Storage.EntitySystems args.Verbs.Add(verb); } - private static void HandleEntityRemovedFromContainer(EntRemovedFromContainerMessage message) + private void HandleEntityRemovedFromContainer(EntRemovedFromContainerMessage message) { var oldParentEntity = message.Container.Owner; - if (oldParentEntity.TryGetComponent(out ServerStorageComponent? storageComp)) + if (EntityManager.TryGetComponent(oldParentEntity, out ServerStorageComponent? storageComp)) { storageComp.HandleEntityMaybeRemoved(message); } } - private static void HandleEntityInsertedIntoContainer(EntInsertedIntoContainerMessage message) + private void HandleEntityInsertedIntoContainer(EntInsertedIntoContainerMessage message) { var oldParentEntity = message.Container.Owner; - if (oldParentEntity.TryGetComponent(out ServerStorageComponent? storageComp)) + if (EntityManager.TryGetComponent(oldParentEntity, out ServerStorageComponent? storageComp)) { storageComp.HandleEntityMaybeInserted(message); } @@ -143,22 +144,20 @@ namespace Content.Server.Storage.EntitySystems if (_sessionCache.Count == 0) return; - var storagePos = storageComp.Owner.Transform.WorldPosition; - var storageMap = storageComp.Owner.Transform.MapID; + var storagePos = EntityManager.GetComponent(storageComp.Owner).WorldPosition; + var storageMap = EntityManager.GetComponent(storageComp.Owner).MapID; foreach (var session in _sessionCache) { - var attachedEntity = session.AttachedEntity; - // The component manages the set of sessions, so this invalid session should be removed soon. - if (attachedEntity == null || !attachedEntity.IsValid()) + if (session.AttachedEntity is not {} attachedEntity || !EntityManager.EntityExists(attachedEntity)) continue; - if (storageMap != attachedEntity.Transform.MapID) + if (storageMap != EntityManager.GetComponent(attachedEntity).MapID) continue; - var distanceSquared = (storagePos - attachedEntity.Transform.WorldPosition).LengthSquared; - if (distanceSquared > InteractionSystem.InteractionRangeSquared) + var distanceSquared = (storagePos - EntityManager.GetComponent(attachedEntity).WorldPosition).LengthSquared; + if (distanceSquared > SharedInteractionSystem.InteractionRangeSquared) { storageComp.UnsubscribeSession(session); } diff --git a/Content.Server/Strip/StrippableComponent.cs b/Content.Server/Strip/StrippableComponent.cs index 00f36eda42..2222f83238 100644 --- a/Content.Server/Strip/StrippableComponent.cs +++ b/Content.Server/Strip/StrippableComponent.cs @@ -14,6 +14,7 @@ using Content.Shared.Strip.Components; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.ViewVariables; using static Content.Shared.Inventory.EquipmentSlotDefines; @@ -24,6 +25,8 @@ namespace Content.Server.Strip [ComponentReference(typeof(SharedStrippableComponent))] public sealed class StrippableComponent : SharedStrippableComponent { + [Dependency] private readonly IEntityManager _entities = default!; + public const float StripDelay = 2f; // TODO: This component needs localization. @@ -44,17 +47,17 @@ namespace Content.Server.Strip Owner.EnsureComponentWarn(); Owner.EnsureComponentWarn(); - if (Owner.TryGetComponent(out CuffableComponent? cuffed)) + if (_entities.TryGetComponent(Owner, out CuffableComponent? cuffed)) { cuffed.OnCuffedStateChanged += UpdateSubscribed; } - if (Owner.TryGetComponent(out InventoryComponent? inventory)) + if (_entities.TryGetComponent(Owner, out InventoryComponent? inventory)) { inventory.OnItemChanged += UpdateSubscribed; } - if (Owner.TryGetComponent(out HandsComponent? hands)) + if (_entities.TryGetComponent(Owner, out HandsComponent? hands)) { hands.OnItemChanged += UpdateSubscribed; } @@ -79,7 +82,7 @@ namespace Content.Server.Strip public override bool Drop(DragDropEvent args) { - if (!args.User.TryGetComponent(out ActorComponent? actor)) return false; + if (!_entities.TryGetComponent(args.User, out ActorComponent? actor)) return false; OpenUserInterface(actor.PlayerSession); return true; @@ -89,14 +92,15 @@ namespace Content.Server.Strip { var dictionary = new Dictionary(); - if (!Owner.TryGetComponent(out CuffableComponent? cuffed)) + if (!_entities.TryGetComponent(Owner, out CuffableComponent? cuffed)) { return dictionary; } - foreach (IEntity entity in cuffed.StoredEntities) + foreach (var entity in cuffed.StoredEntities) { - dictionary.Add(entity.Uid, entity.Name); + var name = _entities.GetComponent(entity).EntityName; + dictionary.Add(entity, name); } return dictionary; @@ -106,14 +110,19 @@ namespace Content.Server.Strip { var dictionary = new Dictionary(); - if (!Owner.TryGetComponent(out InventoryComponent? inventory)) + if (!_entities.TryGetComponent(Owner, out InventoryComponent? inventory)) { return dictionary; } foreach (var slot in inventory.Slots) { - dictionary[slot] = inventory.GetSlotItem(slot)?.Owner.Name ?? "None"; + var name = "None"; + + if (inventory.GetSlotItem(slot) is { } item) + name = _entities.GetComponent(item.Owner).EntityName; + + dictionary[slot] = name; } return dictionary; @@ -123,7 +132,7 @@ namespace Content.Server.Strip { var dictionary = new Dictionary(); - if (!Owner.TryGetComponent(out HandsComponent? hands)) + if (!_entities.TryGetComponent(Owner, out HandsComponent? hands)) { return dictionary; } @@ -132,13 +141,13 @@ namespace Content.Server.Strip { var owner = hands.GetItem(hand)?.Owner; - if (owner?.HasComponent() ?? true) + if (!owner.HasValue || _entities.HasComponent(owner.Value)) { dictionary[hand] = "None"; continue; } - dictionary[hand] = owner.Name; + dictionary[hand] = _entities.GetComponent(owner.Value).EntityName; } return dictionary; @@ -152,15 +161,15 @@ namespace Content.Server.Strip /// /// Places item in user's active hand to an inventory slot. /// - private async void PlaceActiveHandItemInInventory(IEntity user, Slots slot) + private async void PlaceActiveHandItemInInventory(EntityUid user, Slots slot) { - var inventory = Owner.GetComponent(); - var userHands = user.GetComponent(); + var inventory = _entities.GetComponent(Owner); + var userHands = _entities.GetComponent(user); var item = userHands.GetActiveHand; bool Check() { - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) return false; if (item == null) @@ -217,15 +226,15 @@ namespace Content.Server.Strip /// /// Places item in user's active hand in one of the entity's hands. /// - private async void PlaceActiveHandItemInHands(IEntity user, string hand) + private async void PlaceActiveHandItemInHands(EntityUid user, string hand) { - var hands = Owner.GetComponent(); - var userHands = user.GetComponent(); + var hands = _entities.GetComponent(Owner); + var userHands = _entities.GetComponent(user); var item = userHands.GetActiveHand; bool Check() { - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) return false; if (item == null) @@ -283,14 +292,14 @@ namespace Content.Server.Strip /// /// Takes an item from the inventory and places it in the user's active hand. /// - private async void TakeItemFromInventory(IEntity user, Slots slot) + private async void TakeItemFromInventory(EntityUid user, Slots slot) { - var inventory = Owner.GetComponent(); - var userHands = user.GetComponent(); + var inventory = _entities.GetComponent(Owner); + var userHands = _entities.GetComponent(user); bool Check() { - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) return false; if (!inventory.HasSlot(slot)) @@ -339,14 +348,14 @@ namespace Content.Server.Strip /// /// Takes an item from a hand and places it in the user's active hand. /// - private async void TakeItemFromHands(IEntity user, string hand) + private async void TakeItemFromHands(EntityUid user, string hand) { - var hands = Owner.GetComponent(); - var userHands = user.GetComponent(); + var hands = _entities.GetComponent(Owner); + var userHands = _entities.GetComponent(user); bool Check() { - if (!EntitySystem.Get().CanInteract(user.Uid)) + if (!EntitySystem.Get().CanInteract(user)) return false; if (!hands.HasHand(hand)) @@ -358,7 +367,7 @@ namespace Content.Server.Strip return false; } - if (heldItem.Owner.HasComponent()) + if (_entities.HasComponent(heldItem.Owner)) return false; if (!hands.CanDrop(hand, false)) @@ -392,8 +401,9 @@ namespace Content.Server.Strip private void HandleUserInterfaceMessage(ServerBoundUserInterfaceMessage obj) { - var user = obj.Session.AttachedEntity; - if (user == null || !(user.TryGetComponent(out HandsComponent? userHands))) return; + if (obj.Session.AttachedEntity is not {Valid: true} user || + !_entities.TryGetComponent(user, out HandsComponent? userHands)) + return; var placingItem = userHands.GetActiveHand != null; @@ -401,7 +411,7 @@ namespace Content.Server.Strip { case StrippingInventoryButtonPressed inventoryMessage: - if (Owner.TryGetComponent(out var inventory)) + if (_entities.TryGetComponent(Owner, out var inventory)) { if (inventory.TryGetSlotItem(inventoryMessage.Slot, out ItemComponent? _)) placingItem = false; @@ -415,7 +425,7 @@ namespace Content.Server.Strip case StrippingHandButtonPressed handMessage: - if (Owner.TryGetComponent(out var hands)) + if (_entities.TryGetComponent(Owner, out var hands)) { if (hands.TryGetItem(handMessage.Hand, out _)) placingItem = false; @@ -429,11 +439,11 @@ namespace Content.Server.Strip case StrippingHandcuffButtonPressed handcuffMessage: - if (Owner.TryGetComponent(out var cuffed)) + if (_entities.TryGetComponent(Owner, out var cuffed)) { foreach (var entity in cuffed.StoredEntities) { - if (entity.Uid == handcuffMessage.Handcuff) + if (entity == handcuffMessage.Handcuff) { cuffed.TryUncuff(user, entity); return; diff --git a/Content.Server/Strip/StrippableSystem.cs b/Content.Server/Strip/StrippableSystem.cs index 7941e06baf..5a8039c83f 100644 --- a/Content.Server/Strip/StrippableSystem.cs +++ b/Content.Server/Strip/StrippableSystem.cs @@ -1,6 +1,7 @@ using Content.Shared.Verbs; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; namespace Content.Server.Strip @@ -19,7 +20,7 @@ namespace Content.Server.Strip if (args.Hands == null || !args.CanAccess || !args.CanInteract || args.Target == args.User) return; - if (!args.User.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; Verb verb = new(); diff --git a/Content.Server/Stunnable/StunOnCollideSystem.cs b/Content.Server/Stunnable/StunOnCollideSystem.cs index 4e88afe35f..e88fae7ac0 100644 --- a/Content.Server/Stunnable/StunOnCollideSystem.cs +++ b/Content.Server/Stunnable/StunOnCollideSystem.cs @@ -1,11 +1,8 @@ using System; using Content.Server.Alert; using Content.Server.Stunnable.Components; -using Content.Shared.Alert; -using Content.Shared.Movement.Components; using Content.Shared.Standing; using Content.Shared.StatusEffect; -using Content.Shared.Stunnable; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -26,7 +23,7 @@ namespace Content.Server.Stunnable private void HandleCollide(EntityUid uid, StunOnCollideComponent component, StartCollideEvent args) { - var otherUid = args.OtherFixture.Body.Owner.Uid; + var otherUid = args.OtherFixture.Body.Owner; if (EntityManager.TryGetComponent(otherUid, out var status)) { diff --git a/Content.Server/Stunnable/StunSystem.cs b/Content.Server/Stunnable/StunSystem.cs index 78e5404ca4..a2f8317d11 100644 --- a/Content.Server/Stunnable/StunSystem.cs +++ b/Content.Server/Stunnable/StunSystem.cs @@ -48,8 +48,8 @@ namespace Content.Server.Stunnable if (target != null) { // TODO: Use PopupSystem - source.PopupMessageOtherClients(Loc.GetString("stunned-component-disarm-success-others", ("source", source.Name), ("target", target.Name))); - source.PopupMessageCursor(Loc.GetString("stunned-component-disarm-success", ("target", target.Name))); + source.PopupMessageOtherClients(Loc.GetString("stunned-component-disarm-success-others", ("source", Name: EntityManager.GetComponent(source).EntityName), ("target", Name: EntityManager.GetComponent(target).EntityName))); + source.PopupMessageCursor(Loc.GetString("stunned-component-disarm-success", ("target", Name: EntityManager.GetComponent(target).EntityName))); } } diff --git a/Content.Server/Stunnable/StunbatonSystem.cs b/Content.Server/Stunnable/StunbatonSystem.cs index 0074885fe9..9fec34edc2 100644 --- a/Content.Server/Stunnable/StunbatonSystem.cs +++ b/Content.Server/Stunnable/StunbatonSystem.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using Content.Server.Items; -using Content.Server.Jittering; using Content.Server.PowerCell.Components; using Content.Server.Speech.EntitySystems; using Content.Server.Stunnable.Components; @@ -53,7 +52,7 @@ namespace Content.Server.Stunnable if (!EntityManager.TryGetComponent(uid, out var slot) || slot.Cell == null || !slot.Cell.TryUseCharge(comp.EnergyPerUse)) return; - foreach (IEntity entity in args.HitEntities) + foreach (EntityUid entity in args.HitEntities) { StunEntity(entity, comp); } @@ -73,7 +72,7 @@ namespace Content.Server.Stunnable private void OnUseInHand(EntityUid uid, StunbatonComponent comp, UseInHandEvent args) { - if (!Get().CanUse(args.User.Uid)) + if (!Get().CanUse(args.User)) return; if (comp.Activated) @@ -104,7 +103,7 @@ namespace Content.Server.Stunnable private void OnInteractUsing(EntityUid uid, StunbatonComponent comp, InteractUsingEvent args) { - if (!Get().CanInteract(args.User.Uid)) + if (!Get().CanInteract(args.User)) return; if (EntityManager.TryGetComponent(uid, out var cellslot)) @@ -119,33 +118,33 @@ namespace Content.Server.Stunnable args.PushMarkup(msg); } - private void StunEntity(IEntity entity, StunbatonComponent comp) + private void StunEntity(EntityUid entity, StunbatonComponent comp) { - if (!entity.TryGetComponent(out StatusEffectsComponent? status) || !comp.Activated) return; + if (!EntityManager.TryGetComponent(entity, out StatusEffectsComponent? status) || !comp.Activated) return; // TODO: Make slowdown inflicted customizable. SoundSystem.Play(Filter.Pvs(comp.Owner), comp.StunSound.GetSound(), comp.Owner, AudioHelpers.WithVariation(0.25f)); - if (!EntityManager.HasComponent(entity.Uid)) + if (!EntityManager.HasComponent(entity)) { if (_robustRandom.Prob(comp.ParalyzeChanceNoSlowdown)) - _stunSystem.TryParalyze(entity.Uid, TimeSpan.FromSeconds(comp.ParalyzeTime), true, status); + _stunSystem.TryParalyze(entity, TimeSpan.FromSeconds(comp.ParalyzeTime), true, status); else - _stunSystem.TrySlowdown(entity.Uid, TimeSpan.FromSeconds(comp.SlowdownTime), true, 0.5f, 0.5f, status); + _stunSystem.TrySlowdown(entity, TimeSpan.FromSeconds(comp.SlowdownTime), true, 0.5f, 0.5f, status); } else { if (_robustRandom.Prob(comp.ParalyzeChanceWithSlowdown)) - _stunSystem.TryParalyze(entity.Uid, TimeSpan.FromSeconds(comp.ParalyzeTime), true, status); + _stunSystem.TryParalyze(entity, TimeSpan.FromSeconds(comp.ParalyzeTime), true, status); else - _stunSystem.TrySlowdown(entity.Uid, TimeSpan.FromSeconds(comp.SlowdownTime), true, 0.5f, 0.5f, status); + _stunSystem.TrySlowdown(entity, TimeSpan.FromSeconds(comp.SlowdownTime), true, 0.5f, 0.5f, status); } var slowdownTime = TimeSpan.FromSeconds(comp.SlowdownTime); - _jitterSystem.DoJitter(entity.Uid, slowdownTime, true, status:status); - _stutteringSystem.DoStutter(entity.Uid, slowdownTime, true, status); + _jitterSystem.DoJitter(entity, slowdownTime, true, status:status); + _stutteringSystem.DoStutter(entity, slowdownTime, true, status); - if (!comp.Owner.TryGetComponent(out var slot) || slot.Cell == null || !(slot.Cell.CurrentCharge < comp.EnergyPerUse)) + if (!EntityManager.TryGetComponent(comp.Owner, out var slot) || slot.Cell == null || !(slot.Cell.CurrentCharge < comp.EnergyPerUse)) return; SoundSystem.Play(Filter.Pvs(comp.Owner), comp.SparksSound.GetSound(), comp.Owner, AudioHelpers.WithVariation(0.25f)); @@ -159,8 +158,8 @@ namespace Content.Server.Stunnable return; } - if (!comp.Owner.TryGetComponent(out var sprite) || - !comp.Owner.TryGetComponent(out var item)) return; + if (!EntityManager.TryGetComponent(comp.Owner, out var sprite) || + !EntityManager.TryGetComponent(comp.Owner, out var item)) return; SoundSystem.Play(Filter.Pvs(comp.Owner), comp.SparksSound.GetSound(), comp.Owner, AudioHelpers.WithVariation(0.25f)); item.EquippedPrefix = "off"; @@ -169,19 +168,19 @@ namespace Content.Server.Stunnable comp.Activated = false; } - private void TurnOn(StunbatonComponent comp, IEntity user) + private void TurnOn(StunbatonComponent comp, EntityUid user) { if (comp.Activated) { return; } - if (!comp.Owner.TryGetComponent(out var sprite) || - !comp.Owner.TryGetComponent(out var item)) + if (!EntityManager.TryGetComponent(comp.Owner, out var sprite) || + !EntityManager.TryGetComponent(comp.Owner, out var item)) return; var playerFilter = Filter.Pvs(comp.Owner); - if (!comp.Owner.TryGetComponent(out var slot)) + if (!EntityManager.TryGetComponent(comp.Owner, out var slot)) return; if (slot.Cell == null) diff --git a/Content.Server/Suspicion/SuspicionRoleComponent.cs b/Content.Server/Suspicion/SuspicionRoleComponent.cs index 5e683bd518..df51ff8537 100644 --- a/Content.Server/Suspicion/SuspicionRoleComponent.cs +++ b/Content.Server/Suspicion/SuspicionRoleComponent.cs @@ -9,6 +9,7 @@ using Content.Shared.Examine; using Content.Shared.MobState.Components; using Content.Shared.Suspicion; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Players; using Robust.Shared.Utility; @@ -21,6 +22,8 @@ namespace Content.Server.Suspicion public class SuspicionRoleComponent : SharedSuspicionRoleComponent, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + private Role? _role; [ViewVariables] private readonly HashSet _allies = new(); @@ -59,7 +62,7 @@ namespace Content.Server.Suspicion public bool IsDead() { - return Owner.TryGetComponent(out MobStateComponent? state) && + return _entMan.TryGetComponent(Owner, out MobStateComponent? state) && state.IsDead(); } @@ -75,7 +78,7 @@ namespace Content.Server.Suspicion public void SyncRoles() { - if (!Owner.TryGetComponent(out MindComponent? mind) || + if (!_entMan.TryGetComponent(Owner, out MindComponent? mind) || !mind.HasMind) { return; @@ -158,7 +161,7 @@ namespace Content.Server.Suspicion continue; } - allies.Add((role.Role!.Mind.CharacterName, role.Owner.Uid)); + allies.Add((role.Role!.Mind.CharacterName, Uid: role.Owner)); } return new SuspicionRoleComponentState(Role?.Name, Role?.Antagonist, allies.ToArray()); diff --git a/Content.Server/Tabletop/TabletopChessSetup.cs b/Content.Server/Tabletop/TabletopChessSetup.cs index f7f08d092e..55b34b4a73 100644 --- a/Content.Server/Tabletop/TabletopChessSetup.cs +++ b/Content.Server/Tabletop/TabletopChessSetup.cs @@ -17,7 +17,7 @@ namespace Content.Server.Tabletop { var chessboard = entityManager.SpawnEntity(ChessBoardPrototype, session.Position.Offset(-1, 0)); - session.Entities.Add(chessboard.Uid); + session.Entities.Add(chessboard); SpawnPieces(session, entityManager, session.Position.Offset(-4.5f, 3.5f)); } @@ -35,8 +35,10 @@ namespace Content.Server.Tabletop SpawnPiecesRow(session, entityManager, "White", new MapCoordinates(x, y - 7 * separation, mapId), separation); // Extra queens - session.Entities.Add(entityManager.SpawnEntity("BlackQueen", new MapCoordinates(x + 9 * separation + 9f / 32, y - 3 * separation, mapId)).Uid); - session.Entities.Add(entityManager.SpawnEntity("WhiteQueen", new MapCoordinates(x + 9 * separation + 9f / 32, y - 4 * separation, mapId)).Uid); + EntityUid tempQualifier = entityManager.SpawnEntity("BlackQueen", new MapCoordinates(x + 9 * separation + 9f / 32, y - 3 * separation, mapId)); + session.Entities.Add(tempQualifier); + EntityUid tempQualifier1 = entityManager.SpawnEntity("WhiteQueen", new MapCoordinates(x + 9 * separation + 9f / 32, y - 4 * separation, mapId)); + session.Entities.Add(tempQualifier1); } // TODO: refactor to load FEN instead @@ -51,19 +53,24 @@ namespace Content.Server.Tabletop switch (piecesRow[i]) { case 'r': - session.Entities.Add(entityManager.SpawnEntity(color + "Rook", new MapCoordinates(x + i * separation, y, mapId)).Uid); + EntityUid tempQualifier = entityManager.SpawnEntity(color + "Rook", new MapCoordinates(x + i * separation, y, mapId)); + session.Entities.Add(tempQualifier); break; case 'n': - session.Entities.Add(entityManager.SpawnEntity(color + "Knight", new MapCoordinates(x + i * separation, y, mapId)).Uid); + EntityUid tempQualifier1 = entityManager.SpawnEntity(color + "Knight", new MapCoordinates(x + i * separation, y, mapId)); + session.Entities.Add(tempQualifier1); break; case 'b': - session.Entities.Add(entityManager.SpawnEntity(color + "Bishop", new MapCoordinates(x + i * separation, y, mapId)).Uid); + EntityUid tempQualifier2 = entityManager.SpawnEntity(color + "Bishop", new MapCoordinates(x + i * separation, y, mapId)); + session.Entities.Add(tempQualifier2); break; case 'q': - session.Entities.Add(entityManager.SpawnEntity(color + "Queen", new MapCoordinates(x + i * separation, y, mapId)).Uid); + EntityUid tempQualifier3 = entityManager.SpawnEntity(color + "Queen", new MapCoordinates(x + i * separation, y, mapId)); + session.Entities.Add(tempQualifier3); break; case 'k': - session.Entities.Add(entityManager.SpawnEntity(color + "King", new MapCoordinates(x + i * separation, y, mapId)).Uid); + EntityUid tempQualifier4 = entityManager.SpawnEntity(color + "King", new MapCoordinates(x + i * separation, y, mapId)); + session.Entities.Add(tempQualifier4); break; } } @@ -76,7 +83,8 @@ namespace Content.Server.Tabletop for (int i = 0; i < 8; i++) { - session.Entities.Add(entityManager.SpawnEntity(color + "Pawn", new MapCoordinates(x + i * separation, y, mapId)).Uid); + EntityUid tempQualifier = entityManager.SpawnEntity(color + "Pawn", new MapCoordinates(x + i * separation, y, mapId)); + session.Entities.Add(tempQualifier); } } } diff --git a/Content.Server/Tabletop/TabletopParchisSetup.cs b/Content.Server/Tabletop/TabletopParchisSetup.cs index c6de3f916d..38b6f5a5d2 100644 --- a/Content.Server/Tabletop/TabletopParchisSetup.cs +++ b/Content.Server/Tabletop/TabletopParchisSetup.cs @@ -35,28 +35,44 @@ namespace Content.Server.Tabletop var center = session.Position; // Red pieces. - session.Entities.Add(entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x1, -y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x1, -y2)).Uid); - session.Entities.Add(entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x2, -y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x2, -y2)).Uid); + EntityUid tempQualifier = entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x1, -y1)); + session.Entities.Add(tempQualifier); + EntityUid tempQualifier1 = entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x1, -y2)); + session.Entities.Add(tempQualifier1); + EntityUid tempQualifier2 = entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x2, -y1)); + session.Entities.Add(tempQualifier2); + EntityUid tempQualifier3 = entityManager.SpawnEntity(RedPiecePrototype, center.Offset(-x2, -y2)); + session.Entities.Add(tempQualifier3); // Green pieces. - session.Entities.Add(entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x1, -y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x1, -y2)).Uid); - session.Entities.Add(entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x2, -y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x2, -y2)).Uid); + EntityUid tempQualifier4 = entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x1, -y1)); + session.Entities.Add(tempQualifier4); + EntityUid tempQualifier5 = entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x1, -y2)); + session.Entities.Add(tempQualifier5); + EntityUid tempQualifier6 = entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x2, -y1)); + session.Entities.Add(tempQualifier6); + EntityUid tempQualifier7 = entityManager.SpawnEntity(GreenPiecePrototype, center.Offset(x2, -y2)); + session.Entities.Add(tempQualifier7); // Yellow pieces. - session.Entities.Add(entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x1, y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x1, y2)).Uid); - session.Entities.Add(entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x2, y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x2, y2)).Uid); + EntityUid tempQualifier8 = entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x1, y1)); + session.Entities.Add(tempQualifier8); + EntityUid tempQualifier9 = entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x1, y2)); + session.Entities.Add(tempQualifier9); + EntityUid tempQualifier10 = entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x2, y1)); + session.Entities.Add(tempQualifier10); + EntityUid tempQualifier11 = entityManager.SpawnEntity(YellowPiecePrototype, center.Offset(x2, y2)); + session.Entities.Add(tempQualifier11); // Blue pieces. - session.Entities.Add(entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x1, y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x1, y2)).Uid); - session.Entities.Add(entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x2, y1)).Uid); - session.Entities.Add(entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x2, y2)).Uid); + EntityUid tempQualifier12 = entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x1, y1)); + session.Entities.Add(tempQualifier12); + EntityUid tempQualifier13 = entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x1, y2)); + session.Entities.Add(tempQualifier13); + EntityUid tempQualifier14 = entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x2, y1)); + session.Entities.Add(tempQualifier14); + EntityUid tempQualifier15 = entityManager.SpawnEntity(BluePiecePrototype, center.Offset(-x2, y2)); + session.Entities.Add(tempQualifier15); } } } diff --git a/Content.Server/Tabletop/TabletopSystem.Draggable.cs b/Content.Server/Tabletop/TabletopSystem.Draggable.cs index d5267bac15..384d8234ac 100644 --- a/Content.Server/Tabletop/TabletopSystem.Draggable.cs +++ b/Content.Server/Tabletop/TabletopSystem.Draggable.cs @@ -24,7 +24,7 @@ namespace Content.Server.Tabletop /// private void OnTabletopMove(TabletopMoveEvent msg, EntitySessionEventArgs args) { - if (args.SenderSession as IPlayerSession is not { AttachedEntityUid: { } playerEntity } playerSession) + if (args.SenderSession as IPlayerSession is not { AttachedEntity: { } playerEntity } playerSession) return; if (!EntityManager.TryGetComponent(msg.TableUid, out TabletopGameComponent? tabletop) || tabletop.Session is not {} session) @@ -42,29 +42,29 @@ namespace Content.Server.Tabletop return; // Check if moved entity exists and has tabletop draggable component - if (!EntityManager.TryGetEntity(msg.MovedEntityUid, out var movedEntity)) + if (!EntityManager.EntityExists(msg.MovedEntityUid)) return; - if (!EntityManager.HasComponent(movedEntity.Uid)) + if (!EntityManager.HasComponent(msg.MovedEntityUid)) return; // TODO: some permission system, disallow movement if you're not permitted to move the item // Move the entity and dirty it (we use the map ID from the entity so noone can try to be funny and move the item to another map) - var transform = EntityManager.GetComponent(movedEntity.Uid); + var transform = EntityManager.GetComponent(msg.MovedEntityUid); var entityCoordinates = new EntityCoordinates(_mapManager.GetMapEntityId(transform.MapID), msg.Coordinates.Position); transform.Coordinates = entityCoordinates; } private void OnDraggingPlayerChanged(TabletopDraggingPlayerChangedEvent msg) { - var draggedEntity = EntityManager.GetEntity(msg.DraggedEntityUid); + var dragged = msg.DraggedEntityUid; - if (!draggedEntity.TryGetComponent(out var draggableComponent)) return; + if (!EntityManager.TryGetComponent(dragged, out var draggableComponent)) return; draggableComponent.DraggingPlayer = msg.DraggingPlayer; - if (!draggedEntity.TryGetComponent(out var appearance)) return; + if (!EntityManager.TryGetComponent(dragged, out var appearance)) return; if (draggableComponent.DraggingPlayer != null) { diff --git a/Content.Server/Tabletop/TabletopSystem.Session.cs b/Content.Server/Tabletop/TabletopSystem.Session.cs index e5bdd14b11..7ca26cb0ec 100644 --- a/Content.Server/Tabletop/TabletopSystem.Session.cs +++ b/Content.Server/Tabletop/TabletopSystem.Session.cs @@ -3,6 +3,7 @@ using Content.Shared.Tabletop.Events; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Log; using Robust.Shared.Maths; @@ -72,7 +73,7 @@ namespace Content.Server.Tabletop /// The UID of the tabletop game entity. public void OpenSessionFor(IPlayerSession player, EntityUid uid) { - if (!EntityManager.TryGetComponent(uid, out TabletopGameComponent? tabletop) || player.AttachedEntity is not {} attachedEntity) + if (!EntityManager.TryGetComponent(uid, out TabletopGameComponent? tabletop) || player.AttachedEntity is not {Valid: true} attachedEntity) return; // Make sure we have a session, and add the player to it if not added already. @@ -81,7 +82,7 @@ namespace Content.Server.Tabletop if (session.Players.ContainsKey(player)) return; - if(attachedEntity.TryGetComponent(out var gamer)) + if(EntityManager.TryGetComponent(attachedEntity, out var gamer)) CloseSessionFor(player, gamer.Tabletop, false); // Set the entity as an absolute GAMER. @@ -110,13 +111,13 @@ namespace Content.Server.Tabletop if (!session.Players.TryGetValue(player, out var data)) return; - if(removeGamerComponent && player.AttachedEntity is {} attachedEntity && attachedEntity.TryGetComponent(out TabletopGamerComponent? gamer)) + if(removeGamerComponent && player.AttachedEntity is {} attachedEntity && EntityManager.TryGetComponent(attachedEntity, out TabletopGamerComponent? gamer)) { // We invalidate this to prevent an infinite feedback from removing the component. gamer.Tabletop = EntityUid.Invalid; // You stop being a gamer....... - attachedEntity.RemoveComponent(); + EntityManager.RemoveComponent(attachedEntity); } session.Players.Remove(player); @@ -148,9 +149,9 @@ namespace Content.Server.Tabletop eyeComponent.Zoom = tabletop.CameraZoom; // Add the user to the view subscribers. If there is no player session, just skip this step - _viewSubscriberSystem.AddViewSubscriber(camera.Uid, player); + _viewSubscriberSystem.AddViewSubscriber(camera, player); - return camera.Uid; + return camera; } } } diff --git a/Content.Server/Tabletop/TabletopSystem.cs b/Content.Server/Tabletop/TabletopSystem.cs index f278639445..3f69d808a1 100644 --- a/Content.Server/Tabletop/TabletopSystem.cs +++ b/Content.Server/Tabletop/TabletopSystem.cs @@ -42,7 +42,7 @@ namespace Content.Server.Tabletop if (!args.CanAccess || !args.CanInteract) return; - if (!args.User.TryGetComponent(out var actor)) + if (!EntityManager.TryGetComponent(args.User, out var actor)) return; Verb verb = new(); @@ -55,11 +55,11 @@ namespace Content.Server.Tabletop private void OnTabletopActivate(EntityUid uid, TabletopGameComponent component, ActivateInWorldEvent args) { // Check that a player is attached to the entity. - if (!EntityManager.TryGetComponent(args.User.Uid, out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; // Check that the entity can interact with the game board. - if(_actionBlockerSystem.CanInteract(args.User.Uid)) + if(_actionBlockerSystem.CanInteract(args.User)) OpenSessionFor(actor.PlayerSession, uid); } @@ -97,13 +97,13 @@ namespace Content.Server.Tabletop if (!EntityManager.EntityExists(gamer.Tabletop)) continue; - if (!gamer.Owner.TryGetComponent(out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(gamer.Owner, out ActorComponent? actor)) { - gamer.Owner.RemoveComponent(); + EntityManager.RemoveComponent(gamer.Owner); return; }; - var gamerUid = gamer.OwnerUid; + var gamerUid = (gamer).Owner; if (actor.PlayerSession.Status > SessionStatus.Connected || CanSeeTable(gamerUid, gamer.Tabletop) || !StunnedOrNoHands(gamerUid)) diff --git a/Content.Server/Temperature/Components/HeatResistanceComponent.cs b/Content.Server/Temperature/Components/HeatResistanceComponent.cs index 27feb3cb3a..b3cc28da7b 100644 --- a/Content.Server/Temperature/Components/HeatResistanceComponent.cs +++ b/Content.Server/Temperature/Components/HeatResistanceComponent.cs @@ -2,6 +2,7 @@ using Content.Server.Clothing.Components; using Content.Server.Inventory.Components; using Content.Shared.Inventory; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Temperature.Components { @@ -14,7 +15,7 @@ namespace Content.Server.Temperature.Components { // TODO: When making into system: Any animal that touches bulb that has no // InventoryComponent but still would have default heat resistance in the future (maybe) - if (!Owner.TryGetComponent(out var inventoryComp)) + if (!IoCManager.Resolve().TryGetComponent(Owner, out var inventoryComp)) { // Magical number just copied from below return int.MinValue; diff --git a/Content.Server/Temperature/Components/TemperatureComponent.cs b/Content.Server/Temperature/Components/TemperatureComponent.cs index 7f2ef63e70..5f6b19f2f4 100644 --- a/Content.Server/Temperature/Components/TemperatureComponent.cs +++ b/Content.Server/Temperature/Components/TemperatureComponent.cs @@ -2,6 +2,7 @@ using Content.Shared.Atmos; using Content.Shared.Damage; using Content.Shared.FixedPoint; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Physics; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -45,7 +46,7 @@ namespace Content.Server.Temperature.Components { get { - if (Owner.TryGetComponent(out var physics) && physics.Mass != 0) + if (IoCManager.Resolve().TryGetComponent(Owner, out var physics) && physics.Mass != 0) { return SpecificHeat * physics.Mass; } diff --git a/Content.Server/Temperature/Systems/TemperatureSystem.cs b/Content.Server/Temperature/Systems/TemperatureSystem.cs index ea2cbc6a74..a3c5e4ef89 100644 --- a/Content.Server/Temperature/Systems/TemperatureSystem.cs +++ b/Content.Server/Temperature/Systems/TemperatureSystem.cs @@ -59,7 +59,7 @@ namespace Content.Server.Temperature.Systems if (comp.Deleted || comp.Paused) continue; - ChangeDamage(comp.OwnerUid, comp); + ChangeDamage((comp).Owner, comp); } ShouldUpdateDamage.Clear(); diff --git a/Content.Server/Throwing/ThrowHelper.cs b/Content.Server/Throwing/ThrowHelper.cs index 46035fd304..c962a2ac40 100644 --- a/Content.Server/Throwing/ThrowHelper.cs +++ b/Content.Server/Throwing/ThrowHelper.cs @@ -5,6 +5,7 @@ using Content.Shared.MobState.Components; using Content.Shared.Tag; using Content.Shared.Throwing; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Physics; @@ -30,11 +31,12 @@ namespace Content.Server.Throwing /// How much the direction vector should be multiplied for velocity. /// /// The ratio of impulse applied to the thrower - defaults to 10 because otherwise it's not enough to properly recover from getting spaced - internal static void TryThrow(this IEntity entity, Vector2 direction, float strength = 1.0f, IEntity? user = null, float pushbackRatio = 10.0f) + internal static void TryThrow(this EntityUid entity, Vector2 direction, float strength = 1.0f, EntityUid? user = null, float pushbackRatio = 10.0f) { - if (entity.Deleted || + var entities = IoCManager.Resolve(); + if (entities.GetComponent(entity).EntityDeleted || strength <= 0f || - !entity.TryGetComponent(out PhysicsComponent? physicsComponent)) + !entities.TryGetComponent(entity, out PhysicsComponent? physicsComponent)) { return; } @@ -45,14 +47,14 @@ namespace Content.Server.Throwing return; } - if (entity.HasComponent()) + if (entities.HasComponent(entity)) { Logger.Warning("Throwing not supported for mobs!"); return; } var comp = entity.EnsureComponent(); - if (entity.HasComponent()) + if (entities.HasComponent(entity)) { comp.Thrower = user; // Give it a l'il spin. @@ -62,11 +64,11 @@ namespace Content.Server.Throwing } else if(direction != Vector2.Zero) { - entity.Transform.LocalRotation = direction.ToWorldAngle() - Math.PI; + entities.GetComponent(entity).LocalRotation = direction.ToWorldAngle() - Math.PI; } if (user != null) - EntitySystem.Get().ThrownInteraction(user, entity); + EntitySystem.Get().ThrownInteraction(user.Value, entity); } var impulseVector = direction.Normalized * strength * physicsComponent.Mass; @@ -93,10 +95,10 @@ namespace Content.Server.Throwing } // Give thrower an impulse in the other direction - if (user != null && pushbackRatio > 0.0f && user.TryGetComponent(out IPhysBody? body)) + if (user != null && pushbackRatio > 0.0f && entities.TryGetComponent(user.Value, out IPhysBody? body)) { var msg = new ThrowPushbackAttemptEvent(); - body.Owner.EntityManager.EventBus.RaiseLocalEvent(body.Owner.Uid, msg); + entities.EventBus.RaiseLocalEvent(body.Owner, msg); if (!msg.Cancelled) { diff --git a/Content.Server/Tiles/FloorTileItemComponent.cs b/Content.Server/Tiles/FloorTileItemComponent.cs index ce04224e2e..825cdcb71a 100644 --- a/Content.Server/Tiles/FloorTileItemComponent.cs +++ b/Content.Server/Tiles/FloorTileItemComponent.cs @@ -20,6 +20,7 @@ namespace Content.Server.Tiles [RegisterComponent] public class FloorTileItemComponent : Component, IAfterInteract { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!; public override string Name => "FloorTile"; @@ -58,16 +59,16 @@ namespace Content.Server.Tiles if (!eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true)) return true; - if (!Owner.TryGetComponent(out StackComponent? stack)) + if (!_entMan.TryGetComponent(Owner, out StackComponent? stack)) return true; var mapManager = IoCManager.Resolve(); var location = eventArgs.ClickLocation.AlignWithClosestGridTile(); - var locationMap = location.ToMap(Owner.EntityManager); + var locationMap = location.ToMap(_entMan); if (locationMap.MapId == MapId.Nullspace) return true; - mapManager.TryGetGrid(location.GetGridId(Owner.EntityManager), out var mapGrid); + mapManager.TryGetGrid(location.GetGridId(_entMan), out var mapGrid); if (_outputTiles == null) return true; @@ -83,7 +84,7 @@ namespace Content.Server.Tiles if (HasBaseTurf(currentTileDefinition, baseTurf.Name)) { - if (!EntitySystem.Get().Use(Owner.Uid, 1, stack)) + if (!EntitySystem.Get().Use(Owner, 1, stack)) continue; PlaceAt(mapGrid, location, currentTileDefinition.TileId); diff --git a/Content.Server/Toilet/ToiletComponent.cs b/Content.Server/Toilet/ToiletComponent.cs index c9b51b017a..b44f600799 100644 --- a/Content.Server/Toilet/ToiletComponent.cs +++ b/Content.Server/Toilet/ToiletComponent.cs @@ -15,7 +15,6 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Content.Shared.Toilet; using Content.Shared.Tools; -using Content.Shared.Tools.Components; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -35,6 +34,8 @@ namespace Content.Server.Toilet IInteractHand, IMapInit, IExamine, ISuicideAct #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; + public sealed override string Name => "Toilet"; private const float PryLidTime = 1f; @@ -68,7 +69,7 @@ namespace Content.Server.Toilet async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { // are player trying place or lift of cistern lid? - if (eventArgs.Using.TryGetComponent(out ToolComponent? tool) + if (_entMan.TryGetComponent(eventArgs.Using, out ToolComponent? tool) && tool.Qualities.Contains(_pryingQuality)) { // check if someone is already prying this toilet @@ -76,7 +77,7 @@ namespace Content.Server.Toilet return false; _isPrying = true; - if (!await EntitySystem.Get().UseTool(eventArgs.Using.Uid, eventArgs.User.Uid, Owner.Uid, 0f, PryLidTime, _pryingQuality)) + if (!await EntitySystem.Get().UseTool(eventArgs.Using, eventArgs.User, Owner, 0f, PryLidTime, _pryingQuality)) { _isPrying = false; return false; @@ -112,7 +113,7 @@ namespace Content.Server.Toilet // just want to up/down seat? // check that nobody seats on seat right now - if (Owner.TryGetComponent(out StrapComponent? strap)) + if (_entMan.TryGetComponent(Owner, out StrapComponent? strap)) { if (strap.BuckledEntities.Count != 0) return false; @@ -143,33 +144,33 @@ namespace Content.Server.Toilet private void UpdateSprite() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(ToiletVisuals.LidOpen, LidOpen); appearance.SetData(ToiletVisuals.SeatUp, IsSeatUp); } } - SuicideKind ISuicideAct.Suicide(IEntity victim, IChatManager chat) + SuicideKind ISuicideAct.Suicide(EntityUid victim, IChatManager chat) { // check that victim even have head - if (victim.TryGetComponent(out var body) && + if (_entMan.TryGetComponent(victim, out var body) && body.HasPartOfType(BodyPartType.Head)) { - var othersMessage = Loc.GetString("toilet-component-suicide-head-message-others", ("victim",victim.Name),("owner", Owner.Name)); + var othersMessage = Loc.GetString("toilet-component-suicide-head-message-others", ("victim",Name: _entMan.GetComponent(victim).EntityName),("owner", Name: _entMan.GetComponent(Owner).EntityName)); victim.PopupMessageOtherClients(othersMessage); - var selfMessage = Loc.GetString("toilet-component-suicide-head-message", ("owner", Owner.Name)); + var selfMessage = Loc.GetString("toilet-component-suicide-head-message", ("owner", Name: _entMan.GetComponent(Owner).EntityName)); victim.PopupMessage(selfMessage); return SuicideKind.Asphyxiation; } else { - var othersMessage = Loc.GetString("toilet-component-suicide-message-others",("victim", victim.Name),("owner", Owner.Name)); + var othersMessage = Loc.GetString("toilet-component-suicide-message-others",("victim", Name: _entMan.GetComponent(victim).EntityName),("owner", Name: _entMan.GetComponent(Owner).EntityName)); victim.PopupMessageOtherClients(othersMessage); - var selfMessage = Loc.GetString("toilet-component-suicide-message", ("owner",Owner.Name)); + var selfMessage = Loc.GetString("toilet-component-suicide-message", ("owner",Name: _entMan.GetComponent(Owner).EntityName)); victim.PopupMessage(selfMessage); return SuicideKind.Blunt; diff --git a/Content.Server/Tools/Components/TilePryingComponent.cs b/Content.Server/Tools/Components/TilePryingComponent.cs index 98275bd4fb..37123df84b 100644 --- a/Content.Server/Tools/Components/TilePryingComponent.cs +++ b/Content.Server/Tools/Components/TilePryingComponent.cs @@ -3,7 +3,6 @@ using Content.Shared.Interaction; using Content.Shared.Interaction.Helpers; using Content.Shared.Maps; using Content.Shared.Tools; -using Content.Shared.Tools.Components; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; @@ -15,6 +14,7 @@ namespace Content.Server.Tools.Components [RegisterComponent] public class TilePryingComponent : Component, IAfterInteract { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!; [Dependency] private readonly IMapManager _mapManager = default!; @@ -32,12 +32,12 @@ namespace Content.Server.Tools.Components return true; } - public async void TryPryTile(IEntity user, EntityCoordinates clickLocation) + public async void TryPryTile(EntityUid user, EntityCoordinates clickLocation) { - if (!Owner.TryGetComponent(out var tool) && _toolComponentNeeded) + if (!_entMan.TryGetComponent(Owner, out var tool) && _toolComponentNeeded) return; - if (!_mapManager.TryGetGrid(clickLocation.GetGridId(Owner.EntityManager), out var mapGrid)) + if (!_mapManager.TryGetGrid(clickLocation.GetGridId(_entMan), out var mapGrid)) return; var tile = mapGrid.GetTileRef(clickLocation); @@ -52,10 +52,10 @@ namespace Content.Server.Tools.Components if (!tileDef.CanCrowbar) return; - if (_toolComponentNeeded && !await EntitySystem.Get().UseTool(Owner.Uid, user.Uid, null, 0f, 0f, _qualityNeeded, toolComponent:tool)) + if (_toolComponentNeeded && !await EntitySystem.Get().UseTool(Owner, user, null, 0f, 0f, _qualityNeeded, toolComponent:tool)) return; - coordinates.PryTile(Owner.EntityManager, _mapManager); + coordinates.PryTile(_entMan, _mapManager); } } } diff --git a/Content.Server/Tools/ToolSystem.Welder.cs b/Content.Server/Tools/ToolSystem.Welder.cs index 503d2c21d8..b937389bbf 100644 --- a/Content.Server/Tools/ToolSystem.Welder.cs +++ b/Content.Server/Tools/ToolSystem.Welder.cs @@ -6,7 +6,6 @@ using Content.Server.Chemistry.EntitySystems; using Content.Server.Items; using Content.Server.Tools.Components; using Content.Shared.Audio; -using Content.Shared.Chemistry.Reagent; using Content.Shared.Examine; using Content.Shared.FixedPoint; using Content.Shared.Interaction; @@ -114,7 +113,7 @@ namespace Content.Server.Tools SoundSystem.Play(Filter.Pvs(uid), welder.WelderOnSounds.GetSound(), uid, AudioHelpers.WithVariation(0.125f).WithVolume(-5f)); // TODO: Use TransformComponent directly. - _atmosphereSystem.HotspotExpose(welder.Owner.Transform.Coordinates, 700, 50, true); + _atmosphereSystem.HotspotExpose(EntityManager.GetComponent(welder.Owner).Coordinates, 700, 50, true); welder.Dirty(); @@ -196,7 +195,7 @@ namespace Content.Server.Tools private void OnWelderActivate(EntityUid uid, WelderComponent welder, ActivateInWorldEvent args) { - args.Handled = TryToggleWelder(uid, args.User.Uid, welder); + args.Handled = TryToggleWelder(uid, args.User, welder); } private void OnWelderAfterInteract(EntityUid uid, WelderComponent welder, AfterInteractEvent args) @@ -204,27 +203,27 @@ namespace Content.Server.Tools if (args.Handled) return; - if (args.Target == null || !args.CanReach) + if (args.Target is not {Valid: true} target || !args.CanReach) return; // TODO: Clean up this inherited oldcode. - if (args.Target.TryGetComponent(out ReagentTankComponent? tank) + if (EntityManager.TryGetComponent(target, out ReagentTankComponent? tank) && tank.TankType == ReagentTankType.Fuel - && _solutionContainerSystem.TryGetDrainableSolution(args.Target.Uid, out var targetSolution) + && _solutionContainerSystem.TryGetDrainableSolution(target, out var targetSolution) && _solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var welderSolution)) { var trans = FixedPoint2.Min(welderSolution.AvailableVolume, targetSolution.DrainAvailable); if (trans > 0) { - var drained = _solutionContainerSystem.Drain(args.Target.Uid, targetSolution, trans); + var drained = _solutionContainerSystem.Drain(target, targetSolution, trans); _solutionContainerSystem.TryAddSolution(uid, welderSolution, drained); SoundSystem.Play(Filter.Pvs(uid), welder.WelderRefill.GetSound(), uid); - args.Target.PopupMessage(args.User, Loc.GetString("welder-component-after-interact-refueled-message")); + target.PopupMessage(args.User, Loc.GetString("welder-component-after-interact-refueled-message")); } else { - args.Target.PopupMessage(args.User, Loc.GetString("welder-component-no-fuel-in-tank", ("owner", args.Target))); + target.PopupMessage(args.User, Loc.GetString("welder-component-no-fuel-in-tank", ("owner", args.Target))); } } @@ -233,7 +232,7 @@ namespace Content.Server.Tools private void OnWelderUseInHand(EntityUid uid, WelderComponent welder, UseInHandEvent args) { - args.Handled = TryToggleWelder(uid, args.User.Uid, welder); + args.Handled = TryToggleWelder(uid, args.User, welder); } private void OnWelderToolUseAttempt(EntityUid uid, WelderComponent welder, ToolUseAttemptEvent args) @@ -317,7 +316,7 @@ namespace Content.Server.Tools continue; // TODO: Use TransformComponent directly. - _atmosphereSystem.HotspotExpose(welder.Owner.Transform.Coordinates, 700, 50, true); + _atmosphereSystem.HotspotExpose(EntityManager.GetComponent(welder.Owner).Coordinates, 700, 50, true); solution.RemoveReagent(welder.FuelReagent, welder.FuelConsumption * _welderTimer); diff --git a/Content.Server/Traitor/Uplink/Account/UplinkAccountsSystem.cs b/Content.Server/Traitor/Uplink/Account/UplinkAccountsSystem.cs index 4477ff57be..decaf4a236 100644 --- a/Content.Server/Traitor/Uplink/Account/UplinkAccountsSystem.cs +++ b/Content.Server/Traitor/Uplink/Account/UplinkAccountsSystem.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using Content.Server.Mind.Components; -using Content.Server.Stack; using Content.Shared.Stacks; using Content.Shared.Traitor.Uplink; using Robust.Shared.GameObjects; @@ -71,7 +69,7 @@ namespace Content.Server.Traitor.Uplink.Account } - public bool TryPurchaseItem(UplinkAccount acc, string itemId, EntityCoordinates spawnCoords, [NotNullWhen(true)] out IEntity? purchasedItem) + public bool TryPurchaseItem(UplinkAccount acc, string itemId, EntityCoordinates spawnCoords, [NotNullWhen(true)] out EntityUid? purchasedItem) { purchasedItem = null; @@ -107,7 +105,7 @@ namespace Content.Server.Traitor.Uplink.Account // create a stack of TCs near player var stackEntity = EntityManager.SpawnEntity(TelecrystalProtoId, spawnCoords); - stackUid = stackEntity.Uid; + stackUid = stackEntity; // set right amount in stack _stackSystem.SetCount(stackUid.Value, actTC); diff --git a/Content.Server/Traitor/Uplink/Commands/AddUplinkCommand.cs b/Content.Server/Traitor/Uplink/Commands/AddUplinkCommand.cs index 104354d4aa..7f5346c7cc 100644 --- a/Content.Server/Traitor/Uplink/Commands/AddUplinkCommand.cs +++ b/Content.Server/Traitor/Uplink/Commands/AddUplinkCommand.cs @@ -35,15 +35,14 @@ namespace Content.Server.Traitor.Uplink.Commands shell.WriteLine(Loc.GetString("shell-target-player-does-not-exist")); return; } - if (session.AttachedEntity == null) + if (session.AttachedEntity is not {} user) { shell.WriteLine(Loc.GetString("Selected player doesn't controll any entity")); return; } - var user = session.AttachedEntity; // Get target item - IEntity? uplinkEntity = null; + EntityUid? uplinkEntity = null; var entityManager = IoCManager.Resolve(); if (args.Length >= 2) { @@ -60,7 +59,7 @@ namespace Content.Server.Traitor.Uplink.Commands return; } - uplinkEntity = entityManager.GetEntity(eUid); + uplinkEntity = eUid; } // Get TC count @@ -68,13 +67,13 @@ namespace Content.Server.Traitor.Uplink.Commands var tcCount = configManager.GetCVar(CCVars.TraitorStartingBalance); // Get account - var uplinkAccount = new UplinkAccount(tcCount, user.Uid); + var uplinkAccount = new UplinkAccount(tcCount, user); var accounts = entityManager.EntitySysManager.GetEntitySystem(); accounts.AddNewAccount(uplinkAccount); // Finally add uplink if (!entityManager.EntitySysManager.GetEntitySystem() - .AddUplink(user, uplinkAccount!, uplinkEntity)) + .AddUplink(user, uplinkAccount, uplinkEntity)) { shell.WriteLine(Loc.GetString("Failed to add uplink to the player")); return; diff --git a/Content.Server/Traitor/Uplink/Telecrystal/TelecrystalSystem.cs b/Content.Server/Traitor/Uplink/Telecrystal/TelecrystalSystem.cs index 64071fa6b6..e887c567e0 100644 --- a/Content.Server/Traitor/Uplink/Telecrystal/TelecrystalSystem.cs +++ b/Content.Server/Traitor/Uplink/Telecrystal/TelecrystalSystem.cs @@ -26,7 +26,7 @@ namespace Content.Server.Traitor.Uplink.Telecrystal if (args.Handled) return; - if (args.Target == null || !EntityManager.TryGetComponent(args.Target.Uid, out UplinkComponent? uplink)) + if (args.Target == null || !EntityManager.TryGetComponent(args.Target.Value, out UplinkComponent? uplink)) return; // TODO: when uplink will have some auth logic (like PDA ringtone code) diff --git a/Content.Server/Traitor/Uplink/UplinkSystem.cs b/Content.Server/Traitor/Uplink/UplinkSystem.cs index b7a31c95e5..458defd0e2 100644 --- a/Content.Server/Traitor/Uplink/UplinkSystem.cs +++ b/Content.Server/Traitor/Uplink/UplinkSystem.cs @@ -84,7 +84,7 @@ namespace Content.Server.Traitor.Uplink if (component.UplinkAccount == null) return; - if (!EntityManager.TryGetComponent(args.User.Uid, out ActorComponent? actor)) + if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; var actionBlocker = EntitySystem.Get(); @@ -113,12 +113,11 @@ namespace Content.Server.Traitor.Uplink private void OnBuy(EntityUid uid, UplinkComponent uplink, UplinkBuyListingMessage message) { - var player = message.Session.AttachedEntity; - if (player == null) return; + if (message.Session.AttachedEntity is not {Valid: true} player) return; if (uplink.UplinkAccount == null) return; if (!_accounts.TryPurchaseItem(uplink.UplinkAccount, message.ItemId, - player.Transform.Coordinates, out var entity)) + EntityManager.GetComponent(player).Coordinates, out var entity)) { SoundSystem.Play(Filter.SinglePlayer(message.Session), uplink.InsufficientFundsSound.GetSound(), uplink.Owner, AudioParams.Default); @@ -126,8 +125,8 @@ namespace Content.Server.Traitor.Uplink return; } - if (player.TryGetComponent(out HandsComponent? hands) && - entity.TryGetComponent(out ItemComponent? item)) + if (EntityManager.TryGetComponent(player, out HandsComponent? hands) && + EntityManager.TryGetComponent(entity.Value, out ItemComponent? item)) { hands.PutInHandOrDrop(item); } @@ -144,17 +143,16 @@ namespace Content.Server.Traitor.Uplink if (acc == null) return; - var player = args.Session.AttachedEntity; - if (player == null) return; - var cords = player.Transform.Coordinates; + if (args.Session.AttachedEntity is not {Valid: true} player) return; + var cords = EntityManager.GetComponent(player).Coordinates; // try to withdraw TCs from account if (!_accounts.TryWithdrawTC(acc, args.TC, cords, out var tcUid)) return; // try to put it into players hands - if (player.TryGetComponent(out SharedHandsComponent? hands)) - hands.TryPutInAnyHand(EntityManager.GetEntity(tcUid.Value)); + if (EntityManager.TryGetComponent(player, out SharedHandsComponent? hands)) + hands.TryPutInAnyHand(tcUid.Value); // play buying sound SoundSystem.Play(Filter.SinglePlayer(args.Session), uplink.BuySuccessSound.GetSound(), @@ -189,7 +187,7 @@ namespace Content.Server.Traitor.Uplink ui.SetState(new UplinkUpdateState(accData, listings)); } - public bool AddUplink(IEntity user, UplinkAccount account, IEntity? uplinkEntity = null) + public bool AddUplink(EntityUid user, UplinkAccount account, EntityUid? uplinkEntity = null) { // Try to find target item if (uplinkEntity == null) @@ -199,16 +197,16 @@ namespace Content.Server.Traitor.Uplink return false; } - var uplink = uplinkEntity.EnsureComponent(); + var uplink = uplinkEntity.Value.EnsureComponent(); SetAccount(uplink, account); return true; } - private IEntity? FindUplinkTarget(IEntity user) + private EntityUid? FindUplinkTarget(EntityUid user) { // Try to find PDA in inventory - if (user.TryGetComponent(out InventoryComponent? inventory)) + if (EntityManager.TryGetComponent(user, out InventoryComponent? inventory)) { var foundPDA = inventory.LookupItems().FirstOrDefault(); if (foundPDA != null) @@ -216,12 +214,12 @@ namespace Content.Server.Traitor.Uplink } // Also check hands - if (user.TryGetComponent(out HandsComponent? hands)) + if (EntityManager.TryGetComponent(user, out HandsComponent? hands)) { var heldItems = hands.GetAllHeldItems(); foreach (var item in heldItems) { - if (item.Owner.HasComponent()) + if (EntityManager.HasComponent(item.Owner)) return item.Owner; } } diff --git a/Content.Server/TraitorDeathMatch/Components/TraitorDeathMatchRedemptionComponent.cs b/Content.Server/TraitorDeathMatch/Components/TraitorDeathMatchRedemptionComponent.cs index 42ec6f3b24..12fea6870f 100644 --- a/Content.Server/TraitorDeathMatch/Components/TraitorDeathMatchRedemptionComponent.cs +++ b/Content.Server/TraitorDeathMatch/Components/TraitorDeathMatchRedemptionComponent.cs @@ -1,7 +1,6 @@ using System.Threading.Tasks; using Content.Server.Inventory.Components; using Content.Server.Mind.Components; -using Content.Server.PDA; using Content.Server.Traitor.Uplink.Account; using Content.Server.Traitor.Uplink.Components; using Content.Shared.Interaction; @@ -16,19 +15,21 @@ namespace Content.Server.TraitorDeathMatch.Components [RegisterComponent] public class TraitorDeathMatchRedemptionComponent : Component, IInteractUsing { + [Dependency] private readonly IEntityManager _entMan = default!; + /// public override string Name => "TraitorDeathMatchRedemption"; async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out var userInv)) + if (!_entMan.TryGetComponent(eventArgs.User, out var userInv)) { Owner.PopupMessage(eventArgs.User, Loc.GetString("traitor-death-match-redemption-component-interact-using-main-message", ("secondMessage", Loc.GetString("traitor-death-match-redemption-component-interact-using-no-inventory-message")))); return false; } - if (!eventArgs.User.TryGetComponent(out var userMindComponent)) + if (!_entMan.TryGetComponent(eventArgs.User, out var userMindComponent)) { Owner.PopupMessage(eventArgs.User, Loc.GetString("traitor-death-match-redemption-component-interact-using-main-message", ("secondMessage", Loc.GetString("traitor-death-match-redemption-component-interact-using-no-mind-message")))); @@ -43,14 +44,14 @@ namespace Content.Server.TraitorDeathMatch.Components return false; } - if (!eventArgs.Using.TryGetComponent(out var victimUplink)) + if (!_entMan.TryGetComponent(eventArgs.Using, out var victimUplink)) { Owner.PopupMessage(eventArgs.User, Loc.GetString("traitor-death-match-redemption-component-interact-using-main-message", ("secondMessage", Loc.GetString("traitor-death-match-redemption-component-interact-using-no-pda-message")))); return false; } - if (!eventArgs.Using.TryGetComponent(out var victimPDAOwner)) + if (!_entMan.TryGetComponent(eventArgs.Using, out var victimPDAOwner)) { Owner.PopupMessage(eventArgs.User, Loc.GetString("traitor-death-match-redemption-component-interact-using-main-message", ("secondMessage", Loc.GetString("traitor-death-match-redemption-component-interact-using-no-pda-owner-message")))); @@ -64,11 +65,10 @@ namespace Content.Server.TraitorDeathMatch.Components return false; } - var userPDAEntity = userInv.GetSlotItem(EquipmentSlotDefines.Slots.IDCARD)?.Owner; UplinkComponent? userUplink = null; - if (userPDAEntity != null) - if (userPDAEntity.TryGetComponent(out var userUplinkComponent)) + if (userInv.GetSlotItem(EquipmentSlotDefines.Slots.IDCARD)?.Owner is {Valid: true} userPDAEntity) + if (_entMan.TryGetComponent(userPDAEntity, out var userUplinkComponent)) userUplink = userUplinkComponent; if (userUplink == null) @@ -106,12 +106,12 @@ namespace Content.Server.TraitorDeathMatch.Components } // 4 is the per-PDA bonus amount. - var accounts = Owner.EntityManager.EntitySysManager.GetEntitySystem(); + var accounts = _entMan.EntitySysManager.GetEntitySystem(); var transferAmount = victimAccount.Balance + 4; accounts.SetBalance(victimAccount, 0); accounts.AddToBalance(userAccount, transferAmount); - victimUplink.Owner.Delete(); + _entMan.DeleteEntity(victimUplink.Owner); Owner.PopupMessage(eventArgs.User, Loc.GetString("traitor-death-match-redemption-component-interact-using-success-message", ("tcAmount", transferAmount))); return true; diff --git a/Content.Server/UserInterface/ActivatableUISystem.cs b/Content.Server/UserInterface/ActivatableUISystem.cs index 0649769802..5cbabd3eb3 100644 --- a/Content.Server/UserInterface/ActivatableUISystem.cs +++ b/Content.Server/UserInterface/ActivatableUISystem.cs @@ -1,23 +1,15 @@ using System.Linq; -using Content.Shared; -using Content.Shared.CCVar; +using Content.Server.Administration.Managers; using Content.Shared.ActionBlocker; using Content.Shared.Hands; -using Content.Shared.Popups; -using Content.Shared.Standing; -using Content.Shared.Stunnable; -using Content.Shared.Throwing; using Content.Shared.Interaction; -using Content.Shared.Interaction.Helpers; -using Content.Server.Administration.Managers; +using Content.Shared.Popups; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Server.Player; -using Robust.Shared.Configuration; -using Robust.Shared.Localization; using Robust.Shared.GameObjects; -using Robust.Shared.Network; using Robust.Shared.IoC; +using Robust.Shared.Localization; namespace Content.Server.UserInterface { @@ -65,13 +57,13 @@ namespace Content.Server.UserInterface SetCurrentSingleUser(uid, null, component); } - private bool InteractUI(IEntity user, ActivatableUIComponent aui) + private bool InteractUI(EntityUid user, ActivatableUIComponent aui) { - if (!user.TryGetComponent(out ActorComponent? actor)) return false; + if (!EntityManager.TryGetComponent(user, out ActorComponent? actor)) return false; if (aui.AdminOnly && !_adminManager.IsAdmin(actor.PlayerSession)) return false; - if (!_actionBlockerSystem.CanInteract(user.Uid)) + if (!_actionBlockerSystem.CanInteract(user)) { user.PopupMessageCursor(Loc.GetString("base-computer-ui-component-cannot-interact")); return true; @@ -91,10 +83,10 @@ namespace Content.Server.UserInterface // If we've gotten this far, fire a cancellable event that indicates someone is about to activate this. // This is so that stuff can require further conditions (like power). var oae = new ActivatableUIOpenAttemptEvent(user); - RaiseLocalEvent(aui.OwnerUid, oae, false); + RaiseLocalEvent((aui).Owner, oae, false); if (oae.Cancelled) return false; - SetCurrentSingleUser(aui.OwnerUid, actor.PlayerSession, aui); + SetCurrentSingleUser((aui).Owner, actor.PlayerSession, aui); ui.Toggle(actor.PlayerSession); return true; } @@ -124,7 +116,7 @@ namespace Content.Server.UserInterface // Must ToList in order to close things safely. foreach (var session in ui.SubscribedSessions.ToArray()) { - if (session.AttachedEntityUid == null || !_actionBlockerSystem.CanInteract(session.AttachedEntityUid.Value)) + if (session.AttachedEntity == null || !_actionBlockerSystem.CanInteract(session.AttachedEntity.Value)) { ui.Close(session); } @@ -141,8 +133,8 @@ namespace Content.Server.UserInterface public class ActivatableUIOpenAttemptEvent : CancellableEntityEventArgs { - public IEntity User { get; } - public ActivatableUIOpenAttemptEvent(IEntity who) + public EntityUid User { get; } + public ActivatableUIOpenAttemptEvent(EntityUid who) { User = who; } diff --git a/Content.Server/UserInterface/UserInterfaceHelpers.cs b/Content.Server/UserInterface/UserInterfaceHelpers.cs index 5072da1586..e30a4054e4 100644 --- a/Content.Server/UserInterface/UserInterfaceHelpers.cs +++ b/Content.Server/UserInterface/UserInterfaceHelpers.cs @@ -1,13 +1,14 @@ using Robust.Server.GameObjects; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.UserInterface { public static class UserInterfaceHelpers { - public static BoundUserInterface? GetUIOrNull(this IEntity entity, object uiKey) + public static BoundUserInterface? GetUIOrNull(this EntityUid entity, object uiKey) { - return entity.GetComponentOrNull()?.GetBoundUserInterfaceOrNull(uiKey); + return IoCManager.Resolve().GetComponentOrNull(entity)?.GetBoundUserInterfaceOrNull(uiKey); } } } diff --git a/Content.Server/VendingMachines/VendingMachineComponent.cs b/Content.Server/VendingMachines/VendingMachineComponent.cs index c584997030..192e8611f8 100644 --- a/Content.Server/VendingMachines/VendingMachineComponent.cs +++ b/Content.Server/VendingMachines/VendingMachineComponent.cs @@ -3,13 +3,11 @@ using System.Collections.Generic; using System.Linq; using Content.Server.Access.Components; using Content.Server.Access.Systems; -using Content.Server.Advertise; using Content.Server.Popups; using Content.Server.Power.Components; using Content.Server.UserInterface; using Content.Server.WireHacking; using Content.Shared.Acts; -using Content.Shared.Examine; using Content.Shared.Interaction; using Content.Shared.Sound; using Content.Shared.VendingMachines; @@ -22,7 +20,6 @@ using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; -using Robust.Shared.Utility; using Robust.Shared.ViewVariables; using static Content.Shared.Wires.SharedWiresComponent; @@ -32,6 +29,7 @@ namespace Content.Server.VendingMachines [ComponentReference(typeof(IActivate))] public class VendingMachineComponent : SharedVendingMachineComponent, IActivate, IBreakAct, IWires { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; @@ -41,7 +39,7 @@ namespace Content.Server.VendingMachines private string _packPrototypeId = string.Empty; private string _spriteName = ""; - private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered; + private bool Powered => !_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; private bool _broken; [DataField("soundVend")] @@ -57,14 +55,14 @@ namespace Content.Server.VendingMachines void IActivate.Activate(ActivateEventArgs eventArgs) { - if(!eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if(!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { return; } if (!Powered) return; - var wires = Owner.GetComponent(); + var wires = _entMan.GetComponent(Owner); if (wires.IsPanelOpen) { wires.OpenInterface(actor.PlayerSession); @@ -82,12 +80,12 @@ namespace Content.Server.VendingMachines return; } - Owner.Name = packPrototype.Name; + _entMan.GetComponent(Owner).EntityName = packPrototype.Name; _animationDuration = TimeSpan.FromSeconds(packPrototype.AnimationDuration); _spriteName = packPrototype.SpriteName; if (!string.IsNullOrEmpty(_spriteName)) { - var spriteComponent = Owner.GetComponent(); + var spriteComponent = _entMan.GetComponent(Owner); const string vendingMachineRSIPath = "Structures/Machines/VendingMachines/{0}.rsi"; spriteComponent.BaseRSIPath = string.Format(vendingMachineRSIPath, _spriteName); } @@ -109,7 +107,7 @@ namespace Content.Server.VendingMachines UserInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage; } - if (Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver)) + if (_entMan.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver)) { TrySetVisualState(receiver.Powered ? VendingMachineVisualState.Normal : VendingMachineVisualState.Off); } @@ -185,18 +183,18 @@ namespace Content.Server.VendingMachines { _ejecting = false; TrySetVisualState(VendingMachineVisualState.Normal); - Owner.EntityManager.SpawnEntity(id, Owner.Transform.Coordinates); + _entMan.SpawnEntity(id, _entMan.GetComponent(Owner).Coordinates); }); SoundSystem.Play(Filter.Pvs(Owner), _soundVend.GetSound(), Owner, AudioParams.Default.WithVolume(-2f)); } - private void TryEject(string id, IEntity? sender) + private void TryEject(string id, EntityUid? sender) { - if (Owner.TryGetComponent(out var accessReader)) + if (_entMan.TryGetComponent(Owner, out var accessReader)) { var accessSystem = EntitySystem.Get(); - if (sender == null || !accessSystem.IsAllowed(accessReader, sender.Uid)) + if (sender == null || !accessSystem.IsAllowed(accessReader, sender.Value)) { Owner.PopupMessageEveryone(Loc.GetString("vending-machine-component-try-eject-access-denied")); Deny(); @@ -235,7 +233,7 @@ namespace Content.Server.VendingMachines finalState = VendingMachineVisualState.Off; } - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(VendingMachineVisuals.VisualState, finalState); } diff --git a/Content.Server/Verbs/Commands/InvokeVerbCommand.cs b/Content.Server/Verbs/Commands/InvokeVerbCommand.cs index e8a87981c1..cc98d71d22 100644 --- a/Content.Server/Verbs/Commands/InvokeVerbCommand.cs +++ b/Content.Server/Verbs/Commands/InvokeVerbCommand.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Net.Security; using Content.Server.Administration; using Content.Shared.Administration; using Content.Shared.Verbs; @@ -30,12 +29,12 @@ namespace Content.Server.Verbs.Commands var verbSystem = EntitySystem.Get(); // get the 'player' entity (defaulting to command user, otherwise uses a uid) - IEntity? playerEntity = null; + EntityUid playerEntity = default; if (!int.TryParse(args[0], out var intPlayerUid)) { if (args[0] == "self" && shell.Player?.AttachedEntity != null) { - playerEntity = shell.Player.AttachedEntity; + playerEntity = shell.Player.AttachedEntity.Value; } else { @@ -45,7 +44,7 @@ namespace Content.Server.Verbs.Commands } else { - entityManager.TryGetEntity(new EntityUid(intPlayerUid), out playerEntity); + entityManager.EntityExists(new EntityUid(intPlayerUid)); } // gets the target entity @@ -55,30 +54,28 @@ namespace Content.Server.Verbs.Commands return; } - if (playerEntity == null) + if (playerEntity == default) { shell.WriteError(Loc.GetString("invoke-verb-command-invalid-player-entity")); return; } - var entUid = new EntityUid(intUid); - if (!entityManager.TryGetEntity(entUid, out var target)) + var target = new EntityUid(intUid); + if (!entityManager.EntityExists(target)) { shell.WriteError(Loc.GetString("invoke-verb-command-invalid-target-entity")); return; } var verbName = args[2].ToLowerInvariant(); - var verbs = verbSystem.GetLocalVerbs( - target, playerEntity, VerbType.All, true - ); + var verbs = verbSystem.GetLocalVerbs(target, playerEntity, VerbType.All, true); if ((Enum.TryParse(typeof(VerbType), verbName, ignoreCase: true, out var vtype) && vtype is VerbType key) && verbs.TryGetValue(key, out var vset) && vset.Any()) { - verbSystem.ExecuteVerb(vset.First(), playerEntity.Uid, target.Uid, forced: true); + verbSystem.ExecuteVerb(vset.First(), playerEntity, target, forced: true); shell.WriteLine(Loc.GetString("invoke-verb-command-success", ("verb", verbName), ("target", target), ("player", playerEntity))); return; } @@ -89,7 +86,7 @@ namespace Content.Server.Verbs.Commands { if (verb.Text.ToLowerInvariant() == verbName) { - verbSystem.ExecuteVerb(verb, playerEntity.Uid, target.Uid, forced: true); + verbSystem.ExecuteVerb(verb, playerEntity, target, forced: true); shell.WriteLine(Loc.GetString("invoke-verb-command-success", ("verb", verb.Text), ("target", target), ("player", playerEntity))); return; } diff --git a/Content.Server/Verbs/Commands/ListVerbsCommand.cs b/Content.Server/Verbs/Commands/ListVerbsCommand.cs index 57a27ba900..b4af5bccd7 100644 --- a/Content.Server/Verbs/Commands/ListVerbsCommand.cs +++ b/Content.Server/Verbs/Commands/ListVerbsCommand.cs @@ -27,7 +27,7 @@ namespace Content.Server.Verbs.Commands var verbSystem = EntitySystem.Get(); // get the 'player' entity (defaulting to command user, otherwise uses a uid) - IEntity? playerEntity = null; + EntityUid? playerEntity = null; if (!int.TryParse(args[0], out var intPlayerUid)) { if (args[0] == "self" && shell.Player?.AttachedEntity != null) @@ -42,7 +42,7 @@ namespace Content.Server.Verbs.Commands } else { - entityManager.TryGetEntity(new EntityUid(intPlayerUid), out playerEntity); + entityManager.EntityExists(new EntityUid(intPlayerUid)); } // gets the target entity @@ -58,16 +58,14 @@ namespace Content.Server.Verbs.Commands return; } - var entUid = new EntityUid(intUid); - if (!entityManager.TryGetEntity(entUid, out var target)) + var target = new EntityUid(intUid); + if (!entityManager.EntityExists(target)) { shell.WriteError(Loc.GetString("list-verbs-command-invalid-target-entity")); return; } - var verbs = verbSystem.GetLocalVerbs( - target, playerEntity, VerbType.All, true - ); + var verbs = verbSystem.GetLocalVerbs(target, playerEntity.Value, VerbType.All, true); foreach (var (type, set) in verbs) { diff --git a/Content.Server/Verbs/VerbSystem.cs b/Content.Server/Verbs/VerbSystem.cs index 906038366c..369ae31ae8 100644 --- a/Content.Server/Verbs/VerbSystem.cs +++ b/Content.Server/Verbs/VerbSystem.cs @@ -1,7 +1,6 @@ using Content.Shared.Verbs; using Robust.Server.Player; using Robust.Shared.GameObjects; -using Robust.Shared.IoC; using Robust.Shared.Log; namespace Content.Server.Verbs @@ -22,22 +21,21 @@ namespace Content.Server.Verbs public void HandleTryExecuteVerb(ExecuteVerbEvent args, EntitySessionEventArgs eventArgs) { var session = eventArgs.SenderSession; - var userEntity = session.AttachedEntity; - if (userEntity == null) + if (session.AttachedEntity is not {} userEntity) { Logger.Warning($"{nameof(HandleTryExecuteVerb)} called by player {session} with no attached entity."); return; } - if (!EntityManager.TryGetEntity(args.Target, out var targetEntity)) + if (!EntityManager.EntityExists(args.Target)) { return; } // Get the list of verbs. This effectively also checks that the requested verb is in fact a valid verb that // the user can perform. - var verbs = GetLocalVerbs(targetEntity, userEntity, args.Type)[args.Type]; + var verbs = GetLocalVerbs(args.Target, userEntity, args.Type)[args.Type]; // Note that GetLocalVerbs might waste time checking & preparing unrelated verbs even though we know // precisely which one we want to run. However, MOST entities will only have 1 or 2 verbs of a given type. @@ -45,7 +43,7 @@ namespace Content.Server.Verbs // Find the requested verb. if (verbs.TryGetValue(args.RequestedVerb, out var verb)) - ExecuteVerb(verb, userEntity.Uid, args.Target); + ExecuteVerb(verb, userEntity, args.Target); else // 404 Verb not found. Note that this could happen due to something as simple as opening the verb menu, walking away, then trying // to run the pickup-item verb. So maybe this shouldn't even be logged? @@ -56,13 +54,13 @@ namespace Content.Server.Verbs { var player = (IPlayerSession) eventArgs.SenderSession; - if (!EntityManager.TryGetEntity(args.EntityUid, out var target)) + if (!EntityManager.EntityExists(args.EntityUid)) { Logger.Warning($"{nameof(HandleVerbRequest)} called on a non-existent entity with id {args.EntityUid} by player {player}."); return; } - if (player.AttachedEntity == null) + if (player.AttachedEntity is not {} attached) { Logger.Warning($"{nameof(HandleVerbRequest)} called by player {player} with no attached entity."); return; @@ -72,7 +70,7 @@ namespace Content.Server.Verbs // this, and some verbs (e.g. view variables) won't even care about whether an entity is accessible through // the entity menu or not. - var response = new VerbsResponseEvent(args.EntityUid, GetLocalVerbs(target, player.AttachedEntity, args.Type)); + var response = new VerbsResponseEvent(args.EntityUid, GetLocalVerbs(args.EntityUid, attached, args.Type)); RaiseNetworkEvent(response, player.ConnectedClient); } } diff --git a/Content.Server/Weapon/Melee/MeleeWeaponSystem.cs b/Content.Server/Weapon/Melee/MeleeWeaponSystem.cs index 274b05dd0b..c4e8c8d996 100644 --- a/Content.Server/Weapon/Melee/MeleeWeaponSystem.cs +++ b/Content.Server/Weapon/Melee/MeleeWeaponSystem.cs @@ -8,7 +8,6 @@ using Content.Server.Chemistry.Components; using Content.Server.Chemistry.EntitySystems; using Content.Server.Cooldown; using Content.Server.Weapon.Melee.Components; -using Content.Shared.Administration.Logs; using Content.Shared.Damage; using Content.Shared.Database; using Content.Shared.Hands; @@ -70,7 +69,7 @@ namespace Content.Server.Weapon.Melee RaiseLocalEvent(uid, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false); } - private void OnClickAttack(EntityUid uid, MeleeWeaponComponent comp, ClickAttackEvent args) + private void OnClickAttack(EntityUid owner, MeleeWeaponComponent comp, ClickAttackEvent args) { args.Handled = true; var curTime = _gameTiming.CurTime; @@ -78,27 +77,24 @@ namespace Content.Server.Weapon.Melee if (curTime < comp.CooldownEnd || !args.Target.IsValid()) return; - var owner = EntityManager.GetEntity(uid); - var target = args.TargetEntity; - - var location = args.User.Transform.Coordinates; - var diff = args.ClickLocation.ToMapPos(owner.EntityManager) - location.ToMapPos(owner.EntityManager); + var location = EntityManager.GetComponent(args.User).Coordinates; + var diff = args.ClickLocation.ToMapPos(EntityManager) - location.ToMapPos(EntityManager); var angle = Angle.FromWorldVec(diff); - if (target != null) + if (args.Target is {Valid: true} target) { // Raise event before doing damage so we can cancel damage if the event is handled - var hitEvent = new MeleeHitEvent(new List() { target }, args.User); - RaiseLocalEvent(uid, hitEvent, false); + var hitEvent = new MeleeHitEvent(new List() { target }, args.User); + RaiseLocalEvent(owner, hitEvent, false); if (!hitEvent.Handled) { var targets = new[] { target }; SendAnimation(comp.ClickArc, angle, args.User, owner, targets, comp.ClickAttackEffect, false); - RaiseLocalEvent(target.Uid, new AttackedEvent(args.Used, args.User, args.ClickLocation)); + RaiseLocalEvent(target, new AttackedEvent(args.Used, args.User, args.ClickLocation)); - var damage = _damageableSystem.TryChangeDamage(target.Uid, + var damage = _damageableSystem.TryChangeDamage(target, DamageSpecifier.ApplyModifierSets(comp.Damage, hitEvent.ModifiersList)); if (damage != null) @@ -123,10 +119,10 @@ namespace Content.Server.Weapon.Melee comp.LastAttackTime = curTime; comp.CooldownEnd = comp.LastAttackTime + TimeSpan.FromSeconds(comp.CooldownTime); - RaiseLocalEvent(uid, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false); + RaiseLocalEvent(owner, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false); } - private void OnWideAttack(EntityUid uid, MeleeWeaponComponent comp, WideAttackEvent args) + private void OnWideAttack(EntityUid owner, MeleeWeaponComponent comp, WideAttackEvent args) { args.Handled = true; var curTime = _gameTiming.CurTime; @@ -136,22 +132,20 @@ namespace Content.Server.Weapon.Melee return; } - var owner = EntityManager.GetEntity(uid); - - var location = args.User.Transform.Coordinates; - var diff = args.ClickLocation.ToMapPos(owner.EntityManager) - location.ToMapPos(owner.EntityManager); + var location = EntityManager.GetComponent(args.User).Coordinates; + var diff = args.ClickLocation.ToMapPos(EntityManager) - location.ToMapPos(EntityManager); var angle = Angle.FromWorldVec(diff); // This should really be improved. GetEntitiesInArc uses pos instead of bounding boxes. - var entities = ArcRayCast(args.User.Transform.WorldPosition, angle, comp.ArcWidth, comp.Range, owner.Transform.MapID, args.User); + var entities = ArcRayCast(EntityManager.GetComponent(args.User).WorldPosition, angle, comp.ArcWidth, comp.Range, EntityManager.GetComponent(owner).MapID, args.User); - var hitEntities = new List(); + var hitEntities = new List(); foreach (var entity in entities) { if (entity.IsInContainer() || entity == args.User) continue; - if (EntityManager.HasComponent(entity.Uid)) + if (EntityManager.HasComponent(entity)) { hitEntities.Add(entity); } @@ -159,25 +153,25 @@ namespace Content.Server.Weapon.Melee // Raise event before doing damage so we can cancel damage if handled var hitEvent = new MeleeHitEvent(hitEntities, args.User); - RaiseLocalEvent(uid, hitEvent, false); + RaiseLocalEvent(owner, hitEvent, false); SendAnimation(comp.Arc, angle, args.User, owner, hitEntities); if (!hitEvent.Handled) { if (entities.Count != 0) { - SoundSystem.Play(Filter.Pvs(owner), comp.HitSound.GetSound(), entities.First().Transform.Coordinates); + SoundSystem.Play(Filter.Pvs(owner), comp.HitSound.GetSound(), EntityManager.GetComponent(entities.First()).Coordinates); } else { - SoundSystem.Play(Filter.Pvs(owner), comp.MissSound.GetSound(), args.User.Transform.Coordinates); + SoundSystem.Play(Filter.Pvs(owner), comp.MissSound.GetSound(), EntityManager.GetComponent(args.User).Coordinates); } foreach (var entity in hitEntities) { - RaiseLocalEvent(entity.Uid, new AttackedEvent(args.Used, args.User, args.ClickLocation)); + RaiseLocalEvent(entity, new AttackedEvent(args.Used, args.User, args.ClickLocation)); - var damage = _damageableSystem.TryChangeDamage(entity.Uid, + var damage = _damageableSystem.TryChangeDamage(entity, DamageSpecifier.ApplyModifierSets(comp.Damage, hitEvent.ModifiersList)); if (damage != null) @@ -195,14 +189,14 @@ namespace Content.Server.Weapon.Melee comp.LastAttackTime = curTime; comp.CooldownEnd = comp.LastAttackTime + TimeSpan.FromSeconds(comp.ArcCooldownTime); - RaiseLocalEvent(uid, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false); + RaiseLocalEvent(owner, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false); } /// /// Used for melee weapons that want some behavior on AfterInteract, /// but also want the cooldown (stun batons, flashes) /// - private void OnAfterInteract(EntityUid uid, MeleeWeaponComponent comp, AfterInteractEvent args) + private void OnAfterInteract(EntityUid owner, MeleeWeaponComponent comp, AfterInteractEvent args) { if (!args.CanReach) return; @@ -214,35 +208,33 @@ namespace Content.Server.Weapon.Melee return; } - var owner = EntityManager.GetEntity(uid); - - if (args.Target == null) + if (!args.Target.HasValue) return; - var location = args.User.Transform.Coordinates; - var diff = args.ClickLocation.ToMapPos(owner.EntityManager) - location.ToMapPos(owner.EntityManager); + var location = EntityManager.GetComponent(args.User).Coordinates; + var diff = args.ClickLocation.ToMapPos(EntityManager) - location.ToMapPos(EntityManager); var angle = Angle.FromWorldVec(diff); - var hitEvent = new MeleeInteractEvent(args.Target, args.User); - RaiseLocalEvent(uid, hitEvent, false); + var hitEvent = new MeleeInteractEvent(args.Target.Value, args.User); + RaiseLocalEvent(owner, hitEvent, false); if (!hitEvent.CanInteract) return; - SendAnimation(comp.ClickArc, angle, args.User, owner, new List() { args.Target }, comp.ClickAttackEffect, false); + SendAnimation(comp.ClickArc, angle, args.User, owner, new List() { args.Target.Value }, comp.ClickAttackEffect, false); comp.LastAttackTime = curTime; comp.CooldownEnd = comp.LastAttackTime + TimeSpan.FromSeconds(comp.CooldownTime); - RaiseLocalEvent(uid, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false); + RaiseLocalEvent(owner, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false); } - private HashSet ArcRayCast(Vector2 position, Angle angle, float arcWidth, float range, MapId mapId, IEntity ignore) + private HashSet ArcRayCast(Vector2 position, Angle angle, float arcWidth, float range, MapId mapId, EntityUid ignore) { var widthRad = Angle.FromDegrees(arcWidth); var increments = 1 + 35 * (int) Math.Ceiling(widthRad / (2 * Math.PI)); var increment = widthRad / increments; var baseAngle = angle - widthRad / 2; - var resSet = new HashSet(); + var resSet = new HashSet(); for (var i = 0; i < increments; i++) { @@ -260,19 +252,18 @@ namespace Content.Server.Weapon.Melee return resSet; } - private void OnChemicalInjectorHit(EntityUid uid, MeleeChemicalInjectorComponent comp, MeleeHitEvent args) + private void OnChemicalInjectorHit(EntityUid owner, MeleeChemicalInjectorComponent comp, MeleeHitEvent args) { - IEntity owner = EntityManager.GetEntity(uid); - if (!_solutionsSystem.TryGetInjectableSolution(owner.Uid, out var solutionContainer)) + if (!_solutionsSystem.TryGetInjectableSolution(owner, out var solutionContainer)) return; var hitBloodstreams = new List(); foreach (var entity in args.HitEntities) { - if (entity.Deleted) + if (Deleted(entity)) continue; - if (entity.TryGetComponent(out var bloodstream)) + if (EntityManager.TryGetComponent(entity, out var bloodstream)) hitBloodstreams.Add(bloodstream); } @@ -287,19 +278,19 @@ namespace Content.Server.Weapon.Melee foreach (var bloodstream in hitBloodstreams) { var individualInjection = solutionToInject.SplitSolution(volPerBloodstream); - _bloodstreamSystem.TryAddToBloodstream(bloodstream.OwnerUid, individualInjection, bloodstream); + _bloodstreamSystem.TryAddToBloodstream((bloodstream).Owner, individualInjection, bloodstream); } } - public void SendAnimation(string arc, Angle angle, IEntity attacker, IEntity source, IEnumerable hits, bool textureEffect = false, bool arcFollowAttacker = true) + public void SendAnimation(string arc, Angle angle, EntityUid attacker, EntityUid source, IEnumerable hits, bool textureEffect = false, bool arcFollowAttacker = true) { - RaiseNetworkEvent(new MeleeWeaponSystemMessages.PlayMeleeWeaponAnimationMessage(arc, angle, attacker.Uid, source.Uid, - hits.Select(e => e.Uid).ToList(), textureEffect, arcFollowAttacker), Filter.Pvs(source, 1f)); + RaiseNetworkEvent(new MeleeWeaponSystemMessages.PlayMeleeWeaponAnimationMessage(arc, angle, attacker, source, + hits.Select(e => e).ToList(), textureEffect, arcFollowAttacker), Filter.Pvs(source, 1f)); } - public void SendLunge(Angle angle, IEntity source) + public void SendLunge(Angle angle, EntityUid source) { - RaiseNetworkEvent(new MeleeWeaponSystemMessages.PlayLungeAnimationMessage(angle, source.Uid), Filter.Pvs(source, 1f)); + RaiseNetworkEvent(new MeleeWeaponSystemMessages.PlayLungeAnimationMessage(angle, source), Filter.Pvs(source, 1f)); } } @@ -323,14 +314,14 @@ namespace Content.Server.Weapon.Melee /// /// A list containing every hit entity. Can be zero. /// - public IEnumerable HitEntities { get; } + public IEnumerable HitEntities { get; } /// /// The user who attacked with the melee wepaon. /// - public IEntity User { get; } + public EntityUid User { get; } - public MeleeHitEvent(List hitEntities, IEntity user) + public MeleeHitEvent(List hitEntities, EntityUid user) { HitEntities = hitEntities; User = user; @@ -346,12 +337,12 @@ namespace Content.Server.Weapon.Melee /// /// The entity interacted with. /// - public IEntity Entity { get; } + public EntityUid Entity { get; } /// /// The user who interacted using the melee weapon. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Modified by the event handler to specify whether they could successfully interact with the entity. @@ -359,7 +350,7 @@ namespace Content.Server.Weapon.Melee /// public bool CanInteract { get; set; } = false; - public MeleeInteractEvent(IEntity entity, IEntity user) + public MeleeInteractEvent(EntityUid entity, EntityUid user) { Entity = entity; User = user; diff --git a/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoBoxComponent.cs b/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoBoxComponent.cs index 94191507b5..5e47ac28db 100644 --- a/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoBoxComponent.cs +++ b/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoBoxComponent.cs @@ -10,6 +10,7 @@ using Content.Shared.Popups; using Content.Shared.Weapons.Ranged.Barrels.Components; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -21,6 +22,8 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components public sealed class AmmoBoxComponent : Component, IInteractUsing, IUse, IInteractHand, IMapInit, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "AmmoBox"; [DataField("caliber")] @@ -33,14 +36,14 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components set { _capacity = value; - _spawnedAmmo = new Stack(value); + _spawnedAmmo = new Stack(value); } } private int _capacity = 30; public int AmmoLeft => _spawnedAmmo.Count + _unspawnedCount; - private Stack _spawnedAmmo = new(); + private Stack _spawnedAmmo = new(); private Container _ammoContainer = default!; private int _unspawnedCount; @@ -72,7 +75,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { appearanceComponent.SetData(MagazineBarrelVisuals.MagLoaded, true); appearanceComponent.SetData(AmmoVisuals.AmmoCount, AmmoLeft); @@ -80,7 +83,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components } } - public IEntity? TakeAmmo() + public EntityUid? TakeAmmo() { if (_spawnedAmmo.TryPop(out var ammo)) { @@ -90,10 +93,10 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components if (_unspawnedCount > 0) { - ammo = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.Coordinates); + ammo = _entities.SpawnEntity(_fillPrototype, _entities.GetComponent(Owner).Coordinates); // when dumping from held ammo box, this detaches the spawned ammo from the player. - ammo.Transform.AttachParentToContainerOrGrid(); + _entities.GetComponent(ammo).AttachParentToContainerOrGrid(); _unspawnedCount--; } @@ -101,9 +104,9 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components return ammo; } - public bool TryInsertAmmo(IEntity user, IEntity entity) + public bool TryInsertAmmo(EntityUid user, EntityUid entity) { - if (!entity.TryGetComponent(out AmmoComponent? ammoComponent)) + if (!_entities.TryGetComponent(entity, out AmmoComponent? ammoComponent)) { return false; } @@ -128,18 +131,16 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (eventArgs.Using.HasComponent()) + if (_entities.HasComponent(eventArgs.Using)) { return TryInsertAmmo(eventArgs.User, eventArgs.Using); } - if (eventArgs.Using.TryGetComponent(out RangedMagazineComponent? rangedMagazine)) + if (_entities.TryGetComponent(eventArgs.Using, out RangedMagazineComponent? rangedMagazine)) { for (var i = 0; i < Math.Max(10, rangedMagazine.ShotsLeft); i++) { - var ammo = rangedMagazine.TakeAmmo(); - - if (ammo == null) + if (rangedMagazine.TakeAmmo() is not {Valid: true} ammo) { continue; } @@ -157,21 +158,19 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components return false; } - private bool TryUse(IEntity user) + private bool TryUse(EntityUid user) { - if (!user.TryGetComponent(out HandsComponent? handsComponent)) + if (!_entities.TryGetComponent(user, out HandsComponent? handsComponent)) { return false; } - var ammo = TakeAmmo(); - - if (ammo == null) + if (TakeAmmo() is not { } ammo) { return false; } - if (ammo.TryGetComponent(out ItemComponent? item)) + if (_entities.TryGetComponent(ammo, out ItemComponent? item)) { if (!handsComponent.CanPutInHand(item)) { @@ -189,12 +188,11 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components public void EjectContents(int count) { var ejectCount = Math.Min(count, Capacity); - var ejectAmmo = new List(ejectCount); + var ejectAmmo = new List(ejectCount); for (var i = 0; i < Math.Min(count, Capacity); i++) { - var ammo = TakeAmmo(); - if (ammo == null) + if (TakeAmmo() is not { } ammo) { break; } diff --git a/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoComponent.cs b/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoComponent.cs index 79377077db..a12ca95d19 100644 --- a/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoComponent.cs +++ b/Content.Server/Weapon/Ranged/Ammunition/Components/AmmoComponent.cs @@ -25,6 +25,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components public class AmmoComponent : Component, IExamine, ISerializationHooks #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; public override string Name => "Ammo"; @@ -104,7 +105,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components } } - public IEntity? TakeBullet(EntityCoordinates spawnAt) + public EntityUid? TakeBullet(EntityCoordinates spawnAt) { if (_ammoIsProjectile) { @@ -117,17 +118,17 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components } _spent = true; - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { appearanceComponent.SetData(AmmoVisuals.Spent, true); } - var entity = Owner.EntityManager.SpawnEntity(_projectileId, spawnAt); + var entity = _entMan.SpawnEntity(_projectileId, spawnAt); return entity; } - public void MuzzleFlash(IEntity entity, Angle angle) + public void MuzzleFlash(EntityUid entity, Angle angle) { if (_muzzleFlashSprite == null) { @@ -144,7 +145,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components EffectSprite = _muzzleFlashSprite, Born = time, DeathTime = deathTime, - AttachedEntityUid = entity.Uid, + AttachedEntityUid = entity, AttachedOffset = offset, //Rotated from east facing Rotation = (float) angle.Theta, diff --git a/Content.Server/Weapon/Ranged/Ammunition/Components/RangedMagazineComponent.cs b/Content.Server/Weapon/Ranged/Ammunition/Components/RangedMagazineComponent.cs index 6a2039c973..fca41f78d0 100644 --- a/Content.Server/Weapon/Ranged/Ammunition/Components/RangedMagazineComponent.cs +++ b/Content.Server/Weapon/Ranged/Ammunition/Components/RangedMagazineComponent.cs @@ -10,6 +10,7 @@ using Content.Shared.Popups; using Content.Shared.Weapons.Ranged.Barrels.Components; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -21,9 +22,11 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components public class RangedMagazineComponent : Component, IMapInit, IInteractUsing, IUse, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "RangedMagazine"; - private readonly Stack _spawnedAmmo = new(); + private readonly Stack _spawnedAmmo = new(); private Container _ammoContainer = default!; public int ShotsLeft => _spawnedAmmo.Count + _unspawnedCount; @@ -76,7 +79,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components } } - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -90,9 +93,9 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components _appearanceComponent?.SetData(AmmoVisuals.AmmoMax, Capacity); } - public bool TryInsertAmmo(IEntity user, IEntity ammo) + public bool TryInsertAmmo(EntityUid user, EntityUid ammo) { - if (!ammo.TryGetComponent(out AmmoComponent? ammoComponent)) + if (!_entities.TryGetComponent(ammo, out AmmoComponent? ammoComponent)) { return false; } @@ -115,9 +118,9 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components return true; } - public IEntity? TakeAmmo() + public EntityUid? TakeAmmo() { - IEntity? ammo = null; + EntityUid ammo = default; // If anything's spawned use that first, otherwise use the fill prototype as a fallback (if we have spawn count left) if (_spawnedAmmo.TryPop(out var entity)) { @@ -127,7 +130,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components else if (_unspawnedCount > 0) { _unspawnedCount--; - ammo = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.Coordinates); + ammo = _entities.SpawnEntity(_fillPrototype, _entities.GetComponent(Owner).Coordinates); } UpdateAppearance(); @@ -141,21 +144,20 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out HandsComponent? handsComponent)) + if (!_entities.TryGetComponent(eventArgs.User, out HandsComponent? handsComponent)) { return false; } - var ammo = TakeAmmo(); - if (ammo == null) + if (TakeAmmo() is not {Valid: true} ammo) { return false; } - var itemComponent = ammo.GetComponent(); + var itemComponent = _entities.GetComponent(ammo); if (!handsComponent.CanPutInHand(itemComponent)) { - ammo.Transform.Coordinates = eventArgs.User.Transform.Coordinates; + _entities.GetComponent(ammo).Coordinates = _entities.GetComponent(eventArgs.User).Coordinates; ServerRangedBarrelComponent.EjectCasing(ammo); } else diff --git a/Content.Server/Weapon/Ranged/Ammunition/Components/SpeedLoaderComponent.cs b/Content.Server/Weapon/Ranged/Ammunition/Components/SpeedLoaderComponent.cs index b4ffb19ad2..5105f106b6 100644 --- a/Content.Server/Weapon/Ranged/Ammunition/Components/SpeedLoaderComponent.cs +++ b/Content.Server/Weapon/Ranged/Ammunition/Components/SpeedLoaderComponent.cs @@ -8,6 +8,7 @@ using Content.Shared.Popups; using Content.Shared.Weapons.Ranged.Barrels.Components; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; @@ -19,6 +20,8 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components [RegisterComponent] public class SpeedLoaderComponent : Component, IAfterInteract, IInteractUsing, IMapInit, IUse { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "SpeedLoader"; [DataField("caliber")] @@ -27,7 +30,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components [DataField("capacity")] private int _capacity = 6; private Container _ammoContainer = default!; - private Stack _spawnedAmmo = new(); + private Stack _spawnedAmmo = new(); private int _unspawnedCount; public int AmmoLeft => _spawnedAmmo.Count + _unspawnedCount; @@ -58,7 +61,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { appearanceComponent?.SetData(MagazineBarrelVisuals.MagLoaded, true); appearanceComponent?.SetData(AmmoVisuals.AmmoCount, AmmoLeft); @@ -66,9 +69,9 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components } } - public bool TryInsertAmmo(IEntity user, IEntity entity) + public bool TryInsertAmmo(EntityUid user, EntityUid entity) { - if (!entity.TryGetComponent(out AmmoComponent? ammoComponent)) + if (!_entMan.TryGetComponent(entity, out AmmoComponent? ammoComponent)) { return false; } @@ -92,20 +95,20 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components } - private bool UseEntity(IEntity user) + private bool UseEntity(EntityUid user) { - if (!user.TryGetComponent(out HandsComponent? handsComponent)) + if (!_entMan.TryGetComponent(user, out HandsComponent? handsComponent)) { return false; } var ammo = TakeAmmo(); - if (ammo == null) + if (ammo == default) { return false; } - var itemComponent = ammo.GetComponent(); + var itemComponent = _entMan.GetComponent(ammo); if (!handsComponent.CanPutInHand(itemComponent)) { ServerRangedBarrelComponent.EjectCasing(ammo); @@ -119,7 +122,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components return true; } - private IEntity? TakeAmmo() + private EntityUid TakeAmmo() { if (_spawnedAmmo.TryPop(out var entity)) { @@ -129,7 +132,7 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components if (_unspawnedCount > 0) { - entity = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.Coordinates); + entity = _entMan.SpawnEntity(_fillPrototype, _entMan.GetComponent(Owner).Coordinates); _unspawnedCount--; } @@ -146,12 +149,13 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components // This area is dirty but not sure of an easier way to do it besides add an interface or somethin var changed = false; - if (eventArgs.Target.TryGetComponent(out RevolverBarrelComponent? revolverBarrel)) + var entities = _entMan; + if (entities.TryGetComponent(eventArgs.Target.Value, out RevolverBarrelComponent? revolverBarrel)) { for (var i = 0; i < Capacity; i++) { var ammo = TakeAmmo(); - if (ammo == null) + if (ammo == default) { break; } @@ -166,12 +170,13 @@ namespace Content.Server.Weapon.Ranged.Ammunition.Components TryInsertAmmo(eventArgs.User, ammo); break; } - } else if (eventArgs.Target.TryGetComponent(out BoltActionBarrelComponent? boltActionBarrel)) + } + else if (_entMan.TryGetComponent(eventArgs.Target.Value, out BoltActionBarrelComponent? boltActionBarrel)) { for (var i = 0; i < Capacity; i++) { var ammo = TakeAmmo(); - if (ammo == null) + if (ammo == default) { break; } diff --git a/Content.Server/Weapon/Ranged/Barrels/BarrelSystem.cs b/Content.Server/Weapon/Ranged/Barrels/BarrelSystem.cs index c1591926b4..60013c7361 100644 --- a/Content.Server/Weapon/Ranged/Barrels/BarrelSystem.cs +++ b/Content.Server/Weapon/Ranged/Barrels/BarrelSystem.cs @@ -76,14 +76,14 @@ namespace Content.Server.Weapon.Ranged.Barrels !args.CanAccess || !args.CanInteract || !component.HasMagazine || - !_actionBlockerSystem.CanPickup(args.User.Uid)) + !_actionBlockerSystem.CanPickup(args.User)) return; if (component.MagNeedsOpenBolt && !component.BoltOpen) return; Verb verb = new(); - verb.Text = component.MagazineContainer.ContainedEntity!.Name; + verb.Text = EntityManager.GetComponent(component.MagazineContainer.ContainedEntity!.Value).EntityName; verb.Category = VerbCategory.Eject; verb.Act = () => component.RemoveMagazine(args.User); args.Verbs.Add(verb); @@ -105,16 +105,16 @@ namespace Content.Server.Weapon.Ranged.Barrels args.Verbs.Add(toggleBolt); // Are we holding a mag that we can insert? - if (args.Using == null || - !component.CanInsertMagazine(args.User, args.Using) || - !_actionBlockerSystem.CanDrop(args.User.Uid)) + if (args.Using is not {Valid: true} @using || + !component.CanInsertMagazine(args.User, @using) || + !_actionBlockerSystem.CanDrop(args.User)) return; // Insert mag verb Verb insert = new(); - insert.Text = args.Using.Name; + insert.Text = EntityManager.GetComponent(@using).EntityName; insert.Category = VerbCategory.Insert; - insert.Act = () => component.InsertMagazine(args.User, args.Using); + insert.Act = () => component.InsertMagazine(args.User, @using); args.Verbs.Add(insert); } } diff --git a/Content.Server/Weapon/Ranged/Barrels/Components/BoltActionBarrelComponent.cs b/Content.Server/Weapon/Ranged/Barrels/Components/BoltActionBarrelComponent.cs index 1023b1da09..dc6012d76b 100644 --- a/Content.Server/Weapon/Ranged/Barrels/Components/BoltActionBarrelComponent.cs +++ b/Content.Server/Weapon/Ranged/Barrels/Components/BoltActionBarrelComponent.cs @@ -10,10 +10,10 @@ using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -31,6 +31,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components { // Originally I had this logic shared with PumpBarrel and used a couple of variables to control things // but it felt a lot messier to play around with, especially when adding verbs + [Dependency] private readonly IEntityManager _entities = default!; public override string Name => "BoltActionBarrel"; @@ -47,7 +48,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components private int _capacity = 6; private ContainerSlot _chamberContainer = default!; - private Stack _spawnedAmmo = default!; + private Stack _spawnedAmmo = default!; private Container _ammoContainer = default!; [ViewVariables] @@ -110,7 +111,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components if (_unspawnedCount > 0) { _unspawnedCount--; - var chamberEntity = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.Coordinates); + var chamberEntity = _entities.SpawnEntity(_fillPrototype, _entities.GetComponent(Owner).Coordinates); _chamberContainer.Insert(chamberEntity); } } @@ -124,7 +125,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components // (Is one chambered?, is the bullet spend) var chamber = (chamberedExists, false); - if (chamberedExists && _chamberContainer.ContainedEntity!.TryGetComponent(out var ammo)) + if (chamberedExists && _entities.TryGetComponent(_chamberContainer.ContainedEntity!.Value, out var ammo)) { chamber.Item2 = ammo.Spent; } @@ -140,7 +141,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components { // TODO: Add existing ammo support on revolvers base.Initialize(); - _spawnedAmmo = new Stack(_capacity - 1); + _spawnedAmmo = new Stack(_capacity - 1); _ammoContainer = ContainerHelpers.EnsureContainer(Owner, $"{Name}-ammo-container", out var existing); if (existing) @@ -154,7 +155,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components _chamberContainer = ContainerHelpers.EnsureContainer(Owner, $"{Name}-chamber-container"); - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -171,14 +172,13 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components _appearanceComponent?.SetData(AmmoVisuals.AmmoMax, Capacity); } - public override IEntity? PeekAmmo() + public override EntityUid? PeekAmmo() { return _chamberContainer.ContainedEntity; } - public override IEntity? TakeProjectile(EntityCoordinates spawnAt) + public override EntityUid? TakeProjectile(EntityCoordinates spawnAt) { - var chamberEntity = _chamberContainer.ContainedEntity; if (_autoCycle) { Cycle(); @@ -188,7 +188,10 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components Dirty(); } - return chamberEntity?.GetComponentOrNull()?.TakeBullet(spawnAt); + if (_chamberContainer.ContainedEntity is not {Valid: true} chamberEntity) + return null; + + return _entities.GetComponentOrNull(chamberEntity)?.TakeBullet(spawnAt); } protected override bool WeaponCanFire() @@ -224,9 +227,9 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components UpdateAppearance(); } - public bool TryInsertBullet(IEntity user, IEntity ammo) + public bool TryInsertBullet(EntityUid user, EntityUid ammo) { - if (!ammo.TryGetComponent(out AmmoComponent? ammoComponent)) + if (!_entities.TryGetComponent(ammo, out AmmoComponent? ammoComponent)) { return false; } @@ -288,16 +291,15 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components private bool TryEjectChamber() { - var chamberedEntity = _chamberContainer.ContainedEntity; - if (chamberedEntity != null) + if (_chamberContainer.ContainedEntity is {Valid: true} chambered) { - if (!_chamberContainer.Remove(chamberedEntity)) + if (!_chamberContainer.Remove(chambered)) { return false; } - if (!chamberedEntity.GetComponent().Caseless) + if (!_entities.GetComponent(chambered).Caseless) { - EjectCasing(chamberedEntity); + EjectCasing(chambered); } return true; } @@ -319,7 +321,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components else if (_unspawnedCount > 0) { _unspawnedCount--; - var ammoEntity = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.Coordinates); + var ammoEntity = _entities.SpawnEntity(_fillPrototype, _entities.GetComponent(Owner).Coordinates); _chamberContainer.Insert(ammoEntity); return true; } diff --git a/Content.Server/Weapon/Ranged/Barrels/Components/PumpBarrelComponent.cs b/Content.Server/Weapon/Ranged/Barrels/Components/PumpBarrelComponent.cs index c53f50c58a..6b90cf9917 100644 --- a/Content.Server/Weapon/Ranged/Barrels/Components/PumpBarrelComponent.cs +++ b/Content.Server/Weapon/Ranged/Barrels/Components/PumpBarrelComponent.cs @@ -9,10 +9,10 @@ using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -27,6 +27,8 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components [NetworkedComponent()] public sealed class PumpBarrelComponent : ServerRangedBarrelComponent, IUse, IInteractUsing, IMapInit, ISerializationHooks { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "PumpBarrel"; public override int ShotsLeft @@ -44,7 +46,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components // Even a point having a chamber? I guess it makes some of the below code cleaner private ContainerSlot _chamberContainer = default!; - private Stack _spawnedAmmo = new(DefaultCapacity - 1); + private Stack _spawnedAmmo = new(DefaultCapacity - 1); private Container _ammoContainer = default!; [ViewVariables] @@ -85,7 +87,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components // (Is one chambered?, is the bullet spend) var chamber = (chamberedExists, false); - if (chamberedExists && _chamberContainer.ContainedEntity!.TryGetComponent(out var ammo)) + if (chamberedExists && _entMan.TryGetComponent(_chamberContainer.ContainedEntity!.Value, out var ammo)) { chamber.Item2 = ammo.Spent; } @@ -98,7 +100,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components void ISerializationHooks.AfterDeserialization() { - _spawnedAmmo = new Stack(Capacity - 1); + _spawnedAmmo = new Stack(Capacity - 1); } protected override void Initialize() @@ -124,7 +126,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components _unspawnedCount--; } - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -140,14 +142,13 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components _appearanceComponent?.SetData(AmmoVisuals.AmmoMax, Capacity); } - public override IEntity? PeekAmmo() + public override EntityUid? PeekAmmo() { return _chamberContainer.ContainedEntity; } - public override IEntity? TakeProjectile(EntityCoordinates spawnAt) + public override EntityUid? TakeProjectile(EntityCoordinates spawnAt) { - var chamberEntity = _chamberContainer.ContainedEntity; if (!_manualCycle) { Cycle(); @@ -157,16 +158,18 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components Dirty(); } - return chamberEntity?.GetComponentOrNull()?.TakeBullet(spawnAt); + if (_chamberContainer.ContainedEntity is not {Valid: true} chamberEntity) + return null; + + return _entMan.GetComponentOrNull(chamberEntity)?.TakeBullet(spawnAt); } private void Cycle(bool manual = false) { - var chamberedEntity = _chamberContainer.ContainedEntity; - if (chamberedEntity != null) + if (_chamberContainer.ContainedEntity is {Valid: true} chamberedEntity) { _chamberContainer.Remove(chamberedEntity); - var ammoComponent = chamberedEntity.GetComponent(); + var ammoComponent = _entMan.GetComponent(chamberedEntity); if (!ammoComponent.Caseless) { EjectCasing(chamberedEntity); @@ -182,7 +185,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components if (_unspawnedCount > 0) { _unspawnedCount--; - var ammoEntity = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.Coordinates); + var ammoEntity = _entMan.SpawnEntity(_fillPrototype, _entMan.GetComponent(Owner).Coordinates); _chamberContainer.Insert(ammoEntity); } @@ -197,7 +200,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components public bool TryInsertBullet(InteractUsingEventArgs eventArgs) { - if (!eventArgs.Using.TryGetComponent(out AmmoComponent? ammoComponent)) + if (!_entMan.TryGetComponent(eventArgs.Using, out AmmoComponent? ammoComponent)) { return false; } diff --git a/Content.Server/Weapon/Ranged/Barrels/Components/RevolverBarrelComponent.cs b/Content.Server/Weapon/Ranged/Barrels/Components/RevolverBarrelComponent.cs index c6f4735ada..6966a64f88 100644 --- a/Content.Server/Weapon/Ranged/Barrels/Components/RevolverBarrelComponent.cs +++ b/Content.Server/Weapon/Ranged/Barrels/Components/RevolverBarrelComponent.cs @@ -13,7 +13,6 @@ using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Random; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -25,6 +24,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components [NetworkedComponent()] public sealed class RevolverBarrelComponent : ServerRangedBarrelComponent, IUse, IInteractUsing, ISerializationHooks { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IRobustRandom _random = default!; public override string Name => "RevolverBarrel"; @@ -44,7 +44,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components private int _serializedCapacity = 6; [DataField("ammoSlots", readOnly: true)] - private IEntity?[] _ammoSlots = Array.Empty(); + private EntityUid[] _ammoSlots = Array.Empty(); public override int ShotsLeft => _ammoContainer.ContainedEntities.Count; @@ -72,7 +72,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components void ISerializationHooks.AfterDeserialization() { - _ammoSlots = new IEntity[_serializedCapacity]; + _ammoSlots = new EntityUid[_serializedCapacity]; } public override ComponentState GetComponentState() @@ -82,7 +82,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components { slotsSpent[i] = null; var ammoEntity = _ammoSlots[i]; - if (ammoEntity != null && ammoEntity.TryGetComponent(out AmmoComponent? ammo)) + if (ammoEntity != default && _entMan.TryGetComponent(ammoEntity, out AmmoComponent? ammo)) { slotsSpent[i] = ammo.Spent; } @@ -114,7 +114,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components for (var i = 0; i < _unspawnedCount; i++) { - var entity = Owner.EntityManager.SpawnEntity(_fillPrototype, Owner.Transform.Coordinates); + var entity = _entMan.SpawnEntity(_fillPrototype, _entMan.GetComponent(Owner).Coordinates); _ammoSlots[idx] = entity; _ammoContainer.Insert(entity); idx++; @@ -126,7 +126,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components private void UpdateAppearance() { - if (!Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (!_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) { return; } @@ -137,9 +137,9 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components appearance.SetData(AmmoVisuals.AmmoMax, Capacity); } - public bool TryInsertBullet(IEntity user, IEntity entity) + public bool TryInsertBullet(EntityUid user, EntityUid entity) { - if (!entity.TryGetComponent(out AmmoComponent? ammoComponent)) + if (!_entMan.TryGetComponent(entity, out AmmoComponent? ammoComponent)) { return false; } @@ -156,7 +156,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components for (var i = _ammoSlots.Length - 1; i >= 0; i--) { var slot = _ammoSlots[i]; - if (slot == null) + if (slot == default) { _currentSlot = i; _ammoSlots[i] = entity; @@ -192,7 +192,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components Dirty(); } - public override IEntity? PeekAmmo() + public override EntityUid? PeekAmmo() { return _ammoSlots[_currentSlot]; } @@ -203,17 +203,17 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components /// /// /// - public override IEntity? TakeProjectile(EntityCoordinates spawnAt) + public override EntityUid? TakeProjectile(EntityCoordinates spawnAt) { var ammo = _ammoSlots[_currentSlot]; - IEntity? bullet = null; - if (ammo != null) + EntityUid? bullet = null; + if (ammo != default) { - var ammoComponent = ammo.GetComponent(); + var ammoComponent = _entMan.GetComponent(ammo); bullet = ammoComponent.TakeBullet(spawnAt); if (ammoComponent.Caseless) { - _ammoSlots[_currentSlot] = null; + _ammoSlots[_currentSlot] = default; _ammoContainer.Remove(ammo); } } @@ -227,14 +227,14 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components for (var i = 0; i < _ammoSlots.Length; i++) { var entity = _ammoSlots[i]; - if (entity == null) + if (entity == default) { continue; } _ammoContainer.Remove(entity); EjectCasing(entity); - _ammoSlots[i] = null; + _ammoSlots[i] = default; } if (_ammoContainer.ContainedEntities.Count > 0) @@ -244,7 +244,6 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components // May as well point back at the end? _currentSlot = _ammoSlots.Length - 1; - return; } /// diff --git a/Content.Server/Weapon/Ranged/Barrels/Components/ServerBatteryBarrelComponent.cs b/Content.Server/Weapon/Ranged/Barrels/Components/ServerBatteryBarrelComponent.cs index 256d3732b6..c0c9445540 100644 --- a/Content.Server/Weapon/Ranged/Barrels/Components/ServerBatteryBarrelComponent.cs +++ b/Content.Server/Weapon/Ranged/Barrels/Components/ServerBatteryBarrelComponent.cs @@ -6,7 +6,9 @@ using Content.Shared.Weapons.Ranged.Barrels.Components; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Map; +using Robust.Shared.Player; using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -17,6 +19,8 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components [NetworkedComponent()] public sealed class ServerBatteryBarrelComponent : ServerRangedBarrelComponent { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "BatteryBarrel"; [DataField("cellSlot", required: true)] @@ -31,21 +35,19 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components [DataField("ammoPrototype")] [ViewVariables] private string? _ammoPrototype; - public BatteryComponent? PowerCell => CellSlot.Item?.GetComponentOrNull(); + public BatteryComponent? PowerCell => _entities.GetComponentOrNull(CellSlot.Item); private ContainerSlot _ammoContainer = default!; public override int ShotsLeft { get { - var powerCell = CellSlot.Item; - - if (powerCell == null) + if (CellSlot.Item is not {} powerCell) { return 0; } - return (int) Math.Ceiling(powerCell.GetComponent().CurrentCharge / _baseFireCost); + return (int) Math.Ceiling(_entities.GetComponent(powerCell).CurrentCharge / _baseFireCost); } } @@ -53,14 +55,12 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components { get { - var powerCell = CellSlot.Item; - - if (powerCell == null) + if (CellSlot.Item is not {} powerCell) { return 0; } - return (int) Math.Ceiling((float) (powerCell.GetComponent().MaxCharge / _baseFireCost)); + return (int) Math.Ceiling(_entities.GetComponent(powerCell).MaxCharge / _baseFireCost); } } @@ -78,14 +78,15 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components protected override void Initialize() { base.Initialize(); - EntitySystem.Get().AddItemSlot(OwnerUid, $"{Name}-powercell-container", CellSlot); + + EntitySystem.Get().AddItemSlot(Owner, $"{Name}-powercell-container", CellSlot); if (_ammoPrototype != null) { - _ammoContainer = ContainerHelpers.EnsureContainer(Owner, $"{Name}-ammo-container"); + _ammoContainer = Owner.EnsureContainer($"{Name}-ammo-container"); } - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -95,7 +96,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components protected override void OnRemove() { base.OnRemove(); - EntitySystem.Get().RemoveItemSlot(OwnerUid, CellSlot); + EntitySystem.Get().RemoveItemSlot(Owner, CellSlot); } protected override void Startup() @@ -112,64 +113,64 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components Dirty(); } - public override IEntity PeekAmmo() + public override EntityUid? PeekAmmo() { // Spawn a dummy entity because it's easier to work with I guess // This will get re-used for the projectile var ammo = _ammoContainer.ContainedEntity; if (ammo == null) { - ammo = Owner.EntityManager.SpawnEntity(_ammoPrototype, Owner.Transform.Coordinates); - _ammoContainer.Insert(ammo); + ammo = _entities.SpawnEntity(_ammoPrototype, _entities.GetComponent(Owner).Coordinates); + _ammoContainer.Insert(ammo.Value); } - return ammo; + return ammo.Value; } - public override IEntity? TakeProjectile(EntityCoordinates spawnAt) + public override EntityUid? TakeProjectile(EntityCoordinates spawnAt) { var powerCellEntity = CellSlot.Item; if (powerCellEntity == null) { - return null; + return default; } - var capacitor = powerCellEntity.GetComponent(); + var capacitor = _entities.GetComponent(powerCellEntity.Value); if (capacitor.CurrentCharge < _lowerChargeLimit) { - return null; + return default; } // Can fire confirmed // Multiply the entity's damage / whatever by the percentage of charge the shot has. - IEntity entity; + EntityUid? entity; var chargeChange = Math.Min(capacitor.CurrentCharge, _baseFireCost); if (capacitor.UseCharge(chargeChange) < _lowerChargeLimit) { // Handling of funny exploding cells. - return null; + return default; } var energyRatio = chargeChange / _baseFireCost; if (_ammoContainer.ContainedEntity != null) { entity = _ammoContainer.ContainedEntity; - _ammoContainer.Remove(entity); - entity.Transform.Coordinates = spawnAt; + _ammoContainer.Remove(entity.Value); + _entities.GetComponent(entity.Value).Coordinates = spawnAt; } else { - entity = Owner.EntityManager.SpawnEntity(_ammoPrototype, spawnAt); + entity = _entities.SpawnEntity(_ammoPrototype, spawnAt); } - if (entity.TryGetComponent(out ProjectileComponent? projectileComponent)) + if (_entities.TryGetComponent(entity.Value, out ProjectileComponent? projectileComponent)) { if (energyRatio < 1.0) { projectileComponent.Damage *= energyRatio; } - } else if (entity.TryGetComponent(out HitscanComponent? hitscanComponent)) + } else if (_entities.TryGetComponent(entity.Value, out HitscanComponent? hitscanComponent)) { hitscanComponent.Damage *= energyRatio; hitscanComponent.ColorModifier = energyRatio; @@ -181,7 +182,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components Dirty(); UpdateAppearance(); - return entity; + return entity.Value; } } } diff --git a/Content.Server/Weapon/Ranged/Barrels/Components/ServerMagazineBarrelComponent.cs b/Content.Server/Weapon/Ranged/Barrels/Components/ServerMagazineBarrelComponent.cs index e7c055bb29..7e0a30b51f 100644 --- a/Content.Server/Weapon/Ranged/Barrels/Components/ServerMagazineBarrelComponent.cs +++ b/Content.Server/Weapon/Ranged/Barrels/Components/ServerMagazineBarrelComponent.cs @@ -14,10 +14,10 @@ using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; -using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -30,6 +30,8 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components public sealed class ServerMagazineBarrelComponent : ServerRangedBarrelComponent, IUse, IInteractUsing, IExamine #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entities = default!; + public override string Name => "MagazineBarrel"; [ViewVariables] @@ -54,10 +56,9 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components count++; } - var magazine = MagazineContainer.ContainedEntity; - if (magazine != null) + if (MagazineContainer.ContainedEntity is {Valid: true} magazine) { - count += magazine.GetComponent().ShotsLeft; + count += _entities.GetComponent(magazine).ShotsLeft; } return count; @@ -70,10 +71,9 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components { // Chamber var count = 1; - var magazine = MagazineContainer.ContainedEntity; - if (magazine != null) + if (MagazineContainer.ContainedEntity is {Valid: true} magazine) { - count += magazine.GetComponent().Capacity; + count += _entities.GetComponent(magazine).Capacity; } return count; @@ -152,8 +152,8 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components public override ComponentState GetComponentState() { (int, int)? count = null; - var magazine = MagazineContainer.ContainedEntity; - if (magazine != null && magazine.TryGetComponent(out RangedMagazineComponent? rangedMagazineComponent)) + if (MagazineContainer.ContainedEntity is {Valid: true} magazine && + _entities.TryGetComponent(magazine, out RangedMagazineComponent? rangedMagazineComponent)) { count = (rangedMagazineComponent.ShotsLeft, rangedMagazineComponent.Capacity); } @@ -169,17 +169,17 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components { base.Initialize(); - if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } - _chamberContainer = ContainerHelpers.EnsureContainer(Owner, $"{Name}-chamber"); - MagazineContainer = ContainerHelpers.EnsureContainer(Owner, $"{Name}-magazine", out var existing); + _chamberContainer = Owner.EnsureContainer($"{Name}-chamber"); + MagazineContainer = Owner.EnsureContainer($"{Name}-magazine", out var existing); if (!existing && _magFillPrototype != null) { - var magEntity = Owner.EntityManager.SpawnEntity(_magFillPrototype, Owner.Transform.Coordinates); + var magEntity = _entities.SpawnEntity(_magFillPrototype, _entities.GetComponent(Owner).Coordinates); MagazineContainer.Insert(magEntity); } Dirty(); @@ -191,21 +191,21 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components UpdateAppearance(); } - public override IEntity? PeekAmmo() + public override EntityUid? PeekAmmo() { - return BoltOpen ? null : _chamberContainer.ContainedEntity; + return BoltOpen ? default : _chamberContainer.ContainedEntity; } - public override IEntity? TakeProjectile(EntityCoordinates spawnAt) + public override EntityUid? TakeProjectile(EntityCoordinates spawnAt) { if (BoltOpen) { - return null; + return default; } - var entity = _chamberContainer.ContainedEntity; + var entity = _chamberContainer.ContainedEntity ?? default; Cycle(); - return entity?.GetComponent().TakeBullet(spawnAt); + return entity != default ? _entities.GetComponent(entity).TakeBullet(spawnAt) : null; } private void Cycle(bool manual = false) @@ -272,14 +272,13 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components public bool TryEjectChamber() { - var chamberEntity = _chamberContainer.ContainedEntity; - if (chamberEntity != null) + if (_chamberContainer.ContainedEntity is {Valid: true} chamberEntity) { if (!_chamberContainer.Remove(chamberEntity)) { return false; } - var ammoComponent = chamberEntity.GetComponent(); + var ammoComponent = _entities.GetComponent(chamberEntity); if (!ammoComponent.Caseless) { EjectCasing(chamberEntity); @@ -297,17 +296,16 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components } // Try and pull a round from the magazine to replace the chamber if possible - var magazine = MagazineContainer.ContainedEntity; - var nextRound = magazine?.GetComponent().TakeAmmo(); + var magazine = MagazineContainer.ContainedEntity ?? default; - if (nextRound == null) + if (_entities.GetComponentOrNull(magazine)?.TakeAmmo() is not {Valid: true} nextRound) { return false; } _chamberContainer.Insert(nextRound); - if (_autoEjectMag && magazine != null && magazine.GetComponent().ShotsLeft == 0) + if (_autoEjectMag && magazine != null && _entities.GetComponent(magazine).ShotsLeft == 0) { SoundSystem.Play(Filter.Pvs(Owner), _soundAutoEject.GetSound(), Owner, AudioParams.Default.WithVolume(-2)); @@ -319,7 +317,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components return true; } - public void RemoveMagazine(IEntity user) + public void RemoveMagazine(EntityUid user) { var mag = MagazineContainer.ContainedEntity; @@ -334,21 +332,21 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components return; } - MagazineContainer.Remove(mag); + MagazineContainer.Remove(mag.Value); SoundSystem.Play(Filter.Pvs(Owner), _soundMagEject.GetSound(), Owner, AudioParams.Default.WithVolume(-2)); - if (user.TryGetComponent(out HandsComponent? handsComponent)) + if (_entities.TryGetComponent(user, out HandsComponent? handsComponent)) { - handsComponent.PutInHandOrDrop(mag.GetComponent()); + handsComponent.PutInHandOrDrop(_entities.GetComponent(mag.Value)); } Dirty(); UpdateAppearance(); } - public bool CanInsertMagazine(IEntity user, IEntity magazine, bool quiet = true) + public bool CanInsertMagazine(EntityUid user, EntityUid magazine, bool quiet = true) { - if (!magazine.TryGetComponent(out RangedMagazineComponent? magazineComponent)) + if (!_entities.TryGetComponent(magazine, out RangedMagazineComponent? magazineComponent)) { return false; } @@ -384,7 +382,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components return false; } - public void InsertMagazine(IEntity user, IEntity magazine) + public void InsertMagazine(EntityUid user, EntityUid magazine) { SoundSystem.Play(Filter.Pvs(Owner), _soundMagInsert.GetSound(), Owner, AudioParams.Default.WithVolume(-2)); Owner.PopupMessage(user, Loc.GetString("server-magazine-barrel-component-interact-using-success")); @@ -402,7 +400,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components } // Insert 1 ammo - if (eventArgs.Using.TryGetComponent(out AmmoComponent? ammoComponent)) + if (_entities.TryGetComponent(eventArgs.Using, out AmmoComponent? ammoComponent)) { if (!BoltOpen) { diff --git a/Content.Server/Weapon/Ranged/Barrels/Components/ServerRangedBarrelComponent.cs b/Content.Server/Weapon/Ranged/Barrels/Components/ServerRangedBarrelComponent.cs index 208ec83e33..dd83b75198 100644 --- a/Content.Server/Weapon/Ranged/Barrels/Components/ServerRangedBarrelComponent.cs +++ b/Content.Server/Weapon/Ranged/Barrels/Components/ServerRangedBarrelComponent.cs @@ -6,8 +6,6 @@ using Content.Server.Administration.Logs; using Content.Server.Camera; using Content.Server.Projectiles.Components; using Content.Server.Weapon.Ranged.Ammunition.Components; -using Content.Shared.Administration.Logs; -using Content.Shared.Audio; using Content.Shared.Damage; using Content.Shared.Database; using Content.Shared.Examine; @@ -22,7 +20,6 @@ using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; -using Robust.Shared.Physics.Broadphase; using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Random; @@ -45,6 +42,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components // it's just when I re-organised it changed me as the contributor [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly IRobustRandom _robustRandom = default!; + [Dependency] private readonly IEntityManager _entities = default!; public override FireRateSelector FireRateSelector => _fireRateSelector; @@ -59,8 +57,8 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components // _lastFire is when we actually fired (so if we hold the button then recoil doesn't build up if we're not firing) private TimeSpan _lastFire; - public abstract IEntity? PeekAmmo(); - public abstract IEntity? TakeProjectile(EntityCoordinates spawnAt); + public abstract EntityUid? PeekAmmo(); + public abstract EntityUid? TakeProjectile(EntityCoordinates spawnAt); // Recoil / spray control [DataField("minAngle")] @@ -149,7 +147,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components protected override void OnRemove() { base.OnRemove(); - if (Owner.TryGetComponent(out ServerRangedWeaponComponent? rangedWeaponComponent)) + if (_entities.TryGetComponent(Owner, out ServerRangedWeaponComponent? rangedWeaponComponent)) { rangedWeaponComponent.Barrel = null; rangedWeaponComponent.FireHandler -= Fire; @@ -191,7 +189,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components /// /// Entity that is operating the weapon, usually the player. /// Target position on the map to shoot at. - private void Fire(IEntity shooter, Vector2 targetPos) + private void Fire(EntityUid shooter, Vector2 targetPos) { if (ShotsLeft == 0) { @@ -200,32 +198,30 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components } var ammo = PeekAmmo(); - var projectile = TakeProjectile(shooter.Transform.Coordinates); - if (projectile == null) + if (TakeProjectile(_entities.GetComponent(shooter).Coordinates) is not {Valid: true} projectile) { SoundSystem.Play(Filter.Broadcast(), SoundEmpty.GetSound(), Owner); return; } // At this point firing is confirmed - var direction = (targetPos - shooter.Transform.WorldPosition).ToAngle(); + var direction = (targetPos - _entities.GetComponent(shooter).WorldPosition).ToAngle(); var angle = GetRecoilAngle(direction); // This should really be client-side but for now we'll just leave it here - if (shooter.TryGetComponent(out CameraRecoilComponent? recoilComponent)) + if (_entities.TryGetComponent(shooter, out CameraRecoilComponent? recoilComponent)) { recoilComponent.Kick(-angle.ToVec() * 0.15f); } // This section probably needs tweaking so there can be caseless hitscan etc. - if (projectile.TryGetComponent(out HitscanComponent? hitscan)) + if (_entities.TryGetComponent(projectile, out HitscanComponent? hitscan)) { FireHitscan(shooter, hitscan, angle); } - else if (projectile.HasComponent() && - ammo != null && - ammo.TryGetComponent(out AmmoComponent? ammoComponent)) + else if (_entities.HasComponent(projectile) && + _entities.TryGetComponent(ammo, out AmmoComponent? ammoComponent)) { - FireProjectiles(shooter, projectile, ammoComponent.ProjectilesFired, ammoComponent.EvenSpreadAngle, angle, ammoComponent.Velocity, ammo); + FireProjectiles(shooter, projectile, ammoComponent.ProjectilesFired, ammoComponent.EvenSpreadAngle, angle, ammoComponent.Velocity, ammo.Value); if (CanMuzzleFlash) { @@ -234,7 +230,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components if (ammoComponent.Caseless) { - ammo.Delete(); + _entities.DeleteEntity(ammo.Value); } } else @@ -258,23 +254,26 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components /// /// public static void EjectCasing( - IEntity entity, + EntityUid entity, bool playSound = true, + Direction[]? ejectDirections = null, IRobustRandom? robustRandom = null, IPrototypeManager? prototypeManager = null, - Direction[]? ejectDirections = null) + IEntityManager? entities = null) { - robustRandom ??= IoCManager.Resolve(); + IoCManager.Resolve(ref robustRandom, ref prototypeManager, ref entities); + ejectDirections ??= new[] {Direction.East, Direction.North, Direction.NorthWest, Direction.South, Direction.SouthEast, Direction.West}; const float ejectOffset = 1.8f; - var ammo = entity.GetComponent(); + var ammo = entities.GetComponent(entity); var offsetPos = ((robustRandom.NextFloat() - 0.5f) * ejectOffset, (robustRandom.NextFloat() - 0.5f) * ejectOffset); - entity.Transform.Coordinates = entity.Transform.Coordinates.Offset(offsetPos); - entity.Transform.LocalRotation = robustRandom.Pick(ejectDirections).ToAngle(); + entities.GetComponent(entity).Coordinates = entities.GetComponent(entity).Coordinates.Offset(offsetPos); + entities.GetComponent(entity).LocalRotation = robustRandom.Pick(ejectDirections).ToAngle(); - SoundSystem.Play(Filter.Broadcast(), ammo.SoundCollectionEject.GetSound(), entity.Transform.Coordinates, AudioParams.Default.WithVolume(-1)); + var coordinates = entities.GetComponent(entity).Coordinates; + SoundSystem.Play(Filter.Broadcast(), ammo.SoundCollectionEject.GetSound(), coordinates, AudioParams.Default.WithVolume(-1)); } /// @@ -282,7 +281,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components /// Wraps EjectCasing to make it less toxic for bulk ejections /// /// - public static void EjectCasings(IEnumerable entities) + public static void EjectCasings(IEnumerable entities) { var robustRandom = IoCManager.Resolve(); var prototypeManager = IoCManager.Resolve(); @@ -292,7 +291,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components foreach (var entity in entities) { - EjectCasing(entity, playSound, robustRandom, prototypeManager, ejectDirections); + EjectCasing(entity, playSound, ejectDirections, robustRandom, prototypeManager); soundPlayCount++; if (soundPlayCount > 3) { @@ -305,7 +304,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components /// /// Handles firing one or many projectiles /// - private void FireProjectiles(IEntity shooter, IEntity baseProjectile, int count, float evenSpreadAngle, Angle angle, float velocity, IEntity ammo) + private void FireProjectiles(EntityUid shooter, EntityUid baseProjectile, int count, float evenSpreadAngle, Angle angle, float velocity, EntityUid ammo) { List? sprayAngleChange = null; if (count > 1) @@ -317,7 +316,7 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components var firedProjectiles = new EntityUid[count]; for (var i = 0; i < count; i++) { - IEntity projectile; + EntityUid projectile; if (i == 0) { @@ -325,11 +324,12 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components } else { - projectile = - Owner.EntityManager.SpawnEntity(baseProjectile.Prototype?.ID, baseProjectile.Transform.Coordinates); + projectile = _entities.SpawnEntity( + _entities.GetComponent(baseProjectile).EntityPrototype?.ID, + _entities.GetComponent(baseProjectile).Coordinates); } - firedProjectiles[i] = projectile.Uid; + firedProjectiles[i] = projectile; Angle projectileAngle; @@ -342,10 +342,10 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components projectileAngle = angle; } - var physics = projectile.GetComponent(); + var physics = _entities.GetComponent(projectile); physics.BodyStatus = BodyStatus.InAir; - var projectileComponent = projectile.GetComponent(); + var projectileComponent = _entities.GetComponent(projectile); projectileComponent.IgnoreEntity(shooter); // FIXME: Work around issue where inserting and removing an entity from a container, @@ -353,17 +353,16 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components // See SharedBroadphaseSystem.HandleContainerInsert()... It sets Awake to false, which causes this. projectile.SpawnTimer(TimeSpan.FromMilliseconds(25), () => { - projectile - .GetComponent() + _entities.GetComponent(projectile) .LinearVelocity = projectileAngle.ToVec() * velocity; }); - projectile.Transform.WorldRotation = projectileAngle + MathHelper.PiOver2; + _entities.GetComponent(projectile).WorldRotation = projectileAngle + MathHelper.PiOver2; } - Owner.EntityManager.EventBus.RaiseLocalEvent(OwnerUid, new GunShotEvent(firedProjectiles)); - Owner.EntityManager.EventBus.RaiseLocalEvent(ammo.Uid, new AmmoShotEvent(firedProjectiles)); + _entities.EventBus.RaiseLocalEvent(Owner, new GunShotEvent(firedProjectiles)); + _entities.EventBus.RaiseLocalEvent(ammo, new AmmoShotEvent(firedProjectiles)); } /// @@ -385,18 +384,18 @@ namespace Content.Server.Weapon.Ranged.Barrels.Components /// /// Fires hitscan entities and then displays their effects /// - private void FireHitscan(IEntity shooter, HitscanComponent hitscan, Angle angle) + private void FireHitscan(EntityUid shooter, HitscanComponent hitscan, Angle angle) { - var ray = new CollisionRay(Owner.Transform.Coordinates.ToMapPos(Owner.EntityManager), angle.ToVec(), (int) hitscan.CollisionMask); + var ray = new CollisionRay(_entities.GetComponent(Owner).Coordinates.ToMapPos(_entities), angle.ToVec(), (int) hitscan.CollisionMask); var physicsManager = EntitySystem.Get(); - var rayCastResults = physicsManager.IntersectRay(Owner.Transform.MapID, ray, hitscan.MaxLength, shooter, false).ToList(); + var rayCastResults = physicsManager.IntersectRay(_entities.GetComponent(Owner).MapID, ray, hitscan.MaxLength, shooter, false).ToList(); if (rayCastResults.Count >= 1) { var result = rayCastResults[0]; var distance = result.Distance; hitscan.FireEffects(shooter, distance, angle, result.HitEntity); - var dmg = EntitySystem.Get().TryChangeDamage(result.HitEntity.Uid, hitscan.Damage); + var dmg = EntitySystem.Get().TryChangeDamage(result.HitEntity, hitscan.Damage); if (dmg != null) EntitySystem.Get().Add(LogType.HitScanHit, $"{shooter} hit {result.HitEntity} using {hitscan.Owner} and dealt {dmg.Total} damage"); diff --git a/Content.Server/Weapon/Ranged/ServerRangedWeaponComponent.cs b/Content.Server/Weapon/Ranged/ServerRangedWeaponComponent.cs index 2dc93c9cac..ec4e3d6a71 100644 --- a/Content.Server/Weapon/Ranged/ServerRangedWeaponComponent.cs +++ b/Content.Server/Weapon/Ranged/ServerRangedWeaponComponent.cs @@ -4,14 +4,12 @@ using Content.Server.CombatMode; using Content.Server.Hands.Components; using Content.Server.Interaction.Components; using Content.Server.Stunnable; -using Content.Server.Stunnable.Components; using Content.Server.Weapon.Ranged.Barrels.Components; using Content.Shared.ActionBlocker; using Content.Shared.Damage; using Content.Shared.Hands; using Content.Shared.Popups; using Content.Shared.Sound; -using Content.Shared.Stunnable; using Content.Shared.Weapons.Ranged.Components; using Robust.Shared.Audio; using Robust.Shared.GameObjects; @@ -32,6 +30,7 @@ namespace Content.Server.Weapon.Ranged [RegisterComponent] public sealed class ServerRangedWeaponComponent : SharedRangedWeaponComponent, IHandSelected { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; @@ -60,8 +59,8 @@ namespace Content.Server.Weapon.Ranged public DamageSpecifier? ClumsyDamage; public Func? WeaponCanFireHandler; - public Func? UserCanFireHandler; - public Action? FireHandler; + public Func? UserCanFireHandler; + public Action? FireHandler; public ServerRangedBarrelComponent? Barrel { @@ -87,9 +86,9 @@ namespace Content.Server.Weapon.Ranged return WeaponCanFireHandler == null || WeaponCanFireHandler(); } - private bool UserCanFire(IEntity user) + private bool UserCanFire(EntityUid user) { - return (UserCanFireHandler == null || UserCanFireHandler(user)) && EntitySystem.Get().CanInteract(user.Uid); + return (UserCanFireHandler == null || UserCanFireHandler(user)) && EntitySystem.Get().CanInteract(user); } /// @@ -106,8 +105,7 @@ namespace Content.Server.Weapon.Ranged switch (message) { case FirePosComponentMessage msg: - var user = session.AttachedEntity; - if (user == null) + if (session.AttachedEntity is not {Valid: true} user) { return; } @@ -144,14 +142,14 @@ namespace Content.Server.Weapon.Ranged /// /// Entity that is operating the weapon, usually the player. /// Target position on the map to shoot at. - private void TryFire(IEntity user, Vector2 targetPos) + private void TryFire(EntityUid user, Vector2 targetPos) { - if (!user.TryGetComponent(out HandsComponent? hands) || hands.GetActiveHand?.Owner != Owner) + if (!_entMan.TryGetComponent(user, out HandsComponent? hands) || hands.GetActiveHand?.Owner != Owner) { return; } - if (!user.TryGetComponent(out CombatModeComponent? combat) || !combat.IsInCombatMode) + if (!_entMan.TryGetComponent(user, out CombatModeComponent? combat) || !combat.IsInCombatMode) { return; } @@ -173,27 +171,27 @@ namespace Content.Server.Weapon.Ranged if (ClumsyCheck && ClumsyDamage != null && ClumsyComponent.TryRollClumsy(user, ClumsyExplodeChance)) { //Wound them - EntitySystem.Get().TryChangeDamage(user.Uid, ClumsyDamage); - EntitySystem.Get().TryParalyze(user.Uid, TimeSpan.FromSeconds(3f), true); + EntitySystem.Get().TryChangeDamage(user, ClumsyDamage); + EntitySystem.Get().TryParalyze(user, TimeSpan.FromSeconds(3f), true); // Apply salt to the wound ("Honk!") SoundSystem.Play( Filter.Pvs(Owner), _clumsyWeaponHandlingSound.GetSound(), - Owner.Transform.Coordinates, AudioParams.Default.WithMaxDistance(5)); + _entMan.GetComponent(Owner).Coordinates, AudioParams.Default.WithMaxDistance(5)); SoundSystem.Play( Filter.Pvs(Owner), _clumsyWeaponShotSound.GetSound(), - Owner.Transform.Coordinates, AudioParams.Default.WithMaxDistance(5)); + _entMan.GetComponent(Owner).Coordinates, AudioParams.Default.WithMaxDistance(5)); user.PopupMessage(Loc.GetString("server-ranged-weapon-component-try-fire-clumsy")); - Owner.Delete(); + _entMan.DeleteEntity(Owner); return; } if (_canHotspot) { - EntitySystem.Get().HotspotExpose(user.Transform.Coordinates, 700, 50); + EntitySystem.Get().HotspotExpose(_entMan.GetComponent(user).Coordinates, 700, 50); } FireHandler?.Invoke(user, targetPos); } diff --git a/Content.Server/Weapon/WeaponCapacitorChargerComponent.cs b/Content.Server/Weapon/WeaponCapacitorChargerComponent.cs index d7af61facf..3f0563ee03 100644 --- a/Content.Server/Weapon/WeaponCapacitorChargerComponent.cs +++ b/Content.Server/Weapon/WeaponCapacitorChargerComponent.cs @@ -3,6 +3,7 @@ using Content.Server.PowerCell.Components; using Content.Server.Weapon.Ranged.Barrels.Components; using Content.Shared.Interaction; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Server.Weapon { @@ -14,17 +15,19 @@ namespace Content.Server.Weapon [ComponentReference(typeof(BaseCharger))] public sealed class WeaponCapacitorChargerComponent : BaseCharger { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "WeaponCapacitorCharger"; - public override bool IsEntityCompatible(IEntity entity) + public override bool IsEntityCompatible(EntityUid entity) { - return entity.TryGetComponent(out ServerBatteryBarrelComponent? battery) && battery.PowerCell != null || - entity.TryGetComponent(out PowerCellSlotComponent? slot) && slot.HasCell; + return _entMan.TryGetComponent(entity, out ServerBatteryBarrelComponent? battery) && battery.PowerCell != null || + _entMan.TryGetComponent(entity, out PowerCellSlotComponent? slot) && slot.HasCell; } - protected override BatteryComponent? GetBatteryFrom(IEntity entity) + protected override BatteryComponent? GetBatteryFrom(EntityUid entity) { - if (entity.TryGetComponent(out PowerCellSlotComponent? slot)) + if (_entMan.TryGetComponent(entity, out PowerCellSlotComponent? slot)) { if (slot.Cell != null) { @@ -32,7 +35,7 @@ namespace Content.Server.Weapon } } - if (entity.TryGetComponent(out ServerBatteryBarrelComponent? battery)) + if (_entMan.TryGetComponent(entity, out ServerBatteryBarrelComponent? battery)) { if (battery.PowerCell != null) { diff --git a/Content.Server/Wieldable/WieldableSystem.cs b/Content.Server/Wieldable/WieldableSystem.cs index dbf54017a4..1095095be7 100644 --- a/Content.Server/Wieldable/WieldableSystem.cs +++ b/Content.Server/Wieldable/WieldableSystem.cs @@ -43,12 +43,14 @@ namespace Content.Server.Wieldable // TODO VERB TOOLTIPS Make CanWield or some other function return string, set as verb tooltip and disable // verb. Or just don't add it to the list if the action is not executable. - Verb verb = new(); // TODO VERBS ICON + localization - verb.Text = component.Wielded ? "Unwield" : "Wield"; - verb.Act = component.Wielded - ? () => AttemptUnwield(component.Owner.Uid, component, args.User) - : () => AttemptWield(component.Owner.Uid, component, args.User); + Verb verb = new() + { + Text = component.Wielded ? "Unwield" : "Wield", + Act = component.Wielded + ? () => AttemptUnwield(component.Owner, component, args.User) + : () => AttemptWield(component.Owner, component, args.User) + }; args.Verbs.Add(verb); } @@ -63,10 +65,10 @@ namespace Content.Server.Wieldable AttemptUnwield(uid, component, args.User); } - public bool CanWield(EntityUid uid, WieldableComponent component, IEntity user, bool quiet=false) + public bool CanWield(EntityUid uid, WieldableComponent component, EntityUid user, bool quiet=false) { // Do they have enough hands free? - if (!EntityManager.TryGetComponent(user.Uid, out var hands)) + if (!EntityManager.TryGetComponent(user, out var hands)) { if(!quiet) user.PopupMessage(Loc.GetString("wieldable-component-no-hands")); @@ -80,19 +82,18 @@ namespace Content.Server.Wieldable { user.PopupMessage(Loc.GetString("wieldable-component-not-enough-free-hands", ("number", component.FreeHandsRequired), - ("item", EntityManager.GetEntity(uid)))); + ("item", uid))); } return false; } // Is it.. actually in one of their hands? - if (!hands.TryGetHandHoldingEntity(EntityManager.GetEntity(uid), out var _)) + if (!hands.TryGetHandHoldingEntity(uid, out _)) { if (!quiet) { - user.PopupMessage(Loc.GetString("wieldable-component-not-in-hands", - ("item", EntityManager.GetEntity(uid)))); + user.PopupMessage(Loc.GetString("wieldable-component-not-in-hands", ("item", uid))); } return false; @@ -105,13 +106,12 @@ namespace Content.Server.Wieldable /// /// Attempts to wield an item, creating a DoAfter.. /// - public void AttemptWield(EntityUid uid, WieldableComponent component, IEntity user) + public void AttemptWield(EntityUid used, WieldableComponent component, EntityUid user) { - if (!CanWield(uid, component, user)) + if (!CanWield(used, component, user)) return; var ev = new BeforeWieldEvent(); - RaiseLocalEvent(uid, ev, false); - var used = EntityManager.GetEntity(uid); + RaiseLocalEvent(used, ev, false); if (ev.Cancelled) return; @@ -119,8 +119,7 @@ namespace Content.Server.Wieldable user, component.WieldTime, default, - used - ) + used) { BreakOnUserMove = false, BreakOnDamage = true, @@ -136,24 +135,23 @@ namespace Content.Server.Wieldable /// /// Attempts to unwield an item, with no DoAfter. /// - public void AttemptUnwield(EntityUid uid, WieldableComponent component, IEntity user) + public void AttemptUnwield(EntityUid used, WieldableComponent component, EntityUid user) { var ev = new BeforeUnwieldEvent(); - RaiseLocalEvent(uid, ev, false); - var used = EntityManager.GetEntity(uid); + RaiseLocalEvent(used, ev, false); if (ev.Cancelled) return; var targEv = new ItemUnwieldedEvent(user); var userEv = new UnwieldedItemEvent(used); - RaiseLocalEvent(uid, targEv, false); - RaiseLocalEvent(user.Uid, userEv, false); + RaiseLocalEvent(used, targEv, false); + RaiseLocalEvent(user, userEv, false); } private void OnItemWielded(EntityUid uid, WieldableComponent component, ItemWieldedEvent args) { - if (args.User == null) + if (args.User == default) return; if (!CanWield(uid, component, args.User) || component.Wielded) return; @@ -168,21 +166,21 @@ namespace Content.Server.Wieldable if (component.WieldSound != null) { - SoundSystem.Play(Filter.Pvs(EntityManager.GetEntity(uid)), component.WieldSound.GetSound()); + SoundSystem.Play(Filter.Pvs(uid), component.WieldSound.GetSound()); } for (var i = 0; i < component.FreeHandsRequired; i++) { - _virtualItemSystem.TrySpawnVirtualItemInHand(uid, args.User.Uid); + _virtualItemSystem.TrySpawnVirtualItemInHand(uid, args.User); } args.User.PopupMessage(Loc.GetString("wieldable-component-successful-wield", - ("item", EntityManager.GetEntity(uid)))); + ("item", uid))); } private void OnItemUnwielded(EntityUid uid, WieldableComponent component, ItemUnwieldedEvent args) { - if (args.User == null) + if (args.User == default) return; if (!component.Wielded) return; @@ -198,28 +196,28 @@ namespace Content.Server.Wieldable { if (component.UnwieldSound != null) { - SoundSystem.Play(Filter.Pvs(EntityManager.GetEntity(uid)), + SoundSystem.Play(Filter.Pvs(uid), component.UnwieldSound.GetSound()); } args.User.PopupMessage(Loc.GetString("wieldable-component-failed-wield", - ("item", EntityManager.GetEntity(uid)))); + ("item", uid))); } - _virtualItemSystem.DeleteInHandsMatching(args.User.Uid, uid); + _virtualItemSystem.DeleteInHandsMatching(args.User, uid); } private void OnItemLeaveHand(EntityUid uid, WieldableComponent component, UnequippedHandEvent args) { - if (!component.Wielded || component.Owner.Uid != args.Unequipped.Uid) + if (!component.Wielded || component.Owner != args.Unequipped) return; RaiseLocalEvent(uid, new ItemUnwieldedEvent(args.User, force: true)); } private void OnVirtualItemDeleted(EntityUid uid, WieldableComponent component, VirtualItemDeletedEvent args) { - if(args.BlockingEntity == uid && component.Wielded) - AttemptUnwield(args.BlockingEntity, component, EntityManager.GetEntity(args.User)); + if (args.BlockingEntity == uid && component.Wielded) + AttemptUnwield(args.BlockingEntity, component, args.User); } private void OnMeleeHit(EntityUid uid, IncreaseDamageOnWieldComponent component, MeleeHitEvent args) @@ -247,9 +245,9 @@ namespace Content.Server.Wieldable /// public class ItemWieldedEvent : EntityEventArgs { - public IEntity? User; + public EntityUid User; - public ItemWieldedEvent(IEntity? user=null) + public ItemWieldedEvent(EntityUid user = default) { User = user; } @@ -260,9 +258,9 @@ namespace Content.Server.Wieldable /// public class WieldedItemEvent : EntityEventArgs { - public IEntity Item; + public EntityUid Item; - public WieldedItemEvent(IEntity item) + public WieldedItemEvent(EntityUid item) { Item = item; } @@ -277,13 +275,13 @@ namespace Content.Server.Wieldable /// public class ItemUnwieldedEvent : EntityEventArgs { - public IEntity? User; + public EntityUid User; /// /// Whether the item is being forced to be unwielded, or if the player chose to unwield it themselves. /// public bool Force; - public ItemUnwieldedEvent(IEntity? user=null, bool force=false) + public ItemUnwieldedEvent(EntityUid user = default, bool force=false) { User = user; Force = force; @@ -295,9 +293,9 @@ namespace Content.Server.Wieldable /// public class UnwieldedItemEvent : EntityEventArgs { - public IEntity Item; + public EntityUid Item; - public UnwieldedItemEvent(IEntity item) + public UnwieldedItemEvent(EntityUid item) { Item = item; } diff --git a/Content.Server/Window/WindowComponent.cs b/Content.Server/Window/WindowComponent.cs index 52c84a1c7b..150e00a0a8 100644 --- a/Content.Server/Window/WindowComponent.cs +++ b/Content.Server/Window/WindowComponent.cs @@ -9,7 +9,6 @@ using Content.Shared.Interaction; using Content.Shared.Rounding; using Content.Shared.Sound; using Content.Shared.Window; -using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -28,6 +27,7 @@ namespace Content.Server.Window public class WindowComponent : SharedWindowComponent, IExamine, IInteractHand #pragma warning restore 618 { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [ViewVariables(VVAccess.ReadWrite)] private TimeSpan _lastKnockTime; @@ -44,8 +44,8 @@ namespace Content.Server.Window void IExamine.Examine(FormattedMessage message, bool inDetailsRange) { - if (!Owner.TryGetComponent(out DamageableComponent? damageable) || - !Owner.TryGetComponent(out DestructibleComponent? destructible)) + if (!_entMan.TryGetComponent(Owner, out DamageableComponent? damageable) || + !_entMan.TryGetComponent(Owner, out DestructibleComponent? destructible)) { return; } @@ -71,7 +71,7 @@ namespace Content.Server.Window var fraction = damage == 0 || damageThreshold == 0 ? 0f : (float) damage / damageThreshold; - var level = Math.Min(ContentHelpers.RoundToLevels((double) fraction, 1, 7), 5); + var level = Math.Min(ContentHelpers.RoundToLevels(fraction, 1, 7), 5); switch (level) { @@ -105,7 +105,7 @@ namespace Content.Server.Window SoundSystem.Play( Filter.Pvs(eventArgs.Target), _knockSound.GetSound(), - eventArgs.Target.Transform.Coordinates, AudioHelpers.WithVariation(0.05f)); + _entMan.GetComponent(eventArgs.Target).Coordinates, AudioHelpers.WithVariation(0.05f)); eventArgs.Target.PopupMessageEveryone(Loc.GetString("comp-window-knock")); _lastKnockTime = _gameTiming.CurTime; diff --git a/Content.Server/WireHacking/WiresComponent.cs b/Content.Server/WireHacking/WiresComponent.cs index 46b956fc50..d9acca8305 100644 --- a/Content.Server/WireHacking/WiresComponent.cs +++ b/Content.Server/WireHacking/WiresComponent.cs @@ -14,7 +14,6 @@ using Content.Shared.Popups; using Content.Shared.Sound; using Content.Shared.Tools; using Content.Shared.Wires; -using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Audio; @@ -36,8 +35,7 @@ namespace Content.Server.WireHacking #pragma warning restore 618 { [Dependency] private readonly IRobustRandom _random = default!; - - private AudioSystem _audioSystem = default!; + [Dependency] private readonly IEntityManager _entities = default!; private bool _isPanelOpen; @@ -117,7 +115,7 @@ namespace Content.Server.WireHacking private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(WiresVisuals.MaintenancePanelState, IsPanelOpen && IsPanelVisible); } @@ -173,9 +171,8 @@ namespace Content.Server.WireHacking protected override void Initialize() { base.Initialize(); - _audioSystem = EntitySystem.Get(); - if (Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(WiresVisuals.MaintenancePanelState, IsPanelOpen); } @@ -230,7 +227,7 @@ namespace Content.Server.WireHacking hackingSystem.TryGetLayout(_layoutId, out layout); } - foreach (var wiresProvider in Owner.GetAllComponents()) + foreach (var wiresProvider in _entities.GetComponents(Owner)) { var builder = new WiresBuilder(this, wiresProvider, layout); wiresProvider.RegisterWires(builder); @@ -334,8 +331,8 @@ namespace Content.Server.WireHacking /// public class WiresBuilder { - [NotNull] private readonly WiresComponent _wires; - [NotNull] private readonly IWires _owner; + private readonly WiresComponent _wires; + private readonly IWires _owner; private readonly WireLayout? _layout; public WiresBuilder(WiresComponent wires, IWires owner, WireLayout? layout) @@ -410,13 +407,12 @@ namespace Content.Server.WireHacking { case WiresActionMessage msg: var wire = WiresList.Find(x => x.Id == msg.Id); - var player = serverMsg.Session.AttachedEntity; - if (wire == null || player == null) + if (wire == null || serverMsg.Session.AttachedEntity is not {} player) { return; } - if (!player.TryGetComponent(out HandsComponent? handsComponent)) + if (!_entities.TryGetComponent(player, out HandsComponent? handsComponent)) { Owner.PopupMessage(player, Loc.GetString("wires-component-ui-on-receive-message-no-hands")); return; @@ -428,9 +424,9 @@ namespace Content.Server.WireHacking return; } - var activeHandEntity = handsComponent.GetActiveHand?.Owner; ToolComponent? tool = null; - activeHandEntity?.TryGetComponent(out tool); + if (handsComponent.GetActiveHand?.Owner is {Valid: true} activeHandEntity) + _entities.TryGetComponent(activeHandEntity, out tool); var toolSystem = EntitySystem.Get(); switch (msg.Action) @@ -442,8 +438,7 @@ namespace Content.Server.WireHacking return; } - // activeHandEntity cannot be null because tool is not null. - toolSystem.PlayToolSound(activeHandEntity!.Uid, tool); + toolSystem.PlayToolSound(tool.Owner, tool); wire.IsCut = true; UpdateUserInterface(); break; @@ -454,8 +449,7 @@ namespace Content.Server.WireHacking return; } - // activeHandEntity cannot be null because tool is not null. - toolSystem.PlayToolSound(activeHandEntity!.Uid, tool); + toolSystem.PlayToolSound(tool.Owner, tool); wire.IsCut = false; UpdateUserInterface(); break; @@ -501,7 +495,7 @@ namespace Content.Server.WireHacking async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (!eventArgs.Using.TryGetComponent(out var tool)) + if (!_entities.TryGetComponent(eventArgs.Using, out var tool)) { return false; } @@ -513,7 +507,7 @@ namespace Content.Server.WireHacking (tool.Qualities.Contains(_cuttingQuality) || tool.Qualities.Contains(_pulsingQuality))) { - if (eventArgs.User.TryGetComponent(out ActorComponent? actor)) + if (_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor)) { OpenInterface(actor.PlayerSession); return true; @@ -521,7 +515,7 @@ namespace Content.Server.WireHacking } // screws the panel open if the tool can do so - else if (await toolSystem.UseTool(tool.Owner.Uid, eventArgs.User.Uid, Owner.Uid, + else if (await toolSystem.UseTool(tool.Owner, eventArgs.User, Owner, 0f, WireHackingSystem.ScrewTime, _screwingQuality, toolComponent:tool)) { IsPanelOpen = !IsPanelOpen; diff --git a/Content.Shared/Actions/Behaviors/IActionBehavior.cs b/Content.Shared/Actions/Behaviors/IActionBehavior.cs index 74dc3ca08f..304db1620e 100644 --- a/Content.Shared/Actions/Behaviors/IActionBehavior.cs +++ b/Content.Shared/Actions/Behaviors/IActionBehavior.cs @@ -1,6 +1,7 @@ using System; using Content.Shared.Actions.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Shared.Actions.Behaviors { @@ -20,7 +21,7 @@ namespace Content.Shared.Actions.Behaviors /// /// Entity performing the action. /// - public readonly IEntity Performer; + public readonly EntityUid Performer; /// /// Action being performed /// @@ -30,13 +31,13 @@ namespace Content.Shared.Actions.Behaviors /// public readonly SharedActionsComponent? PerformerActions; - public ActionEventArgs(IEntity performer, ActionType actionType) + public ActionEventArgs(EntityUid performer, ActionType actionType) { Performer = performer; ActionType = actionType; - if (!Performer.TryGetComponent(out PerformerActions)) + if (!IoCManager.Resolve().TryGetComponent(Performer, out PerformerActions)) { - throw new InvalidOperationException($"performer {performer.Name} tried to perform action {actionType} " + + throw new InvalidOperationException($"performer {IoCManager.Resolve().GetComponent(performer).EntityName} tried to perform action {actionType} " + $" but the performer had no actions component," + " which should never occur"); } diff --git a/Content.Shared/Actions/Behaviors/IInstantAction.cs b/Content.Shared/Actions/Behaviors/IInstantAction.cs index 9d3c07bed7..910f226bb2 100644 --- a/Content.Shared/Actions/Behaviors/IInstantAction.cs +++ b/Content.Shared/Actions/Behaviors/IInstantAction.cs @@ -18,7 +18,7 @@ namespace Content.Shared.Actions.Behaviors public class InstantActionEventArgs : ActionEventArgs { - public InstantActionEventArgs(IEntity performer, ActionType actionType) : base(performer, actionType) + public InstantActionEventArgs(EntityUid performer, ActionType actionType) : base(performer, actionType) { } } diff --git a/Content.Shared/Actions/Behaviors/ITargetEntityAction.cs b/Content.Shared/Actions/Behaviors/ITargetEntityAction.cs index 9e8e8b8579..4288585371 100644 --- a/Content.Shared/Actions/Behaviors/ITargetEntityAction.cs +++ b/Content.Shared/Actions/Behaviors/ITargetEntityAction.cs @@ -19,9 +19,9 @@ namespace Content.Shared.Actions.Behaviors /// /// Entity being targeted /// - public readonly IEntity Target; + public readonly EntityUid Target; - public TargetEntityActionEventArgs(IEntity performer, ActionType actionType, IEntity target) : + public TargetEntityActionEventArgs(EntityUid performer, ActionType actionType, EntityUid target) : base(performer, actionType) { Target = target; diff --git a/Content.Shared/Actions/Behaviors/ITargetEntityItemAction.cs b/Content.Shared/Actions/Behaviors/ITargetEntityItemAction.cs index 26d5c3eb62..d761251a26 100644 --- a/Content.Shared/Actions/Behaviors/ITargetEntityItemAction.cs +++ b/Content.Shared/Actions/Behaviors/ITargetEntityItemAction.cs @@ -20,9 +20,9 @@ namespace Content.Shared.Actions.Behaviors /// /// Entity being targeted /// - public readonly IEntity Target; + public readonly EntityUid Target; - public TargetEntityItemActionEventArgs(IEntity performer, IEntity target, IEntity item, + public TargetEntityItemActionEventArgs(EntityUid performer, EntityUid target, EntityUid item, ItemActionType actionType) : base(performer, item, actionType) { Target = target; diff --git a/Content.Shared/Actions/Behaviors/ITargetPointAction.cs b/Content.Shared/Actions/Behaviors/ITargetPointAction.cs index 6e03e7ef3e..724a4acd17 100644 --- a/Content.Shared/Actions/Behaviors/ITargetPointAction.cs +++ b/Content.Shared/Actions/Behaviors/ITargetPointAction.cs @@ -23,7 +23,7 @@ namespace Content.Shared.Actions.Behaviors /// public readonly EntityCoordinates Target; - public TargetPointActionEventArgs(IEntity performer, EntityCoordinates target, ActionType actionType) + public TargetPointActionEventArgs(EntityUid performer, EntityCoordinates target, ActionType actionType) : base(performer, actionType) { Target = target; diff --git a/Content.Shared/Actions/Behaviors/ITargetPointItemAction.cs b/Content.Shared/Actions/Behaviors/ITargetPointItemAction.cs index 9619f092c4..a2725ff7e0 100644 --- a/Content.Shared/Actions/Behaviors/ITargetPointItemAction.cs +++ b/Content.Shared/Actions/Behaviors/ITargetPointItemAction.cs @@ -24,7 +24,7 @@ namespace Content.Shared.Actions.Behaviors /// public readonly EntityCoordinates Target; - public TargetPointItemActionEventArgs(IEntity performer, EntityCoordinates target, IEntity item, + public TargetPointItemActionEventArgs(EntityUid performer, EntityCoordinates target, EntityUid item, ItemActionType actionType) : base(performer, item, actionType) { Target = target; diff --git a/Content.Shared/Actions/Behaviors/IToggleAction.cs b/Content.Shared/Actions/Behaviors/IToggleAction.cs index 2c56ec3a97..3fecdc734a 100644 --- a/Content.Shared/Actions/Behaviors/IToggleAction.cs +++ b/Content.Shared/Actions/Behaviors/IToggleAction.cs @@ -33,7 +33,7 @@ namespace Content.Shared.Actions.Behaviors /// public bool ToggledOff => !ToggledOn; - public ToggleActionEventArgs(IEntity performer, ActionType actionType, bool toggledOn) : base(performer, actionType) + public ToggleActionEventArgs(EntityUid performer, ActionType actionType, bool toggledOn) : base(performer, actionType) { ToggledOn = toggledOn; } diff --git a/Content.Shared/Actions/Behaviors/Item/IInstantItemAction.cs b/Content.Shared/Actions/Behaviors/Item/IInstantItemAction.cs index 4ac8656719..918997dc2f 100644 --- a/Content.Shared/Actions/Behaviors/Item/IInstantItemAction.cs +++ b/Content.Shared/Actions/Behaviors/Item/IInstantItemAction.cs @@ -18,7 +18,7 @@ namespace Content.Shared.Actions.Behaviors.Item public class InstantItemActionEventArgs : ItemActionEventArgs { - public InstantItemActionEventArgs(IEntity performer, IEntity item, ItemActionType actionType) : + public InstantItemActionEventArgs(EntityUid performer, EntityUid item, ItemActionType actionType) : base(performer, item, actionType) { } diff --git a/Content.Shared/Actions/Behaviors/Item/IItemActionBehavior.cs b/Content.Shared/Actions/Behaviors/Item/IItemActionBehavior.cs index e49a6a9ba0..d185eb6281 100644 --- a/Content.Shared/Actions/Behaviors/Item/IItemActionBehavior.cs +++ b/Content.Shared/Actions/Behaviors/Item/IItemActionBehavior.cs @@ -1,6 +1,7 @@ using System; using Content.Shared.Actions.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Shared.Actions.Behaviors.Item { @@ -21,11 +22,11 @@ namespace Content.Shared.Actions.Behaviors.Item /// /// Entity performing the action. /// - public readonly IEntity Performer; + public readonly EntityUid Performer; /// /// Item being used to perform the action /// - public readonly IEntity Item; + public readonly EntityUid Item; /// /// Action being performed /// @@ -35,15 +36,16 @@ namespace Content.Shared.Actions.Behaviors.Item /// public readonly ItemActionsComponent? ItemActions; - public ItemActionEventArgs(IEntity performer, IEntity item, ItemActionType actionType) + public ItemActionEventArgs(EntityUid performer, EntityUid item, ItemActionType actionType) { Performer = performer; ActionType = actionType; Item = item; - if (!Item.TryGetComponent(out ItemActions)) + var entMan = IoCManager.Resolve(); + if (!entMan.TryGetComponent(Item, out ItemActions)) { - throw new InvalidOperationException($"performer {performer.Name} tried to perform item action {actionType} " + - $" for item {Item.Name} but the item had no ItemActionsComponent," + + throw new InvalidOperationException($"performer {entMan.GetComponent(performer).EntityName} tried to perform item action {actionType} " + + $" for item {entMan.GetComponent(Item).EntityName} but the item had no ItemActionsComponent," + " which should never occur"); } } diff --git a/Content.Shared/Actions/Behaviors/Item/IToggleItemAction.cs b/Content.Shared/Actions/Behaviors/Item/IToggleItemAction.cs index d21ebf7cf5..4d0a0cdaf4 100644 --- a/Content.Shared/Actions/Behaviors/Item/IToggleItemAction.cs +++ b/Content.Shared/Actions/Behaviors/Item/IToggleItemAction.cs @@ -33,7 +33,7 @@ namespace Content.Shared.Actions.Behaviors.Item /// public bool ToggledOff => !ToggledOn; - public ToggleItemActionEventArgs(IEntity performer, bool toggledOn, IEntity item, + public ToggleItemActionEventArgs(EntityUid performer, bool toggledOn, EntityUid item, ItemActionType actionType) : base(performer, item, actionType) { ToggledOn = toggledOn; diff --git a/Content.Shared/Actions/Components/ItemActionsComponent.cs b/Content.Shared/Actions/Components/ItemActionsComponent.cs index 8540492155..56bbdbac3c 100644 --- a/Content.Shared/Actions/Components/ItemActionsComponent.cs +++ b/Content.Shared/Actions/Components/ItemActionsComponent.cs @@ -4,6 +4,7 @@ using Content.Shared.Hands; using Content.Shared.Hands.Components; using Content.Shared.Inventory; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -46,7 +47,7 @@ namespace Content.Shared.Actions.Components /// /// Entity currently holding this in hand or equip slot. Null if not held. /// - public IEntity? Holder { get; private set; } + public EntityUid? Holder { get; private set; } // cached actions component of the holder, since we'll need to access it frequently private SharedActionsComponent? _holderActionsComponent; @@ -85,7 +86,7 @@ namespace Content.Shared.Actions.Components if (_holderActionsComponent == null) return; foreach (var (actionType, state) in _actions) { - _holderActionsComponent.GrantOrUpdateItemAction(actionType, OwnerUid, state); + _holderActionsComponent.GrantOrUpdateItemAction(actionType, Owner, state); } } @@ -94,7 +95,7 @@ namespace Content.Shared.Actions.Components if (_holderActionsComponent == null) return; foreach (var (actionType, state) in _actions) { - _holderActionsComponent.RevokeItemAction(actionType, OwnerUid); + _holderActionsComponent.RevokeItemAction(actionType, Owner); } } @@ -151,7 +152,7 @@ namespace Content.Shared.Actions.Components if (!dirty) return; _actions[actionType] = actionState; - _holderActionsComponent?.GrantOrUpdateItemAction(actionType, OwnerUid, actionState); + _holderActionsComponent?.GrantOrUpdateItemAction(actionType, Owner, actionState); } /// @@ -183,7 +184,7 @@ namespace Content.Shared.Actions.Components void IEquippedHand.EquippedHand(EquippedHandEventArgs eventArgs) { // this entity cannot be granted actions if no actions component - if (!eventArgs.User.TryGetComponent(out var actionsComponent)) + if (!IoCManager.Resolve().TryGetComponent(eventArgs.User, out var actionsComponent)) return; Holder = eventArgs.User; _holderActionsComponent = actionsComponent; @@ -195,7 +196,7 @@ namespace Content.Shared.Actions.Components void IEquipped.Equipped(EquippedEventArgs eventArgs) { // this entity cannot be granted actions if no actions component - if (!eventArgs.User.TryGetComponent(out var actionsComponent)) + if (!IoCManager.Resolve().TryGetComponent(eventArgs.User, out var actionsComponent)) return; Holder = eventArgs.User; _holderActionsComponent = actionsComponent; diff --git a/Content.Shared/Actions/Components/SharedActionsComponent.cs b/Content.Shared/Actions/Components/SharedActionsComponent.cs index c470c7e1fa..40d0a5df8e 100644 --- a/Content.Shared/Actions/Components/SharedActionsComponent.cs +++ b/Content.Shared/Actions/Components/SharedActionsComponent.cs @@ -119,13 +119,6 @@ namespace Content.Shared.Actions.Components return false; } - /// - public bool TryGetItemActionStates(IEntity item, - [NotNullWhen((true))] out IReadOnlyDictionary? itemActionStates) - { - return TryGetItemActionStates(item.Uid, out itemActionStates); - } - /// /// Gets the item action state associated with the specified item action type for the specified item, if it has any. /// @@ -170,12 +163,6 @@ namespace Content.Shared.Actions.Components .Any(state => state.Key == actionType && state.Value.Enabled); } - /// - public bool TryGetItemActionState(ItemActionType actionType, IEntity item, out ActionState actionState) - { - return TryGetItemActionState(actionType, item.Uid, out actionState); - } - /// /// Gets all action types that have non-initial state (granted, have a cooldown, or toggled on). /// diff --git a/Content.Shared/Actions/IActionAttempt.cs b/Content.Shared/Actions/IActionAttempt.cs index b2d2965ff9..5aa6eb90bd 100644 --- a/Content.Shared/Actions/IActionAttempt.cs +++ b/Content.Shared/Actions/IActionAttempt.cs @@ -39,24 +39,24 @@ namespace Content.Shared.Actions /// /// Perform the server-side logic of the action /// - void DoInstantAction(IEntity player); + void DoInstantAction(EntityUid player); /// /// Perform the server-side logic of the toggle action /// /// true if the attempt to toggle was successful, meaning the state should be toggled to the /// indicated value - bool DoToggleAction(IEntity player, bool on); + bool DoToggleAction(EntityUid player, bool on); /// /// Perform the server-side logic of the target point action /// - void DoTargetPointAction(IEntity player, EntityCoordinates target); + void DoTargetPointAction(EntityUid player, EntityCoordinates target); /// /// Perform the server-side logic of the target entity action /// - void DoTargetEntityAction(IEntity player, IEntity target); + void DoTargetEntityAction(EntityUid player, EntityUid target); } public class ActionAttempt : IActionAttempt @@ -80,22 +80,22 @@ namespace Content.Shared.Actions actionsComponent.ToggleAction(_action.ActionType, toggleOn); } - public void DoInstantAction(IEntity player) + public void DoInstantAction(EntityUid player) { _action.InstantAction.DoInstantAction(new InstantActionEventArgs(player, _action.ActionType)); } - public bool DoToggleAction(IEntity player, bool on) + public bool DoToggleAction(EntityUid player, bool on) { return _action.ToggleAction.DoToggleAction(new ToggleActionEventArgs(player, _action.ActionType, on)); } - public void DoTargetPointAction(IEntity player, EntityCoordinates target) + public void DoTargetPointAction(EntityUid player, EntityCoordinates target) { _action.TargetPointAction.DoTargetPointAction(new TargetPointActionEventArgs(player, target, _action.ActionType)); } - public void DoTargetEntityAction(IEntity player, IEntity target) + public void DoTargetEntityAction(EntityUid player, EntityUid target) { _action.TargetEntityAction.DoTargetEntityAction(new TargetEntityActionEventArgs(player, _action.ActionType, target)); @@ -142,35 +142,35 @@ namespace Content.Shared.Actions public class ItemActionAttempt : IActionAttempt { private readonly ItemActionPrototype _action; - private readonly IEntity _item; + private readonly EntityUid _item; private readonly ItemActionsComponent _itemActions; public BaseActionPrototype Action => _action; - public ItemActionAttempt(ItemActionPrototype action, IEntity item, ItemActionsComponent itemActions) + public ItemActionAttempt(ItemActionPrototype action, EntityUid item, ItemActionsComponent itemActions) { _action = action; _item = item; _itemActions = itemActions; } - public void DoInstantAction(IEntity player) + public void DoInstantAction(EntityUid player) { _action.InstantAction.DoInstantAction(new InstantItemActionEventArgs(player, _item, _action.ActionType)); } - public bool DoToggleAction(IEntity player, bool on) + public bool DoToggleAction(EntityUid player, bool on) { return _action.ToggleAction.DoToggleAction(new ToggleItemActionEventArgs(player, on, _item, _action.ActionType)); } - public void DoTargetPointAction(IEntity player, EntityCoordinates target) + public void DoTargetPointAction(EntityUid player, EntityCoordinates target) { _action.TargetPointAction.DoTargetPointAction(new TargetPointItemActionEventArgs(player, target, _item, _action.ActionType)); } - public void DoTargetEntityAction(IEntity player, IEntity target) + public void DoTargetEntityAction(EntityUid player, EntityUid target) { _action.TargetEntityAction.DoTargetEntityAction(new TargetEntityItemActionEventArgs(player, target, _item, _action.ActionType)); @@ -190,7 +190,7 @@ namespace Content.Shared.Actions public ComponentMessage PerformInstantActionMessage() #pragma warning restore 618 { - return new PerformInstantItemActionMessage(_action.ActionType, _item.Uid); + return new PerformInstantItemActionMessage(_action.ActionType, _item); } #pragma warning disable 618 @@ -199,23 +199,23 @@ namespace Content.Shared.Actions { if (toggleOn) { - return new PerformToggleOnItemActionMessage(_action.ActionType, _item.Uid); + return new PerformToggleOnItemActionMessage(_action.ActionType, _item); } - return new PerformToggleOffItemActionMessage(_action.ActionType, _item.Uid); + return new PerformToggleOffItemActionMessage(_action.ActionType, _item); } #pragma warning disable 618 public ComponentMessage PerformTargetPointActionMessage(PointerInputCmdHandler.PointerInputCmdArgs args) #pragma warning restore 618 { - return new PerformTargetPointItemActionMessage(_action.ActionType, _item.Uid, args.Coordinates); + return new PerformTargetPointItemActionMessage(_action.ActionType, _item, args.Coordinates); } #pragma warning disable 618 public ComponentMessage PerformTargetEntityActionMessage(PointerInputCmdHandler.PointerInputCmdArgs args) #pragma warning restore 618 { - return new PerformTargetEntityItemActionMessage(_action.ActionType, _item.Uid, args.EntityUid); + return new PerformTargetEntityItemActionMessage(_action.ActionType, _item, args.EntityUid); } public override string ToString() diff --git a/Content.Shared/Alert/IAlertClick.cs b/Content.Shared/Alert/IAlertClick.cs index 614c9ee6a0..e953b6f525 100644 --- a/Content.Shared/Alert/IAlertClick.cs +++ b/Content.Shared/Alert/IAlertClick.cs @@ -20,13 +20,13 @@ namespace Content.Shared.Alert /// /// Player clicking the alert /// - public readonly IEntity Player; + public readonly EntityUid Player; /// /// Alert that was clicked /// public readonly AlertPrototype Alert; - public ClickAlertEventArgs(IEntity player, AlertPrototype alert) + public ClickAlertEventArgs(EntityUid player, AlertPrototype alert) { Player = player; Alert = alert; diff --git a/Content.Shared/Body/Components/SharedBodyComponent.cs b/Content.Shared/Body/Components/SharedBodyComponent.cs index 8caafb5251..1cac1d8605 100644 --- a/Content.Shared/Body/Components/SharedBodyComponent.cs +++ b/Content.Shared/Body/Components/SharedBodyComponent.cs @@ -146,8 +146,8 @@ namespace Content.Shared.Body.Components var argsAdded = new BodyPartAddedEventArgs(slot.Id, part); - EntitySystem.Get().BodyPartAdded(OwnerUid, argsAdded); - foreach (var component in Owner.GetAllComponents().ToArray()) + EntitySystem.Get().BodyPartAdded(Owner, argsAdded); + foreach (var component in IoCManager.Resolve().GetComponents(Owner).ToArray()) { component.BodyPartAdded(argsAdded); } @@ -174,8 +174,8 @@ namespace Content.Shared.Body.Components var args = new BodyPartRemovedEventArgs(slot.Id, part); - EntitySystem.Get().BodyPartRemoved(OwnerUid, args); - foreach (var component in Owner.GetAllComponents()) + EntitySystem.Get().BodyPartRemoved(Owner, args); + foreach (var component in IoCManager.Resolve().GetComponents(Owner)) { component.BodyPartRemoved(args); } @@ -184,14 +184,14 @@ namespace Content.Shared.Body.Components if (part.PartType == BodyPartType.Leg && GetPartsOfType(BodyPartType.Leg).ToArray().Length == 0) { - EntitySystem.Get().Down(OwnerUid); + EntitySystem.Get().Down(Owner); } if (part.IsVital && SlotParts.Count(x => x.Value.PartType == part.PartType) == 0) { // TODO BODY SYSTEM KILL : Find a more elegant way of killing em than just dumping bloodloss damage. var damage = new DamageSpecifier(_prototypeManager.Index("Bloodloss"), 300); - EntitySystem.Get().TryChangeDamage(part.OwnerUid, damage); + EntitySystem.Get().TryChangeDamage(part.Owner, damage); } OnBodyChanged(); @@ -468,7 +468,7 @@ namespace Content.Shared.Body.Components var i = 0; foreach (var (part, slot) in SlotParts) { - parts[i] = (slot.Id, part.OwnerUid); + parts[i] = (slot.Id, Owner: part.Owner); i++; } @@ -542,12 +542,12 @@ namespace Content.Shared.Body.Components foreach (var (slot, partId) in PartIds) { - if (!entityManager.TryGetEntity(partId, out var entity)) + if (!entityManager.EntityExists(partId)) { continue; } - if (!entity.TryGetComponent(out SharedBodyPartComponent? part)) + if (!entityManager.TryGetComponent(partId, out SharedBodyPartComponent? part)) { continue; } diff --git a/Content.Shared/Body/Components/SharedBodyPartComponent.cs b/Content.Shared/Body/Components/SharedBodyPartComponent.cs index 8655308f4e..076001d7f3 100644 --- a/Content.Shared/Body/Components/SharedBodyPartComponent.cs +++ b/Content.Shared/Body/Components/SharedBodyPartComponent.cs @@ -18,6 +18,8 @@ namespace Content.Shared.Body.Components [NetworkedComponent()] public abstract class SharedBodyPartComponent : Component, IBodyPartContainer { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "BodyPart"; private SharedBodyComponent? _body; @@ -109,11 +111,11 @@ namespace Content.Shared.Body.Components public BodyPartSymmetry Symmetry { get; private set; } = BodyPartSymmetry.None; [ViewVariables] - public ISurgeryData? SurgeryDataComponent => Owner.GetComponentOrNull(); + public ISurgeryData? SurgeryDataComponent => _entMan.GetComponentOrNull(Owner); protected virtual void OnAddMechanism(SharedMechanismComponent mechanism) { - var prototypeId = mechanism.Owner.Prototype!.ID; + var prototypeId = _entMan.GetComponent(mechanism.Owner).EntityPrototype!.ID; if (!_mechanismIds.Contains(prototypeId)) { @@ -128,7 +130,7 @@ namespace Content.Shared.Body.Components protected virtual void OnRemoveMechanism(SharedMechanismComponent mechanism) { - _mechanismIds.Remove(mechanism.Owner.Prototype!.ID); + _mechanismIds.Remove(_entMan.GetComponent(mechanism.Owner).EntityPrototype!.ID); mechanism.Part = null; SizeUsed -= mechanism.Size; @@ -142,7 +144,7 @@ namespace Content.Shared.Body.Components var i = 0; foreach (var mechanism in _mechanisms) { - mechanismIds[i] = mechanism.OwnerUid; + mechanismIds[i] = mechanism.Owner; i++; } @@ -182,7 +184,7 @@ namespace Content.Shared.Body.Components return SurgeryDataComponent?.CheckSurgery(surgery) ?? false; } - public bool AttemptSurgery(SurgeryType toolType, IBodyPartContainer target, ISurgeon surgeon, IEntity performer) + public bool AttemptSurgery(SurgeryType toolType, IBodyPartContainer target, ISurgeon surgeon, EntityUid performer) { DebugTools.AssertNotNull(toolType); DebugTools.AssertNotNull(target); @@ -267,7 +269,7 @@ namespace Content.Shared.Body.Components { if (RemoveMechanism(mechanism)) { - mechanism.Owner.Transform.Coordinates = coordinates; + _entMan.GetComponent(mechanism.Owner).Coordinates = coordinates; return true; } @@ -292,34 +294,34 @@ namespace Content.Shared.Body.Components return false; } - mechanism.Owner.Delete(); + _entMan.DeleteEntity(mechanism.Owner); return true; } private void AddedToBody(SharedBodyComponent body) { - Owner.Transform.LocalRotation = 0; - Owner.Transform.AttachParent(body.Owner); + _entMan.GetComponent(Owner).LocalRotation = 0; + _entMan.GetComponent(Owner).AttachParent(body.Owner); OnAddedToBody(body); foreach (var mechanism in _mechanisms) { - Owner.EntityManager.EventBus.RaiseLocalEvent(mechanism.OwnerUid, new AddedToBodyEvent(body)); + _entMan.EventBus.RaiseLocalEvent(mechanism.Owner, new AddedToBodyEvent(body)); } } private void RemovedFromBody(SharedBodyComponent old) { - if (!Owner.Transform.Deleted) + if (!_entMan.GetComponent(Owner).Deleted) { - Owner.Transform.AttachToGridOrMap(); + _entMan.GetComponent(Owner).AttachToGridOrMap(); } OnRemovedFromBody(old); foreach (var mechanism in _mechanisms) { - Owner.EntityManager.EventBus.RaiseLocalEvent(mechanism.OwnerUid, new RemovedFromBodyEvent(old)); + _entMan.EventBus.RaiseLocalEvent(mechanism.Owner, new RemovedFromBodyEvent(old)); } } @@ -358,18 +360,18 @@ namespace Content.Shared.Body.Components return _mechanisms; } - entityManager ??= IoCManager.Resolve(); + IoCManager.Resolve(ref entityManager); var mechanisms = new List(MechanismIds.Length); foreach (var id in MechanismIds) { - if (!entityManager.TryGetEntity(id, out var entity)) + if (!entityManager.EntityExists(id)) { continue; } - if (!entity.TryGetComponent(out SharedMechanismComponent? mechanism)) + if (!entityManager.TryGetComponent(id, out SharedMechanismComponent? mechanism)) { continue; } diff --git a/Content.Shared/Body/Components/SharedMechanismComponent.cs b/Content.Shared/Body/Components/SharedMechanismComponent.cs index 106381995d..811521887b 100644 --- a/Content.Shared/Body/Components/SharedMechanismComponent.cs +++ b/Content.Shared/Body/Components/SharedMechanismComponent.cs @@ -2,6 +2,7 @@ using Content.Shared.Body.Events; using Content.Shared.Body.Part; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -9,12 +10,14 @@ namespace Content.Shared.Body.Components { public abstract class SharedMechanismComponent : Component, ISerializationHooks { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Mechanism"; protected readonly Dictionary OptionsCache = new(); protected SharedBodyComponent? BodyCache; protected int IdHash; - protected IEntity? PerformerCache; + protected EntityUid? PerformerCache; private SharedBodyPartComponent? _part; public SharedBodyComponent? Body => Part?.Body; @@ -36,11 +39,11 @@ namespace Content.Shared.Body.Components { if (old.Body == null) { - Owner.EntityManager.EventBus.RaiseLocalEvent(OwnerUid, new RemovedFromPartEvent(old)); + _entMan.EventBus.RaiseLocalEvent(Owner, new RemovedFromPartEvent(old)); } else { - Owner.EntityManager.EventBus.RaiseLocalEvent(OwnerUid, new RemovedFromPartInBodyEvent(old.Body, old)); + _entMan.EventBus.RaiseLocalEvent(Owner, new RemovedFromPartInBodyEvent(old.Body, old)); } } @@ -48,11 +51,11 @@ namespace Content.Shared.Body.Components { if (value.Body == null) { - Owner.EntityManager.EventBus.RaiseLocalEvent(OwnerUid, new AddedToPartEvent(value)); + _entMan.EventBus.RaiseLocalEvent(Owner, new AddedToPartEvent(value)); } else { - Owner.EntityManager.EventBus.RaiseLocalEvent(OwnerUid, new AddedToPartInBodyEvent(value.Body, value)); + _entMan.EventBus.RaiseLocalEvent(Owner, new AddedToPartInBodyEvent(value.Body, value)); } } } diff --git a/Content.Shared/Body/Surgery/ISurgeon.cs b/Content.Shared/Body/Surgery/ISurgeon.cs index 33ec4f375b..a322e779cd 100644 --- a/Content.Shared/Body/Surgery/ISurgeon.cs +++ b/Content.Shared/Body/Surgery/ISurgeon.cs @@ -15,7 +15,7 @@ namespace Content.Shared.Body.Surgery SharedMechanismComponent target, IBodyPartContainer container, ISurgeon surgeon, - IEntity performer); + EntityUid performer); /// /// How long it takes to perform a single surgery step in seconds. diff --git a/Content.Shared/Body/Surgery/SurgeryDataComponent.cs b/Content.Shared/Body/Surgery/SurgeryDataComponent.cs index 1d9c24b93e..d7ad938d3f 100644 --- a/Content.Shared/Body/Surgery/SurgeryDataComponent.cs +++ b/Content.Shared/Body/Surgery/SurgeryDataComponent.cs @@ -9,7 +9,7 @@ namespace Content.Shared.Body.Surgery /// public interface ISurgeryData : IComponent { - public delegate void SurgeryAction(IBodyPartContainer container, ISurgeon surgeon, IEntity performer); + public delegate void SurgeryAction(IBodyPartContainer container, ISurgeon surgeon, EntityUid performer); /// /// The this @@ -78,6 +78,6 @@ namespace Content.Shared.Body.Surgery /// The entity performing the surgery. /// True if successful, false otherwise. public bool PerformSurgery(SurgeryType surgeryType, IBodyPartContainer container, ISurgeon surgeon, - IEntity performer); + EntityUid performer); } } diff --git a/Content.Shared/Buckle/Components/SharedBuckleComponent.cs b/Content.Shared/Buckle/Components/SharedBuckleComponent.cs index c74ab61476..9491e24254 100644 --- a/Content.Shared/Buckle/Components/SharedBuckleComponent.cs +++ b/Content.Shared/Buckle/Components/SharedBuckleComponent.cs @@ -3,6 +3,7 @@ using Content.Shared.DragDrop; using Content.Shared.Interaction; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -32,11 +33,11 @@ namespace Content.Shared.Buckle.Components public bool DontCollide { get; set; } - public abstract bool TryBuckle(IEntity? user, IEntity to); + public abstract bool TryBuckle(EntityUid user, EntityUid to); bool IDraggable.CanDrop(CanDropEvent args) { - return args.Target.HasComponent(); + return IoCManager.Resolve().HasComponent(args.Target); } bool IDraggable.Drop(DragDropEvent args) @@ -79,7 +80,7 @@ namespace Content.Shared.Buckle.Components /// The entity that had its buckling status changed /// The strap that the entity was buckled to or unbuckled from /// True if the entity was buckled, false otherwise - protected BuckleChangeMessage(IEntity entity, IEntity strap, bool buckled) + protected BuckleChangeMessage(EntityUid entity, EntityUid strap, bool buckled) { Entity = entity; Strap = strap; @@ -89,12 +90,12 @@ namespace Content.Shared.Buckle.Components /// /// The entity that had its buckling status changed /// - public IEntity Entity { get; } + public EntityUid Entity { get; } /// /// The strap that the entity was buckled to or unbuckled from /// - public IEntity Strap { get; } + public EntityUid Strap { get; } /// /// True if the entity was buckled, false otherwise. @@ -110,7 +111,7 @@ namespace Content.Shared.Buckle.Components /// /// The entity that had its buckling status changed /// The strap that the entity was buckled to or unbuckled from - public BuckleMessage(IEntity entity, IEntity strap) : base(entity, strap, true) + public BuckleMessage(EntityUid entity, EntityUid strap) : base(entity, strap, true) { } } @@ -123,7 +124,7 @@ namespace Content.Shared.Buckle.Components /// /// The entity that had its buckling status changed /// The strap that the entity was buckled to or unbuckled from - public UnbuckleMessage(IEntity entity, IEntity strap) : base(entity, strap, false) + public UnbuckleMessage(EntityUid entity, EntityUid strap) : base(entity, strap, false) { } } diff --git a/Content.Shared/Buckle/Components/SharedStrapComponent.cs b/Content.Shared/Buckle/Components/SharedStrapComponent.cs index 4dc912f01e..d396eacf32 100644 --- a/Content.Shared/Buckle/Components/SharedStrapComponent.cs +++ b/Content.Shared/Buckle/Components/SharedStrapComponent.cs @@ -3,6 +3,7 @@ using Content.Shared.DragDrop; using Content.Shared.Interaction.Helpers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Serialization; namespace Content.Shared.Buckle.Components @@ -32,8 +33,8 @@ namespace Content.Shared.Buckle.Components bool IDragDropOn.CanDragDropOn(DragDropEvent eventArgs) { - if (!eventArgs.Dragged.TryGetComponent(out SharedBuckleComponent? buckleComponent)) return false; - bool Ignored(IEntity entity) => entity == eventArgs.User || entity == eventArgs.Dragged || entity == eventArgs.Target; + if (!IoCManager.Resolve().TryGetComponent(eventArgs.Dragged, out SharedBuckleComponent? buckleComponent)) return false; + bool Ignored(EntityUid entity) => entity == eventArgs.User || entity == eventArgs.Dragged || entity == eventArgs.Target; return eventArgs.Target.InRangeUnobstructed(eventArgs.Dragged, buckleComponent.Range, predicate: Ignored); } @@ -72,7 +73,7 @@ namespace Content.Shared.Buckle.Components /// The entity that had its buckling status changed /// The strap that the entity was buckled to or unbuckled from /// True if the entity was buckled, false otherwise - protected StrapChangeMessage(IEntity entity, IEntity strap, bool buckled) + protected StrapChangeMessage(EntityUid entity, EntityUid strap, bool buckled) { Entity = entity; Strap = strap; @@ -82,12 +83,12 @@ namespace Content.Shared.Buckle.Components /// /// The entity that had its buckling status changed /// - public IEntity Entity { get; } + public EntityUid Entity { get; } /// /// The strap that the entity was buckled to or unbuckled from /// - public IEntity Strap { get; } + public EntityUid Strap { get; } /// /// True if the entity was buckled, false otherwise. @@ -103,7 +104,7 @@ namespace Content.Shared.Buckle.Components /// /// The entity that had its buckling status changed /// The strap that the entity was buckled to or unbuckled from - public StrapMessage(IEntity entity, IEntity strap) : base(entity, strap, true) + public StrapMessage(EntityUid entity, EntityUid strap) : base(entity, strap, true) { } } @@ -116,7 +117,7 @@ namespace Content.Shared.Buckle.Components /// /// The entity that had its buckling status changed /// The strap that the entity was buckled to or unbuckled from - public UnStrapMessage(IEntity entity, IEntity strap) : base(entity, strap, false) + public UnStrapMessage(EntityUid entity, EntityUid strap) : base(entity, strap, false) { } } diff --git a/Content.Shared/Buckle/SharedBuckleSystem.cs b/Content.Shared/Buckle/SharedBuckleSystem.cs index 86f8724fb4..5bc94119b0 100644 --- a/Content.Shared/Buckle/SharedBuckleSystem.cs +++ b/Content.Shared/Buckle/SharedBuckleSystem.cs @@ -57,7 +57,7 @@ namespace Content.Shared.Buckle private void PreventCollision(EntityUid uid, SharedBuckleComponent component, PreventCollideEvent args) { - if (args.BodyB.OwnerUid != component.LastEntityBuckledTo) return; + if (args.BodyB.Owner != component.LastEntityBuckledTo) return; component.IsOnStrapEntityThisFrame = true; if (component.Buckled || component.DontCollide) diff --git a/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs b/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs index a365d65208..7ad749954f 100644 --- a/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs +++ b/Content.Shared/Chemistry/MetabolismMovespeedModifierSystem.cs @@ -75,9 +75,9 @@ namespace Content.Shared.Chemistry if (component.ModifierTimer > currentTime) continue; _components.RemoveAt(i); - EntityManager.RemoveComponent(component.OwnerUid); + EntityManager.RemoveComponent(component.Owner); - _movespeed.RefreshMovementSpeedModifiers(component.OwnerUid); + _movespeed.RefreshMovementSpeedModifiers(component.Owner); } } } diff --git a/Content.Shared/Chemistry/Reaction/SharedChemicalReactionSystem.cs b/Content.Shared/Chemistry/Reaction/SharedChemicalReactionSystem.cs index ac7122af1f..587fd4b1cf 100644 --- a/Content.Shared/Chemistry/Reaction/SharedChemicalReactionSystem.cs +++ b/Content.Shared/Chemistry/Reaction/SharedChemicalReactionSystem.cs @@ -144,7 +144,7 @@ namespace Content.Shared.Chemistry.Reaction /// Perform a reaction on a solution. This assumes all reaction criteria are met. /// Removes the reactants from the solution, then returns a solution with all products. /// - private Solution PerformReaction(Solution solution, EntityUid ownerUid, ReactionPrototype reaction, FixedPoint2 unitReactions) + private Solution PerformReaction(Solution solution, EntityUid Owner, ReactionPrototype reaction, FixedPoint2 unitReactions) { // We do this so that ReagentEffect can have something to work with, even if it's // a little meaningless. @@ -167,14 +167,14 @@ namespace Content.Shared.Chemistry.Reaction } // Trigger reaction effects - OnReaction(solution, reaction, randomReagent, ownerUid, unitReactions); + OnReaction(solution, reaction, randomReagent, Owner, unitReactions); return products; } - protected virtual void OnReaction(Solution solution, ReactionPrototype reaction, ReagentPrototype randomReagent, EntityUid ownerUid, FixedPoint2 unitReactions) + protected virtual void OnReaction(Solution solution, ReactionPrototype reaction, ReagentPrototype randomReagent, EntityUid Owner, FixedPoint2 unitReactions) { - var args = new ReagentEffectArgs(ownerUid, null, solution, + var args = new ReagentEffectArgs(Owner, null, solution, randomReagent, unitReactions, EntityManager, null); @@ -185,9 +185,9 @@ namespace Content.Shared.Chemistry.Reaction if (effect.ShouldLog) { - var entity = EntityManager.GetEntity(args.SolutionEntity); + var entity = args.SolutionEntity; _logSystem.Add(LogType.ReagentEffect, effect.LogImpact, - $"Reaction effect {effect.GetType().Name} of reaction ${reaction.ID:reaction} applied on entity {entity} at {entity.Transform.Coordinates}"); + $"Reaction effect {effect.GetType().Name} of reaction ${reaction.ID:reaction} applied on entity {entity} at {EntityManager.GetComponent(entity).Coordinates}"); } effect.Effect(args); @@ -199,7 +199,7 @@ namespace Content.Shared.Chemistry.Reaction /// Removes the reactants from the solution, then returns a solution with all products. /// WARNING: Does not trigger reactions between solution and new products. /// - private bool ProcessReactions(Solution solution, EntityUid ownerUid, [MaybeNullWhen(false)] out Solution productSolution) + private bool ProcessReactions(Solution solution, EntityUid Owner, [MaybeNullWhen(false)] out Solution productSolution) { foreach(var reactant in solution.Contents) { @@ -211,7 +211,7 @@ namespace Content.Shared.Chemistry.Reaction if (!CanReact(solution, reaction, out var unitReactions)) continue; - productSolution = PerformReaction(solution, ownerUid, reaction, unitReactions); + productSolution = PerformReaction(solution, Owner, reaction, unitReactions); return true; } } @@ -223,11 +223,11 @@ namespace Content.Shared.Chemistry.Reaction /// /// Continually react a solution until no more reactions occur. /// - public void FullyReactSolution(Solution solution, EntityUid ownerUid) + public void FullyReactSolution(Solution solution, EntityUid Owner) { for (var i = 0; i < MaxReactionIterations; i++) { - if (!ProcessReactions(solution, ownerUid, out var products)) + if (!ProcessReactions(solution, Owner, out var products)) return; if (products.TotalVolume <= 0) @@ -235,18 +235,18 @@ namespace Content.Shared.Chemistry.Reaction solution.AddSolution(products); } - Logger.Error($"{nameof(Solution)} {ownerUid} could not finish reacting in under {MaxReactionIterations} loops."); + Logger.Error($"{nameof(Solution)} {Owner} could not finish reacting in under {MaxReactionIterations} loops."); } /// /// Continually react a solution until no more reactions occur, with a volume constraint. /// If a reaction's products would exceed the max volume, some product is deleted. /// - public void FullyReactSolution(Solution solution, EntityUid ownerUid, FixedPoint2 maxVolume) + public void FullyReactSolution(Solution solution, EntityUid Owner, FixedPoint2 maxVolume) { for (var i = 0; i < MaxReactionIterations; i++) { - if (!ProcessReactions(solution, ownerUid, out var products)) + if (!ProcessReactions(solution, Owner, out var products)) return; if (products.TotalVolume <= 0) @@ -262,7 +262,7 @@ namespace Content.Shared.Chemistry.Reaction solution.AddSolution(products); } - Logger.Error($"{nameof(Solution)} {ownerUid} could not finish reacting in under {MaxReactionIterations} loops."); + Logger.Error($"{nameof(Solution)} {Owner} could not finish reacting in under {MaxReactionIterations} loops."); } } } diff --git a/Content.Shared/Chemistry/ReactiveSystem.cs b/Content.Shared/Chemistry/ReactiveSystem.cs index 837d5f4d51..53da3ae6d6 100644 --- a/Content.Shared/Chemistry/ReactiveSystem.cs +++ b/Content.Shared/Chemistry/ReactiveSystem.cs @@ -64,9 +64,9 @@ namespace Content.Shared.Chemistry if (effect.ShouldLog) { - var entity = EntityManager.GetEntity(args.SolutionEntity); + var entity = args.SolutionEntity; _logSystem.Add(LogType.ReagentEffect, effect.LogImpact, - $"Reactive effect {effect.GetType().Name} of reagent {reagent.ID:reagent} with method {method} applied on entity {entity} at {entity.Transform.Coordinates}"); + $"Reactive effect {effect.GetType().Name} of reagent {reagent.ID:reagent} with method {method} applied on entity {entity} at {EntityManager.GetComponent(entity).Coordinates}"); } effect.Effect(args); @@ -92,9 +92,9 @@ namespace Content.Shared.Chemistry if (effect.ShouldLog) { - var entity = EntityManager.GetEntity(args.SolutionEntity); + var entity = args.SolutionEntity; _logSystem.Add(LogType.ReagentEffect, effect.LogImpact, - $"Reactive effect {effect.GetType().Name} of {entity} using reagent {reagent.ID} with method {method} at {entity.Transform.Coordinates}"); + $"Reactive effect {effect.GetType().Name} of {entity} using reagent {reagent.ID} with method {method} at {EntityManager.GetComponent(entity).Coordinates}"); } effect.Effect(args); diff --git a/Content.Shared/Chemistry/Reagent/ReagentPrototype.cs b/Content.Shared/Chemistry/Reagent/ReagentPrototype.cs index 733ce02709..71076ff794 100644 --- a/Content.Shared/Chemistry/Reagent/ReagentPrototype.cs +++ b/Content.Shared/Chemistry/Reagent/ReagentPrototype.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using Content.Shared.Administration.Logs; using Content.Shared.Body.Prototypes; -using Content.Shared.Botany; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.Reaction; using Content.Shared.Database; @@ -16,7 +15,6 @@ using Robust.Shared.Random; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.Dictionary; -using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.List; using Robust.Shared.ViewVariables; namespace Content.Shared.Chemistry.Reagent @@ -123,9 +121,9 @@ namespace Content.Shared.Chemistry.Reagent if (plantMetabolizable.ShouldLog) { - var entity = entMan.GetEntity(args.SolutionEntity); + var entity = args.SolutionEntity; EntitySystem.Get().Add(LogType.ReagentEffect, plantMetabolizable.LogImpact, - $"Plant metabolism effect {plantMetabolizable.GetType().Name:effect} of reagent {ID} applied on entity {entity} at {entity.Transform.Coordinates}"); + $"Plant metabolism effect {plantMetabolizable.GetType().Name:effect} of reagent {ID} applied on entity {entity} at {IoCManager.Resolve().GetComponent(entity).Coordinates}"); plantMetabolizable.Effect(args); } } diff --git a/Content.Shared/Climbing/SharedClimbableComponent.cs b/Content.Shared/Climbing/SharedClimbableComponent.cs index b27b44dc93..b32dbce0ce 100644 --- a/Content.Shared/Climbing/SharedClimbableComponent.cs +++ b/Content.Shared/Climbing/SharedClimbableComponent.cs @@ -1,6 +1,7 @@ using Content.Shared.DragDrop; using Content.Shared.Interaction; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -19,7 +20,7 @@ namespace Content.Shared.Climbing public virtual bool CanDragDropOn(DragDropEvent eventArgs) { - return eventArgs.Dragged.HasComponent(); + return IoCManager.Resolve().HasComponent(eventArgs.Dragged); } public abstract bool DragDropOn(DragDropEvent eventArgs); diff --git a/Content.Shared/Clothing/SharedMagbootsComponent.cs b/Content.Shared/Clothing/SharedMagbootsComponent.cs index 3d65e295a7..16ba948abb 100644 --- a/Content.Shared/Clothing/SharedMagbootsComponent.cs +++ b/Content.Shared/Clothing/SharedMagbootsComponent.cs @@ -20,7 +20,7 @@ namespace Content.Shared.Clothing // inventory system will automatically hook into the event raised by this and update accordingly if (Owner.TryGetContainer(out var container)) { - EntitySystem.Get().RefreshMovementSpeedModifiers(container.Owner.Uid); + EntitySystem.Get().RefreshMovementSpeedModifiers(container.Owner); } } diff --git a/Content.Shared/CombatMode/SharedCombatModeSystem.cs b/Content.Shared/CombatMode/SharedCombatModeSystem.cs index 70101b35bf..3cdb3231d0 100644 --- a/Content.Shared/CombatMode/SharedCombatModeSystem.cs +++ b/Content.Shared/CombatMode/SharedCombatModeSystem.cs @@ -14,9 +14,9 @@ namespace Content.Shared.CombatMode private void CombatModeActiveHandler(CombatModeSystemMessages.SetCombatModeActiveMessage ev, EntitySessionEventArgs eventArgs) { - var entity = eventArgs.SenderSession?.AttachedEntity; + var entity = eventArgs.SenderSession.AttachedEntity; - if (entity == null || !entity.TryGetComponent(out SharedCombatModeComponent? combatModeComponent)) + if (entity == default || !EntityManager.TryGetComponent(entity, out SharedCombatModeComponent? combatModeComponent)) { return; } diff --git a/Content.Shared/Construction/Conditions/EmptyOrWindowValidInTile.cs b/Content.Shared/Construction/Conditions/EmptyOrWindowValidInTile.cs index cce825c205..9e12089294 100644 --- a/Content.Shared/Construction/Conditions/EmptyOrWindowValidInTile.cs +++ b/Content.Shared/Construction/Conditions/EmptyOrWindowValidInTile.cs @@ -3,6 +3,7 @@ using Content.Shared.Maps; using Content.Shared.Window; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; @@ -16,13 +17,13 @@ namespace Content.Shared.Construction.Conditions [DataField("tileNotBlocked")] private readonly TileNotBlocked _tileNotBlocked = new(); - public bool Condition(IEntity user, EntityCoordinates location, Direction direction) + public bool Condition(EntityUid user, EntityCoordinates location, Direction direction) { var result = false; foreach (var entity in location.GetEntitiesInTile(LookupFlags.Approximate | LookupFlags.IncludeAnchored)) { - if (entity.HasComponent()) + if (IoCManager.Resolve().HasComponent(entity)) result = true; } diff --git a/Content.Shared/Construction/Conditions/IConstructionCondition.cs b/Content.Shared/Construction/Conditions/IConstructionCondition.cs index 44f9084587..ab5ecc8592 100644 --- a/Content.Shared/Construction/Conditions/IConstructionCondition.cs +++ b/Content.Shared/Construction/Conditions/IConstructionCondition.cs @@ -7,6 +7,6 @@ namespace Content.Shared.Construction.Conditions public interface IConstructionCondition { ConstructionGuideEntry? GenerateGuideEntry(); - bool Condition(IEntity user, EntityCoordinates location, Direction direction); + bool Condition(EntityUid user, EntityCoordinates location, Direction direction); } } diff --git a/Content.Shared/Construction/Conditions/NoWindowsInTile.cs b/Content.Shared/Construction/Conditions/NoWindowsInTile.cs index 72a6e13981..a5f37f5aff 100644 --- a/Content.Shared/Construction/Conditions/NoWindowsInTile.cs +++ b/Content.Shared/Construction/Conditions/NoWindowsInTile.cs @@ -2,6 +2,7 @@ using Content.Shared.Window; using JetBrains.Annotations; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; @@ -12,11 +13,11 @@ namespace Content.Shared.Construction.Conditions [DataDefinition] public class NoWindowsInTile : IConstructionCondition { - public bool Condition(IEntity user, EntityCoordinates location, Direction direction) + public bool Condition(EntityUid user, EntityCoordinates location, Direction direction) { foreach (var entity in location.GetEntitiesInTile(LookupFlags.Approximate | LookupFlags.IncludeAnchored)) { - if (entity.HasComponent()) + if (IoCManager.Resolve().HasComponent(entity)) return false; } diff --git a/Content.Shared/Construction/Conditions/TileNotBlocked.cs b/Content.Shared/Construction/Conditions/TileNotBlocked.cs index 190c6c7731..98ded48d46 100644 --- a/Content.Shared/Construction/Conditions/TileNotBlocked.cs +++ b/Content.Shared/Construction/Conditions/TileNotBlocked.cs @@ -14,7 +14,7 @@ namespace Content.Shared.Construction.Conditions [DataField("filterMobs")] private bool _filterMobs = false; [DataField("failIfSpace")] private bool _failIfSpace = true; - public bool Condition(IEntity user, EntityCoordinates location, Direction direction) + public bool Condition(EntityUid user, EntityCoordinates location, Direction direction) { var tileRef = location.GetTileRef(); diff --git a/Content.Shared/Construction/Conditions/TileType.cs b/Content.Shared/Construction/Conditions/TileType.cs index 41b5621ce7..e24d74db76 100644 --- a/Content.Shared/Construction/Conditions/TileType.cs +++ b/Content.Shared/Construction/Conditions/TileType.cs @@ -22,7 +22,7 @@ namespace Content.Shared.Construction.Conditions [DataField("guideIcon")] public SpriteSpecifier? GuideIcon = null; - public bool Condition(IEntity user, EntityCoordinates location, Direction direction) + public bool Condition(EntityUid user, EntityCoordinates location, Direction direction) { if (TargetTiles == null) return true; diff --git a/Content.Shared/Construction/Conditions/WallmountCondition.cs b/Content.Shared/Construction/Conditions/WallmountCondition.cs index 1a29d6a4bb..e9b4866c62 100644 --- a/Content.Shared/Construction/Conditions/WallmountCondition.cs +++ b/Content.Shared/Construction/Conditions/WallmountCondition.cs @@ -16,12 +16,12 @@ namespace Content.Shared.Construction.Conditions [DataDefinition] public class WallmountCondition : IConstructionCondition { - public bool Condition(IEntity user, EntityCoordinates location, Direction direction) + public bool Condition(EntityUid user, EntityCoordinates location, Direction direction) { var entManager = IoCManager.Resolve(); // get blueprint and user position - var userWorldPosition = user.Transform.WorldPosition; + var userWorldPosition = IoCManager.Resolve().GetComponent(user).WorldPosition; var objWorldPosition = location.ToMap(entManager).Position; // find direction from user to blueprint @@ -36,7 +36,7 @@ namespace Content.Shared.Construction.Conditions var physics = EntitySystem.Get(); var rUserToObj = new CollisionRay(userWorldPosition, userToObject.Normalized, (int) CollisionGroup.Impassable); var length = userToObject.Length; - var userToObjRaycastResults = physics.IntersectRayWithPredicate(user.Transform.MapID, rUserToObj, maxLength: length, + var userToObjRaycastResults = physics.IntersectRayWithPredicate(IoCManager.Resolve().GetComponent(user).MapID, rUserToObj, maxLength: length, predicate: (e) => !e.HasTag("Wall")); if (!userToObjRaycastResults.Any()) return false; @@ -46,7 +46,7 @@ namespace Content.Shared.Construction.Conditions // check that we didn't try to build wallmount that facing another adjacent wall var rAdjWall = new CollisionRay(objWorldPosition, direction.ToVec(), (int) CollisionGroup.Impassable); - var adjWallRaycastResults = physics.IntersectRayWithPredicate(user.Transform.MapID, rAdjWall, maxLength: 0.5f, + var adjWallRaycastResults = physics.IntersectRayWithPredicate(IoCManager.Resolve().GetComponent(user).MapID, rAdjWall, maxLength: 0.5f, predicate: (e) => e == targetWall || !e.HasTag("Wall")); return !adjWallRaycastResults.Any(); } diff --git a/Content.Shared/Construction/Steps/MaterialConstructionGraphStep.cs b/Content.Shared/Construction/Steps/MaterialConstructionGraphStep.cs index 90c4f8a982..8ab0ead8bb 100644 --- a/Content.Shared/Construction/Steps/MaterialConstructionGraphStep.cs +++ b/Content.Shared/Construction/Steps/MaterialConstructionGraphStep.cs @@ -32,9 +32,9 @@ namespace Content.Shared.Construction.Steps return entityManager.TryGetComponent(uid, out SharedStackComponent? stack) && stack.StackTypeId.Equals(MaterialPrototypeId) && stack.Count >= Amount; } - public bool EntityValid(IEntity entity, [NotNullWhen(true)] out SharedStackComponent? stack) + public bool EntityValid(EntityUid entity, [NotNullWhen(true)] out SharedStackComponent? stack) { - if (entity.TryGetComponent(out SharedStackComponent? otherStack) && otherStack.StackTypeId.Equals(MaterialPrototypeId) && otherStack.Count >= Amount) + if (IoCManager.Resolve().TryGetComponent(entity, out SharedStackComponent? otherStack) && otherStack.StackTypeId.Equals(MaterialPrototypeId) && otherStack.Count >= Amount) stack = otherStack; else stack = null; diff --git a/Content.Shared/Containers/ItemSlot/ItemSlotsComponent.cs b/Content.Shared/Containers/ItemSlot/ItemSlotsComponent.cs index 9410b748c6..95a32b5a10 100644 --- a/Content.Shared/Containers/ItemSlot/ItemSlotsComponent.cs +++ b/Content.Shared/Containers/ItemSlot/ItemSlotsComponent.cs @@ -190,9 +190,6 @@ namespace Content.Shared.Containers.ItemSlots // Convenience properties public bool HasItem => ContainerSlot.ContainedEntity != null; - public IEntity? Item => ContainerSlot.ContainedEntity; - - // and to make it easier for whenever IEntity is removed - public EntityUid? ItemUid => ContainerSlot.ContainedEntity?.Uid; + public EntityUid? Item => ContainerSlot.ContainedEntity; } } diff --git a/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs b/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs index 881ffab042..765a838ba6 100644 --- a/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs +++ b/Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs @@ -57,7 +57,7 @@ namespace Content.Shared.Containers.ItemSlots if (slot.HasItem || string.IsNullOrEmpty(slot.StartingItem)) continue; - var item = EntityManager.SpawnEntity(slot.StartingItem, itemSlots.Owner.Transform.Coordinates); + var item = EntityManager.SpawnEntity(slot.StartingItem, EntityManager.GetComponent(itemSlots.Owner).Coordinates); slot.ContainerSlot.Insert(item); } } @@ -82,7 +82,7 @@ namespace Content.Shared.Containers.ItemSlots var itemSlots = EntityManager.EnsureComponent(uid); slot.ContainerSlot = ContainerHelpers.EnsureContainer(itemSlots.Owner, id); if (itemSlots.Slots.ContainsKey(id)) - Logger.Error($"Duplicate item slot key. Entity: {itemSlots.Owner.Name} ({uid}), key: {id}"); + Logger.Error($"Duplicate item slot key. Entity: {EntityManager.GetComponent(itemSlots.Owner).EntityName} ({uid}), key: {id}"); itemSlots.Slots[id] = slot; } @@ -121,7 +121,7 @@ namespace Content.Shared.Containers.ItemSlots continue; args.Handled = true; - TryEjectToHands(uid, slot, args.UserUid); + TryEjectToHands(uid, slot, args.User); break; } } @@ -140,7 +140,7 @@ namespace Content.Shared.Containers.ItemSlots continue; args.Handled = true; - TryEjectToHands(uid, slot, args.UserUid); + TryEjectToHands(uid, slot, args.User); break; } } @@ -159,12 +159,12 @@ namespace Content.Shared.Containers.ItemSlots if (args.Handled) return; - if (!EntityManager.TryGetComponent(args.UserUid, out SharedHandsComponent? hands)) + if (!EntityManager.TryGetComponent(args.User, out SharedHandsComponent? hands)) return; foreach (var slot in itemSlots.Slots.Values) { - if (!CanInsert(uid, args.UsedUid, slot, swap: slot.Swap, popup: args.UserUid)) + if (!CanInsert(uid, args.Used, slot, swap: slot.Swap, popup: args.User)) continue; // Drop the held item onto the floor. Return if the user cannot drop. @@ -172,7 +172,7 @@ namespace Content.Shared.Containers.ItemSlots return; if (slot.Item != null) - hands.TryPutInAnyHand(slot.Item); + hands.TryPutInAnyHand(slot.Item.Value); Insert(uid, slot, args.Used); args.Handled = true; @@ -186,7 +186,7 @@ namespace Content.Shared.Containers.ItemSlots /// Insert an item into a slot. This does not perform checks, so make sure to also use or just use instead. /// - private void Insert(EntityUid uid, ItemSlot slot, IEntity item) + private void Insert(EntityUid uid, ItemSlot slot, EntityUid item) { slot.ContainerSlot.Insert(item); // ContainerSlot automatically raises a directed EntInsertedIntoContainerMessage @@ -228,7 +228,7 @@ namespace Content.Shared.Containers.ItemSlots /// Tries to insert item into a specific slot. /// /// False if failed to insert item - public bool TryInsert(EntityUid uid, string id, IEntity item, ItemSlotsComponent? itemSlots = null) + public bool TryInsert(EntityUid uid, string id, EntityUid item, ItemSlotsComponent? itemSlots = null) { if (!Resolve(uid, ref itemSlots)) return false; @@ -243,9 +243,9 @@ namespace Content.Shared.Containers.ItemSlots /// Tries to insert item into a specific slot. /// /// False if failed to insert item - public bool TryInsert(EntityUid uid, ItemSlot slot, IEntity item) + public bool TryInsert(EntityUid uid, ItemSlot slot, EntityUid item) { - if (!CanInsert(uid, item.Uid, slot)) + if (!CanInsert(uid, item, slot)) return false; Insert(uid, slot, item); @@ -264,7 +264,7 @@ namespace Content.Shared.Containers.ItemSlots if (!hands.TryGetActiveHeldEntity(out var item)) return false; - if (!CanInsert(uid, item.Uid, slot)) + if (!CanInsert(uid, item, slot)) return false; // hands.Drop(item) checks CanDrop action blocker @@ -281,7 +281,7 @@ namespace Content.Shared.Containers.ItemSlots /// Eject an item into a slot. This does not perform checks (e.g., is the slot locked?), so you should /// probably just use instead. /// - private void Eject(EntityUid uid, ItemSlot slot, IEntity item) + private void Eject(EntityUid uid, ItemSlot slot, EntityUid item) { slot.ContainerSlot.Remove(item); // ContainerSlot automatically raises a directed EntRemovedFromContainerMessage @@ -294,7 +294,7 @@ namespace Content.Shared.Containers.ItemSlots /// Try to eject an item from a slot. /// /// False if item slot is locked or has no item inserted - public bool TryEject(EntityUid uid, ItemSlot slot, [NotNullWhen(true)] out IEntity? item) + public bool TryEject(EntityUid uid, ItemSlot slot, [NotNullWhen(true)] out EntityUid? item) { item = null; @@ -302,7 +302,7 @@ namespace Content.Shared.Containers.ItemSlots return false; item = slot.Item; - Eject(uid, slot, item); + Eject(uid, slot, item.Value); return true; } @@ -310,7 +310,7 @@ namespace Content.Shared.Containers.ItemSlots /// Try to eject item from a slot. /// /// False if the id is not valid, the item slot is locked, or it has no item inserted - public bool TryEject(EntityUid uid, string id, [NotNullWhen(true)] out IEntity? item, ItemSlotsComponent? itemSlots = null) + public bool TryEject(EntityUid uid, string id, [NotNullWhen(true)] out EntityUid? item, ItemSlotsComponent? itemSlots = null) { item = null; @@ -337,7 +337,7 @@ namespace Content.Shared.Containers.ItemSlots return false; if (user != null && EntityManager.TryGetComponent(user.Value, out SharedHandsComponent? hands)) - hands.TryPutInActiveHandOrAny(item); + hands.TryPutInActiveHandOrAny(item.Value); return true; } @@ -347,7 +347,7 @@ namespace Content.Shared.Containers.ItemSlots private void AddEjectVerbs(EntityUid uid, ItemSlotsComponent itemSlots, GetAlternativeVerbsEvent args) { if (args.Hands == null || !args.CanAccess ||!args.CanInteract || - !_actionBlockerSystem.CanPickup(args.User.Uid)) + !_actionBlockerSystem.CanPickup(args.User)) { return; } @@ -364,10 +364,10 @@ namespace Content.Shared.Containers.ItemSlots var verbSubject = slot.Name != string.Empty ? Loc.GetString(slot.Name) - : slot.Item!.Name ?? string.Empty; + : EntityManager.GetComponent(slot.Item!.Value).EntityName ?? string.Empty; Verb verb = new(); - verb.Act = () => TryEjectToHands(uid, slot, args.User.Uid); + verb.Act = () => TryEjectToHands(uid, slot, args.User); if (slot.EjectVerbText == null) { @@ -390,7 +390,7 @@ namespace Content.Shared.Containers.ItemSlots return; // If there are any slots that eject on left-click, add a "Take " verb. - if (_actionBlockerSystem.CanPickup(args.User.Uid)) + if (_actionBlockerSystem.CanPickup(args.User)) { foreach (var slot in itemSlots.Slots.Values) { @@ -399,10 +399,10 @@ namespace Content.Shared.Containers.ItemSlots var verbSubject = slot.Name != string.Empty ? Loc.GetString(slot.Name) - : slot.Item!.Name ?? string.Empty; + : EntityManager.GetComponent(slot.Item!.Value).EntityName ?? string.Empty; Verb takeVerb = new(); - takeVerb.Act = () => TryEjectToHands(uid, slot, args.User.Uid); + takeVerb.Act = () => TryEjectToHands(uid, slot, args.User); takeVerb.IconTexture = "/Textures/Interface/VerbIcons/pickup.svg.192dpi.png"; if (slot.EjectVerbText == null) @@ -415,20 +415,20 @@ namespace Content.Shared.Containers.ItemSlots } // Next, add the insert-item verbs - if (args.Using == null || !_actionBlockerSystem.CanDrop(args.User.Uid)) + if (args.Using == null || !_actionBlockerSystem.CanDrop(args.User)) return; foreach (var slot in itemSlots.Slots.Values) { - if (!CanInsert(uid, args.Using.Uid, slot)) + if (!CanInsert(uid, args.Using.Value, slot)) continue; var verbSubject = slot.Name != string.Empty ? Loc.GetString(slot.Name) - : args.Using.Name ?? string.Empty; + : EntityManager.GetComponent(args.Using.Value).EntityName ?? string.Empty; Verb insertVerb = new(); - insertVerb.Act = () => Insert(uid, slot, args.Using); + insertVerb.Act = () => Insert(uid, slot, args.Using.Value); if (slot.InsertVerbText != null) { @@ -468,7 +468,7 @@ namespace Content.Shared.Containers.ItemSlots /// /// Get the contents of some item slot. /// - public IEntity? GetItem(EntityUid uid, string id, ItemSlotsComponent? itemSlots = null) + public EntityUid? GetItem(EntityUid uid, string id, ItemSlotsComponent? itemSlots = null) { if (!Resolve(uid, ref itemSlots)) return null; diff --git a/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs b/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs index c6eaace7a1..11c313d592 100644 --- a/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs +++ b/Content.Shared/Coordinates/EntityCoordinatesExtensions.cs @@ -16,26 +16,6 @@ namespace Content.Shared.Coordinates return new(id, x, y); } - public static EntityCoordinates ToCoordinates(this EntityUid id) - { - return ToCoordinates(id, Vector2.Zero); - } - - public static EntityCoordinates ToCoordinates(this IEntity entity, Vector2 offset) - { - return ToCoordinates(entity.Uid, offset); - } - - public static EntityCoordinates ToCoordinates(this IEntity entity, float x, float y) - { - return new(entity.Uid, x, y); - } - - public static EntityCoordinates ToCoordinates(this IEntity entity) - { - return ToCoordinates(entity.Uid, Vector2.Zero); - } - public static EntityCoordinates ToCoordinates(this IMapGrid grid, Vector2 offset) { return ToCoordinates(grid.GridEntityId, offset); diff --git a/Content.Shared/Cuffs/SharedCuffableSystem.cs b/Content.Shared/Cuffs/SharedCuffableSystem.cs index 92d1ee0a72..d4c42a3355 100644 --- a/Content.Shared/Cuffs/SharedCuffableSystem.cs +++ b/Content.Shared/Cuffs/SharedCuffableSystem.cs @@ -35,9 +35,9 @@ namespace Content.Shared.Cuffs private void HandleStopPull(EntityUid uid, SharedCuffableComponent component, StopPullingEvent args) { - if (args.User == null || !EntityManager.TryGetEntity(args.User.Value, out var user)) return; + if (args.User == null || !EntityManager.EntityExists(args.User.Value)) return; - if (user == component.Owner && !component.CanStillInteract) + if (args.User.Value == component.Owner && !component.CanStillInteract) { args.Cancel(); } diff --git a/Content.Shared/Damage/Components/DamageableComponent.cs b/Content.Shared/Damage/Components/DamageableComponent.cs index 39b9dd787b..f446192924 100644 --- a/Content.Shared/Damage/Components/DamageableComponent.cs +++ b/Content.Shared/Damage/Components/DamageableComponent.cs @@ -92,7 +92,7 @@ namespace Content.Shared.Damage damage.DamageDict.Add(typeID, damageValue); } - EntitySystem.Get().TryChangeDamage(OwnerUid, damage); + EntitySystem.Get().TryChangeDamage(Owner, damage); } // TODO EXPLOSION Remove this. @@ -113,7 +113,7 @@ namespace Content.Shared.Damage damage.DamageDict.Add(typeID, damageValue); } - EntitySystem.Get().TryChangeDamage(OwnerUid, damage); + EntitySystem.Get().TryChangeDamage(Owner, damage); } } diff --git a/Content.Shared/Damage/Systems/DamageableSystem.cs b/Content.Shared/Damage/Systems/DamageableSystem.cs index aa2d453042..16b409df8d 100644 --- a/Content.Shared/Damage/Systems/DamageableSystem.cs +++ b/Content.Shared/Damage/Systems/DamageableSystem.cs @@ -85,9 +85,9 @@ namespace Content.Shared.Damage component.TotalDamage = component.Damage.Total; component.Dirty(); - if (EntityManager.TryGetComponent(component.OwnerUid, out var appearance) && damageDelta != null) + if (EntityManager.TryGetComponent(component.Owner, out var appearance) && damageDelta != null) appearance.SetData(DamageVisualizerKeys.DamageUpdateGroups, damageDelta.GetDamagePerGroup().Keys.ToList()); - RaiseLocalEvent(component.OwnerUid, new DamageChangedEvent(component, damageDelta, interruptsDoAfters), false); + RaiseLocalEvent(component.Owner, new DamageChangedEvent(component, damageDelta, interruptsDoAfters), false); } /// @@ -102,7 +102,7 @@ namespace Content.Shared.Damage /// Returns a with information about the actual damage changes. This will be /// null if the user had no applicable components that can take damage. /// - public DamageSpecifier? TryChangeDamage(EntityUid uid, DamageSpecifier damage, bool ignoreResistances = false, + public DamageSpecifier? TryChangeDamage(EntityUid? uid, DamageSpecifier damage, bool ignoreResistances = false, bool interruptsDoAfters = true) { if (!EntityManager.TryGetComponent(uid, out var damageable)) @@ -132,7 +132,7 @@ namespace Content.Shared.Damage } var ev = new DamageModifyEvent(damage); - RaiseLocalEvent(uid, ev, false); + RaiseLocalEvent(uid.Value, ev, false); damage = ev.Damage; if (damage.Empty) diff --git a/Content.Shared/Disposal/SharedDisposalUnitSystem.cs b/Content.Shared/Disposal/SharedDisposalUnitSystem.cs index 8452994613..8a62badacf 100644 --- a/Content.Shared/Disposal/SharedDisposalUnitSystem.cs +++ b/Content.Shared/Disposal/SharedDisposalUnitSystem.cs @@ -31,7 +31,7 @@ namespace Content.Shared.Disposal private void HandlePreventCollide(EntityUid uid, SharedDisposalUnitComponent component, PreventCollideEvent args) { - var otherBody = args.BodyB.OwnerUid; + var otherBody = args.BodyB.Owner; // Items dropped shouldn't collide but items thrown should if (EntityManager.HasComponent(otherBody) && @@ -47,23 +47,23 @@ namespace Content.Shared.Disposal } } - public virtual bool CanInsert(SharedDisposalUnitComponent component, IEntity entity) + public virtual bool CanInsert(SharedDisposalUnitComponent component, EntityUid entity) { - if (!component.Owner.Transform.Anchored) + if (!EntityManager.GetComponent(component.Owner).Anchored) return false; // TODO: Probably just need a disposable tag. - if (!entity.TryGetComponent(out SharedItemComponent? storable) && - !entity.HasComponent()) + if (!EntityManager.TryGetComponent(entity, out SharedItemComponent? storable) && + !EntityManager.HasComponent(entity)) { return false; } - if (!entity.TryGetComponent(out IPhysBody? physics) || + if (!EntityManager.TryGetComponent(entity, out IPhysBody? physics) || !physics.CanCollide && storable == null) { - if (!(entity.TryGetComponent(out MobStateComponent? damageState) && damageState.IsDead())) + if (!(EntityManager.TryGetComponent(entity, out MobStateComponent? damageState) && damageState.IsDead())) { return false; } @@ -71,11 +71,5 @@ namespace Content.Shared.Disposal return true; } - - public bool CanInsert(SharedDisposalUnitComponent component, EntityUid entityId) - { - var entity = EntityManager.GetEntity(entityId); - return CanInsert(component, entity); - } } } diff --git a/Content.Shared/Doors/SharedDoorComponent.cs b/Content.Shared/Doors/SharedDoorComponent.cs index dbf0ad3aa5..efc643b344 100644 --- a/Content.Shared/Doors/SharedDoorComponent.cs +++ b/Content.Shared/Doors/SharedDoorComponent.cs @@ -97,9 +97,9 @@ namespace Content.Shared.Doors /// protected List CurrentlyCrushing = new(); - public bool IsCrushing(IEntity entity) + public bool IsCrushing(EntityUid entity) { - return CurrentlyCrushing.Contains(entity.Uid); + return CurrentlyCrushing.Contains(entity); } protected void SetAppearance(DoorVisualState state) diff --git a/Content.Shared/DragDrop/IDraggable.cs b/Content.Shared/DragDrop/IDraggable.cs index f646eafbe2..c98e66d71e 100644 --- a/Content.Shared/DragDrop/IDraggable.cs +++ b/Content.Shared/DragDrop/IDraggable.cs @@ -61,19 +61,19 @@ namespace Content.Shared.DragDrop /// /// Entity doing the drag and drop. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Entity that is being dragged. /// - public IEntity Dragged { get; } + public EntityUid Dragged { get; } /// /// Creates a new instance of . /// /// The entity doing the drag and drop. /// The entity that is being dragged and dropped. - public StartDragDropEvent(IEntity user, IEntity dragged) + public StartDragDropEvent(EntityUid user, EntityUid dragged) { User = user; Dragged = dragged; @@ -83,10 +83,10 @@ namespace Content.Shared.DragDrop public class CanDropEvent : StartDragDropEvent { /// - /// The entity that + /// The entity uid that /// is being dropped onto. /// - public IEntity Target { get; } + public EntityUid Target { get; } /// /// Creates a new instance of . @@ -94,7 +94,7 @@ namespace Content.Shared.DragDrop /// The entity doing the drag and drop. /// The entity that is being dragged and dropped. /// The entity that is being dropped onto. - public CanDropEvent(IEntity user, IEntity dragged, IEntity target) : base(user, dragged) + public CanDropEvent(EntityUid user, EntityUid dragged, EntityUid target) : base(user, dragged) { Target = target; } @@ -115,7 +115,7 @@ namespace Content.Shared.DragDrop /// The location where is being dropped. /// The entity that is being dragged and dropped. /// The entity that is being dropped onto. - public DragDropEvent(IEntity user, EntityCoordinates dropLocation, IEntity dragged, IEntity target) : base(user, dragged, target) + public DragDropEvent(EntityUid user, EntityCoordinates dropLocation, EntityUid dragged, EntityUid target) : base(user, dragged, target) { DropLocation = dropLocation; } diff --git a/Content.Shared/Examine/ExamineSystemShared.cs b/Content.Shared/Examine/ExamineSystemShared.cs index cc390317d7..19b227dbc1 100644 --- a/Content.Shared/Examine/ExamineSystemShared.cs +++ b/Content.Shared/Examine/ExamineSystemShared.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Content.Shared.DragDrop; using Content.Shared.Interaction; @@ -7,6 +8,7 @@ using Content.Shared.MobState.Components; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; @@ -46,10 +48,10 @@ namespace Content.Shared.Examine public const float ExamineRange = 16f; protected const float ExamineDetailsRange = 3f; - private bool IsInDetailsRange(IEntity examiner, IEntity entity) + private bool IsInDetailsRange(EntityUid examiner, EntityUid entity) { // check if the mob is in ciritcal or dead - if (EntityManager.TryGetComponent(examiner.Uid, out MobStateComponent mobState) && mobState.IsIncapacitated()) + if (EntityManager.TryGetComponent(examiner, out MobStateComponent mobState) && mobState.IsIncapacitated()) return false; if (entity.TryGetContainerMan(out var man) && man.Owner == examiner) @@ -60,28 +62,28 @@ namespace Content.Shared.Examine } [Pure] - public bool CanExamine(IEntity examiner, IEntity examined) + public bool CanExamine(EntityUid examiner, EntityUid examined) { - return CanExamine(examiner, examined.Transform.MapPosition, + return CanExamine(examiner, EntityManager.GetComponent(examined).MapPosition, entity => entity == examiner || entity == examined); } [Pure] - public virtual bool CanExamine(IEntity examiner, MapCoordinates target, Ignored? predicate = null) + public virtual bool CanExamine(EntityUid examiner, MapCoordinates target, Ignored? predicate = null) { - if (!examiner.TryGetComponent(out ExaminerComponent? examinerComponent)) + if (!EntityManager.TryGetComponent(examiner, out ExaminerComponent? examinerComponent)) return false; if (!examinerComponent.DoRangeCheck) return true; - if (examiner.Transform.MapID != target.MapId) + if (EntityManager.GetComponent(examiner).MapID != target.MapId) return false; return InRangeUnOccluded( - examiner.Transform.MapPosition, + EntityManager.GetComponent(examiner).MapPosition, target, - GetExaminerRange(examiner.Uid), + GetExaminerRange(examiner), predicate: predicate, ignoreInsideBlocker: true); } @@ -107,6 +109,7 @@ namespace Content.Shared.Examine other.MapId == MapId.Nullspace) return false; var occluderSystem = Get(); + var entMan = IoCManager.Resolve(); if (!origin.InRange(other, range)) return false; var dir = other.Position - origin.Position; @@ -126,12 +129,12 @@ namespace Content.Shared.Examine foreach (var result in rayResults) { - if (!result.HitEntity.TryGetComponent(out OccluderComponent? o)) + if (!entMan.TryGetComponent(result.HitEntity, out OccluderComponent? o)) { continue; } - var bBox = o.BoundingBox.Translated(o.Owner.Transform.WorldPosition); + var bBox = o.BoundingBox.Translated(entMan.GetComponent(o.Owner).WorldPosition); if (bBox.Contains(origin.Position) || bBox.Contains(other.Position)) { @@ -144,62 +147,70 @@ namespace Content.Shared.Examine return true; } - public static bool InRangeUnOccluded(IEntity origin, IEntity other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) + public static bool InRangeUnOccluded(EntityUid origin, EntityUid other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) { - var originPos = origin.Transform.MapPosition; - var otherPos = other.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var originPos = entMan.GetComponent(origin).MapPosition; + var otherPos = entMan.GetComponent(other).MapPosition; return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker); } - public static bool InRangeUnOccluded(IEntity origin, IComponent other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) + public static bool InRangeUnOccluded(EntityUid origin, IComponent other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) { - var originPos = origin.Transform.MapPosition; - var otherPos = other.Owner.Transform.MapPosition; + 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(IEntity origin, EntityCoordinates other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) + public static bool InRangeUnOccluded(EntityUid origin, EntityCoordinates other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) { - var originPos = origin.Transform.MapPosition; - var otherPos = other.ToMap(origin.EntityManager); + var entMan = IoCManager.Resolve(); + var originPos = entMan.GetComponent(origin).MapPosition; + var otherPos = other.ToMap(entMan); return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker); } - public static bool InRangeUnOccluded(IEntity origin, MapCoordinates other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) + public static bool InRangeUnOccluded(EntityUid origin, MapCoordinates other, float range, Ignored? predicate, bool ignoreInsideBlocker = true) { - var originPos = origin.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var originPos = entMan.GetComponent(origin).MapPosition; return InRangeUnOccluded(originPos, other, range, predicate, ignoreInsideBlocker); } public static bool InRangeUnOccluded(ITargetedInteractEventArgs args, float range, Ignored? predicate, bool ignoreInsideBlocker = true) { - var originPos = args.User.Transform.MapPosition; - var otherPos = args.Target.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var originPos = entMan.GetComponent(args.User).MapPosition; + var otherPos = entMan.GetComponent(args.Target).MapPosition; return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker); } public static bool InRangeUnOccluded(DragDropEvent args, float range, Ignored? predicate, bool ignoreInsideBlocker = true) { - var originPos = args.User.Transform.MapPosition; - var otherPos = args.DropLocation.ToMap(args.User.EntityManager); + var entMan = IoCManager.Resolve(); + var originPos = entMan.GetComponent(args.User).MapPosition; + var otherPos = args.DropLocation.ToMap(entMan); return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker); } public static bool InRangeUnOccluded(AfterInteractEventArgs args, float range, Ignored? predicate, bool ignoreInsideBlocker = true) { - var originPos = args.User.Transform.MapPosition; - var otherPos = args.Target?.Transform.MapPosition ?? args.ClickLocation.ToMap(args.User.EntityManager); + var entityManager = IoCManager.Resolve();; + var originPos = entityManager.GetComponent(args.User).MapPosition; + var target = args.Target; + var otherPos = (target != null ? entityManager.GetComponent(target.Value).MapPosition : args.ClickLocation.ToMap(entityManager)); return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker); } - public FormattedMessage GetExamineText(IEntity entity, IEntity? examiner) + public FormattedMessage GetExamineText(EntityUid entity, EntityUid? examiner) { var message = new FormattedMessage(); @@ -211,21 +222,21 @@ namespace Content.Shared.Examine var doNewline = false; //Add an entity description if one is declared - if (!string.IsNullOrEmpty(entity.Description)) + if (!string.IsNullOrEmpty(EntityManager.GetComponent(entity).EntityDescription)) { - message.AddText(entity.Description); + message.AddText(EntityManager.GetComponent(entity).EntityDescription); doNewline = true; } message.PushColor(Color.DarkGray); // Raise the event and let things that subscribe to it change the message... - var isInDetailsRange = IsInDetailsRange(examiner, entity); - var examinedEvent = new ExaminedEvent(message, entity, examiner, isInDetailsRange, doNewline); - RaiseLocalEvent(entity.Uid, examinedEvent); + var isInDetailsRange = IsInDetailsRange(examiner.Value, entity); + var examinedEvent = new ExaminedEvent(message, entity, examiner.Value, isInDetailsRange, doNewline); + RaiseLocalEvent(entity, examinedEvent); //Add component statuses from components that report one - foreach (var examineComponent in entity.GetAllComponents()) + foreach (var examineComponent in EntityManager.GetComponents(entity)) { var subMessage = new FormattedMessage(); examineComponent.Examine(subMessage, isInDetailsRange); @@ -263,12 +274,12 @@ namespace Content.Shared.Examine /// /// The entity performing the examining. /// - public IEntity Examiner { get; } + public EntityUid Examiner { get; } /// /// Entity being examined, for broadcast event purposes. /// - public IEntity Examined { get; } + public EntityUid Examined { get; } /// /// Whether the examiner is in range of the entity to get some extra details. @@ -277,7 +288,7 @@ namespace Content.Shared.Examine private bool _doNewLine; - public ExaminedEvent(FormattedMessage message, IEntity examined, IEntity examiner, bool isInDetailsRange, bool doNewLine) + public ExaminedEvent(FormattedMessage message, EntityUid examined, EntityUid examiner, bool isInDetailsRange, bool doNewLine) { Message = message; Examined = examined; diff --git a/Content.Shared/Flash/SharedFlashSystem.cs b/Content.Shared/Flash/SharedFlashSystem.cs index 0360a07ae4..ad107690d9 100644 --- a/Content.Shared/Flash/SharedFlashSystem.cs +++ b/Content.Shared/Flash/SharedFlashSystem.cs @@ -16,7 +16,7 @@ namespace Content.Shared.Flash private void OnGetStateAttempt(EntityUid uid, SharedFlashableComponent component, ComponentGetStateAttemptEvent args) { // Only send state to the player attached to the entity. - if (args.Player.AttachedEntityUid != uid) + if (args.Player.AttachedEntity != uid) args.Cancel(); } diff --git a/Content.Shared/Friction/SharedTileFrictionController.cs b/Content.Shared/Friction/SharedTileFrictionController.cs index 1486f20f62..a53b96ed90 100644 --- a/Content.Shared/Friction/SharedTileFrictionController.cs +++ b/Content.Shared/Friction/SharedTileFrictionController.cs @@ -56,10 +56,10 @@ namespace Content.Shared.Friction if (body.Deleted || prediction && !body.Predict || body.BodyStatus == BodyStatus.InAir || - Mover.UseMobMovement(body.OwnerUid)) continue; + Mover.UseMobMovement(body.Owner)) continue; var surfaceFriction = GetTileFriction(body); - var bodyModifier = body.Owner.GetComponentOrNull()?.Modifier ?? 1.0f; + var bodyModifier = IoCManager.Resolve().GetComponentOrNull(body.Owner)?.Modifier ?? 1.0f; var friction = _frictionModifier * surfaceFriction * bodyModifier; ReduceLinearVelocity(prediction, body, friction, frameTime); @@ -132,7 +132,7 @@ namespace Content.Shared.Friction [Pure] private float GetTileFriction(PhysicsComponent body) { - var transform = body.Owner.Transform; + var transform = IoCManager.Resolve().GetComponent(body.Owner); var coords = transform.Coordinates; // TODO: Make IsWeightless event-based; we already have grid traversals tracked so just raise events diff --git a/Content.Shared/Gravity/SharedGravitySystem.cs b/Content.Shared/Gravity/SharedGravitySystem.cs index 4601e6bbac..e3b651b87c 100644 --- a/Content.Shared/Gravity/SharedGravitySystem.cs +++ b/Content.Shared/Gravity/SharedGravitySystem.cs @@ -12,8 +12,7 @@ namespace Content.Shared.Gravity private void HandleGridInitialize(GridInitializeEvent ev) { - var gridEnt = EntityManager.GetEntity(ev.EntityUid); - gridEnt.EnsureComponent(); + EntityManager.EnsureComponent(ev.EntityUid); } } } diff --git a/Content.Shared/Hands/Components/SharedHandsComponent.cs b/Content.Shared/Hands/Components/SharedHandsComponent.cs index 1aad115d26..fe009019e8 100644 --- a/Content.Shared/Hands/Components/SharedHandsComponent.cs +++ b/Content.Shared/Hands/Components/SharedHandsComponent.cs @@ -14,7 +14,6 @@ using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; -using Robust.Shared.Players; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -24,6 +23,8 @@ namespace Content.Shared.Hands.Components [NetworkedComponent] public abstract class SharedHandsComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public sealed override string Name => "Hands"; public event Action? OnItemChanged; //TODO: Try to replace C# event @@ -97,12 +98,14 @@ namespace Content.Shared.Hands.Components UpdateHandVisualizer(); Dirty(); - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new HandsModifiedMessage { Hands = this }); + _entMan.EventBus.RaiseEvent(EventSource.Local, new HandsModifiedMessage { Hands = this }); } public void UpdateHandVisualizer() { - if (!Owner.TryGetComponent(out AppearanceComponent? appearance)) + var entMan = _entMan; + + if (!entMan.TryGetComponent(Owner, out AppearanceComponent? appearance)) return; var hands = new List(); @@ -111,7 +114,7 @@ namespace Content.Shared.Hands.Components if (hand.HeldEntity == null) continue; - if (!hand.HeldEntity.TryGetComponent(out SharedItemComponent? item) || item.RsiPath == null) + if (!entMan.TryGetComponent(hand.HeldEntity, out SharedItemComponent? item) || item.RsiPath == null) continue; var handState = new HandVisualState(item.RsiPath, item.EquippedPrefix, hand.Location, item.Color); @@ -214,27 +217,27 @@ namespace Content.Shared.Hands.Components if (!TryGetActiveHand(out var hand)) return false; - return hand.HeldEntity != null; + return hand.HeldEntity != default; } - public bool TryGetHeldEntity(string handName, [NotNullWhen(true)] out IEntity? heldEntity) + public bool TryGetHeldEntity(string handName, out EntityUid heldEntity) { - heldEntity = null; + heldEntity = default; if (!TryGetHand(handName, out var hand)) return false; heldEntity = hand.HeldEntity; - return heldEntity != null; + return heldEntity != default; } - public bool TryGetActiveHeldEntity([NotNullWhen(true)] out IEntity? heldEntity) + public bool TryGetActiveHeldEntity(out EntityUid heldEntity) { - heldEntity = GetActiveHand()?.HeldEntity; + heldEntity = GetActiveHand()?.HeldEntity ?? default; return heldEntity != null; } - public bool IsHolding(IEntity entity) + public bool IsHolding(EntityUid entity) { foreach (var hand in Hands) { @@ -244,11 +247,11 @@ namespace Content.Shared.Hands.Components return false; } - public IEnumerable GetAllHeldEntities() + public IEnumerable GetAllHeldEntities() { foreach (var hand in Hands) { - if (hand.HeldEntity != null) + if (hand.HeldEntity != default) yield return hand.HeldEntity; } } @@ -262,14 +265,14 @@ namespace Content.Shared.Hands.Components int acc = 0; foreach (var hand in Hands) { - if (hand.HeldEntity == null) + if (hand.HeldEntity == default) acc += 1; } return acc; } - public bool TryGetHandHoldingEntity(IEntity entity, [NotNullWhen(true)] out Hand? handFound) + public bool TryGetHandHoldingEntity(EntityUid entity, [NotNullWhen(true)] out Hand? handFound) { handFound = null; @@ -330,7 +333,7 @@ namespace Content.Shared.Hands.Components /// /// Tries to drop a held entity to the target location. /// - public bool TryDropEntity(IEntity entity, EntityCoordinates coords, bool doMobChecks = true) + public bool TryDropEntity(EntityUid entity, EntityCoordinates coords, bool doMobChecks = true) { if (!TryGetHandHoldingEntity(entity, out var hand)) return false; @@ -356,7 +359,7 @@ namespace Content.Shared.Hands.Components /// /// Attempts to move a held item from a hand into a container that is not another hand, without dropping it on the floor in-between. /// - public bool Drop(IEntity entity, BaseContainer targetContainer, bool checkActionBlocker = true) + public bool Drop(EntityUid entity, BaseContainer targetContainer, bool checkActionBlocker = true) { if (!TryGetHandHoldingEntity(entity, out var hand)) return false; @@ -376,18 +379,18 @@ namespace Content.Shared.Hands.Components if (!TryGetHand(handName, out var hand)) return false; - return TryDropHeldEntity(hand, Owner.Transform.Coordinates, checkActionBlocker); + return TryDropHeldEntity(hand, _entMan.GetComponent(Owner).Coordinates, checkActionBlocker); } /// /// Tries to drop a held entity directly under the player. /// - public bool Drop(IEntity entity, bool checkActionBlocker = true) + public bool Drop(EntityUid entity, bool checkActionBlocker = true) { if (!TryGetHandHoldingEntity(entity, out var hand)) return false; - return TryDropHeldEntity(hand, Owner.Transform.Coordinates, checkActionBlocker); + return TryDropHeldEntity(hand, _entMan.GetComponent(Owner).Coordinates, checkActionBlocker); } /// @@ -412,11 +415,11 @@ namespace Content.Shared.Hands.Components /// private bool CanRemoveHeldEntityFromHand(Hand hand) { - var heldEntity = hand.HeldEntity; - - if (heldEntity == null) + if (hand.HeldEntity == null) return false; + var heldEntity = hand.HeldEntity; + var handContainer = hand.Container; if (handContainer == null) return false; @@ -432,7 +435,7 @@ namespace Content.Shared.Hands.Components /// private bool PlayerCanDrop() { - if (!IoCManager.Resolve().GetEntitySystem().CanDrop(OwnerUid)) + if (!IoCManager.Resolve().GetEntitySystem().CanDrop(Owner)) return false; return true; @@ -443,11 +446,11 @@ namespace Content.Shared.Hands.Components /// private void RemoveHeldEntityFromHand(Hand hand) { - var heldEntity = hand.HeldEntity; - - if (heldEntity == null) + if (hand.HeldEntity == null) return; + var heldEntity = hand.HeldEntity; + var handContainer = hand.Container; if (handContainer == null) return; @@ -471,16 +474,16 @@ namespace Content.Shared.Hands.Components /// public void DropHeldEntity(Hand hand, EntityCoordinates targetDropLocation) { - var heldEntity = hand.HeldEntity; - - if (heldEntity == null) + if (hand.HeldEntity == null) return; + var heldEntity = hand.HeldEntity; + RemoveHeldEntityFromHand(hand); EntitySystem.Get().DroppedInteraction(Owner, heldEntity); - heldEntity.Transform.WorldPosition = GetFinalDropCoordinates(targetDropLocation); + _entMan.GetComponent(heldEntity).WorldPosition = GetFinalDropCoordinates(targetDropLocation); OnItemChanged?.Invoke(); } @@ -490,8 +493,8 @@ namespace Content.Shared.Hands.Components /// private Vector2 GetFinalDropCoordinates(EntityCoordinates targetCoords) { - var origin = Owner.Transform.MapPosition; - var target = targetCoords.ToMap(Owner.EntityManager); + var origin = _entMan.GetComponent(Owner).MapPosition; + var target = targetCoords.ToMap(_entMan); var dropVector = target.Position - origin.Position; var requestedDropDistance = dropVector.Length; @@ -529,16 +532,16 @@ namespace Content.Shared.Hands.Components /// private void DropHeldEntityToFloor(Hand hand) { - DropHeldEntity(hand, Owner.Transform.Coordinates); + DropHeldEntity(hand, _entMan.GetComponent(Owner).Coordinates); } private bool CanPutHeldEntityIntoContainer(Hand hand, IContainer targetContainer, bool checkActionBlocker) { - var heldEntity = hand.HeldEntity; - - if (heldEntity == null) + if (hand.HeldEntity == null) return false; + var heldEntity = hand.HeldEntity; + if (checkActionBlocker && !PlayerCanDrop()) return false; @@ -553,11 +556,11 @@ namespace Content.Shared.Hands.Components /// private void PutHeldEntityIntoContainer(Hand hand, IContainer targetContainer) { - var heldEntity = hand.HeldEntity; - - if (heldEntity == null) + if (hand.HeldEntity == null) return; + var heldEntity = hand.HeldEntity; + RemoveHeldEntityFromHand(hand); if (!targetContainer.Insert(heldEntity)) @@ -571,7 +574,7 @@ namespace Content.Shared.Hands.Components #region Pickup - public bool CanPickupEntity(string handName, IEntity entity, bool checkActionBlocker = true) + public bool CanPickupEntity(string handName, EntityUid entity, bool checkActionBlocker = true) { if (!TryGetHand(handName, out var hand)) return false; @@ -585,7 +588,7 @@ namespace Content.Shared.Hands.Components return true; } - public bool CanPickupEntityToActiveHand(IEntity entity, bool checkActionBlocker = true) + public bool CanPickupEntityToActiveHand(EntityUid entity, bool checkActionBlocker = true) { return ActiveHand != null && CanPickupEntity(ActiveHand, entity, checkActionBlocker); } @@ -593,7 +596,7 @@ namespace Content.Shared.Hands.Components /// /// Tries to pick up an entity to a specific hand. /// - public bool TryPickupEntity(string handName, IEntity entity, bool checkActionBlocker = true) + public bool TryPickupEntity(string handName, EntityUid entity, bool checkActionBlocker = true) { if (!TryGetHand(handName, out var hand)) return false; @@ -601,7 +604,7 @@ namespace Content.Shared.Hands.Components return TryPickupEntity(hand, entity, checkActionBlocker); } - public bool TryPickupEntityToActiveHand(IEntity entity, bool checkActionBlocker = true) + public bool TryPickupEntityToActiveHand(EntityUid entity, bool checkActionBlocker = true) { return ActiveHand != null && TryPickupEntity(ActiveHand, entity, checkActionBlocker); } @@ -609,7 +612,7 @@ namespace Content.Shared.Hands.Components /// /// Checks if an entity can be put into a hand's container. /// - protected bool CanInsertEntityIntoHand(Hand hand, IEntity entity) + protected bool CanInsertEntityIntoHand(Hand hand, EntityUid entity) { var handContainer = hand.Container; if (handContainer == null) @@ -627,7 +630,7 @@ namespace Content.Shared.Hands.Components /// protected bool PlayerCanPickup() { - if (!EntitySystem.Get().CanPickup(Owner.Uid)) + if (!EntitySystem.Get().CanPickup(Owner)) return false; return true; @@ -636,7 +639,7 @@ namespace Content.Shared.Hands.Components /// /// Puts an entity into the player's hand, assumes that the insertion is allowed. /// - public void PutEntityIntoHand(Hand hand, IEntity entity) + public void PutEntityIntoHand(Hand hand, EntityUid entity) { var handContainer = hand.Container; if (handContainer == null) @@ -653,14 +656,14 @@ namespace Content.Shared.Hands.Components if (hand.Name == ActiveHand) SelectActiveHeldEntity(); - entity.Transform.LocalPosition = Vector2.Zero; + _entMan.GetComponent(entity).LocalPosition = Vector2.Zero; OnItemChanged?.Invoke(); HandsModified(); } - private bool TryPickupEntity(Hand hand, IEntity entity, bool checkActionBlocker = true) + private bool TryPickupEntity(Hand hand, EntityUid entity, bool checkActionBlocker = true) { if (!CanInsertEntityIntoHand(hand, entity)) return false; @@ -771,7 +774,7 @@ namespace Content.Shared.Hands.Components private void HandCountChanged() { - Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, new HandCountChangedEvent(Owner)); + _entMan.EventBus.RaiseEvent(EventSource.Local, new HandCountChangedEvent(Owner)); } /// @@ -790,13 +793,13 @@ namespace Content.Shared.Hands.Components var entity = item.Owner; if (!TryPutInActiveHandOrAny(entity, checkActionBlocker)) - entity.Transform.Coordinates = Owner.Transform.Coordinates; + _entMan.GetComponent(entity).Coordinates = _entMan.GetComponent(Owner).Coordinates; } /// /// Tries to pick up an entity into the active hand. If it cannot, tries to pick up the entity into each other hand. /// - public bool TryPutInActiveHandOrAny(IEntity entity, bool checkActionBlocker = true) + public bool TryPutInActiveHandOrAny(EntityUid entity, bool checkActionBlocker = true) { return TryPutInAnyHand(entity, GetActiveHand(), checkActionBlocker); } @@ -804,7 +807,7 @@ namespace Content.Shared.Hands.Components /// /// Tries to pick up an entity into the priority hand, if provided. If it cannot, tries to pick up the entity into each other hand. /// - public bool TryPutInAnyHand(IEntity entity, string? priorityHandName = null, bool checkActionBlocker = true) + public bool TryPutInAnyHand(EntityUid entity, string? priorityHandName = null, bool checkActionBlocker = true) { Hand? priorityHand = null; @@ -817,7 +820,7 @@ namespace Content.Shared.Hands.Components /// /// Tries to pick up an entity into the priority hand, if provided. If it cannot, tries to pick up the entity into each other hand. /// - private bool TryPutInAnyHand(IEntity entity, Hand? priorityHand = null, bool checkActionBlocker = true) + private bool TryPutInAnyHand(EntityUid entity, Hand? priorityHand = null, bool checkActionBlocker = true) { if (priorityHand != null) { @@ -833,9 +836,9 @@ namespace Content.Shared.Hands.Components return false; } - protected virtual void OnHeldEntityRemovedFromHand(IEntity heldEntity, HandState handState) { } + protected virtual void OnHeldEntityRemovedFromHand(EntityUid heldEntity, HandState handState) { } - protected virtual void HandlePickupAnimation(IEntity entity) { } + protected virtual void HandlePickupAnimation(EntityUid entity) { } } #region visualizerData @@ -890,9 +893,9 @@ namespace Content.Shared.Hands.Components public IContainer? Container { get; set; } [ViewVariables] - public IEntity? HeldEntity => Container?.ContainedEntities?.FirstOrDefault(); + public EntityUid HeldEntity => Container?.ContainedEntities.FirstOrDefault() ?? EntityUid.Invalid; - public bool IsEmpty => HeldEntity == null; + public bool IsEmpty => HeldEntity == default; public Hand(string name, HandLocation location, IContainer? container = null) { @@ -995,12 +998,12 @@ namespace Content.Shared.Hands.Components public class HandCountChangedEvent : EntityEventArgs { - public HandCountChangedEvent(IEntity sender) + public HandCountChangedEvent(EntityUid sender) { Sender = sender; } - public IEntity Sender { get; } + public EntityUid Sender { get; } } [Serializable, NetSerializable] diff --git a/Content.Shared/Hands/IEquippedHand.cs b/Content.Shared/Hands/IEquippedHand.cs index dd01e37e6c..fc2a67ae52 100644 --- a/Content.Shared/Hands/IEquippedHand.cs +++ b/Content.Shared/Hands/IEquippedHand.cs @@ -22,7 +22,7 @@ namespace Content.Shared.Hands public class EquippedHandEventArgs : UserEventArgs { - public EquippedHandEventArgs(IEntity user, HandState hand) : base(user) + public EquippedHandEventArgs(EntityUid user, HandState hand) : base(user) { Hand = hand; } @@ -39,19 +39,19 @@ namespace Content.Shared.Hands /// /// Entity that equipped the item. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Item that was equipped. /// - public IEntity Equipped { get; } + public EntityUid Equipped { get; } /// /// Hand that the item was placed into. /// public HandState Hand { get; } - public EquippedHandEvent(IEntity user, IEntity equipped, HandState hand) + public EquippedHandEvent(EntityUid user, EntityUid equipped, HandState hand) { User = user; Equipped = equipped; diff --git a/Content.Shared/Hands/IHandDeselected.cs b/Content.Shared/Hands/IHandDeselected.cs index 980f3dd489..a038569c18 100644 --- a/Content.Shared/Hands/IHandDeselected.cs +++ b/Content.Shared/Hands/IHandDeselected.cs @@ -17,12 +17,12 @@ namespace Content.Shared.Hands public class HandDeselectedEventArgs : EventArgs { - public HandDeselectedEventArgs(IEntity user) + public HandDeselectedEventArgs(EntityUid user) { User = user; } - public IEntity User { get; } + public EntityUid User { get; } } /// @@ -34,14 +34,14 @@ namespace Content.Shared.Hands /// /// Entity that owns the deselected hand. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Item in the hand that was deselected. /// - public IEntity Item { get; } + public EntityUid Item { get; } - public HandDeselectedEvent(IEntity user, IEntity item) + public HandDeselectedEvent(EntityUid user, EntityUid item) { User = user; Item = item; diff --git a/Content.Shared/Hands/IHandSelected.cs b/Content.Shared/Hands/IHandSelected.cs index 5e34cef951..f26e846cc4 100644 --- a/Content.Shared/Hands/IHandSelected.cs +++ b/Content.Shared/Hands/IHandSelected.cs @@ -17,12 +17,12 @@ namespace Content.Shared.Hands public class HandSelectedEventArgs : EventArgs { - public HandSelectedEventArgs(IEntity user) + public HandSelectedEventArgs(EntityUid user) { User = user; } - public IEntity User { get; } + public EntityUid User { get; } } /// @@ -34,14 +34,14 @@ namespace Content.Shared.Hands /// /// Entity that owns the selected hand. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Item in the hand that was selected. /// - public IEntity Item { get; } + public EntityUid Item { get; } - public HandSelectedEvent(IEntity user, IEntity item) + public HandSelectedEvent(EntityUid user, EntityUid item) { User = user; Item = item; diff --git a/Content.Shared/Hands/IUnequippedHand.cs b/Content.Shared/Hands/IUnequippedHand.cs index 9abf762e8c..058d2c4276 100644 --- a/Content.Shared/Hands/IUnequippedHand.cs +++ b/Content.Shared/Hands/IUnequippedHand.cs @@ -21,7 +21,7 @@ namespace Content.Shared.Hands public class UnequippedHandEventArgs : UserEventArgs { - public UnequippedHandEventArgs(IEntity user, HandState hand) : base(user) + public UnequippedHandEventArgs(EntityUid user, HandState hand) : base(user) { Hand = hand; } @@ -38,19 +38,19 @@ namespace Content.Shared.Hands /// /// Entity that equipped the item. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Item that was unequipped. /// - public IEntity Unequipped { get; } + public EntityUid Unequipped { get; } /// /// Hand that the item is removed from. /// public HandState Hand { get; } - public UnequippedHandEvent(IEntity user, IEntity unequipped, HandState hand) + public UnequippedHandEvent(EntityUid user, EntityUid unequipped, HandState hand) { User = user; Unequipped = unequipped; diff --git a/Content.Shared/Hands/SharedHandsSystem.cs b/Content.Shared/Hands/SharedHandsSystem.cs index e3aeeb7a06..11dfda05ed 100644 --- a/Content.Shared/Hands/SharedHandsSystem.cs +++ b/Content.Shared/Hands/SharedHandsSystem.cs @@ -1,8 +1,8 @@ +using System; using Content.Shared.Hands.Components; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Serialization; -using System; namespace Content.Shared.Hands { @@ -18,11 +18,11 @@ namespace Content.Shared.Hands SubscribeAllEvent(HandleSetHand); } - private static void HandleSetHand(RequestSetHandEvent msg, EntitySessionEventArgs eventArgs) + private void HandleSetHand(RequestSetHandEvent msg, EntitySessionEventArgs eventArgs) { var entity = eventArgs.SenderSession.AttachedEntity; - if (entity == null || !entity.TryGetComponent(out SharedHandsComponent? hands)) + if (entity == null || !EntityManager.TryGetComponent(entity, out SharedHandsComponent? hands)) return; hands.ActiveHand = msg.HandName; diff --git a/Content.Shared/Interaction/BeforeInteract.cs b/Content.Shared/Interaction/BeforeInteract.cs index 0c36682d48..ed0bcb1c41 100644 --- a/Content.Shared/Interaction/BeforeInteract.cs +++ b/Content.Shared/Interaction/BeforeInteract.cs @@ -13,32 +13,17 @@ namespace Content.Shared.Interaction /// /// Entity that triggered the interaction. /// - public IEntity User { get; } - - /// - /// Entity that triggered the interaction. - /// - public EntityUid UserUid => User.Uid; + public EntityUid User { get; } /// /// Entity that the user used to interact. /// - public IEntity Used { get; } - - /// - /// Entity that the user used to interact. - /// - public EntityUid UsedUid => Used.Uid; + public EntityUid Used { get; } /// /// Entity that was interacted on. This can be null if the attack did not click on an entity. /// - public IEntity? Target { get; } - - /// - /// Entity that was interacted on. This can be null if the attack did not click on an entity. - /// - public EntityUid? TargetUid => Target?.Uid; + public EntityUid? Target { get; } /// /// Location that the user clicked outside of their interaction range. @@ -52,9 +37,9 @@ namespace Content.Shared.Interaction public bool CanReach { get; } public BeforeInteractEvent( - IEntity user, - IEntity used, - IEntity? target, + EntityUid user, + EntityUid used, + EntityUid? target, EntityCoordinates clickLocation, bool canReach) { diff --git a/Content.Shared/Interaction/Helpers/SharedUnobstructedExtensions.cs b/Content.Shared/Interaction/Helpers/SharedUnobstructedExtensions.cs index b54670ab18..ae640e2538 100644 --- a/Content.Shared/Interaction/Helpers/SharedUnobstructedExtensions.cs +++ b/Content.Shared/Interaction/Helpers/SharedUnobstructedExtensions.cs @@ -14,19 +14,6 @@ namespace Content.Shared.Interaction.Helpers private static SharedInteractionSystem SharedInteractionSystem => EntitySystem.Get(); #region Entities - public static bool InRangeUnobstructed( - this IEntity origin, - IEntity other, - float range = InteractionRange, - CollisionGroup collisionMask = CollisionGroup.Impassable, - Ignored? predicate = null, - bool ignoreInsideBlocker = false, - bool popup = false) - { - return SharedInteractionSystem.InRangeUnobstructed(origin, other, range, collisionMask, predicate, - ignoreInsideBlocker, popup); - } - public static bool InRangeUnobstructed( this EntityUid origin, EntityUid other, @@ -37,14 +24,11 @@ namespace Content.Shared.Interaction.Helpers bool popup = false, IEntityManager? entityManager = null) { - entityManager ??= IoCManager.Resolve(); - - return InRangeUnobstructed(entityManager.GetEntity(origin), entityManager.GetEntity(other), - range, collisionMask, predicate, ignoreInsideBlocker, popup); + return SharedInteractionSystem.InRangeUnobstructed(origin, other, range, collisionMask, predicate, ignoreInsideBlocker, popup); } public static bool InRangeUnobstructed( - this IEntity origin, + this EntityUid origin, IComponent other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, @@ -57,7 +41,7 @@ namespace Content.Shared.Interaction.Helpers } public static bool InRangeUnobstructed( - this IEntity origin, + this EntityUid origin, IContainer other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, @@ -72,7 +56,7 @@ namespace Content.Shared.Interaction.Helpers } public static bool InRangeUnobstructed( - this IEntity origin, + this EntityUid origin, EntityCoordinates other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, @@ -85,7 +69,7 @@ namespace Content.Shared.Interaction.Helpers } public static bool InRangeUnobstructed( - this IEntity origin, + this EntityUid origin, MapCoordinates other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, @@ -101,7 +85,7 @@ namespace Content.Shared.Interaction.Helpers #region Components public static bool InRangeUnobstructed( this IComponent origin, - IEntity other, + EntityUid other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, Ignored? predicate = null, @@ -179,7 +163,7 @@ namespace Content.Shared.Interaction.Helpers #region Containers public static bool InRangeUnobstructed( this IContainer origin, - IEntity other, + EntityUid other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, Ignored? predicate = null, @@ -256,14 +240,14 @@ namespace Content.Shared.Interaction.Helpers #region EntityCoordinates public static bool InRangeUnobstructed( this EntityCoordinates origin, - IEntity other, + EntityUid other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, Ignored? predicate = null, bool ignoreInsideBlocker = false) { - var originPosition = origin.ToMap(other.EntityManager); - var otherPosition = other.Transform.MapPosition; + var originPosition = origin.ToMap(IoCManager.Resolve()); + var otherPosition = IoCManager.Resolve().GetComponent(other).MapPosition; return SharedInteractionSystem.InRangeUnobstructed(originPosition, otherPosition, range, collisionMask, predicate, ignoreInsideBlocker); @@ -277,8 +261,8 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = false) { - var originPosition = origin.ToMap(other.Owner.EntityManager); - var otherPosition = other.Owner.Transform.MapPosition; + var originPosition = origin.ToMap(IoCManager.Resolve()); + var otherPosition = IoCManager.Resolve().GetComponent(other.Owner).MapPosition; return SharedInteractionSystem.InRangeUnobstructed(originPosition, otherPosition, range, collisionMask, predicate, ignoreInsideBlocker); @@ -292,8 +276,8 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = false) { - var originPosition = origin.ToMap(other.Owner.EntityManager); - var otherPosition = other.Owner.Transform.MapPosition; + var originPosition = origin.ToMap(IoCManager.Resolve()); + var otherPosition = IoCManager.Resolve().GetComponent(other.Owner).MapPosition; return SharedInteractionSystem.InRangeUnobstructed(originPosition, otherPosition, range, collisionMask, predicate, ignoreInsideBlocker); @@ -338,13 +322,13 @@ namespace Content.Shared.Interaction.Helpers #region MapCoordinates public static bool InRangeUnobstructed( this MapCoordinates origin, - IEntity other, + EntityUid other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, Ignored? predicate = null, bool ignoreInsideBlocker = false) { - var otherPosition = other.Transform.MapPosition; + var otherPosition = IoCManager.Resolve().GetComponent(other).MapPosition; return SharedInteractionSystem.InRangeUnobstructed(origin, otherPosition, range, collisionMask, predicate, ignoreInsideBlocker); @@ -358,7 +342,7 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = false) { - var otherPosition = other.Owner.Transform.MapPosition; + var otherPosition = IoCManager.Resolve().GetComponent(other.Owner).MapPosition; return SharedInteractionSystem.InRangeUnobstructed(origin, otherPosition, range, collisionMask, predicate, ignoreInsideBlocker); @@ -372,7 +356,7 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = false) { - var otherPosition = other.Owner.Transform.MapPosition; + var otherPosition = IoCManager.Resolve().GetComponent(other.Owner).MapPosition; return SharedInteractionSystem.InRangeUnobstructed(origin, otherPosition, range, collisionMask, predicate, ignoreInsideBlocker); @@ -434,7 +418,7 @@ namespace Content.Shared.Interaction.Helpers if (target == null) return SharedInteractionSystem.InRangeUnobstructed(user, args.ClickLocation, range, collisionMask, predicate, ignoreInsideBlocker, popup); else - return SharedInteractionSystem.InRangeUnobstructed(user, target, range, collisionMask, predicate, ignoreInsideBlocker, popup); + return SharedInteractionSystem.InRangeUnobstructed(user, target.Value, range, collisionMask, predicate, ignoreInsideBlocker, popup); } #endregion @@ -475,7 +459,7 @@ namespace Content.Shared.Interaction.Helpers if (target == null) return SharedInteractionSystem.InRangeUnobstructed(user, args.ClickLocation, range, collisionMask, predicate, ignoreInsideBlocker, popup); else - return SharedInteractionSystem.InRangeUnobstructed(user, target, range, collisionMask, predicate, ignoreInsideBlocker, popup); + return SharedInteractionSystem.InRangeUnobstructed(user, target.Value, range, collisionMask, predicate, ignoreInsideBlocker, popup); } #endregion } diff --git a/Content.Shared/Interaction/Helpers/SharedUnoccludedExtensions.cs b/Content.Shared/Interaction/Helpers/SharedUnoccludedExtensions.cs index 18b5537460..03e22dba5f 100644 --- a/Content.Shared/Interaction/Helpers/SharedUnoccludedExtensions.cs +++ b/Content.Shared/Interaction/Helpers/SharedUnoccludedExtensions.cs @@ -13,8 +13,8 @@ namespace Content.Shared.Interaction.Helpers { #region Entities public static bool InRangeUnOccluded( - this IEntity origin, - IEntity other, + this EntityUid origin, + EntityUid other, float range = ExamineRange, Ignored? predicate = null, bool ignoreInsideBlocker = true) @@ -23,7 +23,7 @@ namespace Content.Shared.Interaction.Helpers } public static bool InRangeUnOccluded( - this IEntity origin, + this EntityUid origin, IComponent other, float range = InteractionRange, Ignored? predicate = null, @@ -33,7 +33,7 @@ namespace Content.Shared.Interaction.Helpers } public static bool InRangeUnOccluded( - this IEntity origin, + this EntityUid origin, IContainer other, float range = InteractionRange, Ignored? predicate = null, @@ -45,7 +45,7 @@ namespace Content.Shared.Interaction.Helpers } public static bool InRangeUnOccluded( - this IEntity origin, + this EntityUid origin, EntityCoordinates other, float range = InteractionRange, Ignored? predicate = null, @@ -55,7 +55,7 @@ namespace Content.Shared.Interaction.Helpers } public static bool InRangeUnOccluded( - this IEntity origin, + this EntityUid origin, MapCoordinates other, float range = InteractionRange, Ignored? predicate = null, @@ -68,7 +68,7 @@ namespace Content.Shared.Interaction.Helpers #region Components public static bool InRangeUnOccluded( this IComponent origin, - IEntity other, + EntityUid other, float range = InteractionRange, Ignored? predicate = null, bool ignoreInsideBlocker = true) @@ -133,7 +133,7 @@ namespace Content.Shared.Interaction.Helpers #region Containers public static bool InRangeUnOccluded( this IContainer origin, - IEntity other, + EntityUid other, float range = InteractionRange, Ignored? predicate = null, bool ignoreInsideBlocker = true) @@ -198,13 +198,14 @@ namespace Content.Shared.Interaction.Helpers #region EntityCoordinates public static bool InRangeUnOccluded( this EntityCoordinates origin, - IEntity other, + EntityUid other, float range = InteractionRange, Ignored? predicate = null, bool ignoreInsideBlocker = true) { - var originPosition = origin.ToMap(other.EntityManager); - var otherPosition = other.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var originPosition = origin.ToMap(entMan); + var otherPosition = entMan.GetComponent(other).MapPosition; return ExamineSystemShared.InRangeUnOccluded(originPosition, otherPosition, range, predicate, ignoreInsideBlocker); @@ -217,8 +218,9 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = true) { - var originPosition = origin.ToMap(other.Owner.EntityManager); - var otherPosition = other.Owner.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var originPosition = origin.ToMap(entMan); + var otherPosition = entMan.GetComponent(other.Owner).MapPosition; return ExamineSystemShared.InRangeUnOccluded(originPosition, otherPosition, range, predicate, ignoreInsideBlocker); @@ -231,8 +233,9 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = true) { - var originPosition = origin.ToMap(other.Owner.EntityManager); - var otherPosition = other.Owner.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var originPosition = origin.ToMap(entMan); + var otherPosition = entMan.GetComponent(other.Owner).MapPosition; return ExamineSystemShared.InRangeUnOccluded(originPosition, otherPosition, range, predicate, ignoreInsideBlocker); @@ -246,7 +249,7 @@ namespace Content.Shared.Interaction.Helpers bool ignoreInsideBlocker = true, IEntityManager? entityManager = null) { - entityManager ??= IoCManager.Resolve(); + IoCManager.Resolve(ref entityManager); var originPosition = origin.ToMap(entityManager); var otherPosition = other.ToMap(entityManager); @@ -263,7 +266,7 @@ namespace Content.Shared.Interaction.Helpers bool ignoreInsideBlocker = true, IEntityManager? entityManager = null) { - entityManager ??= IoCManager.Resolve(); + IoCManager.Resolve(ref entityManager); var originPosition = origin.ToMap(entityManager); @@ -275,12 +278,13 @@ namespace Content.Shared.Interaction.Helpers #region MapCoordinates public static bool InRangeUnOccluded( this MapCoordinates origin, - IEntity other, + EntityUid other, float range = InteractionRange, Ignored? predicate = null, bool ignoreInsideBlocker = true) { - var otherPosition = other.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var otherPosition = entMan.GetComponent(other).MapPosition; return ExamineSystemShared.InRangeUnOccluded(origin, otherPosition, range, predicate, ignoreInsideBlocker); @@ -293,7 +297,8 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = true) { - var otherPosition = other.Owner.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var otherPosition = entMan.GetComponent(other.Owner).MapPosition; return ExamineSystemShared.InRangeUnOccluded(origin, otherPosition, range, predicate, ignoreInsideBlocker); @@ -306,7 +311,8 @@ namespace Content.Shared.Interaction.Helpers Ignored? predicate = null, bool ignoreInsideBlocker = true) { - var otherPosition = other.Owner.Transform.MapPosition; + var entMan = IoCManager.Resolve(); + var otherPosition = entMan.GetComponent(other.Owner).MapPosition; return ExamineSystemShared.InRangeUnOccluded(origin, otherPosition, range, predicate, ignoreInsideBlocker); @@ -320,7 +326,7 @@ namespace Content.Shared.Interaction.Helpers bool ignoreInsideBlocker = true, IEntityManager? entityManager = null) { - entityManager ??= IoCManager.Resolve(); + IoCManager.Resolve(ref entityManager); var otherPosition = other.ToMap(entityManager); diff --git a/Content.Shared/Interaction/IActivate.cs b/Content.Shared/Interaction/IActivate.cs index 7a0ffa6541..b97e4b7820 100644 --- a/Content.Shared/Interaction/IActivate.cs +++ b/Content.Shared/Interaction/IActivate.cs @@ -24,14 +24,14 @@ namespace Content.Shared.Interaction public class ActivateEventArgs : EventArgs, ITargetedInteractEventArgs { - public ActivateEventArgs(IEntity user, IEntity target) + public ActivateEventArgs(EntityUid user, EntityUid target) { User = user; Target = target; } - public IEntity User { get; } - public IEntity Target { get; } + public EntityUid User { get; } + public EntityUid Target { get; } } /// @@ -43,24 +43,14 @@ namespace Content.Shared.Interaction /// /// Entity that activated the target world entity. /// - public IEntity User { get; } - - /// - /// Entity that activated the target world entity. - /// - public EntityUid UserUid => User.Uid; + public EntityUid User { get; } /// /// Entity that was activated in the world. /// - public IEntity Target { get; } + public EntityUid Target { get; } - /// - /// Entity that was activated in the world. - /// - public EntityUid TargetUid => Target.Uid; - - public ActivateInWorldEvent(IEntity user, IEntity target) + public ActivateInWorldEvent(EntityUid user, EntityUid target) { User = user; Target = target; diff --git a/Content.Shared/Interaction/IAfterInteract.cs b/Content.Shared/Interaction/IAfterInteract.cs index 4ae86e6f05..6d85d41f6c 100644 --- a/Content.Shared/Interaction/IAfterInteract.cs +++ b/Content.Shared/Interaction/IAfterInteract.cs @@ -31,12 +31,12 @@ namespace Content.Shared.Interaction public class AfterInteractEventArgs : EventArgs { - public IEntity User { get; } + public EntityUid User { get; } public EntityCoordinates ClickLocation { get; } - public IEntity? Target { get; } + public EntityUid? Target { get; } public bool CanReach { get; } - public AfterInteractEventArgs(IEntity user, EntityCoordinates clickLocation, IEntity? target, bool canReach) + public AfterInteractEventArgs(EntityUid user, EntityCoordinates clickLocation, EntityUid? target, bool canReach) { User = user; ClickLocation = clickLocation; @@ -54,32 +54,17 @@ namespace Content.Shared.Interaction /// /// Entity that triggered the interaction. /// - public IEntity User { get; } - - /// - /// Entity that triggered the interaction. - /// - public EntityUid UserUid => User.Uid; + public EntityUid User { get; } /// /// Entity that the user used to interact. /// - public IEntity Used { get; } - - /// - /// Entity that the user used to interact. - /// - public EntityUid UsedUid => Used.Uid; + public EntityUid Used { get; } /// /// Entity that was interacted on. This can be null if the attack did not click on an entity. /// - public IEntity? Target { get; } - - /// - /// Entity that was interacted on. This can be null if the attack did not click on an entity. - /// - public EntityUid? TargetUid => Target?.Uid; + public EntityUid? Target { get; } /// /// Location that the user clicked outside of their interaction range. @@ -92,7 +77,7 @@ namespace Content.Shared.Interaction /// public bool CanReach { get; } - public AfterInteractEvent(IEntity user, IEntity used, IEntity? target, + public AfterInteractEvent(EntityUid user, EntityUid used, EntityUid? target, EntityCoordinates clickLocation, bool canReach) { User = user; diff --git a/Content.Shared/Interaction/IDropped.cs b/Content.Shared/Interaction/IDropped.cs index 8158524eaa..5fdcd071ae 100644 --- a/Content.Shared/Interaction/IDropped.cs +++ b/Content.Shared/Interaction/IDropped.cs @@ -17,12 +17,12 @@ namespace Content.Shared.Interaction public class DroppedEventArgs : EventArgs { - public DroppedEventArgs(IEntity user) + public DroppedEventArgs(EntityUid user) { User = user; } - public IEntity User { get; } + public EntityUid User { get; } } /// diff --git a/Content.Shared/Interaction/IInteractHand.cs b/Content.Shared/Interaction/IInteractHand.cs index 99fcd25527..723c7e09e6 100644 --- a/Content.Shared/Interaction/IInteractHand.cs +++ b/Content.Shared/Interaction/IInteractHand.cs @@ -21,14 +21,14 @@ namespace Content.Shared.Interaction public class InteractHandEventArgs : EventArgs, ITargetedInteractEventArgs { - public InteractHandEventArgs(IEntity user, IEntity target) + public InteractHandEventArgs(EntityUid user, EntityUid target) { User = user; Target = target; } - public IEntity User { get; } - public IEntity Target { get; } + public EntityUid User { get; } + public EntityUid Target { get; } } /// @@ -40,24 +40,14 @@ namespace Content.Shared.Interaction /// /// Entity that triggered the interaction. /// - public IEntity User { get; } - - /// - /// Entity that triggered the interaction. - /// - public EntityUid UserUid => User.Uid; + public EntityUid User { get; } /// /// Entity that was interacted on. /// - public IEntity Target { get; } + public EntityUid Target { get; } - /// - /// Entity that was interacted on. - /// - public EntityUid TargetUid => Target.Uid; - - public InteractHandEvent(IEntity user, IEntity target) + public InteractHandEvent(EntityUid user, EntityUid target) { User = user; Target = target; diff --git a/Content.Shared/Interaction/IInteractUsing.cs b/Content.Shared/Interaction/IInteractUsing.cs index e220e1538e..c3a380e414 100644 --- a/Content.Shared/Interaction/IInteractUsing.cs +++ b/Content.Shared/Interaction/IInteractUsing.cs @@ -30,7 +30,7 @@ namespace Content.Shared.Interaction public class InteractUsingEventArgs : EventArgs, ITargetedInteractEventArgs { - public InteractUsingEventArgs(IEntity user, EntityCoordinates clickLocation, IEntity @using, IEntity target) + public InteractUsingEventArgs(EntityUid user, EntityCoordinates clickLocation, EntityUid @using, EntityUid target) { User = user; ClickLocation = clickLocation; @@ -38,10 +38,10 @@ namespace Content.Shared.Interaction Target = target; } - public IEntity User { get; } + public EntityUid User { get; } public EntityCoordinates ClickLocation { get; } - public IEntity Using { get; } - public IEntity Target { get; } + public EntityUid Using { get; } + public EntityUid Target { get; } } /// @@ -53,39 +53,24 @@ namespace Content.Shared.Interaction /// /// Entity that triggered the interaction. /// - public IEntity User { get; } - - /// - /// Entity that triggered the interaction. - /// - public EntityUid UserUid => User.Uid; + public EntityUid User { get; } /// /// Entity that the user used to interact. /// - public IEntity Used { get; } - - /// - /// Entity that the user used to interact. - /// - public EntityUid UsedUid => Used.Uid; + public EntityUid Used { get; } /// /// Entity that was interacted on. /// - public IEntity Target { get; } - - /// - /// Entity that was interacted on. - /// - public EntityUid TargetUid => Target.Uid; + public EntityUid Target { get; } /// /// The original location that was clicked by the user. /// public EntityCoordinates ClickLocation { get; } - public InteractUsingEvent(IEntity user, IEntity used, IEntity target, EntityCoordinates clickLocation) + public InteractUsingEvent(EntityUid user, EntityUid used, EntityUid target, EntityCoordinates clickLocation) { User = user; Used = used; diff --git a/Content.Shared/Interaction/IRangedInteract.cs b/Content.Shared/Interaction/IRangedInteract.cs index 89b1f0eb00..c878b1dcd0 100644 --- a/Content.Shared/Interaction/IRangedInteract.cs +++ b/Content.Shared/Interaction/IRangedInteract.cs @@ -23,15 +23,15 @@ namespace Content.Shared.Interaction [PublicAPI] public class RangedInteractEventArgs : EventArgs { - public RangedInteractEventArgs(IEntity user, IEntity @using, EntityCoordinates clickLocation) + public RangedInteractEventArgs(EntityUid user, EntityUid @using, EntityCoordinates clickLocation) { User = user; Using = @using; ClickLocation = clickLocation; } - public IEntity User { get; } - public IEntity Using { get; } + public EntityUid User { get; } + public EntityUid Using { get; } public EntityCoordinates ClickLocation { get; } } diff --git a/Content.Shared/Interaction/ITargetedInteractEventArgs.cs b/Content.Shared/Interaction/ITargetedInteractEventArgs.cs index 1b52dbed2c..13f415e5e9 100644 --- a/Content.Shared/Interaction/ITargetedInteractEventArgs.cs +++ b/Content.Shared/Interaction/ITargetedInteractEventArgs.cs @@ -7,11 +7,11 @@ namespace Content.Shared.Interaction /// /// Performer of the attack /// - IEntity User { get; } + EntityUid User { get; } /// /// Target of the attack /// - IEntity Target { get; } + EntityUid Target { get; } } } diff --git a/Content.Shared/Interaction/IUse.cs b/Content.Shared/Interaction/IUse.cs index 650bf51b8e..5cdb81931d 100644 --- a/Content.Shared/Interaction/IUse.cs +++ b/Content.Shared/Interaction/IUse.cs @@ -22,12 +22,12 @@ namespace Content.Shared.Interaction public class UseEntityEventArgs : EventArgs { - public UseEntityEventArgs(IEntity user) + public UseEntityEventArgs(EntityUid user) { User = user; } - public IEntity User { get; } + public EntityUid User { get; } } /// @@ -39,24 +39,14 @@ namespace Content.Shared.Interaction /// /// Entity holding the item in their hand. /// - public IEntity User { get; } - - /// - /// Entity holding the item in their hand. - /// - public EntityUid UserUid => User.Uid; + public EntityUid User { get; } /// /// Item that was used. /// - public IEntity Used { get; } + public EntityUid Used { get; } - /// - /// Item that was used. - /// - public EntityUid UsedUid => Used.Uid; - - public UseInHandEvent(IEntity user, IEntity used) + public UseInHandEvent(EntityUid user, EntityUid used) { User = user; Used = used; diff --git a/Content.Shared/Interaction/RotateToFaceSystem.cs b/Content.Shared/Interaction/RotateToFaceSystem.cs index 4a90785c96..11f68bbfba 100644 --- a/Content.Shared/Interaction/RotateToFaceSystem.cs +++ b/Content.Shared/Interaction/RotateToFaceSystem.cs @@ -34,25 +34,25 @@ namespace Content.Shared.Interaction public class RotateToFaceSystem : EntitySystem { [Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!; - public bool TryFaceCoordinates(IEntity user, Vector2 coordinates) + public bool TryFaceCoordinates(EntityUid user, Vector2 coordinates) { - var diff = coordinates - user.Transform.MapPosition.Position; + var diff = coordinates - EntityManager.GetComponent(user).MapPosition.Position; if (diff.LengthSquared <= 0.01f) return true; var diffAngle = Angle.FromWorldVec(diff); return TryFaceAngle(user, diffAngle); } - public bool TryFaceAngle(IEntity user, Angle diffAngle) + public bool TryFaceAngle(EntityUid user, Angle diffAngle) { - if (_actionBlockerSystem.CanChangeDirection(user.Uid)) + if (_actionBlockerSystem.CanChangeDirection(user)) { - user.Transform.WorldRotation = diffAngle; + EntityManager.GetComponent(user).WorldRotation = diffAngle; return true; } else { - if (user.TryGetComponent(out SharedBuckleComponent? buckle) && buckle.Buckled) + if (EntityManager.TryGetComponent(user, out SharedBuckleComponent? buckle) && buckle.Buckled) { var suid = buckle.LastEntityBuckledTo; if (suid != null) @@ -64,7 +64,7 @@ namespace Content.Shared.Interaction // (Since the user being buckled to it holds it down with their weight.) // This is logically equivalent to RotateWhileAnchored. // Barstools and office chairs have independent wheels, while regular chairs don't. - rotatable.Owner.Transform.WorldRotation = diffAngle; + EntityManager.GetComponent(rotatable.Owner).WorldRotation = diffAngle; return true; } } diff --git a/Content.Shared/Interaction/SharedInteractionSystem.cs b/Content.Shared/Interaction/SharedInteractionSystem.cs index f004646cdc..1f15f1b9e1 100644 --- a/Content.Shared/Interaction/SharedInteractionSystem.cs +++ b/Content.Shared/Interaction/SharedInteractionSystem.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Content.Shared.ActionBlocker; @@ -42,7 +43,7 @@ namespace Content.Shared.Interaction public const float InteractionRange = 2; public const float InteractionRangeSquared = InteractionRange * InteractionRange; - public delegate bool Ignored(IEntity entity); + public delegate bool Ignored(EntityUid entity); /// /// Traces a ray from coords to otherCoords and returns the length @@ -89,7 +90,7 @@ namespace Content.Shared.Interaction MapCoordinates origin, MapCoordinates other, int collisionMask = (int) CollisionGroup.Impassable, - IEntity? ignoredEnt = null) + EntityUid? ignoredEnt = null) { var predicate = ignoredEnt == null ? null @@ -153,7 +154,7 @@ namespace Content.Shared.Interaction foreach (var result in rayResults) { - if (!result.HitEntity.TryGetComponent(out IPhysBody? p)) + if (!EntityManager.TryGetComponent(result.HitEntity, out IPhysBody? p)) { continue; } @@ -203,8 +204,8 @@ namespace Content.Shared.Interaction /// True if the two points are within a given range without being obstructed. /// public bool InRangeUnobstructed( - IEntity origin, - IEntity other, + EntityUid origin, + EntityUid other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, Ignored? predicate = null, @@ -212,7 +213,7 @@ namespace Content.Shared.Interaction bool popup = false) { predicate ??= e => e == origin || e == other; - return InRangeUnobstructed(origin, other.Transform.MapPosition, range, collisionMask, predicate, ignoreInsideBlocker, popup); + return InRangeUnobstructed(origin, EntityManager.GetComponent(other).MapPosition, range, collisionMask, predicate, ignoreInsideBlocker, popup); } /// @@ -248,7 +249,7 @@ namespace Content.Shared.Interaction /// True if the two points are within a given range without being obstructed. /// public bool InRangeUnobstructed( - IEntity origin, + EntityUid origin, IComponent other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, @@ -292,7 +293,7 @@ namespace Content.Shared.Interaction /// True if the two points are within a given range without being obstructed. /// public bool InRangeUnobstructed( - IEntity origin, + EntityUid origin, EntityCoordinates other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, @@ -336,7 +337,7 @@ namespace Content.Shared.Interaction /// True if the two points are within a given range without being obstructed. /// public bool InRangeUnobstructed( - IEntity origin, + EntityUid origin, MapCoordinates other, float range = InteractionRange, CollisionGroup collisionMask = CollisionGroup.Impassable, @@ -344,7 +345,7 @@ namespace Content.Shared.Interaction bool ignoreInsideBlocker = false, bool popup = false) { - var originPosition = origin.Transform.MapPosition; + var originPosition = EntityManager.GetComponent(origin).MapPosition; predicate ??= e => e == origin; var inRange = InRangeUnobstructed(originPosition, other, range, collisionMask, predicate, ignoreInsideBlocker); @@ -359,14 +360,14 @@ namespace Content.Shared.Interaction } public bool InteractDoBefore( - IEntity user, - IEntity used, - IEntity? target, + EntityUid user, + EntityUid used, + EntityUid? target, EntityCoordinates clickLocation, bool canReach) { var ev = new BeforeInteractEvent(user, used, target, clickLocation, canReach); - RaiseLocalEvent(used.Uid, ev, false); + RaiseLocalEvent(used, ev, false); return ev.Handled; } @@ -375,9 +376,9 @@ namespace Content.Shared.Interaction /// Finds components with the InteractUsing interface and calls their function /// NOTE: Does not have an InRangeUnobstructed check /// - public async Task InteractUsing(IEntity user, IEntity used, IEntity target, EntityCoordinates clickLocation) + public async Task InteractUsing(EntityUid user, EntityUid used, EntityUid target, EntityCoordinates clickLocation) { - if (!_actionBlockerSystem.CanInteract(user.Uid)) + if (!_actionBlockerSystem.CanInteract(user)) return; if (InteractDoBefore(user, used, target, clickLocation, true)) @@ -385,13 +386,13 @@ namespace Content.Shared.Interaction // all interactions should only happen when in range / unobstructed, so no range check is needed var interactUsingEvent = new InteractUsingEvent(user, used, target, clickLocation); - RaiseLocalEvent(target.Uid, interactUsingEvent); + RaiseLocalEvent(target, interactUsingEvent); if (interactUsingEvent.Handled) return; var interactUsingEventArgs = new InteractUsingEventArgs(user, clickLocation, used, target); - var interactUsings = target.GetAllComponents().OrderByDescending(x => x.Priority); + var interactUsings = EntityManager.GetComponents(target).OrderByDescending(x => x.Priority); foreach (var interactUsing in interactUsings) { // If an InteractUsing returns a status completion we finish our interaction @@ -406,15 +407,15 @@ namespace Content.Shared.Interaction /// /// We didn't click on any entity, try doing an AfterInteract on the click location /// - public async Task InteractDoAfter(IEntity user, IEntity used, IEntity? target, EntityCoordinates clickLocation, bool canReach) + public async Task InteractDoAfter(EntityUid user, EntityUid used, EntityUid? target, EntityCoordinates clickLocation, bool canReach) { var afterInteractEvent = new AfterInteractEvent(user, used, target, clickLocation, canReach); - RaiseLocalEvent(used.Uid, afterInteractEvent, false); + RaiseLocalEvent(used, afterInteractEvent, false); if (afterInteractEvent.Handled) return true; var afterInteractEventArgs = new AfterInteractEventArgs(user, clickLocation, target, canReach); - var afterInteracts = used.GetAllComponents().OrderByDescending(x => x.Priority).ToList(); + var afterInteracts = EntityManager.GetComponents(used).OrderByDescending(x => x.Priority).ToList(); foreach (var afterInteract in afterInteracts) { @@ -430,17 +431,17 @@ namespace Content.Shared.Interaction /// Activates the IActivate behavior of an object /// Verifies that the user is capable of doing the use interaction first /// - public void TryInteractionActivate(IEntity? user, IEntity? used) + public void TryInteractionActivate(EntityUid? user, EntityUid? used) { if (user == null || used == null) return; - InteractionActivate(user, used); + InteractionActivate(user.Value, used.Value); } - protected void InteractionActivate(IEntity user, IEntity used) + protected void InteractionActivate(EntityUid user, EntityUid used) { - if (used.TryGetComponent(out var delayComponent)) + if (EntityManager.TryGetComponent(used, out var delayComponent)) { if (delayComponent.ActiveDelay) return; @@ -448,7 +449,7 @@ namespace Content.Shared.Interaction delayComponent.BeginDelay(); } - if (!_actionBlockerSystem.CanInteract(user.Uid) || !_actionBlockerSystem.CanUse(user.Uid)) + if (!_actionBlockerSystem.CanInteract(user) || !_actionBlockerSystem.CanUse(user)) return; // all activates should only fire when in range / unobstructed @@ -457,18 +458,18 @@ namespace Content.Shared.Interaction // Check if interacted entity is in the same container, the direct child, or direct parent of the user. // This is bypassed IF the interaction happened through an item slot (e.g., backpack UI) - if (!user.IsInSameOrParentContainer(used) && !CanAccessViaStorage(user.Uid, used.Uid)) + if (!user.IsInSameOrParentContainer(used) && !CanAccessViaStorage(user, used)) return; var activateMsg = new ActivateInWorldEvent(user, used); - RaiseLocalEvent(used.Uid, activateMsg); + RaiseLocalEvent(used, activateMsg); if (activateMsg.Handled) { _adminLogSystem.Add(LogType.InteractActivate, LogImpact.Low, $"{user} activated {used}"); return; } - if (!used.TryGetComponent(out IActivate? activateComp)) + if (!EntityManager.TryGetComponent(used, out IActivate? activateComp)) return; var activateEventArgs = new ActivateEventArgs(user, used); @@ -485,9 +486,9 @@ namespace Content.Shared.Interaction /// /// /// - public void TryUseInteraction(IEntity user, IEntity used, bool altInteract = false) + public void TryUseInteraction(EntityUid user, EntityUid used, bool altInteract = false) { - if (user != null && used != null && _actionBlockerSystem.CanUse(user.Uid)) + if (user != null && used != null && _actionBlockerSystem.CanUse(user)) { if (altInteract) AltInteract(user, used); @@ -500,9 +501,9 @@ namespace Content.Shared.Interaction /// Activates the IUse behaviors of an entity without first checking /// if the user is capable of doing the use interaction. /// - public void UseInteraction(IEntity user, IEntity used) + public void UseInteraction(EntityUid user, EntityUid used) { - if (used.TryGetComponent(out var delayComponent)) + if (EntityManager.TryGetComponent(used, out var delayComponent)) { if (delayComponent.ActiveDelay) return; @@ -511,11 +512,11 @@ namespace Content.Shared.Interaction } var useMsg = new UseInHandEvent(user, used); - RaiseLocalEvent(used.Uid, useMsg); + RaiseLocalEvent(used, useMsg); if (useMsg.Handled) return; - var uses = used.GetAllComponents().ToList(); + var uses = EntityManager.GetComponents(used).ToList(); // Try to use item on any components which have the interface foreach (var use in uses) @@ -532,12 +533,12 @@ namespace Content.Shared.Interaction /// /// Uses the context menu verb list, and acts out the highest priority alternative interaction verb. /// - public void AltInteract(IEntity user, IEntity target) + public void AltInteract(EntityUid user, EntityUid target) { // Get list of alt-interact verbs var verbs = _verbSystem.GetLocalVerbs(target, user, VerbType.Alternative)[VerbType.Alternative]; if (verbs.Any()) - _verbSystem.ExecuteVerb(verbs.First(), user.Uid, target.Uid); + _verbSystem.ExecuteVerb(verbs.First(), user, target); } #endregion @@ -546,17 +547,17 @@ namespace Content.Shared.Interaction /// Calls Thrown on all components that implement the IThrown interface /// on an entity that has been thrown. /// - public void ThrownInteraction(IEntity user, IEntity thrown) + public void ThrownInteraction(EntityUid user, EntityUid thrown) { var throwMsg = new ThrownEvent(user, thrown); - RaiseLocalEvent(thrown.Uid, throwMsg); + RaiseLocalEvent(thrown, throwMsg); if (throwMsg.Handled) { _adminLogSystem.Add(LogType.Throw, LogImpact.Low,$"{user} threw {thrown}"); return; } - var comps = thrown.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(thrown).ToList(); var args = new ThrownEventArgs(user); // Call Thrown on all components that implement the interface @@ -573,14 +574,14 @@ namespace Content.Shared.Interaction /// Calls Equipped on all components that implement the IEquipped interface /// on an entity that has been equipped. /// - public void EquippedInteraction(IEntity user, IEntity equipped, EquipmentSlotDefines.Slots slot) + public void EquippedInteraction(EntityUid user, EntityUid equipped, EquipmentSlotDefines.Slots slot) { var equipMsg = new EquippedEvent(user, equipped, slot); - RaiseLocalEvent(equipped.Uid, equipMsg); + RaiseLocalEvent(equipped, equipMsg); if (equipMsg.Handled) return; - var comps = equipped.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(equipped).ToList(); // Call Thrown on all components that implement the interface foreach (var comp in comps) @@ -593,14 +594,14 @@ namespace Content.Shared.Interaction /// Calls Unequipped on all components that implement the IUnequipped interface /// on an entity that has been equipped. /// - public void UnequippedInteraction(IEntity user, IEntity equipped, EquipmentSlotDefines.Slots slot) + public void UnequippedInteraction(EntityUid user, EntityUid equipped, EquipmentSlotDefines.Slots slot) { var unequipMsg = new UnequippedEvent(user, equipped, slot); - RaiseLocalEvent(equipped.Uid, unequipMsg); + RaiseLocalEvent(equipped, unequipMsg); if (unequipMsg.Handled) return; - var comps = equipped.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(equipped).ToList(); // Call Thrown on all components that implement the interface foreach (var comp in comps) @@ -614,14 +615,14 @@ namespace Content.Shared.Interaction /// Calls EquippedHand on all components that implement the IEquippedHand interface /// on an item. /// - public void EquippedHandInteraction(IEntity user, IEntity item, HandState hand) + public void EquippedHandInteraction(EntityUid user, EntityUid item, HandState hand) { var equippedHandMessage = new EquippedHandEvent(user, item, hand); - RaiseLocalEvent(item.Uid, equippedHandMessage); + RaiseLocalEvent(item, equippedHandMessage); if (equippedHandMessage.Handled) return; - var comps = item.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(item).ToList(); foreach (var comp in comps) { @@ -633,14 +634,14 @@ namespace Content.Shared.Interaction /// Calls UnequippedHand on all components that implement the IUnequippedHand interface /// on an item. /// - public void UnequippedHandInteraction(IEntity user, IEntity item, HandState hand) + public void UnequippedHandInteraction(EntityUid user, EntityUid item, HandState hand) { var unequippedHandMessage = new UnequippedHandEvent(user, item, hand); - RaiseLocalEvent(item.Uid, unequippedHandMessage); + RaiseLocalEvent(item, unequippedHandMessage); if (unequippedHandMessage.Handled) return; - var comps = item.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(item).ToList(); foreach (var comp in comps) { @@ -655,9 +656,9 @@ namespace Content.Shared.Interaction /// Activates the Dropped behavior of an object /// Verifies that the user is capable of doing the drop interaction first /// - public bool TryDroppedInteraction(IEntity user, IEntity item) + public bool TryDroppedInteraction(EntityUid user, EntityUid item) { - if (user == null || item == null || !_actionBlockerSystem.CanDrop(user.Uid)) return false; + if (user == null || item == null || !_actionBlockerSystem.CanDrop(user)) return false; DroppedInteraction(user, item); return true; @@ -667,19 +668,19 @@ namespace Content.Shared.Interaction /// Calls Dropped on all components that implement the IDropped interface /// on an entity that has been dropped. /// - public void DroppedInteraction(IEntity user, IEntity item) + public void DroppedInteraction(EntityUid user, EntityUid item) { - var dropMsg = new DroppedEvent(user.Uid, item.Uid); - RaiseLocalEvent(item.Uid, dropMsg); + var dropMsg = new DroppedEvent(user, item); + RaiseLocalEvent(item, dropMsg); if (dropMsg.Handled) { _adminLogSystem.Add(LogType.Drop, LogImpact.Low, $"{user} dropped {item}"); return; } - item.Transform.LocalRotation = Angle.Zero; + EntityManager.GetComponent(item).LocalRotation = Angle.Zero; - var comps = item.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(item).ToList(); // Call Land on all components that implement the interface foreach (var comp in comps) @@ -695,14 +696,14 @@ namespace Content.Shared.Interaction /// Calls HandSelected on all components that implement the IHandSelected interface /// on an item entity on a hand that has just been selected. /// - public void HandSelectedInteraction(IEntity user, IEntity item) + public void HandSelectedInteraction(EntityUid user, EntityUid item) { var handSelectedMsg = new HandSelectedEvent(user, item); - RaiseLocalEvent(item.Uid, handSelectedMsg); + RaiseLocalEvent(item, handSelectedMsg); if (handSelectedMsg.Handled) return; - var comps = item.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(item).ToList(); // Call Land on all components that implement the interface foreach (var comp in comps) @@ -715,14 +716,14 @@ namespace Content.Shared.Interaction /// Calls HandDeselected on all components that implement the IHandDeselected interface /// on an item entity on a hand that has just been deselected. /// - public void HandDeselectedInteraction(IEntity user, IEntity item) + public void HandDeselectedInteraction(EntityUid user, EntityUid item) { var handDeselectedMsg = new HandDeselectedEvent(user, item); - RaiseLocalEvent(item.Uid, handDeselectedMsg); + RaiseLocalEvent(item, handDeselectedMsg); if (handDeselectedMsg.Handled) return; - var comps = item.GetAllComponents().ToList(); + var comps = EntityManager.GetComponents(item).ToList(); // Call Land on all components that implement the interface foreach (var comp in comps) diff --git a/Content.Shared/Inventory/IEquipped.cs b/Content.Shared/Inventory/IEquipped.cs index 9021190108..b8e3bad7f7 100644 --- a/Content.Shared/Inventory/IEquipped.cs +++ b/Content.Shared/Inventory/IEquipped.cs @@ -23,9 +23,9 @@ namespace Content.Shared.Inventory public abstract class UserEventArgs : EventArgs { - public IEntity User { get; } + public EntityUid User { get; } - protected UserEventArgs(IEntity user) + protected UserEventArgs(EntityUid user) { User = user; } @@ -33,7 +33,7 @@ namespace Content.Shared.Inventory public class EquippedEventArgs : UserEventArgs { - public EquippedEventArgs(IEntity user, EquipmentSlotDefines.Slots slot) : base(user) + public EquippedEventArgs(EntityUid user, EquipmentSlotDefines.Slots slot) : base(user) { Slot = slot; } @@ -50,19 +50,19 @@ namespace Content.Shared.Inventory /// /// Entity that equipped the item. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Item that was equipped. /// - public IEntity Equipped { get; } + public EntityUid Equipped { get; } /// /// Slot that the item was placed into. /// public EquipmentSlotDefines.Slots Slot { get; } - public EquippedEvent(IEntity user, IEntity equipped, EquipmentSlotDefines.Slots slot) + public EquippedEvent(EntityUid user, EntityUid equipped, EquipmentSlotDefines.Slots slot) { User = user; Equipped = equipped; diff --git a/Content.Shared/Inventory/IUnequipped.cs b/Content.Shared/Inventory/IUnequipped.cs index 2a3985231e..5981ca1dd2 100644 --- a/Content.Shared/Inventory/IUnequipped.cs +++ b/Content.Shared/Inventory/IUnequipped.cs @@ -23,7 +23,7 @@ namespace Content.Shared.Inventory public class UnequippedEventArgs : UserEventArgs { - public UnequippedEventArgs(IEntity user, EquipmentSlotDefines.Slots slot) : base(user) + public UnequippedEventArgs(EntityUid user, EquipmentSlotDefines.Slots slot) : base(user) { Slot = slot; } @@ -40,19 +40,19 @@ namespace Content.Shared.Inventory /// /// Entity that equipped the item. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Item that was unequipped. /// - public IEntity Unequipped { get; } + public EntityUid Unequipped { get; } /// /// Slot that the item was removed from. /// public EquipmentSlotDefines.Slots Slot { get; } - public UnequippedEvent(IEntity user, IEntity unequipped, EquipmentSlotDefines.Slots slot) + public UnequippedEvent(EntityUid user, EntityUid unequipped, EquipmentSlotDefines.Slots slot) { User = user; Unequipped = unequipped; diff --git a/Content.Shared/Inventory/SharedInventoryComponent.cs b/Content.Shared/Inventory/SharedInventoryComponent.cs index 27733bb097..a49a2018d5 100644 --- a/Content.Shared/Inventory/SharedInventoryComponent.cs +++ b/Content.Shared/Inventory/SharedInventoryComponent.cs @@ -44,7 +44,7 @@ namespace Content.Shared.Inventory /// true if the item is equipped to an equip slot (NOT inside an equipped container /// like inside a backpack) - public abstract bool IsEquipped(IEntity item); + public abstract bool IsEquipped(EntityUid item); [Serializable, NetSerializable] protected class InventoryComponentState : ComponentState diff --git a/Content.Shared/Item/SharedItemComponent.cs b/Content.Shared/Item/SharedItemComponent.cs index a4ca8fe165..bd86f8e983 100644 --- a/Content.Shared/Item/SharedItemComponent.cs +++ b/Content.Shared/Item/SharedItemComponent.cs @@ -6,6 +6,7 @@ using Content.Shared.Interaction.Helpers; using Content.Shared.Inventory; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Players; @@ -21,6 +22,8 @@ namespace Content.Shared.Item [NetworkedComponent()] public abstract class SharedItemComponent : Component, IEquipped, IUnequipped, IInteractHand { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Item"; /// @@ -109,15 +112,15 @@ namespace Content.Shared.Item /// /// If a player can pick up this item. /// - public bool CanPickup(IEntity user, bool popup = true) + public bool CanPickup(EntityUid user, bool popup = true) { - if (!EntitySystem.Get().CanPickup(user.Uid)) + if (!EntitySystem.Get().CanPickup(user)) return false; - if (user.Transform.MapID != Owner.Transform.MapID) + if (_entMan.GetComponent(user).MapID != _entMan.GetComponent(Owner).MapID) return false; - if (!Owner.TryGetComponent(out IPhysBody? physics) || physics.BodyType == BodyType.Static) + if (!_entMan.TryGetComponent(Owner, out IPhysBody? physics) || physics.BodyType == BodyType.Static) return false; return user.InRangeUnobstructed(Owner, ignoreInsideBlocker: true, popup: popup); @@ -140,7 +143,7 @@ namespace Content.Shared.Item if (!CanPickup(user)) return false; - if (!user.TryGetComponent(out SharedHandsComponent? hands)) + if (!_entMan.TryGetComponent(user, out SharedHandsComponent? hands)) return false; var activeHand = hands.ActiveHand; diff --git a/Content.Shared/Kitchen/Components/SharedKitchenSpikeComponent.cs b/Content.Shared/Kitchen/Components/SharedKitchenSpikeComponent.cs index 3649fdf8c9..283eb976e2 100644 --- a/Content.Shared/Kitchen/Components/SharedKitchenSpikeComponent.cs +++ b/Content.Shared/Kitchen/Components/SharedKitchenSpikeComponent.cs @@ -3,6 +3,7 @@ using Content.Shared.DragDrop; using Content.Shared.Nutrition.Components; using Content.Shared.Sound; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -23,7 +24,7 @@ namespace Content.Shared.Kitchen.Components bool IDragDropOn.CanDragDropOn(DragDropEvent eventArgs) { - if (!eventArgs.Dragged.HasComponent()) + if (!IoCManager.Resolve().HasComponent(eventArgs.Dragged)) { return false; } diff --git a/Content.Shared/Lathe/SharedLatheComponent.cs b/Content.Shared/Lathe/SharedLatheComponent.cs index ee1dc79546..e8a428b078 100644 --- a/Content.Shared/Lathe/SharedLatheComponent.cs +++ b/Content.Shared/Lathe/SharedLatheComponent.cs @@ -12,14 +12,15 @@ namespace Content.Shared.Lathe [NetworkedComponent()] public class SharedLatheComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; [Dependency] protected readonly IPrototypeManager PrototypeManager = default!; public override string Name => "Lathe"; public bool CanProduce(LatheRecipePrototype recipe, int quantity = 1) { - if (!Owner.TryGetComponent(out SharedMaterialStorageComponent? storage) - || !Owner.TryGetComponent(out SharedLatheDatabaseComponent? database)) return false; + if (!_entMan.TryGetComponent(Owner, out SharedMaterialStorageComponent? storage) + || !_entMan.TryGetComponent(Owner, out SharedLatheDatabaseComponent? database)) return false; if (!database.Contains(recipe)) return false; diff --git a/Content.Shared/Maps/TurfHelpers.cs b/Content.Shared/Maps/TurfHelpers.cs index 092766ddc4..36ac9ea839 100644 --- a/Content.Shared/Maps/TurfHelpers.cs +++ b/Content.Shared/Maps/TurfHelpers.cs @@ -148,7 +148,7 @@ namespace Content.Shared.Maps //Actually spawn the relevant tile item at the right position and give it some random offset. var tileItem = entityManager.SpawnEntity(tileDef.ItemDropPrototypeName, indices.ToEntityCoordinates(tileRef.GridIndex, mapManager).Offset(new Vector2(x, y))); - entityManager.GetComponent(tileItem.Uid).LocalRotation = robustRandom.NextDouble() * Math.Tau; + entityManager.GetComponent(tileItem).LocalRotation = robustRandom.NextDouble() * Math.Tau; return true; } @@ -157,12 +157,12 @@ namespace Content.Shared.Maps /// Helper that returns all entities in a turf. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable GetEntitiesInTile(this TileRef turf, LookupFlags flags = LookupFlags.IncludeAnchored, IEntityLookup? lookupSystem = null) + public static IEnumerable GetEntitiesInTile(this TileRef turf, LookupFlags flags = LookupFlags.IncludeAnchored, IEntityLookup? lookupSystem = null) { lookupSystem ??= IoCManager.Resolve(); if (!GetWorldTileBox(turf, out var worldBox)) - return Enumerable.Empty(); + return Enumerable.Empty(); return lookupSystem.GetEntitiesIntersecting(turf.MapIndex, worldBox, flags); } @@ -170,12 +170,12 @@ namespace Content.Shared.Maps /// /// Helper that returns all entities in a turf. /// - public static IEnumerable GetEntitiesInTile(this EntityCoordinates coordinates, LookupFlags flags = LookupFlags.IncludeAnchored, IEntityLookup? lookupSystem = null) + public static IEnumerable GetEntitiesInTile(this EntityCoordinates coordinates, LookupFlags flags = LookupFlags.IncludeAnchored, IEntityLookup? lookupSystem = null) { var turf = coordinates.GetTileRef(); if (turf == null) - return Enumerable.Empty(); + return Enumerable.Empty(); return GetEntitiesInTile(turf.Value, flags, lookupSystem); } @@ -183,7 +183,7 @@ namespace Content.Shared.Maps /// /// Helper that returns all entities in a turf. /// - public static IEnumerable GetEntitiesInTile(this Vector2i indices, GridId gridId, LookupFlags flags = LookupFlags.IncludeAnchored, IEntityLookup? lookupSystem = null) + public static IEnumerable GetEntitiesInTile(this Vector2i indices, GridId gridId, LookupFlags flags = LookupFlags.IncludeAnchored, IEntityLookup? lookupSystem = null) { return GetEntitiesInTile(indices.GetTileRef(gridId), flags, lookupSystem); } diff --git a/Content.Shared/MedicalScanner/SharedMedicalScannerComponent.cs b/Content.Shared/MedicalScanner/SharedMedicalScannerComponent.cs index e3621fb936..ac80a583a4 100644 --- a/Content.Shared/MedicalScanner/SharedMedicalScannerComponent.cs +++ b/Content.Shared/MedicalScanner/SharedMedicalScannerComponent.cs @@ -5,6 +5,7 @@ using Content.Shared.Damage; using Content.Shared.DragDrop; using Content.Shared.FixedPoint; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; namespace Content.Shared.MedicalScanner @@ -78,9 +79,9 @@ namespace Content.Shared.MedicalScanner } } - public bool CanInsert(IEntity entity) + public bool CanInsert(EntityUid entity) { - return entity.HasComponent(); + return IoCManager.Resolve().HasComponent(entity); } bool IDragDropOn.CanDragDropOn(DragDropEvent eventArgs) diff --git a/Content.Shared/MobState/Components/MobStateComponent.cs b/Content.Shared/MobState/Components/MobStateComponent.cs index bf2d29a541..697849abe5 100644 --- a/Content.Shared/MobState/Components/MobStateComponent.cs +++ b/Content.Shared/MobState/Components/MobStateComponent.cs @@ -8,6 +8,7 @@ using Content.Shared.FixedPoint; using Content.Shared.MobState.State; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Players; using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; @@ -25,6 +26,8 @@ namespace Content.Shared.MobState.Components [NetworkedComponent] public class MobStateComponent : Component { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "MobState"; /// @@ -59,13 +62,13 @@ namespace Content.Shared.MobState.Components else { // Initialize with some amount of damage, defaulting to 0. - UpdateState(Owner.GetComponentOrNull()?.TotalDamage ?? FixedPoint2.Zero); + UpdateState(_entMan.GetComponentOrNull(Owner)?.TotalDamage ?? FixedPoint2.Zero); } } protected override void OnRemove() { - if (Owner.TryGetComponent(out SharedAlertsComponent? status)) + if (_entMan.TryGetComponent(Owner, out SharedAlertsComponent? status)) { status.ClearAlert(AlertType.HumanHealth); } @@ -288,9 +291,11 @@ namespace Content.Shared.MobState.Components /// private void SetMobState(IMobState? old, (IMobState state, FixedPoint2 threshold)? current) { + var entMan = _entMan; + if (!current.HasValue) { - old?.ExitState(OwnerUid, Owner.EntityManager); + old?.ExitState(Owner, entMan); return; } @@ -300,19 +305,19 @@ namespace Content.Shared.MobState.Components if (state == old) { - state.UpdateState(OwnerUid, threshold, Owner.EntityManager); + state.UpdateState(Owner, threshold, entMan); return; } - old?.ExitState(OwnerUid, Owner.EntityManager); + old?.ExitState(Owner, entMan); CurrentState = state; - state.EnterState(OwnerUid, Owner.EntityManager); - state.UpdateState(OwnerUid, threshold, Owner.EntityManager); + state.EnterState(Owner, entMan); + state.UpdateState(Owner, threshold, entMan); var message = new MobStateChangedEvent(this, old, state); - Owner.EntityManager.EventBus.RaiseLocalEvent(OwnerUid, message); + entMan.EventBus.RaiseLocalEvent(Owner, message); Dirty(); } diff --git a/Content.Shared/MobState/DamageStateVisuals.cs b/Content.Shared/MobState/DamageStateVisuals.cs index a7628bbfc8..e332921ada 100644 --- a/Content.Shared/MobState/DamageStateVisuals.cs +++ b/Content.Shared/MobState/DamageStateVisuals.cs @@ -11,7 +11,7 @@ namespace Content.Shared.MobState } /// - /// Defines what state an is in. + /// Defines what state an is in. /// /// Ordered from most alive to least alive. /// To enumerate them in this way see diff --git a/Content.Shared/MobState/MobStateChangedEvent.cs b/Content.Shared/MobState/MobStateChangedEvent.cs index a862e98cd3..8fcb40b1fc 100644 --- a/Content.Shared/MobState/MobStateChangedEvent.cs +++ b/Content.Shared/MobState/MobStateChangedEvent.cs @@ -16,7 +16,7 @@ namespace Content.Shared.MobState CurrentMobState = currentMobState; } - public IEntity Entity => Component.Owner; + public EntityUid Entity => Component.Owner; public MobStateComponent Component { get; } diff --git a/Content.Shared/Movement/Components/MovementIgnoreGravityComponent.cs b/Content.Shared/Movement/Components/MovementIgnoreGravityComponent.cs index 4fb57b6736..74f54aeeab 100644 --- a/Content.Shared/Movement/Components/MovementIgnoreGravityComponent.cs +++ b/Content.Shared/Movement/Components/MovementIgnoreGravityComponent.cs @@ -14,15 +14,17 @@ namespace Content.Shared.Movement.Components public static class GravityExtensions { - public static bool IsWeightless(this IEntity entity, PhysicsComponent? body = null, EntityCoordinates? coords = null, IMapManager? mapManager = null, IEntityManager? entityManager = null) + public static bool IsWeightless(this EntityUid entity, PhysicsComponent? body = null, EntityCoordinates? coords = null, IMapManager? mapManager = null, IEntityManager? entityManager = null) { - if (body == null) - entity.TryGetComponent(out body); + entityManager ??= IoCManager.Resolve(); - if (entity.HasComponent() || + if (body == null) + entityManager.TryGetComponent(entity, out body); + + if (entityManager.HasComponent(entity) || (body?.BodyType & (BodyType.Static | BodyType.Kinematic)) != 0) return false; - var transform = entity.Transform; + var transform = entityManager.GetComponent(entity); var gridId = transform.GridID; if (!gridId.IsValid()) @@ -34,18 +36,15 @@ namespace Content.Shared.Movement.Components mapManager ??= IoCManager.Resolve(); var grid = mapManager.GetGrid(gridId); - var gridEntityId = grid.GridEntityId; - entityManager ??= IoCManager.Resolve(); - var gridEntity = entityManager.GetEntity(gridEntityId); - if (!gridEntity.GetComponent().Enabled) + if (!entityManager.GetComponent(grid.GridEntityId).Enabled) { return true; } coords ??= transform.Coordinates; - if (!coords.Value.IsValid(entity.EntityManager)) + if (!coords.Value.IsValid(entityManager)) { return true; } diff --git a/Content.Shared/Movement/Components/SharedPlayerInputMoverComponent.cs b/Content.Shared/Movement/Components/SharedPlayerInputMoverComponent.cs index 88137fd73d..8dfdd9aaf6 100644 --- a/Content.Shared/Movement/Components/SharedPlayerInputMoverComponent.cs +++ b/Content.Shared/Movement/Components/SharedPlayerInputMoverComponent.cs @@ -119,7 +119,7 @@ namespace Content.Shared.Movement.Components { base.Initialize(); Owner.EnsureComponentWarn(); - LastGridAngle = Owner.Transform.Parent?.WorldRotation ?? new Angle(0); + LastGridAngle = IoCManager.Resolve().GetComponent(Owner).Parent?.WorldRotation ?? new Angle(0); } /// diff --git a/Content.Shared/Movement/Components/SharedPlayerMobMoverComponent.cs b/Content.Shared/Movement/Components/SharedPlayerMobMoverComponent.cs index 98c0952651..6129fad4c0 100644 --- a/Content.Shared/Movement/Components/SharedPlayerMobMoverComponent.cs +++ b/Content.Shared/Movement/Components/SharedPlayerMobMoverComponent.cs @@ -1,6 +1,7 @@ using System; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Players; @@ -85,7 +86,7 @@ namespace Content.Shared.Movement.Components protected override void Initialize() { base.Initialize(); - if (!Owner.HasComponent()) + if (!IoCManager.Resolve().HasComponent(Owner)) { Owner.EnsureComponentWarn(); } diff --git a/Content.Shared/Movement/EntitySystems/SharedMobMoverSystem.cs b/Content.Shared/Movement/EntitySystems/SharedMobMoverSystem.cs index ea7654ce99..389df8402a 100644 --- a/Content.Shared/Movement/EntitySystems/SharedMobMoverSystem.cs +++ b/Content.Shared/Movement/EntitySystems/SharedMobMoverSystem.cs @@ -43,7 +43,7 @@ namespace Content.Shared.Movement.EntitySystems if (otherBody.BodyType != BodyType.Dynamic || !otherFixture.Hard) return; - if (!ourFixture.Body.Owner.TryGetComponent(out IMobMoverComponent? mobMover) || worldNormal == Vector2.Zero) return; + if (!EntityManager.TryGetComponent(ourFixture.Body.Owner, out IMobMoverComponent? mobMover) || worldNormal == Vector2.Zero) return; otherBody.ApplyLinearImpulse(-worldNormal * mobMover.PushStrength * frameTime); } diff --git a/Content.Shared/Movement/EntitySystems/SharedMoverSystem.cs b/Content.Shared/Movement/EntitySystems/SharedMoverSystem.cs index 6851f41d9b..9012abdc7e 100644 --- a/Content.Shared/Movement/EntitySystems/SharedMoverSystem.cs +++ b/Content.Shared/Movement/EntitySystems/SharedMoverSystem.cs @@ -5,6 +5,7 @@ using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Input; using Robust.Shared.Input.Binding; +using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Players; @@ -49,15 +50,15 @@ namespace Content.Shared.Movement.EntitySystems if (owner != null && session != null) { - EntityManager.EventBus.RaiseLocalEvent(owner.Uid, new RelayMoveInputEvent(session)); + EntityManager.EventBus.RaiseLocalEvent(owner.Value, new RelayMoveInputEvent(session)); // For stuff like "Moving out of locker" or the likes - if (owner.IsInContainer() && - (!owner.TryGetComponent(out MobStateComponent? mobState) || + if (owner.Value.IsInContainer() && + (!EntityManager.TryGetComponent(owner.Value, out MobStateComponent? mobState) || mobState.IsAlive())) { - var relayMoveEvent = new RelayMovementEntityEvent(owner); - owner.EntityManager.EventBus.RaiseLocalEvent(owner.Transform.ParentUid, relayMoveEvent); + var relayMoveEvent = new RelayMovementEntityEvent(owner.Value); + EntityManager.EventBus.RaiseLocalEvent(EntityManager.GetComponent(owner.Value).ParentUid, relayMoveEvent); } } @@ -81,10 +82,12 @@ namespace Content.Shared.Movement.EntitySystems var ent = session?.AttachedEntity; - if (ent == null || !ent.IsValid()) + var entMan = IoCManager.Resolve(); + + if (ent == null || !entMan.EntityExists(ent.Value)) return false; - if (!ent.TryGetComponent(out T? comp)) + if (!entMan.TryGetComponent(ent.Value, out T? comp)) return false; component = comp; diff --git a/Content.Shared/Movement/EntitySystems/SlowContactsSystem.cs b/Content.Shared/Movement/EntitySystems/SlowContactsSystem.cs index 93c065dec4..667f91b67e 100644 --- a/Content.Shared/Movement/EntitySystems/SlowContactsSystem.cs +++ b/Content.Shared/Movement/EntitySystems/SlowContactsSystem.cs @@ -36,7 +36,7 @@ public class SlowContactsSystem : EntitySystem foreach (var colliding in _physics.GetCollidingEntities(physicsComponent)) { - var ent = colliding.OwnerUid; + var ent = colliding.Owner; if (!EntityManager.TryGetComponent(ent, out var slowContactsComponent)) continue; @@ -49,7 +49,7 @@ public class SlowContactsSystem : EntitySystem private void OnEntityExit(EntityUid uid, SlowContactsComponent component, EndCollideEvent args) { - var otherUid = args.OtherFixture.Body.OwnerUid; + var otherUid = args.OtherFixture.Body.Owner; if (!EntityManager.HasComponent(otherUid) || !EntityManager.HasComponent(otherUid)) return; @@ -64,7 +64,7 @@ public class SlowContactsSystem : EntitySystem private void OnEntityEnter(EntityUid uid, SlowContactsComponent component, StartCollideEvent args) { - var otherUid = args.OtherFixture.Body.OwnerUid; + var otherUid = args.OtherFixture.Body.Owner; if (!EntityManager.HasComponent(otherUid)) return; if (!_statusCapableInContact.ContainsKey(otherUid)) diff --git a/Content.Shared/Movement/RelayMovementEntityEvent.cs b/Content.Shared/Movement/RelayMovementEntityEvent.cs index 79021d816f..ad8609aaf3 100644 --- a/Content.Shared/Movement/RelayMovementEntityEvent.cs +++ b/Content.Shared/Movement/RelayMovementEntityEvent.cs @@ -4,9 +4,9 @@ namespace Content.Shared.Movement { public sealed class RelayMovementEntityEvent : EntityEventArgs { - public IEntity Entity { get; } + public EntityUid Entity { get; } - public RelayMovementEntityEvent(IEntity entity) + public RelayMovementEntityEvent(EntityUid entity) { Entity = entity; } diff --git a/Content.Shared/Movement/SharedMoverController.cs b/Content.Shared/Movement/SharedMoverController.cs index 13e71a3f9f..363f8a19d0 100644 --- a/Content.Shared/Movement/SharedMoverController.cs +++ b/Content.Shared/Movement/SharedMoverController.cs @@ -67,7 +67,7 @@ namespace Content.Shared.Movement { var (walkDir, sprintDir) = mover.VelocityDir; - var transform = mover.Owner.Transform; + var transform = EntityManager.GetComponent(mover.Owner); var parentRotation = transform.Parent!.WorldRotation; // Regular movement. @@ -96,16 +96,16 @@ namespace Content.Shared.Movement protected void HandleMobMovement(IMoverComponent mover, PhysicsComponent physicsComponent, IMobMoverComponent mobMover) { - DebugTools.Assert(!UsedMobMovement.ContainsKey(mover.OwnerUid)); + DebugTools.Assert(!UsedMobMovement.ContainsKey(mover.Owner)); if (!UseMobMovement(physicsComponent)) { - UsedMobMovement[mover.OwnerUid] = false; + UsedMobMovement[mover.Owner] = false; return; } - UsedMobMovement[mover.OwnerUid] = true; - var transform = mover.Owner.Transform; + UsedMobMovement[mover.Owner] = true; + var transform = EntityManager.GetComponent(mover.Owner); var weightless = mover.Owner.IsWeightless(physicsComponent, mapManager: _mapManager, entityManager: _entityManager); var (walkDir, sprintDir) = mover.VelocityDir; @@ -164,10 +164,10 @@ namespace Content.Shared.Movement protected bool UseMobMovement(PhysicsComponent body) { return body.BodyStatus == BodyStatus.OnGround && - body.Owner.HasComponent() && + EntityManager.HasComponent(body.Owner) && // If we're being pulled then don't mess with our velocity. - (!body.Owner.TryGetComponent(out SharedPullableComponent? pullable) || !pullable.BeingPulled) && - _blocker.CanMove(body.OwnerUid); + (!EntityManager.TryGetComponent(body.Owner, out SharedPullableComponent? pullable) || !pullable.BeingPulled) && + _blocker.CanMove((body).Owner); } /// @@ -186,7 +186,7 @@ namespace Content.Shared.Movement !otherCollider.CanCollide || ((collider.CollisionMask & otherCollider.CollisionLayer) == 0 && (otherCollider.CollisionMask & collider.CollisionLayer) == 0) || - (otherCollider.Owner.TryGetComponent(out SharedPullableComponent? pullable) && pullable.BeingPulled)) + (IoCManager.Resolve().TryGetComponent(otherCollider.Owner, out SharedPullableComponent? pullable) && pullable.BeingPulled)) { continue; } diff --git a/Content.Shared/Nutrition/EntitySystems/SharedCreamPieSystem.cs b/Content.Shared/Nutrition/EntitySystems/SharedCreamPieSystem.cs index 11efae555c..d0e7149778 100644 --- a/Content.Shared/Nutrition/EntitySystems/SharedCreamPieSystem.cs +++ b/Content.Shared/Nutrition/EntitySystems/SharedCreamPieSystem.cs @@ -62,7 +62,7 @@ namespace Content.Shared.Nutrition.EntitySystems private void OnCreamPiedHitBy(EntityUid uid, CreamPiedComponent creamPied, ThrowHitByEvent args) { - if (args.Thrown.Deleted || !args.Thrown.TryGetComponent(out CreamPieComponent? creamPie)) return; + if (!EntityManager.EntityExists(args.Thrown) || !EntityManager.TryGetComponent(args.Thrown, out CreamPieComponent? creamPie)) return; SetCreamPied(uid, creamPied, true); diff --git a/Content.Shared/Placeable/PlaceableSurfaceSystem.cs b/Content.Shared/Placeable/PlaceableSurfaceSystem.cs index 322b897735..aa1b174ccb 100644 --- a/Content.Shared/Placeable/PlaceableSurfaceSystem.cs +++ b/Content.Shared/Placeable/PlaceableSurfaceSystem.cs @@ -2,6 +2,7 @@ using Content.Shared.Hands.Components; using Content.Shared.Interaction; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Shared.Placeable @@ -51,19 +52,19 @@ namespace Content.Shared.Placeable if (!surface.IsPlaceable) return; - if(!args.User.TryGetComponent(out var handComponent)) + if(!EntityManager.TryGetComponent(args.User, out var handComponent)) return; - if (!args.ClickLocation.IsValid(args.User.EntityManager)) + if (!args.ClickLocation.IsValid(EntityManager)) return; - if(!handComponent.TryDropEntity(args.Used, surface.Owner.Transform.Coordinates)) + if(!handComponent.TryDropEntity(args.Used, EntityManager.GetComponent(surface.Owner).Coordinates)) return; if (surface.PlaceCentered) - args.Used.Transform.LocalPosition = args.Target.Transform.LocalPosition + surface.PositionOffset; + EntityManager.GetComponent(args.Used).LocalPosition = EntityManager.GetComponent(args.Target).LocalPosition + surface.PositionOffset; else - args.Used.Transform.Coordinates = args.ClickLocation; + EntityManager.GetComponent(args.Used).Coordinates = args.ClickLocation; args.Handled = true; } diff --git a/Content.Shared/Popups/SharedPopupExtensions.cs b/Content.Shared/Popups/SharedPopupExtensions.cs index ae3d9fde27..26cec77eda 100644 --- a/Content.Shared/Popups/SharedPopupExtensions.cs +++ b/Content.Shared/Popups/SharedPopupExtensions.cs @@ -13,11 +13,11 @@ namespace Content.Shared.Popups /// The entity above which the message will appear. /// The entity that will see the message. /// The message to show. - public static void PopupMessage(this IEntity source, IEntity viewer, string message) + public static void PopupMessage(this EntityUid source, EntityUid viewer, string message) { var popupSystem = EntitySystem.Get(); - popupSystem.PopupEntity(message, source.Uid, Filter.Entities(viewer.Uid)); + popupSystem.PopupEntity(message, source, Filter.Entities(viewer)); } /// @@ -25,7 +25,7 @@ namespace Content.Shared.Popups /// /// The entity that will see the message. /// The message to be seen. - public static void PopupMessage(this IEntity viewer, string message) + public static void PopupMessage(this EntityUid viewer, string message) { viewer.PopupMessage(viewer, message); } @@ -36,10 +36,10 @@ namespace Content.Shared.Popups /// Location on a grid that the message floats up from. /// The client attached entity that the message is being sent to. /// Text contents of the message. - public static void PopupMessage(this EntityCoordinates coordinates, IEntity viewer, string message) + public static void PopupMessage(this EntityCoordinates coordinates, EntityUid viewer, string message) { var popupSystem = EntitySystem.Get(); - popupSystem.PopupCoordinates(message, coordinates, Filter.Entities(viewer.Uid)); + popupSystem.PopupCoordinates(message, coordinates, Filter.Entities(viewer)); } /// @@ -49,10 +49,10 @@ namespace Content.Shared.Popups /// The client attached entity that the message is being sent to. /// /// Text contents of the message. - public static void PopupMessageCursor(this IEntity viewer, string message) + public static void PopupMessageCursor(this EntityUid viewer, string message) { var popupSystem = EntitySystem.Get(); - popupSystem.PopupCursor(message, Filter.Entities(viewer.Uid)); + popupSystem.PopupCursor(message, Filter.Entities(viewer)); } } } diff --git a/Content.Shared/Projectiles/ProjectileSystem.cs b/Content.Shared/Projectiles/ProjectileSystem.cs index 227b2a74e0..cb81df02f9 100644 --- a/Content.Shared/Projectiles/ProjectileSystem.cs +++ b/Content.Shared/Projectiles/ProjectileSystem.cs @@ -13,7 +13,7 @@ namespace Content.Shared.Projectiles private void PreventCollision(EntityUid uid, SharedProjectileComponent component, PreventCollideEvent args) { - if (component.IgnoreShooter && args.BodyB.OwnerUid == component.Shooter) + if (component.IgnoreShooter && args.BodyB.Owner == component.Shooter) { args.Cancel(); return; diff --git a/Content.Shared/Pulling/Components/PullableComponent.cs b/Content.Shared/Pulling/Components/PullableComponent.cs index 2dd4c17d20..3aca72a317 100644 --- a/Content.Shared/Pulling/Components/PullableComponent.cs +++ b/Content.Shared/Pulling/Components/PullableComponent.cs @@ -1,14 +1,11 @@ using System; -using Content.Shared.Physics.Pull; using Robust.Shared.Analyzers; -using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Map; -using Robust.Shared.Physics; using Robust.Shared.Physics.Dynamics.Joints; -using Robust.Shared.Players; using Robust.Shared.Serialization; namespace Content.Shared.Pulling.Components @@ -27,20 +24,20 @@ namespace Content.Shared.Pulling.Components /// The current entity pulling this component. /// SharedPullingStateManagementSystem should be writing this. This means definitely not you. /// - public IEntity? Puller { get; set; } + public EntityUid? Puller { get; set; } /// /// The pull joint. /// SharedPullingStateManagementSystem should be writing this. This means probably not you. /// public DistanceJoint? PullJoint { get; set; } - public bool BeingPulled => Puller != null; + public bool BeingPulled => Puller != default; public EntityCoordinates? MovingTo { get; set; } public override ComponentState GetComponentState() { - return new PullableComponentState(Puller?.Uid); + return new PullableComponentState(Puller); } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) @@ -52,25 +49,25 @@ namespace Content.Shared.Pulling.Components return; } - if (state.Puller == null) + if (!state.Puller.HasValue) { EntitySystem.Get().ForceDisconnectPullable(this); return; } - if (!Owner.EntityManager.TryGetEntity(state.Puller.Value, out var entity)) + if (!state.Puller.Value.IsValid()) { Logger.Error($"Invalid entity {state.Puller.Value} for pulling"); return; } - if (Puller == entity) + if (Puller == state.Puller) { // don't disconnect and reconnect a puller for no reason return; } - if (!entity.TryGetComponent(out var comp)) + if (!IoCManager.Resolve().TryGetComponent(state.Puller.Value, out var comp)) { Logger.Error($"Entity {state.Puller.Value} for pulling had no Puller component"); // ensure it disconnects from any different puller, still @@ -89,7 +86,7 @@ namespace Content.Shared.Pulling.Components protected override void OnRemove() { - if (Puller != null) + if (Puller != default) { // This is absolute paranoia but it's also absolutely necessary. Too many puller state bugs. - 20kdc Logger.ErrorS("c.go.c.pulling", "PULLING STATE CORRUPTION IMMINENT IN PULLABLE {0} - OnRemove called when Puller is set!", Owner); diff --git a/Content.Shared/Pulling/Components/SharedPullerComponent.cs b/Content.Shared/Pulling/Components/SharedPullerComponent.cs index ca89c3d6da..efb84aca80 100644 --- a/Content.Shared/Pulling/Components/SharedPullerComponent.cs +++ b/Content.Shared/Pulling/Components/SharedPullerComponent.cs @@ -1,10 +1,7 @@ -using Content.Shared.Pulling; -using Content.Shared.Movement.Components; -using Robust.Shared.Analyzers; +using Robust.Shared.Analyzers; using Robust.Shared.GameObjects; -using Robust.Shared.ViewVariables; using Robust.Shared.Log; -using Component = Robust.Shared.GameObjects.Component; +using Robust.Shared.ViewVariables; namespace Content.Shared.Pulling.Components { @@ -15,12 +12,12 @@ namespace Content.Shared.Pulling.Components public override string Name => "Puller"; // Before changing how this is updated, please see SharedPullerSystem.RefreshMovementSpeed - public float WalkSpeedModifier => Pulling == null ? 1.0f : 0.75f; + public float WalkSpeedModifier => Pulling == default ? 1.0f : 0.75f; - public float SprintSpeedModifier => Pulling == null ? 1.0f : 0.75f; + public float SprintSpeedModifier => Pulling == default ? 1.0f : 0.75f; [ViewVariables] - public IEntity? Pulling { get; set; } + public EntityUid? Pulling { get; set; } protected override void Shutdown() { @@ -30,7 +27,7 @@ namespace Content.Shared.Pulling.Components protected override void OnRemove() { - if (Pulling != null) + if (Pulling != default) { // This is absolute paranoia but it's also absolutely necessary. Too many puller state bugs. - 20kdc Logger.ErrorS("c.go.c.pulling", "PULLING STATE CORRUPTION IMMINENT IN PULLER {0} - OnRemove called when Pulling is set!", Owner); diff --git a/Content.Shared/Pulling/Events/StartPullAttemptEvent.cs b/Content.Shared/Pulling/Events/StartPullAttemptEvent.cs index a45e289b7a..d8f2665319 100644 --- a/Content.Shared/Pulling/Events/StartPullAttemptEvent.cs +++ b/Content.Shared/Pulling/Events/StartPullAttemptEvent.cs @@ -7,13 +7,13 @@ namespace Content.Shared.Pulling.Events /// public class StartPullAttemptEvent : CancellableEntityEventArgs { - public StartPullAttemptEvent(IEntity puller, IEntity pulled) + public StartPullAttemptEvent(EntityUid puller, EntityUid pulled) { Puller = puller; Pulled = pulled; } - public IEntity Puller { get; } - public IEntity Pulled { get; } + public EntityUid Puller { get; } + public EntityUid Pulled { get; } } } diff --git a/Content.Shared/Pulling/Systems/SharedPullableSystem.cs b/Content.Shared/Pulling/Systems/SharedPullableSystem.cs index 03b8c48d57..7d928c0a7c 100644 --- a/Content.Shared/Pulling/Systems/SharedPullableSystem.cs +++ b/Content.Shared/Pulling/Systems/SharedPullableSystem.cs @@ -19,7 +19,7 @@ namespace Content.Shared.Pulling.Systems private void OnRelayMoveInput(EntityUid uid, SharedPullableComponent component, RelayMoveInputEvent args) { - var entity = args.Session.AttachedEntityUid; + var entity = args.Session.AttachedEntity; if (entity == null || !_blocker.CanMove(entity.Value)) return; _pullSystem.TryStopPull(component); } diff --git a/Content.Shared/Pulling/Systems/SharedPullerSystem.cs b/Content.Shared/Pulling/Systems/SharedPullerSystem.cs index b8838b386b..d69fca7773 100644 --- a/Content.Shared/Pulling/Systems/SharedPullerSystem.cs +++ b/Content.Shared/Pulling/Systems/SharedPullerSystem.cs @@ -1,6 +1,5 @@ using Content.Shared.Alert; using Content.Shared.Hands; -using Content.Shared.Movement.Components; using Content.Shared.Movement.EntitySystems; using Content.Shared.Physics.Pull; using Content.Shared.Pulling.Components; @@ -31,11 +30,11 @@ namespace Content.Shared.Pulling.Systems if (component.Pulling == null) return; - if (component.Pulling == EntityManager.GetEntity(args.BlockingEntity)) + if (component.Pulling == args.BlockingEntity) { if (EntityManager.TryGetComponent(args.BlockingEntity, out var comp)) { - _pullSystem.TryStopPull(comp, EntityManager.GetEntity(uid)); + _pullSystem.TryStopPull(comp, uid); } } } @@ -45,10 +44,10 @@ namespace Content.Shared.Pulling.Systems SharedPullerComponent component, PullStartedMessage args) { - if (args.Puller.OwnerUid != uid) + if (args.Puller.Owner != uid) return; - if (component.Owner.TryGetComponent(out SharedAlertsComponent? alerts)) + if (EntityManager.TryGetComponent(component.Owner, out SharedAlertsComponent? alerts)) alerts.ShowAlert(AlertType.Pulling); RefreshMovementSpeed(component); @@ -59,10 +58,10 @@ namespace Content.Shared.Pulling.Systems SharedPullerComponent component, PullStoppedMessage args) { - if (args.Puller.OwnerUid != uid) + if (args.Puller.Owner != uid) return; - if (component.Owner.TryGetComponent(out SharedAlertsComponent? alerts)) + if (EntityManager.TryGetComponent(component.Owner, out SharedAlertsComponent? alerts)) alerts.ClearAlert(AlertType.Pulling); RefreshMovementSpeed(component); @@ -75,7 +74,7 @@ namespace Content.Shared.Pulling.Systems private void RefreshMovementSpeed(SharedPullerComponent component) { - _movementSpeedModifierSystem.RefreshMovementSpeedModifiers(component.OwnerUid); + _movementSpeedModifierSystem.RefreshMovementSpeedModifiers((component).Owner); } } } diff --git a/Content.Shared/Pulling/Systems/SharedPullingStateManagementSystem.cs b/Content.Shared/Pulling/Systems/SharedPullingStateManagementSystem.cs index ca550ac1ac..3d0d76be35 100644 --- a/Content.Shared/Pulling/Systems/SharedPullingStateManagementSystem.cs +++ b/Content.Shared/Pulling/Systems/SharedPullingStateManagementSystem.cs @@ -36,14 +36,14 @@ namespace Content.Shared.Pulling // They do not expect to be cancellable. private void ForceDisconnect(SharedPullerComponent puller, SharedPullableComponent pullable) { - var pullerPhysics = puller.Owner.GetComponent(); - var pullablePhysics = pullable.Owner.GetComponent(); + var pullerPhysics = EntityManager.GetComponent(puller.Owner); + var pullablePhysics = EntityManager.GetComponent(pullable.Owner); // MovingTo shutdown ForceSetMovingTo(pullable, null); // Joint shutdown - if (puller.Owner.TryGetComponent(out var jointComp)) + if (EntityManager.TryGetComponent(puller.Owner, out var jointComp)) { if (jointComp.GetJoints.Contains(pullable.PullJoint!)) { @@ -59,10 +59,10 @@ namespace Content.Shared.Pulling // Messaging var message = new PullStoppedMessage(pullerPhysics, pullablePhysics); - RaiseLocalEvent(puller.OwnerUid, message, broadcast: false); + RaiseLocalEvent(puller.Owner, message, broadcast: false); - if (pullable.Owner.LifeStage <= EntityLifeStage.MapInitialized) - RaiseLocalEvent(pullable.OwnerUid, message); + if (Initialized(pullable.Owner)) + RaiseLocalEvent(pullable.Owner, message); // Networking puller.Dirty(); @@ -81,22 +81,22 @@ namespace Content.Shared.Pulling var pullableOldPullerE = pullable?.Puller; if (pullableOldPullerE != null) { - ForceDisconnect(pullableOldPullerE.GetComponent(), pullable!); + ForceDisconnect(EntityManager.GetComponent(pullableOldPullerE.Value), pullable!); } // Continue with the puller. var pullerOldPullableE = puller?.Pulling; if (pullerOldPullableE != null) { - ForceDisconnect(puller!, pullerOldPullableE.GetComponent()); + ForceDisconnect(puller!, EntityManager.GetComponent(pullerOldPullableE.Value)); } // And now for the actual connection (if any). if ((puller != null) && (pullable != null)) { - var pullerPhysics = puller.Owner.GetComponent(); - var pullablePhysics = pullable.Owner.GetComponent(); + var pullerPhysics = EntityManager.GetComponent(puller.Owner); + var pullablePhysics = EntityManager.GetComponent(pullable.Owner); // State startup puller.Pulling = pullable.Owner; @@ -106,7 +106,7 @@ namespace Content.Shared.Pulling var union = pullerPhysics.GetWorldAABB().Union(pullablePhysics.GetWorldAABB()); var length = Math.Max(union.Size.X, union.Size.Y) * 0.75f; - pullable.PullJoint = _jointSystem.CreateDistanceJoint(pullablePhysics.OwnerUid, pullerPhysics.Owner.Uid, id:$"pull-joint-{pullablePhysics.Owner.Uid}"); + pullable.PullJoint = _jointSystem.CreateDistanceJoint(pullablePhysics.Owner, pullerPhysics.Owner, id:$"pull-joint-{pullablePhysics.Owner}"); pullable.PullJoint.CollideConnected = false; // This maximum has to be there because if the object is constrained too closely, the clamping goes backwards and asserts. pullable.PullJoint.MaxLength = Math.Max(1.0f, length); @@ -117,8 +117,8 @@ namespace Content.Shared.Pulling // Messaging var message = new PullStartedMessage(pullerPhysics, pullablePhysics); - RaiseLocalEvent(puller.OwnerUid, message, broadcast: false); - RaiseLocalEvent(pullable.OwnerUid, message); + RaiseLocalEvent(puller.Owner, message, broadcast: false); + RaiseLocalEvent(pullable.Owner, message); // Networking puller.Dirty(); @@ -158,11 +158,11 @@ namespace Content.Shared.Pulling if (movingTo == null) { - RaiseLocalEvent(pullable.Owner.Uid, new PullableStopMovingMessage()); + RaiseLocalEvent(pullable.Owner, new PullableStopMovingMessage()); } else { - RaiseLocalEvent(pullable.Owner.Uid, new PullableMoveMessage()); + RaiseLocalEvent(pullable.Owner, new PullableMoveMessage()); } } } diff --git a/Content.Shared/Pulling/Systems/SharedPullingSystem.Actions.cs b/Content.Shared/Pulling/Systems/SharedPullingSystem.Actions.cs index b7e56a6442..a5cb4d11b9 100644 --- a/Content.Shared/Pulling/Systems/SharedPullingSystem.Actions.cs +++ b/Content.Shared/Pulling/Systems/SharedPullingSystem.Actions.cs @@ -27,19 +27,19 @@ namespace Content.Shared.Pulling { [Dependency] private readonly ActionBlockerSystem _blocker = default!; - public bool CanPull(IEntity puller, IEntity pulled) + public bool CanPull(EntityUid puller, EntityUid pulled) { - if (!puller.HasComponent()) + if (!EntityManager.HasComponent(puller)) { return false; } - if (!_blocker.CanInteract(puller.Uid)) + if (!_blocker.CanInteract(puller)) { return false; } - if (!pulled.TryGetComponent(out var _physics)) + if (!EntityManager.TryGetComponent(pulled, out var _physics)) { return false; } @@ -59,21 +59,21 @@ namespace Content.Shared.Pulling return false; } - if (puller.TryGetComponent(out var buckle)) + if (EntityManager.TryGetComponent(puller, out var buckle)) { // Prevent people pulling the chair they're on, etc. - if (buckle.Buckled && (buckle.LastEntityBuckledTo == pulled.Uid)) + if (buckle.Buckled && (buckle.LastEntityBuckledTo == pulled)) { return false; } } var startPull = new StartPullAttemptEvent(puller, pulled); - RaiseLocalEvent(puller.Uid, startPull); + RaiseLocalEvent(puller, startPull); return !startPull.Cancelled; } - public bool TogglePull(IEntity puller, SharedPullableComponent pullable) + public bool TogglePull(EntityUid puller, SharedPullableComponent pullable) { if (pullable.Puller == puller) { @@ -84,15 +84,15 @@ namespace Content.Shared.Pulling // -- Core attempted actions -- - public bool TryStopPull(SharedPullableComponent pullable, IEntity? user = null) + public bool TryStopPull(SharedPullableComponent pullable, EntityUid? user = null) { if (!pullable.BeingPulled) { return false; } - var msg = new StopPullingEvent(user?.Uid); - RaiseLocalEvent(pullable.OwnerUid, msg); + var msg = new StopPullingEvent(user); + RaiseLocalEvent(pullable.Owner, msg); if (msg.Cancelled) return false; @@ -100,13 +100,13 @@ namespace Content.Shared.Pulling return true; } - public bool TryStartPull(IEntity puller, IEntity pullable) + public bool TryStartPull(EntityUid puller, EntityUid pullable) { - if (!puller.TryGetComponent(out var pullerComp)) + if (!EntityManager.TryGetComponent(puller, out var pullerComp)) { return false; } - if (!pullable.TryGetComponent(out var pullableComp)) + if (!EntityManager.TryGetComponent(pullable, out var pullableComp)) { return false; } @@ -121,17 +121,17 @@ namespace Content.Shared.Pulling // Pulling a new object : Perform sanity checks. - if (!EntitySystem.Get().CanPull(puller.Owner, pullable.Owner)) + if (!CanPull(puller.Owner, pullable.Owner)) { return false; } - if (!puller.Owner.TryGetComponent(out var pullerPhysics)) + if (!EntityManager.TryGetComponent(puller.Owner, out var pullerPhysics)) { return false; } - if (!pullable.Owner.TryGetComponent(out var pullablePhysics)) + if (!EntityManager.TryGetComponent(pullable.Owner, out var pullablePhysics)) { return false; } @@ -143,7 +143,7 @@ namespace Content.Shared.Pulling var oldPullable = puller.Pulling; if (oldPullable != null) { - if (oldPullable.TryGetComponent(out var oldPullableComp)) + if (EntityManager.TryGetComponent(oldPullable.Value, out var oldPullableComp)) { if (!TryStopPull(oldPullableComp)) { @@ -173,14 +173,14 @@ namespace Content.Shared.Pulling var pullAttempt = new PullAttemptMessage(pullerPhysics, pullablePhysics); - RaiseLocalEvent(puller.OwnerUid, pullAttempt, broadcast: false); + RaiseLocalEvent(puller.Owner, pullAttempt, broadcast: false); if (pullAttempt.Cancelled) { return false; } - RaiseLocalEvent(pullable.OwnerUid, pullAttempt); + RaiseLocalEvent(pullable.Owner, pullAttempt); if (pullAttempt.Cancelled) { @@ -198,7 +198,7 @@ namespace Content.Shared.Pulling return false; } - if (!pullable.Owner.HasComponent()) + if (!EntityManager.HasComponent(pullable.Owner)) { return false; } diff --git a/Content.Shared/Pulling/Systems/SharedPullingSystem.cs b/Content.Shared/Pulling/Systems/SharedPullingSystem.cs index 8fcf548769..1ed7422f75 100644 --- a/Content.Shared/Pulling/Systems/SharedPullingSystem.cs +++ b/Content.Shared/Pulling/Systems/SharedPullingSystem.cs @@ -6,19 +6,18 @@ using Content.Shared.GameTicking; using Content.Shared.Input; using Content.Shared.Physics.Pull; using Content.Shared.Pulling.Components; -using Content.Shared.Pulling.Events; using Content.Shared.Rotatable; +using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Input.Binding; +using Robust.Shared.IoC; +using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Players; -using Robust.Shared.IoC; -using Content.Shared.Verbs; -using Robust.Shared.Localization; namespace Content.Shared.Pulling { @@ -30,7 +29,7 @@ namespace Content.Shared.Pulling /// /// A mapping of pullers to the entity that they are pulling. /// - private readonly Dictionary _pullers = + private readonly Dictionary _pullers = new(); private readonly HashSet _moving = new(); @@ -100,21 +99,21 @@ namespace Content.Shared.Pulling } // Raise a "you are being pulled" alert if the pulled entity has alerts. - private static void PullableHandlePullStarted(EntityUid uid, SharedPullableComponent component, PullStartedMessage args) + private void PullableHandlePullStarted(EntityUid uid, SharedPullableComponent component, PullStartedMessage args) { - if (args.Pulled.OwnerUid != uid) + if (args.Pulled.Owner != uid) return; - if (component.Owner.TryGetComponent(out SharedAlertsComponent? alerts)) + if (EntityManager.TryGetComponent(component.Owner, out SharedAlertsComponent? alerts)) alerts.ShowAlert(AlertType.Pulled); } - private static void PullableHandlePullStopped(EntityUid uid, SharedPullableComponent component, PullStoppedMessage args) + private void PullableHandlePullStopped(EntityUid uid, SharedPullableComponent component, PullStoppedMessage args) { - if (args.Pulled.OwnerUid != uid) + if (args.Pulled.Owner != uid) return; - if (component.Owner.TryGetComponent(out SharedAlertsComponent? alerts)) + if (EntityManager.TryGetComponent(component.Owner, out SharedAlertsComponent? alerts)) alerts.ClearAlert(AlertType.Pulled); } @@ -165,17 +164,17 @@ namespace Content.Shared.Pulling // The pulled object may have already been deleted. // TODO: Work out why. Monkey + meat spike is a good test for this, // assuming you're still pulling the monkey when it gets gibbed. - if (pulled.Deleted) + if (Deleted(pulled.Value)) { return; } - if (!pulled.TryGetComponent(out IPhysBody? physics)) + if (!EntityManager.TryGetComponent(pulled.Value, out IPhysBody? physics)) { return; } - UpdatePulledRotation(puller, pulled); + UpdatePulledRotation(puller, pulled.Value); physics.WakeBody(); } @@ -183,16 +182,16 @@ namespace Content.Shared.Pulling // TODO: When Joint networking is less shitcodey fix this to use a dedicated joints message. private void HandleContainerInsert(EntInsertedIntoContainerMessage message) { - if (message.Entity.TryGetComponent(out SharedPullableComponent? pullable)) + if (EntityManager.TryGetComponent(message.Entity, out SharedPullableComponent? pullable)) { TryStopPull(pullable); } - if (message.Entity.TryGetComponent(out SharedPullerComponent? puller)) + if (EntityManager.TryGetComponent(message.Entity, out SharedPullerComponent? puller)) { if (puller.Pulling == null) return; - if (!puller.Pulling.TryGetComponent(out SharedPullableComponent? pulling)) + if (!EntityManager.TryGetComponent(puller.Pulling.Value, out SharedPullableComponent? pulling)) { return; } @@ -203,19 +202,16 @@ namespace Content.Shared.Pulling private bool HandleMovePulledObject(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { - var player = session?.AttachedEntity; - - if (player == null) - { + if (session?.AttachedEntity is not { } player || + !player.IsValid()) return false; - } if (!TryGetPulled(player, out var pulled)) { return false; } - if (!pulled.TryGetComponent(out SharedPullableComponent? pullable)) + if (!EntityManager.TryGetComponent(pulled.Value, out SharedPullableComponent? pullable)) { return false; } @@ -225,44 +221,46 @@ namespace Content.Shared.Pulling return false; } - private void SetPuller(IEntity puller, IEntity pulled) + private void SetPuller(EntityUid puller, EntityUid pulled) { _pullers[puller] = pulled; } - private bool RemovePuller(IEntity puller) + private bool RemovePuller(EntityUid puller) { return _pullers.Remove(puller); } - public IEntity? GetPulled(IEntity by) + public EntityUid GetPulled(EntityUid by) { return _pullers.GetValueOrDefault(by); } - public bool TryGetPulled(IEntity by, [NotNullWhen(true)] out IEntity? pulled) + public bool TryGetPulled(EntityUid by, [NotNullWhen(true)] out EntityUid? pulled) { return (pulled = GetPulled(by)) != null; } - public bool IsPulling(IEntity puller) + public bool IsPulling(EntityUid puller) { return _pullers.ContainsKey(puller); } - private void UpdatePulledRotation(IEntity puller, IEntity pulled) + private void UpdatePulledRotation(EntityUid puller, EntityUid pulled) { // TODO: update once ComponentReference works with directed event bus. - if (!pulled.TryGetComponent(out RotatableComponent? rotatable)) + if (!EntityManager.TryGetComponent(pulled, out RotatableComponent? rotatable)) return; if (!rotatable.RotateWhilePulling) return; - var dir = puller.Transform.WorldPosition - pulled.Transform.WorldPosition; + var pulledXform = EntityManager.GetComponent(pulled); + + var dir = EntityManager.GetComponent(puller).WorldPosition - pulledXform.WorldPosition; if (dir.LengthSquared > ThresholdRotDistance * ThresholdRotDistance) { - var oldAngle = pulled.Transform.WorldRotation; + var oldAngle = pulledXform.WorldRotation; var newAngle = Angle.FromWorldVec(dir); var diff = newAngle - oldAngle; @@ -272,10 +270,10 @@ namespace Content.Shared.Pulling // Otherwise PIANO DOOR STUCK! happens. // But it also needs to work with station rotation / align to the local parent. // So... - var baseRotation = pulled.Transform.Parent?.WorldRotation ?? 0f; + var baseRotation = pulledXform.Parent?.WorldRotation ?? 0f; var localRotation = newAngle - baseRotation; var localRotationSnapped = Angle.FromDegrees(Math.Floor((localRotation.Degrees / ThresholdRotAngle) + 0.5f) * ThresholdRotAngle); - pulled.Transform.LocalRotation = localRotationSnapped; + pulledXform.LocalRotation = localRotationSnapped; } } } diff --git a/Content.Shared/Random/Helpers/SharedEntityExtensions.cs b/Content.Shared/Random/Helpers/SharedEntityExtensions.cs index bd33c46bd5..cb83761d27 100644 --- a/Content.Shared/Random/Helpers/SharedEntityExtensions.cs +++ b/Content.Shared/Random/Helpers/SharedEntityExtensions.cs @@ -9,7 +9,7 @@ namespace Content.Shared.Random.Helpers { public static class SharedEntityExtensions { - public static void RandomOffset(this IEntity entity, float minX, float maxX, float minY, float maxY) + public static void RandomOffset(this EntityUid entity, float minX, float maxX, float minY, float maxY) { DebugTools.AssertNotNull(entity); DebugTools.Assert(minX <= maxX, $"Minimum X value ({minX}) must be smaller than or equal to the maximum X value ({maxX})"); @@ -20,10 +20,10 @@ namespace Content.Shared.Random.Helpers var randomY = random.NextFloat() * (maxY - minY) + minY; var offset = new Vector2(randomX, randomY); - entity.Transform.LocalPosition += offset; + IoCManager.Resolve().GetComponent(entity).LocalPosition += offset; } - public static void RandomOffset(this IEntity entity, float min, float max) + public static void RandomOffset(this EntityUid entity, float min, float max) { DebugTools.AssertNotNull(entity); DebugTools.Assert(min <= max, $"Minimum value ({min}) must be smaller than or equal to the maximum value ({max})"); @@ -31,7 +31,7 @@ namespace Content.Shared.Random.Helpers entity.RandomOffset(min, max, min, max); } - public static void RandomOffset(this IEntity entity, float value) + public static void RandomOffset(this EntityUid entity, float value) { value = Math.Abs(value); entity.RandomOffset(-value, value); diff --git a/Content.Shared/Roles/JobSpecial.cs b/Content.Shared/Roles/JobSpecial.cs index 8ef76fda0f..54259e3058 100644 --- a/Content.Shared/Roles/JobSpecial.cs +++ b/Content.Shared/Roles/JobSpecial.cs @@ -9,6 +9,6 @@ namespace Content.Shared.Roles [ImplicitDataDefinitionForInheritors] public abstract class JobSpecial { - public abstract void AfterEquip(IEntity mob); + public abstract void AfterEquip(EntityUid mob); } } diff --git a/Content.Shared/Shuttles/Components/PilotComponent.cs b/Content.Shared/Shuttles/Components/PilotComponent.cs index 8e3789e537..9477bcc689 100644 --- a/Content.Shared/Shuttles/Components/PilotComponent.cs +++ b/Content.Shared/Shuttles/Components/PilotComponent.cs @@ -1,9 +1,9 @@ using System; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Map; -using Robust.Shared.Players; using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; @@ -31,16 +31,18 @@ namespace Content.Shared.Shuttles.Components base.HandleComponentState(curState, nextState); if (curState is not PilotComponentState state) return; - if (state.Console == null) + var console = state.Console.GetValueOrDefault(); + if (!console.IsValid()) { Console = null; return; } - if (!Owner.EntityManager.TryGetEntity(state.Console.Value, out var consoleEnt) || - !consoleEnt.TryGetComponent(out SharedShuttleConsoleComponent? shuttleConsoleComponent)) + var entityManager = IoCManager.Resolve(); + + if (!entityManager.TryGetComponent(console, out SharedShuttleConsoleComponent? shuttleConsoleComponent)) { - Logger.Warning($"Unable to set Helmsman console to {state.Console.Value}"); + Logger.Warning($"Unable to set Helmsman console to {console}"); return; } @@ -49,7 +51,7 @@ namespace Content.Shared.Shuttles.Components public override ComponentState GetComponentState() { - return new PilotComponentState(Console?.OwnerUid); + return Console == null ? new PilotComponentState(null) : new PilotComponentState(Console.Owner); } [Serializable, NetSerializable] diff --git a/Content.Shared/Singularity/SharedSingularitySystem.cs b/Content.Shared/Singularity/SharedSingularitySystem.cs index dbb4fe4921..25c4c14a6e 100644 --- a/Content.Shared/Singularity/SharedSingularitySystem.cs +++ b/Content.Shared/Singularity/SharedSingularitySystem.cs @@ -55,7 +55,7 @@ namespace Content.Shared.Singularity value = Math.Clamp(value, 0, 6); - var physics = singularity.Owner.GetComponentOrNull(); + var physics = EntityManager.GetComponentOrNull(singularity.Owner); if (singularity.Level > 1 && value <= 1) { @@ -68,12 +68,12 @@ namespace Content.Shared.Singularity singularity.Level = value; - if (singularity.Owner.TryGetComponent(out SharedRadiationPulseComponent? pulse)) + if (EntityManager.TryGetComponent(singularity.Owner, out SharedRadiationPulseComponent? pulse)) { pulse.RadsPerSecond = 10 * value; } - if (singularity.Owner.TryGetComponent(out AppearanceComponent? appearance)) + if (EntityManager.TryGetComponent(singularity.Owner, out AppearanceComponent? appearance)) { appearance.SetData(SingularityVisuals.Level, value); } @@ -83,7 +83,7 @@ namespace Content.Shared.Singularity circle.Radius = value - 0.5f; } - if (singularity.Owner.TryGetComponent(out SingularityDistortionComponent? distortion)) + if (EntityManager.TryGetComponent(singularity.Owner, out SingularityDistortionComponent? distortion)) { distortion.Falloff = GetFalloff(value); distortion.Intensity = GetIntensity(value); @@ -102,8 +102,8 @@ namespace Content.Shared.Singularity { var other = args.BodyB.Owner; - if ((!other.HasComponent() && - !other.HasComponent()) || + if ((!EntityManager.HasComponent(other) && + !EntityManager.HasComponent(other)) || component.Level >= 4) { args.Cancel(); diff --git a/Content.Shared/Slippery/SharedSlipperySystem.cs b/Content.Shared/Slippery/SharedSlipperySystem.cs index cd24cbac76..f9c57c74b8 100644 --- a/Content.Shared/Slippery/SharedSlipperySystem.cs +++ b/Content.Shared/Slippery/SharedSlipperySystem.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Shared.Administration.Logs; using Content.Shared.Database; @@ -33,7 +32,7 @@ namespace Content.Shared.Slippery private void HandleCollide(EntityUid uid, SlipperyComponent component, StartCollideEvent args) { - var otherUid = args.OtherFixture.Body.OwnerUid; + var otherUid = args.OtherFixture.Body.Owner; if (!CanSlip(component, otherUid)) return; @@ -74,7 +73,7 @@ namespace Content.Shared.Slippery private bool TrySlip(SlipperyComponent component, IPhysBody ourBody, IPhysBody otherBody) { - if (!CanSlip(component, otherBody.OwnerUid)) return false; + if (!CanSlip(component, otherBody.Owner)) return false; if (otherBody.LinearVelocity.Length < component.RequiredSlipSpeed) { @@ -89,16 +88,16 @@ namespace Content.Shared.Slippery } var ev = new SlipAttemptEvent(); - RaiseLocalEvent(otherBody.OwnerUid, ev, false); + RaiseLocalEvent(otherBody.Owner, ev, false); if (ev.Cancelled) return false; otherBody.LinearVelocity *= component.LaunchForwardsMultiplier; - bool playSound = !_statusEffectsSystem.HasStatusEffect(otherBody.OwnerUid, "KnockedDown"); + bool playSound = !_statusEffectsSystem.HasStatusEffect(otherBody.Owner, "KnockedDown"); - _stunSystem.TryParalyze(otherBody.OwnerUid, TimeSpan.FromSeconds(component.ParalyzeTime), true); - component.Slipped.Add(otherBody.OwnerUid); + _stunSystem.TryParalyze(otherBody.Owner, TimeSpan.FromSeconds(component.ParalyzeTime), true); + component.Slipped.Add(otherBody.Owner); component.Dirty(); //Preventing from playing the slip sound when you are already knocked down. @@ -120,7 +119,7 @@ namespace Content.Shared.Slippery if (component.Deleted || !component.Slippery || component.Colliding.Count == 0) return true; - if (!EntityManager.TryGetComponent(component.Owner.Uid, out PhysicsComponent? body)) + if (!EntityManager.TryGetComponent(component.Owner, out PhysicsComponent? body)) { component.Colliding.Clear(); return true; @@ -128,7 +127,7 @@ namespace Content.Shared.Slippery foreach (var uid in component.Colliding.ToArray()) { - if (!uid.IsValid() || !EntityManager.TryGetEntity(uid, out var entity)) + if (!uid.IsValid()) { component.Colliding.Remove(uid); component.Slipped.Remove(uid); @@ -136,7 +135,7 @@ namespace Content.Shared.Slippery continue; } - if (!entity.TryGetComponent(out PhysicsComponent? otherPhysics) || + if (!EntityManager.TryGetComponent(uid, out PhysicsComponent? otherPhysics) || !body.GetWorldAABB().Intersects(otherPhysics.GetWorldAABB())) { component.Colliding.Remove(uid); diff --git a/Content.Shared/Spawning/EntitySystemExtensions.cs b/Content.Shared/Spawning/EntitySystemExtensions.cs index 0bd9bc78d7..497852f3a2 100644 --- a/Content.Shared/Spawning/EntitySystemExtensions.cs +++ b/Content.Shared/Spawning/EntitySystemExtensions.cs @@ -10,7 +10,7 @@ namespace Content.Shared.Spawning { public static class EntitySystemExtensions { - public static IEntity? SpawnIfUnobstructed( + public static EntityUid? SpawnIfUnobstructed( this IEntityManager entityManager, string? prototypeName, EntityCoordinates coordinates, @@ -24,7 +24,7 @@ namespace Content.Shared.Spawning return entityManager.SpawnIfUnobstructed(prototypeName, mapCoordinates, collisionLayer, box, physicsManager); } - public static IEntity? SpawnIfUnobstructed( + public static EntityUid? SpawnIfUnobstructed( this IEntityManager entityManager, string? prototypeName, MapCoordinates coordinates, @@ -59,7 +59,7 @@ namespace Content.Shared.Spawning string? prototypeName, EntityCoordinates coordinates, CollisionGroup collisionLayer, - [NotNullWhen(true)] out IEntity? entity, + [NotNullWhen(true)] out EntityUid? entity, Box2? box = null, SharedPhysicsSystem? physicsManager = null) { @@ -73,7 +73,7 @@ namespace Content.Shared.Spawning string? prototypeName, MapCoordinates coordinates, CollisionGroup collisionLayer, - [NotNullWhen(true)] out IEntity? entity, + [NotNullWhen(true)] out EntityUid? entity, in Box2? box = null, SharedPhysicsSystem? physicsManager = null) { diff --git a/Content.Shared/StatusEffect/StatusEffectsSystem.cs b/Content.Shared/StatusEffect/StatusEffectsSystem.cs index cea682f31d..d724056d5c 100644 --- a/Content.Shared/StatusEffect/StatusEffectsSystem.cs +++ b/Content.Shared/StatusEffect/StatusEffectsSystem.cs @@ -37,7 +37,7 @@ namespace Content.Shared.StatusEffect // if we're past the end point of the effect if (_gameTiming.CurTime > state.Value.Cooldown.Item2) { - TryRemoveStatusEffect(status.Owner.Uid, state.Key, status); + TryRemoveStatusEffect(status.Owner, state.Key, status); } } } @@ -121,7 +121,7 @@ namespace Content.Shared.StatusEffect { // Fuck this shit I hate it var newComponent = (Component) _componentFactory.GetComponent(component); - newComponent.Owner = EntityManager.GetEntity(uid); + newComponent.Owner = uid; EntityManager.AddComponent(uid, newComponent); status.ActiveEffects[key].RelevantComponent = component; diff --git a/Content.Shared/Storage/EntitySystems/SharedItemCounterSystem.cs b/Content.Shared/Storage/EntitySystems/SharedItemCounterSystem.cs index 018962581e..b1715fdfdc 100644 --- a/Content.Shared/Storage/EntitySystems/SharedItemCounterSystem.cs +++ b/Content.Shared/Storage/EntitySystems/SharedItemCounterSystem.cs @@ -3,6 +3,7 @@ using Content.Shared.Storage.Components; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Shared.Storage.EntitySystems { @@ -20,32 +21,32 @@ namespace Content.Shared.Storage.EntitySystems private void CounterEntityInserted(EntityUid uid, ItemCounterComponent itemCounter, EntInsertedIntoContainerMessage args) { - if (!itemCounter.Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) return; - + if (!EntityManager.TryGetComponent(itemCounter.Owner, out AppearanceComponent? appearanceComponent)) return; + var count = GetCount(args, itemCounter); if (count == null) return; - + appearanceComponent.SetData(StackVisuals.Actual, count); if (itemCounter.MaxAmount != null) appearanceComponent.SetData(StackVisuals.MaxCount, itemCounter.MaxAmount); - + } private void CounterEntityRemoved(EntityUid uid, ItemCounterComponent itemCounter, EntRemovedFromContainerMessage args) { - if (!itemCounter.Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) return; - + if (!EntityManager.TryGetComponent(itemCounter.Owner, out AppearanceComponent? appearanceComponent)) return; + var count = GetCount(args, itemCounter); if (count == null) return; - + appearanceComponent.SetData(StackVisuals.Actual, count); if (itemCounter.MaxAmount != null) appearanceComponent.SetData(StackVisuals.MaxCount, itemCounter.MaxAmount); } - + protected abstract int? GetCount(ContainerModifiedMessage msg, ItemCounterComponent itemCounter); } -} \ No newline at end of file +} diff --git a/Content.Shared/Storage/EntitySystems/SharedItemMapperSystem.cs b/Content.Shared/Storage/EntitySystems/SharedItemMapperSystem.cs index 9609387567..5aabe3afb7 100644 --- a/Content.Shared/Storage/EntitySystems/SharedItemMapperSystem.cs +++ b/Content.Shared/Storage/EntitySystems/SharedItemMapperSystem.cs @@ -3,6 +3,7 @@ using Content.Shared.Storage.Components; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Shared.Storage.EntitySystems { @@ -20,7 +21,7 @@ namespace Content.Shared.Storage.EntitySystems private void InitLayers(EntityUid uid, ItemMapperComponent component, ComponentInit args) { - if (component.Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) + if (EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearanceComponent)) { var list = new List(component.MapLayers.Keys); appearanceComponent.SetData(StorageMapVisuals.InitLayers, new ShowLayerData(list)); @@ -30,7 +31,7 @@ namespace Content.Shared.Storage.EntitySystems private void MapperEntityRemoved(EntityUid uid, ItemMapperComponent itemMapper, EntRemovedFromContainerMessage args) { - if (itemMapper.Owner.TryGetComponent(out AppearanceComponent? appearanceComponent) + if (EntityManager.TryGetComponent(itemMapper.Owner, out AppearanceComponent? appearanceComponent) && TryGetLayers(args, itemMapper, out var containedLayers)) { appearanceComponent.SetData(StorageMapVisuals.LayerChanged, new ShowLayerData(containedLayers)); @@ -40,7 +41,7 @@ namespace Content.Shared.Storage.EntitySystems private void MapperEntityInserted(EntityUid uid, ItemMapperComponent itemMapper, EntInsertedIntoContainerMessage args) { - if (itemMapper.Owner.TryGetComponent(out AppearanceComponent? appearanceComponent) + if (EntityManager.TryGetComponent(itemMapper.Owner, out AppearanceComponent? appearanceComponent) && TryGetLayers(args, itemMapper, out var containedLayers)) { appearanceComponent.SetData(StorageMapVisuals.LayerChanged, new ShowLayerData(containedLayers)); @@ -51,4 +52,4 @@ namespace Content.Shared.Storage.EntitySystems ItemMapperComponent itemMapper, out IReadOnlyList containedLayers); } -} \ No newline at end of file +} diff --git a/Content.Shared/Storage/SharedStorageComponent.cs b/Content.Shared/Storage/SharedStorageComponent.cs index 068149d962..dd2a1ba6d6 100644 --- a/Content.Shared/Storage/SharedStorageComponent.cs +++ b/Content.Shared/Storage/SharedStorageComponent.cs @@ -7,6 +7,7 @@ using Content.Shared.Interaction.Events; using Content.Shared.Placeable; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; +using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Serialization; @@ -15,26 +16,28 @@ namespace Content.Shared.Storage [NetworkedComponent()] public abstract class SharedStorageComponent : Component, IDraggable { + [Dependency] private readonly IEntityManager _entMan = default!; + public override string Name => "Storage"; - public abstract IReadOnlyList? StoredEntities { get; } + public abstract IReadOnlyList? StoredEntities { get; } /// /// Removes from the storage container and updates the stored value /// /// The entity to remove /// True if no longer in storage, false otherwise - public abstract bool Remove(IEntity entity); + public abstract bool Remove(EntityUid entity); bool IDraggable.CanDrop(CanDropEvent args) { - return args.Target.TryGetComponent(out PlaceableSurfaceComponent? placeable) && + return _entMan.TryGetComponent(args.Target, out PlaceableSurfaceComponent? placeable) && placeable.IsPlaceable; } bool IDraggable.Drop(DragDropEvent eventArgs) { - if (!EntitySystem.Get().CanInteract(eventArgs.User.Uid)) + if (!EntitySystem.Get().CanInteract(eventArgs.User)) { return false; } @@ -51,7 +54,7 @@ namespace Content.Shared.Storage { if (Remove(storedEntity)) { - storedEntity.Transform.WorldPosition = eventArgs.DropLocation.Position; + _entMan.GetComponent(storedEntity).WorldPosition = eventArgs.DropLocation.Position; } } diff --git a/Content.Shared/Strip/Components/SharedStrippableComponent.cs b/Content.Shared/Strip/Components/SharedStrippableComponent.cs index ab369ede20..165d693c1a 100644 --- a/Content.Shared/Strip/Components/SharedStrippableComponent.cs +++ b/Content.Shared/Strip/Components/SharedStrippableComponent.cs @@ -4,6 +4,7 @@ using Content.Shared.ActionBlocker; using Content.Shared.DragDrop; using Content.Shared.Hands.Components; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Serialization; using static Content.Shared.Inventory.EquipmentSlotDefines; @@ -13,11 +14,11 @@ namespace Content.Shared.Strip.Components { public override string Name => "Strippable"; - public bool CanBeStripped(IEntity by) + public bool CanBeStripped(EntityUid by) { return by != Owner - && by.HasComponent() - && EntitySystem.Get().CanInteract(by.Uid); + && IoCManager.Resolve().HasComponent(@by) + && EntitySystem.Get().CanInteract(@by); } bool IDraggable.CanDrop(CanDropEvent args) diff --git a/Content.Shared/Strip/Components/SharedStrippingComponent.cs b/Content.Shared/Strip/Components/SharedStrippingComponent.cs index 294f5c331f..0210989a3a 100644 --- a/Content.Shared/Strip/Components/SharedStrippingComponent.cs +++ b/Content.Shared/Strip/Components/SharedStrippingComponent.cs @@ -1,5 +1,6 @@ using Content.Shared.DragDrop; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Shared.Strip.Components { @@ -13,7 +14,7 @@ namespace Content.Shared.Strip.Components bool IDragDropOn.CanDragDropOn(DragDropEvent eventArgs) { - if (!eventArgs.Dragged.TryGetComponent(out SharedStrippableComponent? strippable)) return false; + if (!IoCManager.Resolve().TryGetComponent(eventArgs.Dragged, out SharedStrippableComponent? strippable)) return false; return strippable.CanBeStripped(Owner); } diff --git a/Content.Shared/SubFloor/SubFloorHideSystem.cs b/Content.Shared/SubFloor/SubFloorHideSystem.cs index f31402e800..e127431bcf 100644 --- a/Content.Shared/SubFloor/SubFloorHideSystem.cs +++ b/Content.Shared/SubFloor/SubFloorHideSystem.cs @@ -60,14 +60,14 @@ namespace Content.Shared.SubFloor { subFloor.Enabled = enabled; subFloor.Dirty(); - UpdateEntity(subFloor.Owner.Uid); + UpdateEntity(subFloor.Owner); } public void SetRequireAnchoring(SubFloorHideComponent subFloor, bool requireAnchored) { subFloor.RequireAnchored = requireAnchored; subFloor.Dirty(); - UpdateEntity(subFloor.Owner.Uid); + UpdateEntity(subFloor.Owner); } private void OnSubFloorStarted(EntityUid uid, SubFloorHideComponent component, ComponentStartup _) @@ -79,7 +79,8 @@ namespace Content.Shared.SubFloor private void OnSubFloorTerminating(EntityUid uid, SubFloorHideComponent component, ComponentShutdown _) { // If component is being deleted don't need to worry about updating any component stuff because it won't matter very shortly. - if (EntityManager.GetEntity(uid).LifeStage >= EntityLifeStage.Terminating) return; + if (EntityManager.GetComponent(uid).EntityLifeStage >= EntityLifeStage.Terminating) + return; // Regardless of whether we're on a subfloor or not, unhide. UpdateEntity(uid, true); @@ -125,7 +126,7 @@ namespace Content.Shared.SubFloor { foreach (var comp in EntityManager.EntityQuery(true)) { - UpdateEntity(comp.Owner.Uid); + UpdateEntity(comp.Owner); } } diff --git a/Content.Shared/Tabletop/SharedTabletopSystem.cs b/Content.Shared/Tabletop/SharedTabletopSystem.cs index 3e395a1543..da267354de 100644 --- a/Content.Shared/Tabletop/SharedTabletopSystem.cs +++ b/Content.Shared/Tabletop/SharedTabletopSystem.cs @@ -44,7 +44,7 @@ namespace Content.Shared.Tabletop return false; } - if (!parent.HasComponent() && !parent.HasComponent()) + if (!EntityManager.HasComponent(parent) && !EntityManager.HasComponent(parent)) { return false; } diff --git a/Content.Shared/Tag/TagComponentExtensions.cs b/Content.Shared/Tag/TagComponentExtensions.cs index 082a160705..b722b8699f 100644 --- a/Content.Shared/Tag/TagComponentExtensions.cs +++ b/Content.Shared/Tag/TagComponentExtensions.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Prototypes; namespace Content.Shared.Tag @@ -17,7 +18,7 @@ namespace Content.Shared.Tag /// /// Thrown if no exists with the given id. /// - public static bool AddTag(this IEntity entity, string id) + public static bool AddTag(this EntityUid entity, string id) { return entity.EnsureComponent(out TagComponent tagComponent) && tagComponent.AddTag(id); @@ -34,7 +35,7 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool AddTags(this IEntity entity, params string[] ids) + public static bool AddTags(this EntityUid entity, params string[] ids) { return entity.EnsureComponent(out TagComponent tagComponent) && tagComponent.AddTags(ids); @@ -51,7 +52,7 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool AddTags(this IEntity entity, IEnumerable ids) + public static bool AddTags(this EntityUid entity, IEnumerable ids) { return entity.EnsureComponent(out TagComponent tagComponent) && tagComponent.AddTags(ids); @@ -69,9 +70,9 @@ namespace Content.Shared.Tag /// /// Thrown if no exists with the given id. /// - public static bool TryAddTag(this IEntity entity, string id) + public static bool TryAddTag(this EntityUid entity, string id) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.AddTag(id); } @@ -87,9 +88,9 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool TryAddTags(this IEntity entity, params string[] ids) + public static bool TryAddTags(this EntityUid entity, params string[] ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.AddTags(ids); } @@ -105,9 +106,9 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool TryAddTags(this IEntity entity, IEnumerable ids) + public static bool TryAddTags(this EntityUid entity, IEnumerable ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.AddTags(ids); } @@ -120,9 +121,9 @@ namespace Content.Shared.Tag /// /// Thrown if no exists with the given id. /// - public static bool HasTag(this IEntity entity, string id) + public static bool HasTag(this EntityUid entity, string id) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.HasTag(id); } @@ -135,9 +136,9 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool HasAllTags(this IEntity entity, params string[] ids) + public static bool HasAllTags(this EntityUid entity, params string[] ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.HasAllTags(ids); } @@ -150,9 +151,9 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool HasAllTags(this IEntity entity, IEnumerable ids) + public static bool HasAllTags(this EntityUid entity, IEnumerable ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.HasAllTags(ids); } @@ -165,9 +166,9 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool HasAnyTag(this IEntity entity, params string[] ids) + public static bool HasAnyTag(this EntityUid entity, params string[] ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.HasAnyTag(ids); } @@ -180,9 +181,9 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool HasAnyTag(this IEntity entity, IEnumerable ids) + public static bool HasAnyTag(this EntityUid entity, IEnumerable ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.HasAnyTag(ids); } @@ -197,9 +198,9 @@ namespace Content.Shared.Tag /// /// Thrown if no exists with the given id. /// - public static bool RemoveTag(this IEntity entity, string id) + public static bool RemoveTag(this EntityUid entity, string id) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.RemoveTag(id); } @@ -214,9 +215,9 @@ namespace Content.Shared.Tag /// Thrown if one of the ids represents an unregistered . /// /// - public static bool RemoveTags(this IEntity entity, params string[] ids) + public static bool RemoveTags(this EntityUid entity, params string[] ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.RemoveTags(ids); } @@ -231,9 +232,9 @@ namespace Content.Shared.Tag /// /// Thrown if one of the ids represents an unregistered . /// - public static bool RemoveTags(this IEntity entity, IEnumerable ids) + public static bool RemoveTags(this EntityUid entity, IEnumerable ids) { - return entity.TryGetComponent(out TagComponent? tagComponent) && + return IoCManager.Resolve().TryGetComponent(entity, out TagComponent? tagComponent) && tagComponent.RemoveTags(ids); } } diff --git a/Content.Shared/Throwing/IThrown.cs b/Content.Shared/Throwing/IThrown.cs index 03e308232d..6d26a0d8b9 100644 --- a/Content.Shared/Throwing/IThrown.cs +++ b/Content.Shared/Throwing/IThrown.cs @@ -17,12 +17,12 @@ namespace Content.Shared.Throwing public class ThrownEventArgs : EventArgs { - public ThrownEventArgs(IEntity user) + public ThrownEventArgs(EntityUid user) { User = user; } - public IEntity User { get; } + public EntityUid User { get; } } /// @@ -34,14 +34,14 @@ namespace Content.Shared.Throwing /// /// Entity that threw the item. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// Item that was thrown. /// - public IEntity Thrown { get; } + public EntityUid Thrown { get; } - public ThrownEvent(IEntity user, IEntity thrown) + public ThrownEvent(EntityUid user, EntityUid thrown) { User = user; Thrown = thrown; diff --git a/Content.Shared/Throwing/ThrowEvents.cs b/Content.Shared/Throwing/ThrowEvents.cs index 714ff3af7b..1142eceb07 100644 --- a/Content.Shared/Throwing/ThrowEvents.cs +++ b/Content.Shared/Throwing/ThrowEvents.cs @@ -13,19 +13,19 @@ namespace Content.Shared.Throwing /// /// The entity that threw . /// - public IEntity? User { get; } + public EntityUid? User { get; } /// /// The entity thrown by that hit /// - public IEntity Thrown { get; } + public EntityUid Thrown { get; } /// /// The entity hit with by /// - public IEntity Target { get; } + public EntityUid Target { get; } - public ThrowEvent(IEntity? user, IEntity thrown, IEntity target) + public ThrowEvent(EntityUid? user, EntityUid thrown, EntityUid target) { User = user; Thrown = thrown; @@ -38,7 +38,7 @@ namespace Content.Shared.Throwing /// public class ThrowHitByEvent : ThrowEvent { - public ThrowHitByEvent(IEntity? user, IEntity thrown, IEntity target) : base(user, thrown, target) + public ThrowHitByEvent(EntityUid? user, EntityUid thrown, EntityUid target) : base(user, thrown, target) { } } @@ -48,7 +48,7 @@ namespace Content.Shared.Throwing /// public class ThrowDoHitEvent : ThrowEvent { - public ThrowDoHitEvent(IEntity? user, IEntity thrown, IEntity target) : base(user, thrown, target) + public ThrowDoHitEvent(EntityUid? user, EntityUid thrown, EntityUid target) : base(user, thrown, target) { } } diff --git a/Content.Shared/Throwing/ThrownItemComponent.cs b/Content.Shared/Throwing/ThrownItemComponent.cs index 6a4e49cc28..404ee8e9f0 100644 --- a/Content.Shared/Throwing/ThrownItemComponent.cs +++ b/Content.Shared/Throwing/ThrownItemComponent.cs @@ -10,7 +10,7 @@ namespace Content.Shared.Throwing { public override string Name => "ThrownItem"; - public IEntity? Thrower { get; set; } + public EntityUid? Thrower { get; set; } } [Serializable, NetSerializable] diff --git a/Content.Shared/Throwing/ThrownItemSystem.cs b/Content.Shared/Throwing/ThrownItemSystem.cs index 5a73b751a7..f31f02f70d 100644 --- a/Content.Shared/Throwing/ThrownItemSystem.cs +++ b/Content.Shared/Throwing/ThrownItemSystem.cs @@ -1,5 +1,4 @@ using Content.Shared.Administration.Logs; -using Content.Shared.CCVar; using Content.Shared.Database; using Content.Shared.Hands.Components; using Content.Shared.Physics; @@ -39,21 +38,23 @@ namespace Content.Shared.Throwing private void OnGetState(EntityUid uid, ThrownItemComponent component, ref ComponentGetState args) { - args.State = new ThrownItemComponentState(component.Thrower?.Uid); + args.State = new ThrownItemComponentState(component.Thrower); } private void OnHandleState(EntityUid uid, ThrownItemComponent component, ref ComponentHandleState args) { - if (args.Current is not ThrownItemComponentState state || state.Thrower == null) + if (args.Current is not ThrownItemComponentState {Thrower: not null } state || + !state.Thrower.Value.IsValid()) + { return; + } - if(EntityManager.TryGetEntity(state.Thrower.Value, out var entity)) - component.Thrower = entity; + component.Thrower = state.Thrower.Value; } private void ThrowItem(EntityUid uid, ThrownItemComponent component, ThrownEvent args) { - if (!component.Owner.TryGetComponent(out PhysicsComponent? physicsComponent) || + if (!EntityManager.TryGetComponent(component.Owner, out PhysicsComponent? physicsComponent) || physicsComponent.Fixtures.Count != 1) return; if (_fixtures.GetFixtureOrNull(physicsComponent, ThrowingFixture) != null) @@ -91,8 +92,8 @@ namespace Content.Shared.Throwing private void HandlePullStarted(PullStartedMessage message) { // TODO: this isn't directed so things have to be done the bad way - if (EntityManager.TryGetComponent(message.Pulled.Owner.Uid, out ThrownItemComponent? thrownItemComponent)) - StopThrow(message.Pulled.Owner.Uid, thrownItemComponent); + if (EntityManager.TryGetComponent(message.Pulled.Owner, out ThrownItemComponent? thrownItemComponent)) + StopThrow(message.Pulled.Owner, thrownItemComponent); } private void StopThrow(EntityUid uid, ThrownItemComponent thrownItemComponent) @@ -107,21 +108,21 @@ namespace Content.Shared.Throwing } } - EntityManager.EventBus.RaiseLocalEvent(uid, new StopThrowEvent {User = thrownItemComponent.Thrower?.Uid}); + EntityManager.EventBus.RaiseLocalEvent(uid, new StopThrowEvent {User = thrownItemComponent.Thrower}); EntityManager.RemoveComponent(uid); } public void LandComponent(ThrownItemComponent thrownItem) { - if (thrownItem.Deleted || thrownItem.Owner.Deleted || _containerSystem.IsEntityInContainer(thrownItem.Owner.Uid)) return; + if (thrownItem.Deleted || Deleted(thrownItem.Owner) || _containerSystem.IsEntityInContainer(thrownItem.Owner)) return; var landing = thrownItem.Owner; // Unfortunately we can't check for hands containers as they have specific names. if (thrownItem.Owner.TryGetContainerMan(out var containerManager) && - containerManager.Owner.HasComponent()) + EntityManager.HasComponent(containerManager.Owner)) { - EntityManager.RemoveComponent(landing.Uid, thrownItem); + EntityManager.RemoveComponent(landing, thrownItem); return; } @@ -129,21 +130,21 @@ namespace Content.Shared.Throwing if (thrownItem.Thrower is not null) _adminLogSystem.Add(LogType.Landed, LogImpact.Low, $"{landing} thrown by {thrownItem.Thrower:thrower} landed."); - var landMsg = new LandEvent {User = thrownItem.Thrower?.Uid}; - RaiseLocalEvent(landing.Uid, landMsg, false); + var landMsg = new LandEvent {User = thrownItem.Thrower}; + RaiseLocalEvent(landing, landMsg, false); } /// /// Raises collision events on the thrown and target entities. /// - public void ThrowCollideInteraction(IEntity? user, IPhysBody thrown, IPhysBody target) + public void ThrowCollideInteraction(EntityUid? user, IPhysBody thrown, IPhysBody target) { if (user is not null) _adminLogSystem.Add(LogType.ThrowHit, LogImpact.Low, $"{thrown.Owner:thrown} thrown by {user:thrower} hit {target.Owner:target}."); // TODO: Just pass in the bodies directly - RaiseLocalEvent(target.Owner.Uid, new ThrowHitByEvent(user, thrown.Owner, target.Owner)); - RaiseLocalEvent(thrown.Owner.Uid, new ThrowDoHitEvent(user, thrown.Owner, target.Owner)); + RaiseLocalEvent(target.Owner, new ThrowHitByEvent(user, thrown.Owner, target.Owner)); + RaiseLocalEvent(thrown.Owner, new ThrowDoHitEvent(user, thrown.Owner, target.Owner)); } } } diff --git a/Content.Shared/Timing/UseDelayComponent.cs b/Content.Shared/Timing/UseDelayComponent.cs index 79793296a2..f0d7c03d5a 100644 --- a/Content.Shared/Timing/UseDelayComponent.cs +++ b/Content.Shared/Timing/UseDelayComponent.cs @@ -46,7 +46,7 @@ namespace Content.Shared.Timing _lastUseTime = IoCManager.Resolve().CurTime; - if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown)) + if (IoCManager.Resolve().TryGetComponent(Owner, out ItemCooldownComponent? cooldown)) { cooldown.CooldownStart = _lastUseTime; cooldown.CooldownEnd = _lastUseTime + TimeSpan.FromSeconds(Delay); @@ -59,7 +59,7 @@ namespace Content.Shared.Timing cancellationTokenSource?.Cancel(); ActiveDelay = false; - if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown)) + if (IoCManager.Resolve().TryGetComponent(Owner, out ItemCooldownComponent? cooldown)) { cooldown.CooldownEnd = IoCManager.Resolve().CurTime; } diff --git a/Content.Shared/Transform/TransformExtensions.cs b/Content.Shared/Transform/TransformExtensions.cs index fcc2473b08..a8a389234a 100644 --- a/Content.Shared/Transform/TransformExtensions.cs +++ b/Content.Shared/Transform/TransformExtensions.cs @@ -1,4 +1,5 @@ using Robust.Shared.GameObjects; +using Robust.Shared.IoC; namespace Content.Shared.Transform { @@ -17,9 +18,9 @@ namespace Content.Shared.Transform transform.AttachParent(grandParent); } - public static void AttachToGrandparent(this IEntity entity) + public static void AttachToGrandparent(this EntityUid entity) { - AttachToGrandparent(entity.Transform); + AttachToGrandparent(IoCManager.Resolve().GetComponent(entity)); } } } diff --git a/Content.Shared/Verbs/SharedVerbSystem.cs b/Content.Shared/Verbs/SharedVerbSystem.cs index a6771c4fd7..9d9e76c373 100644 --- a/Content.Shared/Verbs/SharedVerbSystem.cs +++ b/Content.Shared/Verbs/SharedVerbSystem.cs @@ -20,7 +20,7 @@ namespace Content.Shared.Verbs /// Raises a number of events in order to get all verbs of the given type(s) defined in local systems. This /// does not request verbs from the server. /// - public virtual Dictionary> GetLocalVerbs(IEntity target, IEntity user, VerbType verbTypes, bool force = false) + public virtual Dictionary> GetLocalVerbs(EntityUid target, EntityUid user, VerbType verbTypes, bool force = false) { Dictionary> verbs = new(); @@ -34,52 +34,52 @@ namespace Content.Shared.Verbs canAccess = true; else // the item might be in a backpack that the user has open - canAccess = _interactionSystem.CanAccessViaStorage(user.Uid, target.Uid); + canAccess = _interactionSystem.CanAccessViaStorage(user, target); } // A large number of verbs need to check action blockers. Instead of repeatedly having each system individually // call ActionBlocker checks, just cache it for the verb request. - var canInteract = force || _actionBlockerSystem.CanInteract(user.Uid); + var canInteract = force || _actionBlockerSystem.CanInteract(user); - IEntity? @using = null; - if (user.TryGetComponent(out SharedHandsComponent? hands) && (force || _actionBlockerSystem.CanUse(user.Uid))) + EntityUid @using = default; + if (EntityManager.TryGetComponent(user, out SharedHandsComponent? hands) && (force || _actionBlockerSystem.CanUse(user))) { hands.TryGetActiveHeldEntity(out @using); // Check whether the "Held" entity is a virtual pull entity. If yes, set that as the entity being "Used". // This allows you to do things like buckle a dragged person onto a surgery table, without click-dragging // their sprite. - if (@using != null && @using.TryGetComponent(out var pull)) + if (@using != default && EntityManager.TryGetComponent(@using, out var pull)) { - @using = IoCManager.Resolve().GetEntity(pull.BlockingEntity); + @using = pull.BlockingEntity; } } if ((verbTypes & VerbType.Interaction) == VerbType.Interaction) { GetInteractionVerbsEvent getVerbEvent = new(user, target, @using, hands, canInteract, canAccess); - RaiseLocalEvent(target.Uid, getVerbEvent); + RaiseLocalEvent(target, getVerbEvent); verbs.Add(VerbType.Interaction, getVerbEvent.Verbs); } if ((verbTypes & VerbType.Activation) == VerbType.Activation) { GetActivationVerbsEvent getVerbEvent = new(user, target, @using, hands, canInteract, canAccess); - RaiseLocalEvent(target.Uid, getVerbEvent); + RaiseLocalEvent(target, getVerbEvent); verbs.Add(VerbType.Activation, getVerbEvent.Verbs); } if ((verbTypes & VerbType.Alternative) == VerbType.Alternative) { GetAlternativeVerbsEvent getVerbEvent = new(user, target, @using, hands, canInteract, canAccess); - RaiseLocalEvent(target.Uid, getVerbEvent); + RaiseLocalEvent(target, getVerbEvent); verbs.Add(VerbType.Alternative, getVerbEvent.Verbs); } if ((verbTypes & VerbType.Other) == VerbType.Other) { GetOtherVerbsEvent getVerbEvent = new(user, target, @using, hands, canInteract, canAccess); - RaiseLocalEvent(target.Uid, getVerbEvent); + RaiseLocalEvent(target, getVerbEvent); verbs.Add(VerbType.Other, getVerbEvent.Verbs); } @@ -110,26 +110,25 @@ namespace Content.Shared.Verbs } } - public void LogVerb(Verb verb, EntityUid userUid, EntityUid targetUid, bool forced) + public void LogVerb(Verb verb, EntityUid user, EntityUid target, bool forced) { // first get the held item. again. - EntityUid? usedUid = null; - if (EntityManager.TryGetComponent(userUid, out SharedHandsComponent? hands)) + EntityUid usedUid = default; + if (EntityManager.TryGetComponent(user, out SharedHandsComponent? hands) && + hands.TryGetActiveHeldEntity(out var heldEntity)) { - hands.TryGetActiveHeldEntity(out var useEntityd); - usedUid = useEntityd?.Uid; - if (usedUid != null && EntityManager.TryGetComponent(usedUid.Value, out HandVirtualItemComponent? pull)) + usedUid = heldEntity; + if (usedUid != default && EntityManager.TryGetComponent(usedUid, out HandVirtualItemComponent? pull)) usedUid = pull.BlockingEntity; } // get all the entities - if (!EntityManager.TryGetEntity(userUid, out var user) || - !EntityManager.TryGetEntity(targetUid, out var target)) + if (!user.IsValid() || !target.IsValid()) return; - IEntity? used = null; - if (usedUid != null) - EntityManager.TryGetEntity(usedUid.Value, out used); + EntityUid? used = null; + if (usedUid != default) + EntityManager.EntityExists(usedUid); // then prepare the basic log message body var verbText = $"{verb.Category?.Text} {verb.Text}".Trim(); diff --git a/Content.Shared/Verbs/VerbEvents.cs b/Content.Shared/Verbs/VerbEvents.cs index 49c89ce283..e11386c36b 100644 --- a/Content.Shared/Verbs/VerbEvents.cs +++ b/Content.Shared/Verbs/VerbEvents.cs @@ -81,7 +81,7 @@ namespace Content.Shared.Verbs /// public class GetInteractionVerbsEvent : GetVerbsEvent { - public GetInteractionVerbsEvent(IEntity user, IEntity target, IEntity? @using, SharedHandsComponent? hands, + public GetInteractionVerbsEvent(EntityUid user, EntityUid target, EntityUid? @using, SharedHandsComponent? hands, bool canInteract, bool canAccess) : base(user, target, @using, hands, canInteract, canAccess) { } } @@ -97,7 +97,7 @@ namespace Content.Shared.Verbs /// public class GetActivationVerbsEvent : GetVerbsEvent { - public GetActivationVerbsEvent(IEntity user, IEntity target, IEntity? @using, SharedHandsComponent? hands, + public GetActivationVerbsEvent(EntityUid user, EntityUid target, EntityUid? @using, SharedHandsComponent? hands, bool canInteract, bool canAccess) : base(user, target, @using, hands, canInteract, canAccess) { } } @@ -110,7 +110,7 @@ namespace Content.Shared.Verbs /// public class GetAlternativeVerbsEvent : GetVerbsEvent { - public GetAlternativeVerbsEvent(IEntity user, IEntity target, IEntity? @using, SharedHandsComponent? hands, + public GetAlternativeVerbsEvent(EntityUid user, EntityUid target, EntityUid? @using, SharedHandsComponent? hands, bool canInteract, bool canAccess) : base(user, target, @using, hands, canInteract, canAccess) { } } @@ -123,7 +123,7 @@ namespace Content.Shared.Verbs /// public class GetOtherVerbsEvent : GetVerbsEvent { - public GetOtherVerbsEvent(IEntity user, IEntity target, IEntity? @using, SharedHandsComponent? hands, + public GetOtherVerbsEvent(EntityUid user, EntityUid target, EntityUid? @using, SharedHandsComponent? hands, bool canInteract, bool canAccess) : base(user, target, @using, hands, canInteract, canAccess) { } } @@ -149,12 +149,12 @@ namespace Content.Shared.Verbs /// /// The entity being targeted for the verb. /// - public readonly IEntity Target; + public readonly EntityUid Target; /// /// The entity that will be "performing" the verb. /// - public readonly IEntity User; + public readonly EntityUid User; /// /// Can the user physically interact? @@ -178,17 +178,12 @@ namespace Content.Shared.Verbs /// The entity currently being held by the active hand. /// /// - /// This is only ever not null when is true and the user + /// This is only ever not null when is true and the user /// has hands. /// - public readonly IEntity? Using; + public readonly EntityUid? Using; - // for eventual removal of IEntity. - public EntityUid UserUid => User.Uid; - public EntityUid TargetUid => Target.Uid; - public EntityUid? UsingUid => Using?.Uid; - - public GetVerbsEvent(IEntity user, IEntity target, IEntity? @using, SharedHandsComponent? hands, bool canInteract, bool canAccess) + public GetVerbsEvent(EntityUid user, EntityUid target, EntityUid? @using, SharedHandsComponent? hands, bool canInteract, bool canAccess) { User = user; Target = target; diff --git a/Content.Shared/Weapons/Melee/AttackEvent.cs b/Content.Shared/Weapons/Melee/AttackEvent.cs index c053694d46..b55bef6b0c 100644 --- a/Content.Shared/Weapons/Melee/AttackEvent.cs +++ b/Content.Shared/Weapons/Melee/AttackEvent.cs @@ -12,12 +12,12 @@ namespace Content.Shared.Weapons.Melee /// /// Entity used to attack, for broadcast purposes. /// - public IEntity Used { get; } + public EntityUid Used { get; } /// /// Entity that triggered the attack. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// The original location that was clicked by the user. @@ -32,17 +32,16 @@ namespace Content.Shared.Weapons.Melee /// /// Entity that was attacked. /// - public IEntity? TargetEntity { get; } + public EntityUid? TargetEntity { get; } - public ClickAttackEvent(IEntity used, IEntity user, EntityCoordinates clickLocation, EntityUid target = default) + public ClickAttackEvent(EntityUid used, EntityUid user, EntityCoordinates clickLocation, EntityUid target = default) { Used = used; User = user; ClickLocation = clickLocation; Target = target; - IoCManager.Resolve().TryGetEntity(Target, out var targetEntity); - TargetEntity = targetEntity; + TargetEntity = IoCManager.Resolve().EntityExists(Target) ? Target : default(EntityUid?); } } @@ -54,19 +53,19 @@ namespace Content.Shared.Weapons.Melee /// /// Entity used to attack, for broadcast purposes. /// - public IEntity Used { get; } + public EntityUid Used { get; } /// /// Entity that triggered the attack. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// The original location that was clicked by the user. /// public EntityCoordinates ClickLocation { get; } - public WideAttackEvent(IEntity used, IEntity user, EntityCoordinates clickLocation) + public WideAttackEvent(EntityUid used, EntityUid user, EntityCoordinates clickLocation) { Used = used; User = user; @@ -82,19 +81,19 @@ namespace Content.Shared.Weapons.Melee /// /// Entity used to attack, for broadcast purposes. /// - public IEntity Used { get; } + public EntityUid Used { get; } /// /// Entity that triggered the attack. /// - public IEntity User { get; } + public EntityUid User { get; } /// /// The original location that was clicked by the user. /// public EntityCoordinates ClickLocation { get; } - public AttackedEvent(IEntity used, IEntity user, EntityCoordinates clickLocation) + public AttackedEvent(EntityUid used, EntityUid user, EntityCoordinates clickLocation) { Used = used; User = user; diff --git a/Content.Tests/Shared/Chemistry/FixedPoint2_Tests.cs b/Content.Tests/Shared/Chemistry/FixedPoint2_Tests.cs index b4e4c9772b..dae9806e63 100644 --- a/Content.Tests/Shared/Chemistry/FixedPoint2_Tests.cs +++ b/Content.Tests/Shared/Chemistry/FixedPoint2_Tests.cs @@ -1,6 +1,4 @@ using System; -using Content.Shared.Chemistry; -using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using NUnit.Framework; @@ -108,7 +106,7 @@ namespace Content.Tests.Shared.Chemistry [TestCase(2.005f, 201)] public void FloatRoundingTest(float a, int expected) { - var result = (int) MathF.Round(a * (float) MathF.Pow(10, 2), MidpointRounding.AwayFromZero); + var result = (int) MathF.Round(a * MathF.Pow(10, 2), MidpointRounding.AwayFromZero); Assert.That(result, Is.EqualTo(expected)); } diff --git a/RobustToolbox b/RobustToolbox index c6a9113144..2fd15b0375 160000 --- a/RobustToolbox +++ b/RobustToolbox @@ -1 +1 @@ -Subproject commit c6a91131443459105bccd6c9c27be4b6cc09c21a +Subproject commit 2fd15b037569f3ce810248fedb0e4c648ce409ce