Fix lathe unanchor interaction & general cleanup (#10156)

This commit is contained in:
Leon Friedrich
2022-08-04 12:38:56 +12:00
committed by GitHub
parent e98f728b7c
commit bbd6482420
5 changed files with 144 additions and 154 deletions

View File

@@ -29,13 +29,10 @@ namespace Content.Server.Lathe.Components
/// <summary> /// <summary>
/// The lathe's construction queue /// The lathe's construction queue
/// </summary> /// </summary>
[ViewVariables] [DataField("queue", customTypeSerializer: typeof(PrototypeIdListSerializer<LatheRecipePrototype>))]
public Queue<LatheRecipePrototype> Queue { get; } = new(); public List<string> Queue { get; } = new();
/// <summary> // TODO queue serializer.
/// The recipe the lathe is currently producing
/// </summary>
[ViewVariables]
public LatheRecipePrototype? ProducingRecipe;
/// <summary> /// <summary>
/// How long the inserting animation will play /// How long the inserting animation will play
/// </summary> /// </summary>
@@ -46,12 +43,6 @@ namespace Content.Server.Lathe.Components
/// </suummary> /// </suummary>
[DataField("insertionAccumulator")] [DataField("insertionAccumulator")]
public float InsertionAccumulator = 0f; public float InsertionAccumulator = 0f;
/// <summary>
/// Production accumulator for the production time.
/// </summary>
[ViewVariables]
[DataField("producingAccumulator")]
public float ProducingAccumulator = 0f;
/// <summary> /// <summary>
/// The sound that plays when the lathe is producing an item, if any /// The sound that plays when the lathe is producing an item, if any

View File

@@ -5,5 +5,11 @@ namespace Content.Server.Lathe.Components
/// <summary> /// <summary>
[RegisterComponent] [RegisterComponent]
public sealed class LatheInsertingComponent : Component public sealed class LatheInsertingComponent : Component
{} {
/// <summary>
/// Remaining insertion time, in seconds.
/// </summary>
[DataField("timeRemaining", required: true)]
public float TimeRemaining;
}
} }

View File

@@ -1,3 +1,6 @@
using Content.Shared.Research.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Server.Lathe.Components namespace Content.Server.Lathe.Components
{ {
/// <summary> /// <summary>
@@ -5,5 +8,17 @@ namespace Content.Server.Lathe.Components
/// <summary> /// <summary>
[RegisterComponent] [RegisterComponent]
public sealed class LatheProducingComponent : Component public sealed class LatheProducingComponent : Component
{} {
/// <summary>
/// The recipe the lathe is currently producing
/// </summary>
[DataField("recipe", required:true, customTypeSerializer:typeof(PrototypeIdSerializer<LatheRecipePrototype>))]
public string? Recipe;
/// <summary>
/// Remaining production time, in seconds.
/// </summary>
[DataField("timeRemaining", required: true)]
public float TimeRemaining;
}
} }

View File

@@ -6,18 +6,16 @@ using Content.Server.Research.Components;
using Content.Shared.Interaction; using Content.Shared.Interaction;
using Content.Server.Materials; using Content.Server.Materials;
using Content.Server.Popups; using Content.Server.Popups;
using Content.Server.Power.Components;
using Content.Server.Power.EntitySystems; using Content.Server.Power.EntitySystems;
using Content.Server.Research; using Content.Server.Research;
using Content.Server.Stack; using Content.Server.Stack;
using Content.Server.UserInterface;
using Content.Shared.Research.Components; using Content.Shared.Research.Components;
using Robust.Server.GameObjects; using Robust.Server.GameObjects;
using Robust.Shared.Prototypes; using Robust.Shared.Prototypes;
using Robust.Shared.Player; using Robust.Shared.Player;
using Robust.Shared.Audio;
using JetBrains.Annotations; using JetBrains.Annotations;
using System.Linq; using System.Linq;
using Robust.Server.Player;
namespace Content.Server.Lathe namespace Content.Server.Lathe
{ {
@@ -26,59 +24,40 @@ namespace Content.Server.Lathe
{ {
[Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly PopupSystem _popupSystem = default!; [Dependency] private readonly PopupSystem _popupSystem = default!;
[Dependency] private readonly SharedAudioSystem _audioSys = default!;
[Dependency] private readonly UserInterfaceSystem _uiSys = default!;
[Dependency] private readonly ResearchSystem _researchSys = default!;
public override void Initialize() public override void Initialize()
{ {
base.Initialize(); base.Initialize();
SubscribeLocalEvent<LatheComponent, InteractUsingEvent>(OnInteractUsing); SubscribeLocalEvent<LatheComponent, InteractUsingEvent>(OnInteractUsing);
SubscribeLocalEvent<LatheComponent, ComponentInit>(OnComponentInit); SubscribeLocalEvent<LatheComponent, ComponentInit>(OnComponentInit);
SubscribeLocalEvent<LatheComponent, LatheQueueRecipeMessage>(OnLatheQueueRecipeMessage);
SubscribeLocalEvent<LatheComponent, LatheSyncRequestMessage>(OnLatheSyncRequestMessage);
SubscribeLocalEvent<LatheComponent, LatheServerSelectionMessage>(OnLatheServerSelectionMessage);
SubscribeLocalEvent<TechnologyDatabaseComponent, LatheServerSyncMessage>(OnLatheServerSyncMessage);
} }
// These queues are to add/remove COMPONENTS to the lathes
private Queue<EntityUid> ProducingAddQueue = new();
private Queue<EntityUid> ProducingRemoveQueue = new();
private Queue<EntityUid> InsertingAddQueue = new();
private Queue<EntityUid> InsertingRemoveQueue = new();
public override void Update(float frameTime) public override void Update(float frameTime)
{ {
foreach (var uid in ProducingAddQueue) foreach (var comp in EntityQuery<LatheInsertingComponent>())
EnsureComp<LatheProducingComponent>(uid); {
ProducingAddQueue.Clear(); comp.TimeRemaining -= frameTime;
foreach (var uid in ProducingRemoveQueue)
RemComp<LatheProducingComponent>(uid);
ProducingRemoveQueue.Clear();
foreach (var uid in InsertingAddQueue)
EnsureComp<LatheInsertingComponent>(uid);
InsertingAddQueue.Clear();
foreach (var uid in InsertingRemoveQueue)
RemComp<LatheInsertingComponent>(uid);
InsertingRemoveQueue.Clear();
foreach (var (insertingComp, lathe) in EntityQuery<LatheInsertingComponent, LatheComponent>(false)) if (comp.TimeRemaining > 0)
{
if (lathe.InsertionAccumulator < lathe.InsertionTime)
{
lathe.InsertionAccumulator += frameTime;
continue; continue;
}
lathe.InsertionAccumulator = 0; UpdateInsertingAppearance(comp.Owner, false);
UpdateInsertingAppearance(lathe.Owner, false); RemCompDeferred(comp.Owner, comp);
InsertingRemoveQueue.Enqueue(lathe.Owner);
} }
foreach (var (producingComp, lathe) in EntityQuery<LatheProducingComponent, LatheComponent>(false)) foreach (var comp in EntityQuery<LatheProducingComponent>())
{ {
if (lathe.ProducingRecipe == null) comp.TimeRemaining -= frameTime;
continue;
if (lathe.ProducingAccumulator < lathe.ProducingRecipe.CompleteTime.TotalSeconds)
{
lathe.ProducingAccumulator += frameTime;
continue;
}
lathe.ProducingAccumulator = 0;
FinishProducing(lathe.ProducingRecipe, lathe, true); if (comp.TimeRemaining <= 0)
FinishProducing(comp.Owner, comp);
} }
} }
@@ -88,12 +67,6 @@ namespace Content.Server.Lathe
/// </summary> /// </summary>
private void OnComponentInit(EntityUid uid, LatheComponent component, ComponentInit args) private void OnComponentInit(EntityUid uid, LatheComponent component, ComponentInit args)
{ {
component.UserInterface = uid.GetUIOrNull(LatheUiKey.Key);
if (component.UserInterface != null)
{
component.UserInterface.OnReceiveMessage += msg => UserInterfaceOnOnReceiveMessage(uid, component, msg);
}
if (TryComp<AppearanceComponent>(uid, out var appearance)) if (TryComp<AppearanceComponent>(uid, out var appearance))
{ {
appearance.SetData(LatheVisuals.IsInserting, false); appearance.SetData(LatheVisuals.IsInserting, false);
@@ -111,10 +84,14 @@ namespace Content.Server.Lathe
return; return;
foreach (var recipe in recipes) foreach (var recipe in recipes)
{
foreach (var mat in recipe.RequiredMaterials) foreach (var mat in recipe.RequiredMaterials)
{
if (!component.MaterialWhiteList.Contains(mat.Key)) if (!component.MaterialWhiteList.Contains(mat.Key))
component.MaterialWhiteList.Add(mat.Key); component.MaterialWhiteList.Add(mat.Key);
} }
}
}
/// <summary> /// <summary>
/// When someone tries to use an item on the lathe, /// When someone tries to use an item on the lathe,
@@ -124,13 +101,14 @@ namespace Content.Server.Lathe
{ {
if (args.Handled) if (args.Handled)
return; return;
args.Handled = true;
if (!TryComp<MaterialStorageComponent>(uid, out var storage) if (!TryComp<MaterialStorageComponent>(uid, out var storage)
|| !TryComp<MaterialComponent>(args.Used, out var material) || !TryComp<MaterialComponent>(args.Used, out var material)
|| component.LatheWhitelist?.IsValid(args.Used) == false) || component.LatheWhitelist?.IsValid(args.Used) == false)
return; return;
args.Handled = true;
var matUsed = false; var matUsed = false;
foreach (var mat in material.Materials) foreach (var mat in material.Materials)
if (component.MaterialWhiteList.Contains(mat.ID)) if (component.MaterialWhiteList.Contains(mat.ID))
@@ -160,6 +138,7 @@ namespace Content.Server.Lathe
// Check if it can take ALL of the material's volume. // Check if it can take ALL of the material's volume.
if (storage.StorageLimit > 0 && !storage.CanTakeAmount(totalAmount)) if (storage.StorageLimit > 0 && !storage.CanTakeAmount(totalAmount))
return; return;
var lastMat = string.Empty; var lastMat = string.Empty;
foreach (var (mat, vol) in material._materials) foreach (var (mat, vol) in material._materials)
{ {
@@ -169,17 +148,18 @@ namespace Content.Server.Lathe
// Play a sound when inserting, if any // Play a sound when inserting, if any
if (component.InsertingSound != null) if (component.InsertingSound != null)
{ _audioSys.PlayPvs(component.InsertingSound, uid);
SoundSystem.Play(component.InsertingSound.GetSound(), Filter.Pvs(component.Owner, entityManager: EntityManager), component.Owner);
}
// We need the prototype to get the color // We need the prototype to get the color
_prototypeManager.TryIndex(lastMat, out MaterialPrototype? matProto); _prototypeManager.TryIndex(lastMat, out MaterialPrototype? matProto);
EntityManager.QueueDeleteEntity(args.Used); EntityManager.QueueDeleteEntity(args.Used);
InsertingAddQueue.Enqueue(uid);
EnsureComp<LatheInsertingComponent>(uid).TimeRemaining = component.InsertionTime;
_popupSystem.PopupEntity(Loc.GetString("machine-insert-item", ("machine", uid), _popupSystem.PopupEntity(Loc.GetString("machine-insert-item", ("machine", uid),
("item", args.Used)), uid, Filter.Entities(args.User)); ("item", args.Used)), uid, Filter.Entities(args.User));
if (matProto != null) if (matProto != null)
{ {
UpdateInsertingAppearance(uid, true, matProto.Color); UpdateInsertingAppearance(uid, true, matProto.Color);
@@ -191,30 +171,34 @@ namespace Content.Server.Lathe
/// This handles the checks to start producing an item, and /// This handles the checks to start producing an item, and
/// starts up the sound and visuals /// starts up the sound and visuals
/// </summary> /// </summary>
private void Produce(LatheComponent component, LatheRecipePrototype recipe, bool SkipCheck = false) private bool TryStartProducing(EntityUid uid, LatheProducingComponent? prodComp = null, LatheComponent? component = null)
{ {
if (!component.CanProduce(recipe) if (!Resolve(uid, ref component) || component.Queue.Count == 0)
|| !TryComp(component.Owner, out MaterialStorageComponent? storage)) return false;
if (!this.IsPowered(uid, EntityManager))
return false;
var recipeId = component.Queue[0];
if (!_prototypeManager.TryIndex<LatheRecipePrototype>(recipeId, out var recipe))
{ {
FinishProducing(recipe, component, false); // recipie does not exist. Remove and try produce the next item.
return; component.Queue.RemoveAt(0);
return TryStartProducing(uid, prodComp, component);
} }
if (!SkipCheck && HasComp<LatheProducingComponent>(component.Owner)) if (!component.CanProduce(recipe) || !TryComp(uid, out MaterialStorageComponent? storage))
{ return false;
FinishProducing(recipe, component, false);
return;
}
if (!this.IsPowered(component.Owner, EntityManager)) prodComp ??= EnsureComp<LatheProducingComponent>(uid);
{
FinishProducing(recipe, component, false);
return;
}
component.UserInterface?.SendMessage(new LatheFullQueueMessage(GetIdQueue(component))); if (prodComp.Recipe != null)
return false;
component.ProducingRecipe = recipe; component.Queue.RemoveAt(0);
prodComp.Recipe = recipeId;
prodComp.TimeRemaining = (float)recipe.CompleteTime.TotalSeconds;
foreach (var (material, amount) in recipe.RequiredMaterials) foreach (var (material, amount) in recipe.RequiredMaterials)
{ {
@@ -222,33 +206,42 @@ namespace Content.Server.Lathe
storage.RemoveMaterial(material, amount); storage.RemoveMaterial(material, amount);
} }
component.UserInterface?.SendMessage(new LatheProducingRecipeMessage(recipe.ID)); // Again, this should really just be a bui state instead of two separate messages.
_uiSys.TrySendUiMessage(uid, LatheUiKey.Key, new LatheProducingRecipeMessage(recipe.ID));
_uiSys.TrySendUiMessage(uid, LatheUiKey.Key, new LatheFullQueueMessage(component.Queue));
if (component.ProducingSound != null) if (component.ProducingSound != null)
{ _audioSys.PlayPvs(component.ProducingSound, component.Owner);
SoundSystem.Play(component.ProducingSound.GetSound(), Filter.Pvs(component.Owner), component.Owner);
} UpdateRunningAppearance(uid, true);
UpdateRunningAppearance(component.Owner, true); return true;
ProducingAddQueue.Enqueue(component.Owner);
} }
/// <summary> /// <summary>
/// If we were able to produce the recipe, /// If we were able to produce the recipe,
/// spawn it and cleanup. If we weren't, just do cleanup. /// spawn it and cleanup. If we weren't, just do cleanup.
/// </summary> /// </summary>
private void FinishProducing(LatheRecipePrototype recipe, LatheComponent component, bool productionSucceeded = true) private void FinishProducing(EntityUid uid, LatheProducingComponent prodComp)
{ {
component.ProducingRecipe = null; if (prodComp.Recipe == null || !_prototypeManager.TryIndex<LatheRecipePrototype>(prodComp.Recipe, out var recipe))
if (productionSucceeded)
EntityManager.SpawnEntity(recipe.Result, Comp<TransformComponent>(component.Owner).Coordinates);
component.UserInterface?.SendMessage(new LatheStoppedProducingRecipeMessage());
// Continue to next in queue if there are items left
if (component.Queue.Count > 0)
{ {
Produce(component, component.Queue.Dequeue(), true); RemCompDeferred(prodComp.Owner, prodComp);
UpdateRunningAppearance(uid, false);
return; return;
} }
ProducingRemoveQueue.Enqueue(component.Owner);
UpdateRunningAppearance(component.Owner, false); Spawn(recipe.Result, Transform(uid).Coordinates);
prodComp.Recipe = null;
// TODO this should probably just be a BUI state, not a special message.
_uiSys.TrySendUiMessage(uid, LatheUiKey.Key, new LatheStoppedProducingRecipeMessage());
// Continue to next in queue if there are items left
if (TryStartProducing(uid, prodComp))
return;
RemComp(prodComp.Owner, prodComp);
UpdateRunningAppearance(uid, false);
} }
/// <summary> /// <summary>
@@ -277,64 +270,49 @@ namespace Content.Server.Lathe
appearance.SetData(LatheVisuals.InsertingColor, color); appearance.SetData(LatheVisuals.InsertingColor, color);
} }
/// <summary> #region UI Messages
/// Handles all the button presses in the lathe UI
/// </summary>
private void UserInterfaceOnOnReceiveMessage(EntityUid uid, LatheComponent component, ServerBoundUserInterfaceMessage message)
{
if (!this.IsPowered(uid, EntityManager))
return;
switch (message.Message) private void OnLatheQueueRecipeMessage(EntityUid uid, LatheComponent component, LatheQueueRecipeMessage args)
{ {
case LatheQueueRecipeMessage msg: if (_prototypeManager.TryIndex(args.ID, out LatheRecipePrototype? recipe))
_prototypeManager.TryIndex(msg.ID, out LatheRecipePrototype? recipe);
if (recipe != null!)
for (var i = 0; i < msg.Quantity; i++)
{ {
component.Queue.Enqueue(recipe); for (var i = 0; i < args.Quantity; i++)
component.UserInterface?.SendMessage(new LatheFullQueueMessage(GetIdQueue(component))); {
component.Queue.Add(recipe.ID);
} }
if (!HasComp<LatheProducingComponent>(component.Owner) && component.Queue.Count > 0)
Produce(component, component.Queue.Dequeue());
break; // Again: TODO this should be handled by BUI states
case LatheSyncRequestMessage _: _uiSys.TrySendUiMessage(uid, LatheUiKey.Key, new LatheFullQueueMessage(component.Queue));
}
TryStartProducing(component.Owner, null, component);
}
private void OnLatheSyncRequestMessage(EntityUid uid, LatheComponent component, LatheSyncRequestMessage args)
{
if (!HasComp<MaterialStorageComponent>(uid)) return; if (!HasComp<MaterialStorageComponent>(uid)) return;
component.UserInterface?.SendMessage(new LatheFullQueueMessage(GetIdQueue(component)));
if (component.ProducingRecipe != null)
component.UserInterface?.SendMessage(new LatheProducingRecipeMessage(component.ProducingRecipe.ID));
break;
case LatheServerSelectionMessage _: // Again: TODO BUI states. Why TF was this was this ever two separate messages!?!?
if (!TryComp(uid, out ResearchClientComponent? researchClient)) return; _uiSys.TrySendUiMessage(uid, LatheUiKey.Key, new LatheFullQueueMessage(component.Queue));
IoCManager.Resolve<IEntitySystemManager>() if (TryComp(uid, out LatheProducingComponent? prodComp) && prodComp.Recipe != null)
.GetEntitySystem<UserInterfaceSystem>() _uiSys.TrySendUiMessage(uid, LatheUiKey.Key, new LatheProducingRecipeMessage(prodComp.Recipe));
.TryOpen(uid, ResearchClientUiKey.Key, message.Session); }
break;
case LatheServerSyncMessage _: private void OnLatheServerSelectionMessage(EntityUid uid, LatheComponent component, LatheServerSelectionMessage args)
if (!TryComp(uid, out TechnologyDatabaseComponent? database) {
|| !TryComp(uid, out ProtolatheDatabaseComponent? protoDatabase)) return; // TODO W.. b.. why?
// the client can just open the ui itself. why tf is it asking the server to open it for it.
_uiSys.TryOpen(uid, ResearchClientUiKey.Key, (IPlayerSession) args.Session);
}
if (IoCManager.Resolve<IEntitySystemManager>().GetEntitySystem<ResearchSystem>().SyncWithServer(database)) private void OnLatheServerSyncMessage(EntityUid uid, TechnologyDatabaseComponent component, LatheServerSyncMessage args)
{
_researchSys.SyncWithServer(component);
if (TryComp(uid, out ProtolatheDatabaseComponent? protoDatabase))
protoDatabase.Sync(); protoDatabase.Sync();
break;
}
} }
/// <summary> #endregion
/// Gets all the prototypes in the lathe's construction queue
/// </summary>
private Queue<string> GetIdQueue(LatheComponent lathe)
{
var queue = new Queue<string>();
foreach (var recipePrototype in lathe.Queue)
{
queue.Enqueue(recipePrototype.ID);
}
return queue;
}
} }
} }

View File

@@ -65,8 +65,8 @@ namespace Content.Shared.Lathe;
[Serializable, NetSerializable] [Serializable, NetSerializable]
public sealed class LatheFullQueueMessage : BoundUserInterfaceMessage public sealed class LatheFullQueueMessage : BoundUserInterfaceMessage
{ {
public readonly Queue<string> Recipes; public readonly List<string> Recipes;
public LatheFullQueueMessage(Queue<string> recipes) public LatheFullQueueMessage(List<string> recipes)
{ {
Recipes = recipes; Recipes = recipes;
} }