Merge branch 'master' into 2020-04-28-tool-component

This commit is contained in:
zumorica
2020-05-11 12:24:43 +02:00
114 changed files with 3532 additions and 531 deletions

View File

@@ -151,6 +151,12 @@ namespace Content.Server.GameObjects
return success;
}
public void PutInHandOrDrop(ItemComponent item)
{
if (!PutInHand(item))
item.Owner.Transform.GridPosition = Owner.Transform.GridPosition;
}
public bool CanPutInHand(ItemComponent item)
{
foreach (var hand in ActivePriorityEnumerable())

View File

@@ -0,0 +1,206 @@
using Content.Server.GameObjects.Components.Damage;
using Content.Server.GameObjects.Components.Interactable.Tools;
using Content.Server.GameObjects.Components.Power;
using Content.Server.GameObjects.EntitySystems;
using Content.Server.Interfaces;
using Content.Shared.GameObjects.Components.Gravity;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Robust.Server.GameObjects;
using Robust.Server.GameObjects.Components.UserInterface;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Server.Interfaces.GameObjects;
using Robust.Server.Interfaces.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Serialization;
namespace Content.Server.GameObjects.Components.Gravity
{
[RegisterComponent]
public class GravityGeneratorComponent: SharedGravityGeneratorComponent, IAttackBy, IBreakAct, IAttackHand
{
private BoundUserInterface _userInterface;
private PowerDeviceComponent _powerDevice;
private SpriteComponent _sprite;
private bool _switchedOn;
private bool _intact;
private GravityGeneratorStatus _status;
public bool Powered => _powerDevice.Powered;
public bool SwitchedOn => _switchedOn;
public bool Intact => _intact;
public GravityGeneratorStatus Status => _status;
public bool NeedsUpdate
{
get
{
switch (_status)
{
case GravityGeneratorStatus.On:
return !(Powered && SwitchedOn && Intact);
case GravityGeneratorStatus.Off:
return SwitchedOn || !(Powered && Intact);
case GravityGeneratorStatus.Unpowered:
return SwitchedOn || Powered || !Intact;
case GravityGeneratorStatus.Broken:
return SwitchedOn || Powered || Intact;
default:
return true; // This _should_ be unreachable
}
}
}
public override string Name => "GravityGenerator";
public override void Initialize()
{
base.Initialize();
_userInterface = Owner.GetComponent<ServerUserInterfaceComponent>()
.GetBoundUserInterface(GravityGeneratorUiKey.Key);
_userInterface.OnReceiveMessage += HandleUIMessage;
_powerDevice = Owner.GetComponent<PowerDeviceComponent>();
_sprite = Owner.GetComponent<SpriteComponent>();
_switchedOn = true;
_intact = true;
_status = GravityGeneratorStatus.On;
UpdateState();
}
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _switchedOn, "switched_on", true);
serializer.DataField(ref _intact, "intact", true);
}
bool IAttackHand.AttackHand(AttackHandEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent<IActorComponent>(out var actor))
return false;
if (Status != GravityGeneratorStatus.Off && Status != GravityGeneratorStatus.On)
{
return false;
}
OpenUserInterface(actor.playerSession);
return true;
}
public bool AttackBy(AttackByEventArgs eventArgs)
{
if (!eventArgs.AttackWith.TryGetComponent<WelderComponent>(out var welder)) return false;
if (welder.TryUse(5.0f))
{
// Repair generator
var damagable = Owner.GetComponent<DamageableComponent>();
var breakable = Owner.GetComponent<BreakableComponent>();
damagable.HealAllDamage();
breakable.broken = false;
_intact = true;
var entitySystemManager = IoCManager.Resolve<IEntitySystemManager>();
var notifyManager = IoCManager.Resolve<IServerNotifyManager>();
entitySystemManager.GetEntitySystem<AudioSystem>().Play("/Audio/items/welder2.ogg", Owner);
notifyManager.PopupMessage(Owner, eventArgs.User, Loc.GetString("You repair the gravity generator with the welder"));
return true;
} else
{
return false;
}
}
public void OnBreak(BreakageEventArgs eventArgs)
{
_intact = false;
_switchedOn = false;
}
public void UpdateState()
{
if (!Intact)
{
MakeBroken();
} else if (!Powered)
{
MakeUnpowered();
} else if (!SwitchedOn)
{
MakeOff();
} else
{
MakeOn();
}
}
private void HandleUIMessage(ServerBoundUserInterfaceMessage message)
{
switch (message.Message)
{
case GeneratorStatusRequestMessage _:
_userInterface.SetState(new GeneratorState(Status == GravityGeneratorStatus.On));
break;
case SwitchGeneratorMessage msg:
_switchedOn = msg.On;
UpdateState();
break;
default:
break;
}
}
private void OpenUserInterface(IPlayerSession playerSession)
{
_userInterface.Open(playerSession);
}
private void MakeBroken()
{
_status = GravityGeneratorStatus.Broken;
_sprite.LayerSetState(0, "broken");
_sprite.LayerSetVisible(1, false);
}
private void MakeUnpowered()
{
_status = GravityGeneratorStatus.Unpowered;
_sprite.LayerSetState(0, "off");
_sprite.LayerSetVisible(1, false);
}
private void MakeOff()
{
_status = GravityGeneratorStatus.Off;
_sprite.LayerSetState(0, "off");
_sprite.LayerSetVisible(1, false);
}
private void MakeOn()
{
_status = GravityGeneratorStatus.On;
_sprite.LayerSetState(0, "on");
_sprite.LayerSetVisible(1, true);
}
}
public enum GravityGeneratorStatus
{
Broken,
Unpowered,
Off,
On
}
}

View File

@@ -45,6 +45,8 @@ namespace Content.Server.GameObjects
private int StorageCapacityMax = 10000;
public HashSet<IPlayerSession> SubscribedSessions = new HashSet<IPlayerSession>();
public IReadOnlyCollection<IEntity> StoredEntities => storage.ContainedEntities;
public override void Initialize()
{
base.Initialize();
@@ -140,7 +142,6 @@ namespace Content.Server.GameObjects
/// <returns></returns>
public bool AttackBy(AttackByEventArgs eventArgs)
{
_ensureInitialCalculated();
Logger.DebugS("Storage", "Storage (UID {0}) attacked by user (UID {1}) with entity (UID {2}).", Owner.Uid, eventArgs.User.Uid, eventArgs.AttackWith.Uid);
if(Owner.TryGetComponent<PlaceableSurfaceComponent>(out var placeableSurfaceComponent))
@@ -363,8 +364,10 @@ namespace Content.Server.GameObjects
/// <summary>
/// Inserts an entity into the storage component from the players active hand.
/// </summary>
private bool PlayerInsertEntity(IEntity player)
public bool PlayerInsertEntity(IEntity player)
{
_ensureInitialCalculated();
if (!player.TryGetComponent(out IHandsComponent hands) || hands.GetActiveHand == null)
return false;

View File

@@ -0,0 +1,408 @@
using System.Collections.Generic;
using System.Linq;
using Content.Server.GameObjects.EntitySystems;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.ViewVariables;
using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.Components.Nutrition;
using Content.Shared.Chemistry;
using Robust.Shared.Serialization;
using Robust.Shared.Interfaces.GameObjects;
using Content.Shared.Prototypes.Kitchen;
using Content.Shared.Kitchen;
using Robust.Shared.Timers;
using Robust.Server.GameObjects;
using Content.Shared.GameObjects.Components.Power;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Server.GameObjects.Components.Container;
using Content.Server.GameObjects.Components.Power;
using Robust.Server.GameObjects.Components.UserInterface;
using Robust.Server.Interfaces.GameObjects;
using Robust.Shared.Prototypes;
using Robust.Shared.Localization;
using Content.Server.Interfaces;
using Robust.Shared.Audio;
using YamlDotNet.Serialization.NodeTypeResolvers;
namespace Content.Server.GameObjects.Components.Kitchen
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
public class KitchenMicrowaveComponent : SharedMicrowaveComponent, IActivate, IAttackBy, ISolutionChange
{
#pragma warning disable 649
[Dependency] private readonly IEntitySystemManager _entitySystemManager;
[Dependency] private readonly IEntityManager _entityManager;
[Dependency] private readonly RecipeManager _recipeManager;
[Dependency] private readonly IServerNotifyManager _notifyManager;
#pragma warning restore 649
#region YAMLSERIALIZE
private int _cookTimeDefault;
private int _cookTimeMultiplier; //For upgrades and stuff I guess?
private string _badRecipeName;
private string _startCookingSound;
private string _cookingCompleteSound;
#endregion
#region VIEWVARIABLES
[ViewVariables]
private SolutionComponent _solution;
[ViewVariables]
private bool _busy = false;
/// <summary>
/// This is a fixed offset of 5.
/// The cook times for all recipes should be divisible by 5,with a minimum of 1 second.
/// For right now, I don't think any recipe cook time should be greater than 60 seconds.
/// </summary>
[ViewVariables]
private uint _currentCookTimerTime { get; set; } = 1;
#endregion
private bool Powered => _powerDevice.Powered;
private bool HasContents => _solution.ReagentList.Count > 0 || _storage.ContainedEntities.Count > 0;
void ISolutionChange.SolutionChanged(SolutionChangeEventArgs eventArgs) => UpdateUserInterface();
private AudioSystem _audioSystem;
private AppearanceComponent _appearance;
private PowerDeviceComponent _powerDevice;
private BoundUserInterface _userInterface;
private Container _storage;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _badRecipeName, "failureResult", "FoodBadRecipe");
serializer.DataField(ref _cookTimeDefault, "cookTime", 5);
serializer.DataField(ref _cookTimeMultiplier, "cookTimeMultiplier", 1000);
serializer.DataField(ref _startCookingSound, "beginCookingSound","/Audio/machines/microwave_start_beep.ogg" );
serializer.DataField(ref _cookingCompleteSound, "foodDoneSound","/Audio/machines/microwave_done_beep.ogg" );
}
public override void Initialize()
{
base.Initialize();
_solution ??= Owner.TryGetComponent(out SolutionComponent solutionComponent)
? solutionComponent
: Owner.AddComponent<SolutionComponent>();
_storage = ContainerManagerComponent.Ensure<Container>("microwave_entity_container", Owner, out var existed);
_appearance = Owner.GetComponent<AppearanceComponent>();
_powerDevice = Owner.GetComponent<PowerDeviceComponent>();
_audioSystem = _entitySystemManager.GetEntitySystem<AudioSystem>();
_userInterface = Owner.GetComponent<ServerUserInterfaceComponent>()
.GetBoundUserInterface(MicrowaveUiKey.Key);
_userInterface.OnReceiveMessage += UserInterfaceOnReceiveMessage;
}
private void UserInterfaceOnReceiveMessage(ServerBoundUserInterfaceMessage message)
{
if (!Powered || _busy)
{
return;
}
switch (message.Message)
{
case MicrowaveStartCookMessage msg :
wzhzhzh();
break;
case MicrowaveEjectMessage msg :
if (HasContents)
{
VaporizeReagents();
EjectSolids();
ClickSound();
UpdateUserInterface();
}
break;
case MicrowaveEjectSolidIndexedMessage msg:
if (HasContents)
{
EjectSolidWithIndex(msg.EntityID);
ClickSound();
UpdateUserInterface();
}
break;
case MicrowaveVaporizeReagentIndexedMessage msg:
if (HasContents)
{
VaporizeReagentWithReagentQuantity(msg.ReagentQuantity);
ClickSound();
UpdateUserInterface();
}
break;
case MicrowaveSelectCookTimeMessage msg:
_currentCookTimerTime = msg.newCookTime;
ClickSound();
UpdateUserInterface();
break;
}
}
private void SetAppearance(MicrowaveVisualState state)
{
if (_appearance != null || Owner.TryGetComponent(out _appearance))
{
_appearance.SetData(PowerDeviceVisuals.VisualState, state);
}
}
private void UpdateUserInterface()
{
var solidsVisualList = new List<EntityUid>();
foreach(var item in _storage.ContainedEntities)
{
solidsVisualList.Add(item.Uid);
}
_userInterface.SetState(new MicrowaveUpdateUserInterfaceState(_solution.Solution.Contents, solidsVisualList));
}
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent(out IActorComponent actor) || !Powered)
{
return;
}
UpdateUserInterface();
_userInterface.Open(actor.playerSession);
}
public bool AttackBy(AttackByEventArgs eventArgs)
{
var itemEntity = eventArgs.User.GetComponent<HandsComponent>().GetActiveHand.Owner;
if(itemEntity.TryGetComponent<PourableComponent>(out var attackPourable))
{
//Get target and check if it can be poured into
if (!Owner.TryGetComponent<SolutionComponent>(out var mySolution)
|| !mySolution.CanPourIn)
{
return false;
}
if (!itemEntity.TryGetComponent<SolutionComponent>(out var attackSolution)
|| !attackSolution.CanPourOut)
{
return false;
}
//Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount = ReagentUnit.Min(attackPourable.TransferAmount, mySolution.EmptyVolume);
if (realTransferAmount <= 0) //Special message if container is full
{
_notifyManager.PopupMessage(Owner.Transform.GridPosition, eventArgs.User,
Loc.GetString("Container is full"));
return false;
}
//Move units from attackSolution to targetSolution
var removedSolution = attackSolution.SplitSolution(realTransferAmount);
if (!mySolution.TryAddSolution(removedSolution))
{
return false;
}
_notifyManager.PopupMessage(Owner.Transform.GridPosition, eventArgs.User,
Loc.GetString("Transferred {0}u", removedSolution.TotalVolume));
return true;
}
if (!itemEntity.TryGetComponent(typeof(FoodComponent), out var food))
{
return false;
}
var ent = food.Owner; //Get the entity of the ItemComponent.
_storage.Insert(ent);
UpdateUserInterface();
return true;
}
//This is required. It's 'cook'.
private void wzhzhzh()
{
if (!HasContents)
{
return;
}
_busy = true;
// Convert storage into Dictionary of ingredients
var solidsDict = new Dictionary<string, int>();
foreach(var item in _storage.ContainedEntities)
{
if(solidsDict.ContainsKey(item.Prototype.ID))
{
solidsDict[item.Prototype.ID]++;
}
else
{
solidsDict.Add(item.Prototype.ID, 1);
}
}
// Check recipes
FoodRecipePrototype recipeToCook = null;
foreach(var r in _recipeManager.Recipes)
{
if (!CanSatisfyRecipe(r, solidsDict))
{
continue;
}
recipeToCook = r;
}
var goodMeal = (recipeToCook != null)
&&
(_currentCookTimerTime == (uint)recipeToCook.CookTime) ? true : false;
SetAppearance(MicrowaveVisualState.Cooking);
_audioSystem.Play(_startCookingSound);
Timer.Spawn((int)(_currentCookTimerTime * _cookTimeMultiplier), () =>
{
if (goodMeal)
{
SubtractContents(recipeToCook);
}
else
{
VaporizeReagents();
VaporizeSolids();
}
var entityToSpawn = goodMeal ? recipeToCook.Result : _badRecipeName;
_entityManager.SpawnEntity(entityToSpawn, Owner.Transform.GridPosition);
_audioSystem.Play(_cookingCompleteSound);
SetAppearance(MicrowaveVisualState.Idle);
_busy = false;
});
UpdateUserInterface();
return;
}
private void VaporizeReagents()
{
_solution.RemoveAllSolution();
}
private void VaporizeReagentWithReagentQuantity(Solution.ReagentQuantity reagentQuantity)
{
_solution.TryRemoveReagent(reagentQuantity.ReagentId, reagentQuantity.Quantity);
}
private void VaporizeSolids()
{
for(var i = _storage.ContainedEntities.Count-1; i>=0; i--)
{
var item = _storage.ContainedEntities.ElementAt(i);
_storage.Remove(item);
item.Delete();
}
}
private void EjectSolids()
{
for(var i = _storage.ContainedEntities.Count-1; i>=0; i--)
{
_storage.Remove(_storage.ContainedEntities.ElementAt(i));
}
}
private void EjectSolidWithIndex(EntityUid entityID)
{
if (_entityManager.EntityExists(entityID))
{
_storage.Remove(_entityManager.GetEntity(entityID));
}
}
private void SubtractContents(FoodRecipePrototype recipe)
{
foreach(var recipeReagent in recipe.IngredientsReagents)
{
_solution.TryRemoveReagent(recipeReagent.Key, ReagentUnit.New(recipeReagent.Value));
}
foreach (var recipeSolid in recipe.IngredientsSolids)
{
for (var i = 0; i < recipeSolid.Value; i++)
{
foreach (var item in _storage.ContainedEntities)
{
if (item.Prototype.ID == recipeSolid.Key)
{
_storage.Remove(item);
item.Delete();
break;
}
}
}
}
}
private bool CanSatisfyRecipe(FoodRecipePrototype recipe, Dictionary<string,int> solids)
{
foreach (var reagent in recipe.IngredientsReagents)
{
if (!_solution.ContainsReagent(reagent.Key, out var amount))
{
return false;
}
if (amount.Int() < reagent.Value)
{
return false;
}
}
foreach (var solid in recipe.IngredientsSolids)
{
if (!solids.ContainsKey(solid.Key))
{
return false;
}
if (solids[solid.Key] < solid.Value)
{
return false;
}
}
return true;
}
private void ClickSound()
{
_audioSystem.Play("/Audio/machines/machine_switch.ogg", AudioParams.Default.WithVolume(-2f));
}
}
}

View File

@@ -118,9 +118,17 @@ namespace Content.Server.GameObjects.Components.Mobs
if (!ShowExamineInfo)
return;
var dead = false;
if(Owner.TryGetComponent<SpeciesComponent>(out var species))
if (species.CurrentDamageState is DeadState)
dead = true;
// TODO: Use gendered pronouns depending on the entity
if(!HasMind)
message.AddMarkup($"[color=red]They are totally catatonic. The stresses of life in deep-space must have been too much for them. Any recovery is unlikely.[/color]");
message.AddMarkup(!dead
? $"[color=red]They are totally catatonic. The stresses of life in deep-space must have been too much for them. Any recovery is unlikely.[/color]"
: $"[color=purple]Their soul has departed.[/color]");
else if(Mind.Session == null)
message.AddMarkup("[color=yellow]They have a blank, absent-minded stare and appears completely unresponsive to anything. They may snap out of it soon.[/color]");
}

View File

@@ -177,7 +177,7 @@ namespace Content.Server.GameObjects
currentstate = threshold;
EntityEventArgs toRaise = new MobDamageStateChangedMessage(this);
var toRaise = new MobDamageStateChangedMessage(this);
Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, toRaise);
}

View File

@@ -90,6 +90,15 @@ namespace Content.Server.GameObjects.Components.Movement
}
}
/// <inheritdoc />
[ViewVariables]
public float CurrentPushSpeed => 5.0f;
/// <inheritdoc />
[ViewVariables]
public float GrabRange => 0.2f;
/// <summary>
/// Is the entity Sprinting (running)?
/// </summary>

View File

@@ -67,6 +67,14 @@ namespace Content.Server.GameObjects.Components.Movement
}
}
/// <inheritdoc />
[ViewVariables]
public float CurrentPushSpeed => 5.0f;
/// <inheritdoc />
[ViewVariables]
public float GrabRange => 0.2f;
/// <summary>
/// Is the entity Sprinting (running)?
/// </summary>

View File

@@ -34,6 +34,15 @@ namespace Content.Server.GameObjects.Components.Movement
[ViewVariables(VVAccess.ReadWrite)]
public float CurrentWalkSpeed { get; set; } = 8;
public float CurrentSprintSpeed { get; set; }
/// <inheritdoc />
[ViewVariables]
public float CurrentPushSpeed => 0.0f;
/// <inheritdoc />
[ViewVariables]
public float GrabRange => 0.0f;
public bool Sprinting { get; set; }
public Vector2 VelocityDir { get; } = Vector2.Zero;
public GridCoordinates LastPosition { get; set; }

View File

@@ -1,4 +1,5 @@
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.Audio;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
@@ -16,17 +17,24 @@ namespace Content.Server.GameObjects.Components.Sound
public override string Name => "EmitSoundOnUse";
public string _soundName;
public float _pitchVariation;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _soundName, "sound", "");
serializer.DataField(ref _soundName, "sound", string.Empty);
serializer.DataField(ref _pitchVariation, "variation", 0.0f);
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
if (!string.IsNullOrWhiteSpace(_soundName))
{
if (_pitchVariation > 0.0)
{
Owner.GetComponent<SoundComponent>().Play(_soundName, AudioHelpers.WithVariation(_pitchVariation).WithVolume(-2f));
return true;
}
Owner.GetComponent<SoundComponent>().Play(_soundName, AudioParams.Default.WithVolume(-2f));
return true;
}

View File

@@ -235,6 +235,14 @@ namespace Content.Server.GameObjects.Components
_notifyManager.PopupMessage(Owner.Transform.GridPosition, player, _localizationManager.GetString("You have no hands."));
return;
}
var interactionSystem = IoCManager.Resolve<EntitySystemManager>().GetEntitySystem<InteractionSystem>();
if (!interactionSystem.InRangeUnobstructed(player.Transform.MapPosition, Owner.Transform.WorldPosition, ignoredEnt: Owner))
{
_notifyManager.PopupMessage(Owner.Transform.GridPosition, player, _localizationManager.GetString("You can't reach there!"));
return;
}
var activeHandEntity = handsComponent.GetActiveHand?.Owner;
activeHandEntity.TryGetComponent<ToolComponent>(out var tool);
switch (msg.Action)

View File

@@ -417,8 +417,8 @@ namespace Content.Server.GameObjects.EntitySystems
var inputSys = EntitySystemManager.GetEntitySystem<InputSystem>();
inputSys.BindMap.BindFunction(EngineKeyFunctions.Use,
new PointerInputCmdHandler(HandleUseItemInHand));
inputSys.BindMap.BindFunction(ContentKeyFunctions.Attack,
new PointerInputCmdHandler(HandleAttack));
inputSys.BindMap.BindFunction(ContentKeyFunctions.WideAttack,
new PointerInputCmdHandler(HandleWideAttack));
inputSys.BindMap.BindFunction(ContentKeyFunctions.ActivateItemInWorld,
new PointerInputCmdHandler(HandleActivateItemInWorld));
}
@@ -477,7 +477,7 @@ namespace Content.Server.GameObjects.EntitySystems
activateComp.Activate(new ActivateEventArgs {User = user});
}
private bool HandleAttack(ICommonSession session, GridCoordinates coords, EntityUid uid)
private bool HandleWideAttack(ICommonSession session, GridCoordinates coords, EntityUid uid)
{
// client sanitization
if (!_mapManager.GridExists(coords.GridID))

View File

@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.GameObjects.Components.Gravity;
using Content.Server.GameObjects.Components.Mobs;
using JetBrains.Annotations;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Server.Interfaces.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Map;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Random;
namespace Content.Server.GameObjects.EntitySystems
{
[UsedImplicitly]
public class GravitySystem: EntitySystem
{
#pragma warning disable 649
[Dependency] private readonly IMapManager _mapManager;
[Dependency] private readonly IPlayerManager _playerManager;
[Dependency] private readonly IEntitySystemManager _entitySystemManager;
[Dependency] private readonly IRobustRandom _random;
#pragma warning restore 649
private const float GravityKick = 100.0f;
private const uint ShakeTimes = 10;
private Dictionary<GridId, uint> _gridsToShake;
private float internalTimer = 0.0f;
public override void Initialize()
{
EntityQuery = new TypeEntityQuery<GravityGeneratorComponent>();
_gridsToShake = new Dictionary<GridId, uint>();
}
public override void Update(float frameTime)
{
internalTimer += frameTime;
var gridsWithGravity = new List<GridId>();
foreach (var entity in RelevantEntities)
{
var generator = entity.GetComponent<GravityGeneratorComponent>();
if (generator.NeedsUpdate)
{
generator.UpdateState();
}
if (generator.Status == GravityGeneratorStatus.On)
{
gridsWithGravity.Add(entity.Transform.GridID);
}
}
foreach (var grid in _mapManager.GetAllGrids())
{
if (grid.HasGravity && !gridsWithGravity.Contains(grid.Index))
{
grid.HasGravity = false;
ScheduleGridToShake(grid.Index, ShakeTimes);
} else if (!grid.HasGravity && gridsWithGravity.Contains(grid.Index))
{
grid.HasGravity = true;
ScheduleGridToShake(grid.Index, ShakeTimes);
}
}
if (internalTimer > 0.2f)
{
ShakeGrids();
internalTimer = 0.0f;
}
}
private void ScheduleGridToShake(GridId gridId, uint shakeTimes)
{
if (!_gridsToShake.Keys.Contains(gridId))
{
_gridsToShake.Add(gridId, shakeTimes);
}
else
{
_gridsToShake[gridId] = shakeTimes;
}
// Play the gravity sound
foreach (var player in _playerManager.GetAllPlayers())
{
if (player.AttachedEntity == null
|| player.AttachedEntity.Transform.GridID != gridId) continue;
_entitySystemManager.GetEntitySystem<AudioSystem>().Play("/Audio/effects/alert.ogg", player.AttachedEntity);
}
}
private void ShakeGrids()
{
// I have to copy this because C# doesn't allow changing collections while they're
// getting enumerated.
var gridsToShake = new Dictionary<GridId, uint>(_gridsToShake);
foreach (var gridId in _gridsToShake.Keys)
{
if (_gridsToShake[gridId] == 0)
{
gridsToShake.Remove(gridId);
continue;
}
ShakeGrid(gridId);
gridsToShake[gridId] -= 1;
}
_gridsToShake = gridsToShake;
}
private void ShakeGrid(GridId gridId)
{
foreach (var player in _playerManager.GetAllPlayers())
{
if (player.AttachedEntity == null
|| player.AttachedEntity.Transform.GridID != gridId
|| !player.AttachedEntity.TryGetComponent(out CameraRecoilComponent recoil))
{
continue;
}
recoil.Kick(new Vector2(_random.NextFloat(), _random.NextFloat()) * GravityKick);
}
}
}
}

View File

@@ -1,9 +1,14 @@
using System;
using System.Linq;
using Content.Server.GameObjects;
using Content.Server.GameObjects.Components;
using Content.Server.GameObjects.Components.Stack;
using Content.Server.Interfaces;
using Content.Server.Interfaces.GameObjects;
using Content.Server.Throw;
using Content.Shared.GameObjects.Components.Inventory;
using Content.Shared.Input;
using Content.Shared.Interfaces;
using Content.Shared.Physics;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
@@ -19,6 +24,7 @@ using Robust.Shared.Interfaces.Map;
using Robust.Shared.Interfaces.Physics;
using Robust.Shared.Interfaces.Timing;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
@@ -33,6 +39,7 @@ namespace Content.Server.GameObjects.EntitySystems
#pragma warning disable 649
[Dependency] private readonly IMapManager _mapManager;
[Dependency] private readonly IEntitySystemManager _entitySystemManager;
[Dependency] private readonly IServerNotifyManager _notifyManager;
#pragma warning restore 649
private const float ThrowForce = 1.5f; // Throwing force of mobs in Newtons
@@ -50,6 +57,8 @@ namespace Content.Server.GameObjects.EntitySystems
input.BindMap.BindFunction(ContentKeyFunctions.Drop, new PointerInputCmdHandler(HandleDrop));
input.BindMap.BindFunction(ContentKeyFunctions.ActivateItemInHand, InputCmdHandler.FromDelegate(HandleActivateItem));
input.BindMap.BindFunction(ContentKeyFunctions.ThrowItemInHand, new PointerInputCmdHandler(HandleThrowItem));
input.BindMap.BindFunction(ContentKeyFunctions.SmartEquipBackpack, InputCmdHandler.FromDelegate(HandleSmartEquipBackpack));
input.BindMap.BindFunction(ContentKeyFunctions.SmartEquipBelt, InputCmdHandler.FromDelegate(HandleSmartEquipBelt));
}
/// <inheritdoc />
@@ -126,7 +135,7 @@ namespace Content.Server.GameObjects.EntitySystems
var interactionSystem = _entitySystemManager.GetEntitySystem<InteractionSystem>();
if(interactionSystem.InRangeUnobstructed(coords.ToMap(_mapManager), ent.Transform.WorldPosition, 0f, ignoredEnt: ent))
if(interactionSystem.InRangeUnobstructed(coords.ToMap(_mapManager), ent.Transform.WorldPosition, ignoredEnt: ent))
if (coords.InRange(_mapManager, ent.Transform.GridPosition, InteractionSystem.InteractionRange))
{
handsComp.Drop(handsComp.ActiveIndex, coords);
@@ -190,5 +199,53 @@ namespace Content.Server.GameObjects.EntitySystems
return true;
}
private void HandleSmartEquipBackpack(ICommonSession session)
{
HandleSmartEquip(session, EquipmentSlotDefines.Slots.BACKPACK);
}
private void HandleSmartEquipBelt(ICommonSession session)
{
HandleSmartEquip(session, EquipmentSlotDefines.Slots.BELT);
}
private void HandleSmartEquip(ICommonSession session, EquipmentSlotDefines.Slots equipementSlot)
{
var plyEnt = ((IPlayerSession) session).AttachedEntity;
if (plyEnt == null || !plyEnt.IsValid())
return;
if (!plyEnt.TryGetComponent(out HandsComponent handsComp) || !plyEnt.TryGetComponent(out InventoryComponent inventoryComp))
return;
if (!inventoryComp.TryGetSlotItem(equipementSlot, out ItemComponent equipmentItem)
|| !equipmentItem.Owner.TryGetComponent<ServerStorageComponent>(out var storageComponent))
{
_notifyManager.PopupMessage(plyEnt, plyEnt, Loc.GetString("You have no {0} to take something out of!", EquipmentSlotDefines.SlotNames[equipementSlot].ToLower()));
return;
}
var heldItem = handsComp.GetHand(handsComp.ActiveIndex)?.Owner;
if (heldItem != null)
{
storageComponent.PlayerInsertEntity(plyEnt);
}
else
{
if (storageComponent.StoredEntities.Count == 0)
{
_notifyManager.PopupMessage(plyEnt, plyEnt, Loc.GetString("There's nothing in your {0} to take out!", EquipmentSlotDefines.SlotNames[equipementSlot].ToLower()));
}
else
{
var lastStoredEntity = Enumerable.Last(storageComponent.StoredEntities);
if (storageComponent.Remove(lastStoredEntity))
handsComp.PutInHandOrDrop(lastStoredEntity.GetComponent<ItemComponent>());
}
}
}
}
}

View File

@@ -1,4 +1,6 @@
using Content.Server.GameObjects.Components;
using System;
using System.Net;
using Content.Server.GameObjects.Components;
using Content.Server.GameObjects.Components.Mobs;
using Content.Server.GameObjects.Components.Movement;
using Content.Server.GameObjects.Components.Sound;
@@ -15,6 +17,7 @@ using Robust.Server.Interfaces.Player;
using Robust.Server.Interfaces.Timing;
using Robust.Shared.Configuration;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.GameObjects.Components.Transform;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Input;
@@ -28,6 +31,7 @@ using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Network;
using Robust.Shared.Physics;
using Robust.Shared.Players;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
@@ -44,6 +48,7 @@ namespace Content.Server.GameObjects.EntitySystems
[Dependency] private readonly IMapManager _mapManager;
[Dependency] private readonly IRobustRandom _robustRandom;
[Dependency] private readonly IConfigurationManager _configurationManager;
[Dependency] private readonly IEntityManager _entityManager;
#pragma warning restore 649
private AudioSystem _audioSystem;
@@ -130,13 +135,43 @@ namespace Content.Server.GameObjects.EntitySystems
}
var mover = entity.GetComponent<IMoverComponent>();
var physics = entity.GetComponent<PhysicsComponent>();
UpdateKinematics(entity.Transform, mover, physics);
if (entity.TryGetComponent<CollidableComponent>(out var collider))
{
UpdateKinematics(entity.Transform, mover, physics, collider);
}
else
{
UpdateKinematics(entity.Transform, mover, physics);
}
}
}
private void UpdateKinematics(ITransformComponent transform, IMoverComponent mover, PhysicsComponent physics)
private void UpdateKinematics(ITransformComponent transform, IMoverComponent mover, PhysicsComponent physics, CollidableComponent collider = null)
{
bool weightless = false;
var tile = _mapManager.GetGrid(transform.GridID).GetTileRef(transform.GridPosition).Tile;
if ((!_mapManager.GetGrid(transform.GridID).HasGravity || tile.IsEmpty) && collider != null)
{
weightless = true;
// No gravity: is our entity touching anything?
var touching = false;
foreach (var entity in _entityManager.GetEntitiesInRange(transform.Owner, mover.GrabRange, true))
{
if (entity.TryGetComponent<CollidableComponent>(out var otherCollider))
{
if (otherCollider.Owner == transform.Owner) continue; // Don't try to push off of yourself!
touching |= ((collider.CollisionMask & otherCollider.CollisionLayer) != 0x0
|| (otherCollider.CollisionMask & collider.CollisionLayer) != 0x0) // Ensure collision
&& !entity.HasComponent<ItemComponent>(); // This can't be an item
}
}
if (!touching)
{
return;
}
}
if (mover.VelocityDir.LengthSquared < 0.001 || !ActionBlockerSystem.CanMove(mover.Owner))
{
if (physics.LinearVelocity != Vector2.Zero)
@@ -145,6 +180,13 @@ namespace Content.Server.GameObjects.EntitySystems
}
else
{
if (weightless)
{
physics.LinearVelocity = mover.VelocityDir * mover.CurrentPushSpeed;
transform.LocalRotation = mover.VelocityDir.GetDir().ToAngle();
return;
}
physics.LinearVelocity = mover.VelocityDir * (mover.Sprinting ? mover.CurrentSprintSpeed : mover.CurrentWalkSpeed);
transform.LocalRotation = mover.VelocityDir.GetDir().ToAngle();