Unstable 1.1.14.0

This commit is contained in:
Markus Isberg
2023-10-02 16:43:54 +03:00
parent 94f5a93a0c
commit cf8f0de659
606 changed files with 21906 additions and 11456 deletions
@@ -0,0 +1,499 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
namespace Barotrauma.Items.Components
{
internal sealed partial class CircuitBox
{
public CircuitBoxUI? UI;
public readonly Dictionary<Character, CircuitBoxCursor> ActiveCursors = new Dictionary<Character, CircuitBoxCursor>();
public Option<ItemPrefab> HeldComponent = Option.None;
private const float CursorUpdateInterval = 1f;
private float cursorUpdateTimer;
private readonly Vector2[] recordedCursorPositions = new Vector2[10];
private Option<Vector2> recordedDragStart = Option.None;
private Option<ItemPrefab> recordedHeldPrefab = Option.None;
/// <summary>
/// If the circuit box was initialized by the server instead of from the save file.
/// Used to ensure the wires the server sends are properly connected up when we load in.
/// </summary>
private bool wasInitializedByServer;
public Sprite? WireSprite { get; private set; }
public Sprite? ConnectionSprite { get; private set; }
public Sprite? WireConnectorSprite { get; private set; }
public Sprite? ConnectionScrewSprite { get; private set; }
public UISprite? NodeFrameSprite { get; private set; }
public UISprite? NodeTopSprite { get; private set; }
protected override void CreateGUI()
{
base.CreateGUI();
GuiFrame.ClearChildren();
UI?.CreateGUI(GuiFrame);
}
partial void InitProjSpecific(ContentXElement element)
{
UI = new CircuitBoxUI(this);
IsActive = true;
CreateGUI();
foreach (var subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "wiresprite":
WireSprite = new Sprite(subElement);
break;
case "connectionsprite":
ConnectionSprite = new Sprite(subElement);
break;
case "wireconnectorsprite":
WireConnectorSprite = new Sprite(subElement);
break;
case "connectionscrewsprite":
ConnectionScrewSprite = new Sprite(subElement);
break;
}
}
if (GUIStyle.GetComponentStyle("CircuitBoxTop") is { } topStyle)
{
NodeTopSprite = topStyle.Sprites[GUIComponent.ComponentState.None][0];
}
if (GUIStyle.GetComponentStyle("CircuitBoxFrame") is { } compStyle)
{
NodeFrameSprite = compStyle.Sprites[GUIComponent.ComponentState.None][0];
}
}
public override bool ShouldDrawHUD(Character character)
=> character == Character.Controlled && (character.SelectedItem == item || character.SelectedSecondaryItem == item);
public override void UpdateHUDComponentSpecific(Character character, float deltaTime, Camera cam)
{
if (UI is null) { return; }
UI.Update(deltaTime);
if (GameMain.NetworkMember is null) { return; }
foreach (var (cursorChar, cursor) in ActiveCursors)
{
if (!cursor.IsActive) { continue; }
ActiveCursors[cursorChar].Update(deltaTime);
}
Vector2 cursorPos = UI.GetCursorPosition();
int lastCursorPosIndex = recordedCursorPositions.Length - 1;
if (cursorUpdateTimer < CursorUpdateInterval)
{
cursorUpdateTimer += deltaTime;
int cursorIndex = (int)MathF.Floor(cursorUpdateTimer * lastCursorPosIndex);
RecordCursorPosition(cursorIndex);
}
else
{
RecordCursorPosition(lastCursorPosIndex);
SendCursorState(recordedCursorPositions, recordedDragStart, recordedHeldPrefab.Select(static c => c.Identifier));
recordedDragStart = Option.None;
recordedHeldPrefab = Option.None;
cursorUpdateTimer = 0f;
}
void RecordCursorPosition(int index)
{
var dragStart = UI.GetDragStart();
if (dragStart.IsSome()) { recordedDragStart = dragStart; }
var heldComponent = HeldComponent;
if (heldComponent.IsSome()) { recordedHeldPrefab = heldComponent; }
if (index >= 0 && index < recordedCursorPositions.Length) { recordedCursorPositions[index] = cursorPos; }
}
}
public void RemoveComponents(IReadOnlyCollection<CircuitBoxComponent> node)
{
var ids = node.Select(static n => n.ID).ToImmutableArray();
if (GameMain.NetworkMember is null)
{
CreateRefundItemsForUsedResources(ids, Character.Controlled);
RemoveComponentInternal(ids);
return;
}
if (!node.Any()) { return; }
CreateClientEvent(new CircuitBoxRemoveComponentEvent(ids));
}
public void AddWire(CircuitBoxConnection one, CircuitBoxConnection two)
{
if (GameMain.NetworkMember is null)
{
Connect(one, two, static delegate { }, CircuitBoxWire.SelectedWirePrefab);
return;
}
if (!VerifyConnection(one, two)) { return; }
CreateClientEvent(new CircuitBoxClientAddWireEvent(Color.White, CircuitBoxConnectorIdentifier.FromConnection(one), CircuitBoxConnectorIdentifier.FromConnection(two), CircuitBoxWire.SelectedWirePrefab.UintIdentifier));
}
public void RemoveWires(IReadOnlyCollection<CircuitBoxWire> wires)
{
var ids = wires.Select(static w => w.ID).ToImmutableArray();
if (GameMain.NetworkMember is null)
{
RemoveWireInternal(ids);
return;
}
if (!ids.Any()) { return; }
CreateClientEvent(new CircuitBoxRemoveWireEvent(ids));
}
public void SelectComponents(IReadOnlyCollection<CircuitBoxNode> moveables, bool overwrite)
{
if (Character.Controlled is not { ID: var controlledId }) { return; }
var ids = ImmutableArray.CreateBuilder<ushort>();
var ios = ImmutableArray.CreateBuilder<CircuitBoxInputOutputNode.Type>();
foreach (var moveable in moveables)
{
if (moveable is { IsSelected: true, IsSelectedByMe: false }) { continue; }
switch (moveable)
{
case CircuitBoxComponent node:
ids.Add(node.ID);
break;
case CircuitBoxInputOutputNode io:
ios.Add(io.NodeType);
break;
}
}
if (GameMain.NetworkMember is null)
{
SelectComponentsInternal(ids, controlledId, overwrite);
SelectInputOutputInternal(ios, controlledId, overwrite);
return;
}
if ((!ids.Any() && !ios.Any()) && !overwrite) { return; }
CreateClientEvent(new CircuitBoxSelectNodesEvent(ids.ToImmutable(), ios.ToImmutable(), overwrite, controlledId));
}
public void SelectWires(IReadOnlyCollection<CircuitBoxWire> wires, bool overwrite)
{
if (Character.Controlled is not { ID: var controlledId }) { return; }
var ids = (from wire in wires where !wire.IsSelected || wire.IsSelectedByMe select wire.ID).ToImmutableArray();
if (GameMain.NetworkMember is null)
{
SelectWiresInternal(ids, controlledId, overwrite);
return;
}
if (!ids.Any() && !overwrite) { return; }
CreateClientEvent(new CircuitBoxSelectWiresEvent(ids, overwrite, Character.Controlled.ID));
}
public void MoveComponent(Vector2 moveAmount, IReadOnlyCollection<CircuitBoxNode> moveables)
{
var ids = ImmutableArray.CreateBuilder<ushort>();
var ios = ImmutableArray.CreateBuilder<CircuitBoxInputOutputNode.Type>();
foreach (CircuitBoxNode move in moveables)
{
switch (move)
{
case CircuitBoxComponent node:
ids.Add(node.ID);
break;
case CircuitBoxInputOutputNode io:
ios.Add(io.NodeType);
break;
}
}
if (GameMain.NetworkMember is null)
{
MoveNodesInternal(ids, ios, moveAmount);
return;
}
if (!ids.Any() && !ios.Any()) { return; }
CreateClientEvent(new CircuitBoxMoveComponentEvent(ids.ToImmutable(), ios.ToImmutable(), moveAmount));
}
public void AddComponent(ItemPrefab prefab, Vector2 pos)
{
if (GameMain.NetworkMember is null)
{
ItemPrefab resource;
if (IsFull) { return; }
if (IsInGame())
{
if (!GetApplicableResourcePlayerHas(prefab, Character.Controlled).TryUnwrap(out var r)) { return; }
resource = r.Prefab;
RemoveItem(r);
}
else
{
resource = ItemPrefab.Prefabs[Tags.FPGACircuit];
}
AddComponentInternal(ICircuitBoxIdentifiable.FindFreeID(Components), prefab, resource, pos, static delegate { });
return;
}
CreateClientEvent(new CircuitBoxAddComponentEvent(prefab.UintIdentifier, pos));
}
public partial void OnViewUpdateProjSpecific()
{
UI?.MouseSnapshotHandler.UpdateConnections();
UI?.UpdateComponentList();
}
protected override void OnResolutionChanged()
{
base.OnResolutionChanged();
CreateGUI();
}
// Remove selection when the circuit box is deselected
public partial void OnDeselected(Character c)
{
cursorUpdateTimer = 0f;
// Server will broadcast the deselection, we don't need to do it ourselves
if (GameMain.NetworkMember is not null) { return; }
ClearAllSelectionsInternal(c.ID);
}
public void ClientRead(INetSerializableStruct data)
{
switch (data)
{
case NetCircuitBoxCursorInfo cursorInfo:
{
ClientReadCursor(cursorInfo);
break;
}
case CircuitBoxErrorEvent errorData:
{
DebugConsole.ThrowError($"The server responded with an error: {errorData.Message}");
break;
}
default:
throw new ArgumentOutOfRangeException(nameof(data), data, "This data cannot be handled using direct network messages.");
}
}
public void SendMessage(CircuitBoxOpcode opcode, INetSerializableStruct data)
{
IWriteMessage msg = new WriteOnlyMessage().WithHeader(ClientPacketHeader.CIRCUITBOX);
msg.WriteNetSerializableStruct(new NetCircuitBoxHeader(
Opcode: opcode,
ItemID: item.ID,
ComponentIndex: (byte)item.GetComponentIndex(this)));
msg.WriteNetSerializableStruct(data);
DeliveryMethod deliveryMethod =
UnrealiableOpcodes.Contains(opcode)
? DeliveryMethod.Unreliable
: DeliveryMethod.Reliable;
GameMain.Client?.ClientPeer?.Send(msg, deliveryMethod);
}
private void SendCursorState(Vector2[] cursorPositions, Option<Vector2> dragStart, Option<Identifier> heldComponent)
{
if (!IsRoundRunning()) { return; }
var msg = new NetCircuitBoxCursorInfo(
RecordedPositions: cursorPositions,
DragStart: dragStart,
HeldItem: heldComponent);
SendMessage(CircuitBoxOpcode.Cursor, msg);
}
public void ClientReadCursor(NetCircuitBoxCursorInfo info)
{
if (Entity.FindEntityByID(info.CharacterID) is not Character character) { return; }
if (!ActiveCursors.ContainsKey(character))
{
var newCursor = new CircuitBoxCursor(info);
ActiveCursors.Add(character, newCursor);
return;
}
var activeCursor = ActiveCursors[character];
activeCursor.UpdateInfo(info);
activeCursor.ResetTimers();
}
public void CreateClientEvent(INetSerializableStruct data)
=> item.CreateClientEvent(this, new CircuitBoxEventData(data));
public void ClientEventWrite(IWriteMessage msg, NetEntityEvent.IData? extraData = null)
{
if (extraData is null) { return; }
var eventData = ExtractEventData<CircuitBoxEventData>(extraData);
msg.WriteByte((byte)eventData.Opcode);
msg.WriteNetSerializableStruct(eventData.Data);
}
public void ClientEventRead(IReadMessage msg, float sendingTime)
{
var header = (CircuitBoxOpcode)msg.ReadByte();
switch (header)
{
case CircuitBoxOpcode.AddComponent:
{
var data = INetSerializableStruct.Read<CircuitBoxServerCreateComponentEvent>(msg);
AddComponentFromData(data);
break;
}
case CircuitBoxOpcode.DeleteComponent:
{
var data = INetSerializableStruct.Read<CircuitBoxRemoveComponentEvent>(msg);
RemoveComponentInternal(data.TargetIDs);
break;
}
case CircuitBoxOpcode.MoveComponent:
{
var data = INetSerializableStruct.Read<CircuitBoxMoveComponentEvent>(msg);
MoveNodesInternal(data.TargetIDs, data.IOs, data.MoveAmount);
break;
}
case CircuitBoxOpcode.UpdateSelection:
{
var data = INetSerializableStruct.Read<CircuitBoxServerUpdateSelection>(msg);
var nodeDict = data.ComponentIds.ToImmutableDictionary(static s => s.ID, static s => s.SelectedBy);
var wireDict = data.WireIds.ToImmutableDictionary(static s => s.ID, static s => s.SelectedBy);
var ioDict = data.InputOutputs.ToImmutableDictionary(static s => s.Type, static s => s.SelectedBy);
UpdateSelections(nodeDict, wireDict, ioDict);
break;
}
case CircuitBoxOpcode.AddWire:
{
var data = INetSerializableStruct.Read<CircuitBoxServerCreateWireEvent>(msg);
AddWireFromData(data);
break;
}
case CircuitBoxOpcode.RemoveWire:
{
var data = INetSerializableStruct.Read<CircuitBoxRemoveWireEvent>(msg);
RemoveWireInternal(data.TargetIDs);
break;
}
case CircuitBoxOpcode.ServerInitialize:
{
Components.Clear();
Wires.Clear();
var data = INetSerializableStruct.Read<CircuitBoxInitializeStateFromServerEvent>(msg);
foreach (var compData in data.Components) { AddComponentFromData(compData); }
foreach (var wireData in data.Wires) { AddWireFromData(wireData); }
foreach (var node in InputOutputNodes)
{
node.Position = node.NodeType switch
{
CircuitBoxInputOutputNode.Type.Input => data.InputPos,
CircuitBoxInputOutputNode.Type.Output => data.OutputPos,
_ => node.Position
};
}
wasInitializedByServer = true;
break;
}
default:
throw new ArgumentOutOfRangeException(nameof(header), header, "This opcode cannot be handled using entity events");
}
}
public void AddComponentFromData(CircuitBoxServerCreateComponentEvent data)
{
if (ItemPrefab.Prefabs.Find(p => p.UintIdentifier == data.UsedResource) is not { } prefab)
{
throw new Exception($"No item prefab found for \"{data.UsedResource}\"");
}
AddComponentInternalUnsafe(data.ComponentId, FindItemByID(data.BackingItemId), prefab, data.Position);
}
public void AddWireFromData(CircuitBoxServerCreateWireEvent data)
{
var (req, wireId, possibleItemId) = data;
var prefab = ItemPrefab.Prefabs.Find(p => p.UintIdentifier == req.SelectedWirePrefabIdentifier);
if (prefab is null)
{
throw new Exception($"No prefab found for \"{req.SelectedWirePrefabIdentifier}\"");
}
if (!req.Start.FindConnection(this).TryUnwrap(out var start))
{
throw new Exception($"No connection found for ({req.Start})");
}
if (!req.End.FindConnection(this).TryUnwrap(out var end))
{
throw new Exception($"No connection found for ({req.Start})");
}
if (possibleItemId.TryUnwrap(out var backingItem))
{
CreateWireWithItem(start, end, wireId, FindItemByID(backingItem));
}
else
{
CreateWireWithoutItem(start, end, wireId, prefab);
}
}
public static Item FindItemByID(ushort id)
=> Entity.FindEntityByID(id) as Item ?? throw new Exception($"No item with ID {id} exists.");
public override void AddToGUIUpdateList(int order = 0)
{
base.AddToGUIUpdateList(order);
UI?.AddToGUIUpdateList();
}
}
}
@@ -21,6 +21,8 @@ namespace Barotrauma.Items.Components
public float FlashTimer { get; private set; }
public static Wire DraggingConnected { get; private set; }
private static float ConnectionSpriteSize => 35.0f * GUI.Scale;
public static void DrawConnections(SpriteBatch spriteBatch, ConnectionPanel panel, Rectangle dragArea, Character character,
out (Vector2 tooltipPos, LocalizedString text) tooltip)
{
@@ -33,8 +35,6 @@ namespace Barotrauma.Items.Components
int x = panelRect.X, y = panelRect.Y;
int width = panelRect.Width, height = panelRect.Height;
Vector2 scale = GetScale(panel.GuiFrame.RectTransform.MaxSize, panel.GuiFrame.Rect.Size);
bool mouseInRect = panelRect.Contains(PlayerInput.MousePosition);
int totalWireCount = 0;
@@ -70,15 +70,15 @@ namespace Barotrauma.Items.Components
//two passes: first the connector, then the wires to get the wires to render in front
for (int i = 0; i < 2; i++)
{
Vector2 rightPos = GetRightPos(x, y, width, scale);
Vector2 leftPos = GetLeftPos(x, y, scale);
Vector2 rightPos = GetRightPos(x, y, width);
Vector2 leftPos = GetLeftPos(x, y);
Vector2 rightWirePos = new Vector2(x + width - 5 * scale.X, y + 30 * scale.Y);
Vector2 leftWirePos = new Vector2(x + 5 * scale.X, y + 30 * scale.Y);
Vector2 rightWirePos = new Vector2(x + width - 5 * GUI.Scale, y + 30 * GUI.Scale);
Vector2 leftWirePos = new Vector2(x + 5 * GUI.Scale, y + 30 * GUI.Scale);
int wireInterval = (height - (int)(20 * scale.Y)) / Math.Max(totalWireCount, 1);
int connectorIntervalLeft = GetConnectorIntervalLeft(height, scale, panel);
int connectorIntervalRight = GetConnectorIntervalRight(height, scale, panel);
int wireInterval = (height - (int)(20 * GUI.Scale)) / Math.Max(totalWireCount, 1);
int connectorIntervalLeft = GetConnectorIntervalLeft(height, panel);
int connectorIntervalRight = GetConnectorIntervalRight(height, panel);
foreach (Connection c in panel.Connections)
{
@@ -101,47 +101,26 @@ namespace Barotrauma.Items.Components
}
Vector2 position = c.IsOutput ? rightPos : leftPos;
Color highlightColor = Color.Transparent;
if (ConnectionPanel.ShouldDebugDrawWiring)
{
if (c.IsPower)
{
highlightColor = VisualizeSignal(0.0f, highlightColor, Color.Red);
}
else
{
highlightColor = VisualizeSignal(c.LastReceivedSignal.TimeSinceCreated, highlightColor, Color.LightGreen);
highlightColor = VisualizeSignal(c.LastSentSignal.TimeSinceCreated, highlightColor, Color.Orange);
}
bool mouseOn = Vector2.DistanceSquared(position, PlayerInput.MousePosition) < MathUtils.Pow2(35 * GUI.Scale);
DrawConnectionDebugInfo(spriteBatch, c, position, GUI.Scale, out var tooltipText);
LocalizedString toolTipText = c.GetToolTip();
if (mouseOn) { tooltip = (position, toolTipText); }
if (!toolTipText.IsNullOrEmpty())
if (!tooltipText.IsNullOrEmpty())
{
var glowSprite = GUIStyle.UIGlowCircular.Value.Sprite;
glowSprite.Draw(spriteBatch, position, highlightColor, glowSprite.size / 2,
scale: 45.0f / glowSprite.size.X * panel.Scale);
bool mouseOn = Vector2.DistanceSquared(position, PlayerInput.MousePosition) < MathUtils.Pow2(35 * GUI.Scale);
if (mouseOn)
{
tooltip = (position, tooltipText);
}
}
}
static Color VisualizeSignal(double timeSinceCreated, Color defaultColor, Color color)
{
if (timeSinceCreated < 1.0f)
{
float pulseAmount = (MathF.Sin((float)Timing.TotalTimeUnpaused * 10.0f) + 3.0f) / 4.0f;
Color targetColor = Color.Lerp(defaultColor, color, pulseAmount);
return Color.Lerp(targetColor, defaultColor, (float)timeSinceCreated);
}
return defaultColor;
}
//outputs are drawn at the right side of the panel, inputs at the left
if (c.IsOutput)
{
if (i == 0)
{
c.DrawConnection(spriteBatch, panel, rightPos, GetOutputLabelPosition(rightPos, panel, c), scale);
c.DrawConnection(spriteBatch, panel, rightPos, GetOutputLabelPosition(rightPos, panel, c));
}
else
{
@@ -154,7 +133,7 @@ namespace Barotrauma.Items.Components
{
if (i == 0)
{
c.DrawConnection(spriteBatch, panel, leftPos, GetInputLabelPosition(leftPos, panel, c), scale);
c.DrawConnection(spriteBatch, panel, leftPos, GetInputLabelPosition(leftPos, panel, c));
}
else
{
@@ -224,8 +203,8 @@ namespace Barotrauma.Items.Components
}
float step = (width * 0.75f) / panel.DisconnectedWires.Count();
x = (int)(x + width / 2 - step * (panel.DisconnectedWires.Count() - 1) / 2);
float step = (width * 0.75f) / panel.DisconnectedWires.Count;
x = (int)(x + width / 2 - step * (panel.DisconnectedWires.Count - 1) / 2);
foreach (Wire wire in panel.DisconnectedWires)
{
if (wire == DraggingConnected && mouseInRect) { continue; }
@@ -243,26 +222,61 @@ namespace Barotrauma.Items.Components
//stop dragging a wire item if the cursor is within any connection panel
//(so we don't drop the item when dropping the wire on a connection)
if (mouseInRect || (GUI.MouseOn?.UserData is ConnectionPanel && GUI.MouseOn.MouseRect.Contains(PlayerInput.MousePosition)))
{
Inventory.DraggingItems.Clear();
}
{
Inventory.DraggingItems.Clear();
}
}
private void DrawConnection(SpriteBatch spriteBatch, ConnectionPanel panel, Vector2 position, Vector2 labelPos, Vector2 scale)
public static void DrawConnectionDebugInfo(SpriteBatch spriteBatch, Connection c, Vector2 position, float scale, out LocalizedString tooltip)
{
Color highlightColor = Color.Transparent;
if (c.IsPower)
{
highlightColor = VisualizeSignal(0.0f, highlightColor, Color.Red);
}
else
{
highlightColor = VisualizeSignal(c.LastReceivedSignal.TimeSinceCreated, highlightColor, Color.LightGreen);
highlightColor = VisualizeSignal(c.LastSentSignal.TimeSinceCreated, highlightColor, Color.Orange);
}
LocalizedString toolTipText = c.GetToolTip();
if (!toolTipText.IsNullOrEmpty())
{
var glowSprite = GUIStyle.UIGlowCircular.Value.Sprite;
glowSprite.Draw(spriteBatch, position, highlightColor, glowSprite.size / 2,
scale: 45.0f / glowSprite.size.X * scale);
}
tooltip = toolTipText;
static Color VisualizeSignal(double timeSinceCreated, Color defaultColor, Color color)
{
if (timeSinceCreated < 1.0f)
{
float pulseAmount = (MathF.Sin((float)Timing.TotalTimeUnpaused * 10.0f) + 3.0f) / 4.0f;
Color targetColor = Color.Lerp(defaultColor, color, pulseAmount);
return Color.Lerp(targetColor, defaultColor, (float)timeSinceCreated);
}
return defaultColor;
}
}
private void DrawConnection(SpriteBatch spriteBatch, ConnectionPanel panel, Vector2 position, Vector2 labelPos)
{
string text = DisplayName.Value.ToUpperInvariant();
//nasty
if (GUIStyle.GetComponentStyle("ConnectionPanelLabel")?.Sprites.Values.First().First() is UISprite labelSprite)
{
Rectangle labelArea = GetLabelArea(labelPos, text, scale);
Rectangle labelArea = GetLabelArea(labelPos, text);
labelSprite.Draw(spriteBatch, labelArea, IsPower ? GUIStyle.Red : Color.SteelBlue);
}
GUI.DrawString(spriteBatch, labelPos + Vector2.UnitY, text, Color.Black * 0.8f, font: GUIStyle.SmallFont);
GUI.DrawString(spriteBatch, labelPos, text, GUIStyle.TextColorBright, font: GUIStyle.SmallFont);
float connectorSpriteScale = (35.0f / connectionSprite.SourceRect.Width) * panel.Scale;
float connectorSpriteScale = ConnectionSpriteSize / connectionSprite.SourceRect.Width;
connectionSprite.Draw(spriteBatch, position, scale: connectorSpriteScale);
@@ -270,7 +284,7 @@ namespace Barotrauma.Items.Components
private void DrawWires(SpriteBatch spriteBatch, ConnectionPanel panel, Vector2 position, Vector2 wirePosition, bool mouseIn, Wire equippedWire, float wireInterval)
{
float connectorSpriteScale = (35.0f / connectionSprite.SourceRect.Width) * panel.Scale;
float connectorSpriteScale = ConnectionSpriteSize / connectionSprite.SourceRect.Width;
foreach (var wire in wires)
{
@@ -285,9 +299,14 @@ namespace Barotrauma.Items.Components
wirePosition.Y += wireInterval;
}
if (DraggingConnected != null && Vector2.Distance(position, PlayerInput.MousePosition) < (20.0f * GUI.Scale))
bool isMouseOn = Vector2.Distance(position, PlayerInput.MousePosition) < (20.0f * GUI.Scale);
if (isMouseOn)
{
connectionSpriteHighlight.Draw(spriteBatch, position, scale: connectorSpriteScale);
}
if (DraggingConnected != null && isMouseOn)
{
if (!PlayerInput.PrimaryMouseButtonHeld())
{
@@ -418,7 +437,7 @@ namespace Barotrauma.Items.Components
bool mouseOn =
canDrag &&
!(GUI.MouseOn is GUIDragHandle) &&
GUI.MouseOn is not GUIDragHandle &&
((PlayerInput.MousePosition.X > Math.Min(start.X, end.X) &&
PlayerInput.MousePosition.X < Math.Max(start.X, end.X) &&
MathUtils.LineToPointDistanceSquared(start, end, PlayerInput.MousePosition) < 36) ||
@@ -442,12 +461,12 @@ namespace Barotrauma.Items.Components
}
}
var wireEnd = end + Vector2.Normalize(start - end) * 30.0f * panel.Scale;
var wireEnd = end + Vector2.Normalize(start - end) * 30.0f * GUI.Scale;
float dist = Vector2.Distance(start, wireEnd);
float wireWidth = 12 * panel.Scale;
float highlight = 5 * panel.Scale;
float wireWidth = 12 * GUI.Scale;
float highlight = 5 * GUI.Scale;
if (mouseOn)
{
spriteBatch.Draw(wireVertical.Texture, new Rectangle(wireEnd.ToPoint(), new Point((int)(wireWidth + highlight), (int)dist)), wireVertical.SourceRect,
@@ -488,110 +507,84 @@ namespace Barotrauma.Items.Components
{
Rectangle panelRect = panel.GuiFrame.Rect;
int x = panelRect.X, y = panelRect.Y;
Vector2 scale = GetScale(panel.GuiFrame.RectTransform.MaxSize, panel.GuiFrame.Rect.Size);
Vector2 rightPos = GetRightPos(x, y, panelRect.Width, scale);
Vector2 leftPos = GetLeftPos(x, y, scale);
int connectorIntervalLeft = GetConnectorIntervalLeft(panelRect.Height, scale, panel);
int connectorIntervalRight = GetConnectorIntervalRight(panelRect.Height, scale, panel);
Vector2 rightPos = GetRightPos(x, y, panelRect.Width);
Vector2 leftPos = GetLeftPos(x, y);
int connectorIntervalLeft = GetConnectorIntervalLeft(panelRect.Height, panel);
int connectorIntervalRight = GetConnectorIntervalRight(panelRect.Height, panel);
newRectSize = panelRect.Size;
var labelAreas = new List<Rectangle>();
for (int i = 0; i < 100; i++)
//make sure the connection labels don't overlap horizontally
float rightMostInput = panelRect.Center.X;
float leftMostOutput = panelRect.Center.X;
foreach (var c in panel.Connections)
{
labelAreas.Clear();
foreach (var c in panel.Connections)
if (c.IsOutput)
{
if (c.IsOutput)
{
var labelArea = GetLabelArea(GetOutputLabelPosition(rightPos, panel, c), c.DisplayName.Value.ToUpperInvariant(), scale);
labelAreas.Add(labelArea);
rightPos.Y += connectorIntervalLeft;
}
else
{
var labelArea = GetLabelArea(GetInputLabelPosition(leftPos, panel, c), c.DisplayName.Value.ToUpperInvariant(), scale);
labelAreas.Add(labelArea);
leftPos.Y += connectorIntervalRight;
}
var labelArea = GetLabelArea(GetOutputLabelPosition(rightPos, panel, c), c.DisplayName.Value.ToUpperInvariant());
leftMostOutput = Math.Min(leftMostOutput, labelArea.X);
rightPos.Y += connectorIntervalLeft;
}
bool foundOverlap = false;
for (int j = 0; j < labelAreas.Count; j++)
else
{
for (int k = 0; k < labelAreas.Count; k++)
{
if (k == j) { continue; }
if (!labelAreas[j].Intersects(labelAreas[k])) { continue; }
newRectSize += new Point(10);
Point maxSize = new Point(
Math.Max(panel.GuiFrame.RectTransform.MaxSize.X, newRectSize.X),
Math.Max(panel.GuiFrame.RectTransform.MaxSize.Y, newRectSize.Y));
scale = GetScale(maxSize, newRectSize);
rightPos = GetRightPos(x, y, newRectSize.X, scale);
leftPos = GetLeftPos(x, y, scale);
connectorIntervalLeft = GetConnectorIntervalLeft(newRectSize.Y, scale, panel);
connectorIntervalRight = GetConnectorIntervalRight(newRectSize.Y, scale, panel);
foundOverlap = true;
break;
}
var labelArea = GetLabelArea(GetInputLabelPosition(leftPos, panel, c), c.DisplayName.Value.ToUpperInvariant());
rightMostInput = Math.Max(rightMostInput, labelArea.Right);
leftPos.Y += connectorIntervalRight;
}
if (!foundOverlap) { break; }
}
if (leftMostOutput < rightMostInput)
{
newRectSize += new Point((int)(rightMostInput - leftMostOutput) + GUI.IntScale(15), 0);
}
//make sure connection sprites don't overlap vertically
while (GetConnectorIntervalLeft(newRectSize.Y, panel) < ConnectionSpriteSize ||
GetConnectorIntervalRight(newRectSize.Y, panel) < ConnectionSpriteSize)
{
newRectSize.Y += 10;
}
return newRectSize.X != panel.GuiFrame.Rect.Width || newRectSize.Y > panel.GuiFrame.Rect.Height;
}
private static Vector2 GetScale(Point maxSize, Point size)
{
Vector2 scale = new Vector2(GUI.Scale);
if (maxSize.X < int.MaxValue)
{
scale.X = maxSize.X / size.X;
}
if (maxSize.Y < int.MaxValue)
{
scale.Y = maxSize.Y / size.Y;
}
return scale;
}
private static Vector2 GetInputLabelPosition(Vector2 connectorPosition, ConnectionPanel panel, Connection connection)
{
return new Vector2(
connectorPosition.X + 25 * panel.Scale,
connectorPosition.Y - 5 * panel.Scale - GUIStyle.SmallFont.MeasureString(connection.DisplayName.ToUpper()).Y);
connectorPosition.X + 25 * GUI.Scale,
connectorPosition.Y - GUIStyle.SmallFont.MeasureString(connection.DisplayName.ToUpper()).Y / 2);
}
private static Vector2 GetOutputLabelPosition(Vector2 connectorPosition, ConnectionPanel panel, Connection connection)
{
return new Vector2(
connectorPosition.X - 25 * panel.Scale - GUIStyle.SmallFont.MeasureString(connection.DisplayName.ToUpper()).X,
connectorPosition.Y + 5 * panel.Scale);
connectorPosition.X - 25 * GUI.Scale - GUIStyle.SmallFont.MeasureString(connection.DisplayName.ToUpper()).X,
connectorPosition.Y - GUIStyle.SmallFont.MeasureString(connection.DisplayName.ToUpper()).Y / 2);
}
private static Rectangle GetLabelArea(Vector2 labelPos, string text, Vector2 scale)
private static Rectangle GetLabelArea(Vector2 labelPos, string text)
{
Vector2 textSize = GUIStyle.SmallFont.MeasureString(text);
Rectangle labelArea = new Rectangle(labelPos.ToPoint(), textSize.ToPoint());
labelArea.Inflate(10 * scale.X, 3 * scale.Y);
labelArea.Inflate(GUI.IntScale(10), GUI.IntScale(3));
return labelArea;
}
private static Vector2 GetLeftPos(int x, int y, Vector2 scale)
private static Vector2 GetLeftPos(int x, int y)
{
return new Vector2(x + 80 * scale.X, y + 60 * scale.Y);
return new Vector2(x + 80 * GUI.Scale, y + 60 * GUI.Scale);
}
private static Vector2 GetRightPos(int x, int y, int width, Vector2 scale)
private static Vector2 GetRightPos(int x, int y, int width)
{
return new Vector2(x + width - 80 * scale.X, y + 60 * scale.Y);
return new Vector2(x + width - 80 * GUI.Scale, y + 60 * GUI.Scale);
}
private static int GetConnectorIntervalLeft(int height, Vector2 scale, ConnectionPanel panel)
private static int GetConnectorIntervalLeft(int height, ConnectionPanel panel)
{
return (height - (int)(100 * scale.Y)) / Math.Max(panel.Connections.Count(c => c.IsOutput), 1);
return (height - GUI.IntScale(60)) / Math.Max(panel.Connections.Count(c => c.IsOutput), 1);
}
private static int GetConnectorIntervalRight(int height, Vector2 scale, ConnectionPanel panel)
private static int GetConnectorIntervalRight(int height, ConnectionPanel panel)
{
return (height - (int)(100 * scale.Y)) / Math.Max(panel.Connections.Count(c => !c.IsOutput), 1);
return (height - GUI.IntScale(60)) / Math.Max(panel.Connections.Count(c => !c.IsOutput), 1);
}
}
}
@@ -22,11 +22,6 @@ namespace Barotrauma.Items.Components
private SoundChannel rewireSoundChannel;
private float rewireSoundTimer;
public float Scale
{
get { return GuiFrame.Rect.Width / 400.0f; }
}
private Point originalMaxSize;
private Vector2 originalRelativeSize;
@@ -104,10 +99,10 @@ namespace Barotrauma.Items.Components
public override bool ShouldDrawHUD(Character character)
{
return character == Character.Controlled && character == user && character.SelectedItem == item;
return character == Character.Controlled && character == user && (character.SelectedItem == item || character.SelectedSecondaryItem == item);
}
public override void UpdateHUD(Character character, float deltaTime, Camera cam)
public override void UpdateHUDComponentSpecific(Character character, float deltaTime, Camera cam)
{
if (character != Character.Controlled || character != user || character.SelectedItem != item) { return; }
@@ -162,10 +157,11 @@ namespace Barotrauma.Items.Components
//because some of the wires connected to the panel may not exist yet
long msgStartPos = msg.BitPosition;
msg.ReadUInt16(); //user ID
foreach (Connection _ in Connections)
byte connectionCount = msg.ReadByte();
for (int i = 0; i < connectionCount; i++)
{
uint wireCount = msg.ReadVariableUInt32();
for (int i = 0; i < wireCount; i++)
for (int j = 0; j < wireCount; j++)
{
msg.ReadUInt16();
}
@@ -208,21 +204,25 @@ namespace Barotrauma.Items.Components
connection.ClearConnections();
}
foreach (Connection connection in Connections)
byte connectionCount = msg.ReadByte();
for (int i = 0; i < connectionCount; i++)
{
HashSet<Wire> newWires = new HashSet<Wire>();
uint wireCount = msg.ReadVariableUInt32();
for (int i = 0; i < wireCount; i++)
for (int j = 0; j < wireCount; j++)
{
ushort wireId = msg.ReadUInt16();
if (!(Entity.FindEntityByID(wireId) is Item wireItem)) { continue; }
if (Entity.FindEntityByID(wireId) is not Item wireItem) { continue; }
Wire wireComponent = wireItem.GetComponent<Wire>();
if (wireComponent == null) { continue; }
newWires.Add(wireComponent);
}
//this may happen if the item has been deleted server-side at the point the server is writing this event to the client
if (i >= Connections.Count) { continue; }
var connection = Connections[i];
Wire[] oldWires = connection.Wires.Where(w => !newWires.Contains(w)).ToArray();
foreach (var wire in oldWires)
{
@@ -244,7 +244,7 @@ namespace Barotrauma.Items.Components
}
}
public override void UpdateHUD(Character character, float deltaTime, Camera cam)
public override void UpdateHUDComponentSpecific(Character character, float deltaTime, Camera cam)
{
bool elementVisibilityChanged = false;
int visibleElementCount = 0;
@@ -335,17 +335,18 @@ namespace Barotrauma.Items.Components
if (signals == null) { return; }
for (int i = 0; i < signals.Length && i < uiElements.Count; i++)
{
string signal = customInterfaceElementList[i].Signal;
if (uiElements[i] is GUITextBox tb)
{
tb.Text = Screen.Selected is { IsEditor: true } ?
customInterfaceElementList[i].Signal :
TextManager.Get(customInterfaceElementList[i].Signal).Value;
signal :
TextManager.Get(signal).Fallback(signal).Value;
}
else if (uiElements[i] is GUINumberInput ni)
{
if (ni.InputType == NumberType.Int)
{
int.TryParse(customInterfaceElementList[i].Signal, out int value);
int.TryParse(signal, out int value);
ni.IntValue = value;
}
}
@@ -10,7 +10,7 @@ namespace Barotrauma.Items.Components
get { return new Vector2(rangeX, rangeY) * 2.0f; }
}
public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1)
public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1, Color? overrideColor = null)
{
if (!editing || !MapEntity.SelectedList.Contains(item)) { return; }
@@ -86,15 +86,15 @@ namespace Barotrauma.Items.Components
}
OutputValue = input;
ShowOnDisplay(input, addToHistory: true, TextColor);
ShowOnDisplay(input, addToHistory: true, TextColor, isWelcomeMessage: false);
item.SendSignal(input, "signal_out");
}
partial void ShowOnDisplay(string input, bool addToHistory, Color color)
partial void ShowOnDisplay(string input, bool addToHistory, Color color, bool isWelcomeMessage)
{
if (addToHistory)
{
messageHistory.Add(new TerminalMessage(input, color));
messageHistory.Add(new TerminalMessage(input, color, isWelcomeMessage));
while (messageHistory.Count > MaxMessages)
{
messageHistory.RemoveAt(0);
@@ -11,9 +11,9 @@ namespace Barotrauma.Items.Components
get { return new Vector2(range * 2); }
}
public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1)
public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1, Color? overrideColor = null)
{
if (!editing || !MapEntity.SelectedList.Contains(item)) return;
if (!editing || !MapEntity.SelectedList.Contains(item)) { return; }
Vector2 pos = new Vector2(item.DrawPosition.X, -item.DrawPosition.Y);
ShapeExtensions.DrawLine(spriteBatch, pos + Vector2.UnitY * range, pos - Vector2.UnitY * range, Color.Cyan * 0.5f, 2);
@@ -186,12 +186,12 @@ namespace Barotrauma.Items.Components
return Color.LightBlue;
}
public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1)
public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1, Color? overrideColor = null)
{
Draw(spriteBatch, editing, Vector2.Zero, itemDepth);
Draw(spriteBatch, editing, Vector2.Zero, itemDepth, overrideColor);
}
public void Draw(SpriteBatch spriteBatch, bool editing, Vector2 offset, float itemDepth = -1)
public void Draw(SpriteBatch spriteBatch, bool editing, Vector2 offset, float itemDepth = -1, Color? overrideColor = null)
{
if (sections.Count == 0 && !IsActive || Hidden)
{
@@ -223,7 +223,7 @@ namespace Barotrauma.Items.Components
foreach (WireSection section in sections)
{
section.Draw(spriteBatch, wireSprite, item.Color, drawOffset, depth, Width);
section.Draw(spriteBatch, wireSprite, overrideColor ?? item.Color, drawOffset, depth, Width);
}
if (nodes.Count > 0)
@@ -271,13 +271,13 @@ namespace Barotrauma.Items.Components
spriteBatch, wireSprite,
nodes[^1] + drawOffset,
new Vector2(newNodePos.X, newNodePos.Y) + drawOffset,
item.Color, 0.0f, Width);
overrideColor ?? item.Color, 0.0f, Width);
WireSection.Draw(
spriteBatch, wireSprite,
new Vector2(newNodePos.X, newNodePos.Y) + drawOffset,
item.DrawPosition,
item.Color, itemDepth, Width);
overrideColor ?? item.Color, itemDepth, Width);
GUI.DrawRectangle(spriteBatch, new Vector2(newNodePos.X + drawOffset.X, -(newNodePos.Y + drawOffset.Y)) - Vector2.One * 3, Vector2.One * 6, item.Color);
}
@@ -287,7 +287,7 @@ namespace Barotrauma.Items.Components
spriteBatch, wireSprite,
nodes[^1] + drawOffset,
item.DrawPosition,
item.Color, 0.0f, Width);
overrideColor ?? item.Color, 0.0f, Width);
}
}
}
@@ -594,7 +594,7 @@ namespace Barotrauma.Items.Components
selectedWire.shouldClearConnections = false;
Character.Controlled.Inventory.TryPutItem(selectedWire.item, Character.Controlled, new List<InvSlotType> { InvSlotType.LeftHand, InvSlotType.RightHand });
foreach (var entity in MapEntity.mapEntityList)
foreach (var entity in MapEntity.MapEntityList)
{
if (entity is Item item)
{