(e42047dc1) Tester's build, January 30th 2020

This commit is contained in:
Juan Pablo Arce
2020-01-30 15:56:31 -03:00
parent eaa18a20a3
commit 15499cb704
203 changed files with 8274 additions and 4950 deletions
@@ -311,7 +311,7 @@ namespace Barotrauma
{ {
Freeze = true; Freeze = true;
} }
if (CharacterHealth.OpenHealthWindow != null) if (CharacterHealth.OpenHealthWindow != null || CrewManager.IsCommandInterfaceOpen)
{ {
offset *= 0; offset *= 0;
Freeze = false; Freeze = false;
@@ -34,7 +34,7 @@ namespace Barotrauma
targetPos = attackWorldPos; targetPos = attackWorldPos;
} }
targetPos.Y = -targetPos.Y; targetPos.Y = -targetPos.Y;
GUI.DrawLine(spriteBatch, pos, targetPos, Color.Red * 0.5f, 0, 4); GUI.DrawLine(spriteBatch, pos, targetPos, GUI.Style.Red * 0.5f, 0, 4);
if (wallTarget != null) if (wallTarget != null)
{ {
Vector2 wallTargetPos = wallTarget.Position; Vector2 wallTargetPos = wallTarget.Position;
@@ -43,19 +43,19 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, wallTargetPos - new Vector2(10.0f, 10.0f), new Vector2(20.0f, 20.0f), Color.Orange, false); GUI.DrawRectangle(spriteBatch, wallTargetPos - new Vector2(10.0f, 10.0f), new Vector2(20.0f, 20.0f), Color.Orange, false);
GUI.DrawLine(spriteBatch, pos, wallTargetPos, Color.Orange * 0.5f, 0, 5); GUI.DrawLine(spriteBatch, pos, wallTargetPos, Color.Orange * 0.5f, 0, 5);
} }
GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 60.0f, $"{SelectedAiTarget.Entity.ToString()} ({GetTargetMemory(SelectedAiTarget).Priority.FormatZeroDecimal()})", Color.Red, Color.Black); GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 60.0f, $"{SelectedAiTarget.Entity.ToString()} ({GetTargetMemory(SelectedAiTarget).Priority.FormatZeroDecimal()})", GUI.Style.Red, Color.Black);
GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 40.0f, $"({targetValue.FormatZeroDecimal()})", Color.Red, Color.Black); GUI.DrawString(spriteBatch, pos - Vector2.UnitY * 40.0f, $"({targetValue.FormatZeroDecimal()})", GUI.Style.Red, Color.Black);
} }
/*GUI.Font.DrawString(spriteBatch, targetValue.ToString(), pos - Vector2.UnitY * 80.0f, Color.Red); /*GUI.Font.DrawString(spriteBatch, targetValue.ToString(), pos - Vector2.UnitY * 80.0f, GUI.Style.Red);
GUI.Font.DrawString(spriteBatch, "updatetargets: " + MathUtils.Round(updateTargetsTimer, 0.1f), pos - Vector2.UnitY * 100.0f, Color.Red); GUI.Font.DrawString(spriteBatch, "updatetargets: " + MathUtils.Round(updateTargetsTimer, 0.1f), pos - Vector2.UnitY * 100.0f, GUI.Style.Red);
GUI.Font.DrawString(spriteBatch, "cooldown: " + MathUtils.Round(coolDownTimer, 0.1f), pos - Vector2.UnitY * 120.0f, Color.Red);*/ GUI.Font.DrawString(spriteBatch, "cooldown: " + MathUtils.Round(coolDownTimer, 0.1f), pos - Vector2.UnitY * 120.0f, GUI.Style.Red);*/
Color stateColor = Color.White; Color stateColor = Color.White;
switch (State) switch (State)
{ {
case AIState.Attack: case AIState.Attack:
stateColor = IsCoolDownRunning ? Color.Orange : Color.Red; stateColor = IsCoolDownRunning ? Color.Orange : GUI.Style.Red;
break; break;
case AIState.Escape: case AIState.Escape:
stateColor = Color.LightBlue; stateColor = Color.LightBlue;
@@ -75,13 +75,13 @@ namespace Barotrauma
{ {
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
ConvertUnits.ToDisplayUnits(new Vector2(attachJoint.WorldAnchorA.X, -attachJoint.WorldAnchorA.Y)), ConvertUnits.ToDisplayUnits(new Vector2(attachJoint.WorldAnchorA.X, -attachJoint.WorldAnchorA.Y)),
ConvertUnits.ToDisplayUnits(new Vector2(attachJoint.WorldAnchorB.X, -attachJoint.WorldAnchorB.Y)), Color.Green, 0, 4); ConvertUnits.ToDisplayUnits(new Vector2(attachJoint.WorldAnchorB.X, -attachJoint.WorldAnchorB.Y)), GUI.Style.Green, 0, 4);
} }
if (LatchOntoAI.WallAttachPos.HasValue) if (LatchOntoAI.WallAttachPos.HasValue)
{ {
//GUI.DrawLine(spriteBatch, pos, //GUI.DrawLine(spriteBatch, pos,
// ConvertUnits.ToDisplayUnits(new Vector2(LatchOntoAI.WallAttachPos.Value.X, -LatchOntoAI.WallAttachPos.Value.Y)), Color.Green, 0, 3); // ConvertUnits.ToDisplayUnits(new Vector2(LatchOntoAI.WallAttachPos.Value.X, -LatchOntoAI.WallAttachPos.Value.Y)), GUI.Style.Green, 0, 3);
} }
} }
@@ -105,12 +105,12 @@ namespace Barotrauma
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
new Vector2(currentNode.DrawPosition.X, -currentNode.DrawPosition.Y), new Vector2(currentNode.DrawPosition.X, -currentNode.DrawPosition.Y),
new Vector2(previousNode.DrawPosition.X, -previousNode.DrawPosition.Y), new Vector2(previousNode.DrawPosition.X, -previousNode.DrawPosition.Y),
Color.Red * 0.5f, 0, 3); GUI.Style.Red * 0.5f, 0, 3);
GUI.SmallFont.DrawString(spriteBatch, GUI.SmallFont.DrawString(spriteBatch,
currentNode.ID.ToString(), currentNode.ID.ToString(),
new Vector2(currentNode.DrawPosition.X - 10, -currentNode.DrawPosition.Y - 30), new Vector2(currentNode.DrawPosition.X - 10, -currentNode.DrawPosition.Y - 30),
Color.Red); GUI.Style.Red);
} }
} }
} }
@@ -121,7 +121,7 @@ namespace Barotrauma
Vector2 hitPos = ConvertUnits.ToDisplayUnits(steeringManager.AvoidRayCastHitPosition); Vector2 hitPos = ConvertUnits.ToDisplayUnits(steeringManager.AvoidRayCastHitPosition);
hitPos.Y = -hitPos.Y; hitPos.Y = -hitPos.Y;
GUI.DrawLine(spriteBatch, hitPos, hitPos + new Vector2(steeringManager.AvoidDir.X, -steeringManager.AvoidDir.Y) * 100, Color.Red, width: 5); GUI.DrawLine(spriteBatch, hitPos, hitPos + new Vector2(steeringManager.AvoidDir.X, -steeringManager.AvoidDir.Y) * 100, GUI.Style.Red, width: 5);
//GUI.DrawLine(spriteBatch, pos, ConvertUnits.ToDisplayUnits(steeringManager.AvoidLookAheadPos.X, -steeringManager.AvoidLookAheadPos.Y), Color.Orange, width: 4); //GUI.DrawLine(spriteBatch, pos, ConvertUnits.ToDisplayUnits(steeringManager.AvoidLookAheadPos.X, -steeringManager.AvoidLookAheadPos.Y), Color.Orange, width: 4);
} }
} }
@@ -29,7 +29,7 @@ namespace Barotrauma
if (SelectedAiTarget?.Entity != null) if (SelectedAiTarget?.Entity != null)
{ {
//GUI.DrawLine(spriteBatch, pos, new Vector2(SelectedAiTarget.WorldPosition.X, -SelectedAiTarget.WorldPosition.Y), Color.Red); //GUI.DrawLine(spriteBatch, pos, new Vector2(SelectedAiTarget.WorldPosition.X, -SelectedAiTarget.WorldPosition.Y), GUI.Style.Red);
//GUI.DrawString(spriteBatch, pos + textOffset, $"AI TARGET: {SelectedAiTarget.Entity.ToString()}", Color.White, Color.Black); //GUI.DrawString(spriteBatch, pos + textOffset, $"AI TARGET: {SelectedAiTarget.Entity.ToString()}", Color.White, Color.Black);
} }
@@ -439,7 +439,7 @@ namespace Barotrauma
Color? color = null; Color? color = null;
if (character.ExternalHighlight) if (character.ExternalHighlight)
{ {
color = Color.Lerp(Color.White, Color.OrangeRed, (float)Math.Sin(Timing.TotalTime * 3.5f)); color = Color.Lerp(Color.White, GUI.Style.Orange, (float)Math.Sin(Timing.TotalTime * 3.5f));
} }
float depthOffset = GetDepthOffset(); float depthOffset = GetDepthOffset();
@@ -498,13 +498,13 @@ namespace Barotrauma
Vector2 pos = ConvertUnits.ToDisplayUnits(limb.PullJointWorldAnchorA); Vector2 pos = ConvertUnits.ToDisplayUnits(limb.PullJointWorldAnchorA);
if (currentHull?.Submarine != null) pos += currentHull.Submarine.DrawPosition; if (currentHull?.Submarine != null) pos += currentHull.Submarine.DrawPosition;
pos.Y = -pos.Y; pos.Y = -pos.Y;
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)pos.Y, 5, 5), Color.Red, true, 0.01f); GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)pos.Y, 5, 5), GUI.Style.Red, true, 0.01f);
} }
limb.body.DebugDraw(spriteBatch, inWater ? (currentHull == null ? Color.Blue : Color.Cyan) : Color.White); limb.body.DebugDraw(spriteBatch, inWater ? (currentHull == null ? Color.Blue : Color.Cyan) : Color.White);
} }
Collider.DebugDraw(spriteBatch, frozen ? Color.Red : (inWater ? Color.SkyBlue : Color.Gray)); Collider.DebugDraw(spriteBatch, frozen ? GUI.Style.Red : (inWater ? Color.SkyBlue : Color.Gray));
GUI.Font.DrawString(spriteBatch, Collider.LinearVelocity.X.FormatSingleDecimal(), new Vector2(Collider.DrawPosition.X, -Collider.DrawPosition.Y), Color.Orange); GUI.Font.DrawString(spriteBatch, Collider.LinearVelocity.X.FormatSingleDecimal(), new Vector2(Collider.DrawPosition.X, -Collider.DrawPosition.Y), Color.Orange);
foreach (RevoluteJoint joint in LimbJoints) foreach (RevoluteJoint joint in LimbJoints)
@@ -532,9 +532,9 @@ namespace Barotrauma
if (this is HumanoidAnimController humanoid) if (this is HumanoidAnimController humanoid)
{ {
Vector2 pos = ConvertUnits.ToDisplayUnits(humanoid.RightHandIKPos); Vector2 pos = ConvertUnits.ToDisplayUnits(humanoid.RightHandIKPos);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 4, 4), Color.Green, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 4, 4), GUI.Style.Green, true);
pos = ConvertUnits.ToDisplayUnits(humanoid.LeftHandIKPos); pos = ConvertUnits.ToDisplayUnits(humanoid.LeftHandIKPos);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 4, 4), Color.Green, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 4, 4), GUI.Style.Green, true);
} }
if (character.MemState.Count > 1) if (character.MemState.Count > 1)
@@ -1,3 +1,4 @@
using Barotrauma.Items.Components;
using Barotrauma.Networking; using Barotrauma.Networking;
using Barotrauma.Particles; using Barotrauma.Particles;
using Barotrauma.Sounds; using Barotrauma.Sounds;
@@ -58,7 +59,7 @@ namespace Barotrauma
CharacterHealth.OpenHealthWindow = null; CharacterHealth.OpenHealthWindow = null;
} }
} }
private Dictionary<object, HUDProgressBar> hudProgressBars; private Dictionary<object, HUDProgressBar> hudProgressBars;
private readonly List<KeyValuePair<object, HUDProgressBar>> progressBarRemovals = new List<KeyValuePair<object, HUDProgressBar>>(); private readonly List<KeyValuePair<object, HUDProgressBar>> progressBarRemovals = new List<KeyValuePair<object, HUDProgressBar>>();
@@ -650,6 +651,34 @@ namespace Barotrauma
if (GUI.DisableHUD) return; if (GUI.DisableHUD) return;
if (Controlled != null &&
Controlled != this &&
Submarine != null &&
Controlled.Submarine == Submarine &&
GameMain.Config.LosMode != LosMode.None)
{
float yPos = Controlled.AnimController.FloorY - 1.5f;
if (Controlled.AnimController.Stairs != null)
{
yPos = Controlled.AnimController.Stairs.SimPosition.Y - Controlled.AnimController.Stairs.RectHeight * 0.5f;
}
foreach (var ladder in Ladder.List)
{
if (CanInteractWith(ladder.Item) && Controlled.CanInteractWith(ladder.Item))
{
float xPos = ladder.Item.SimPosition.X;
if (Math.Abs(xPos - SimPosition.X) < 3.0)
{
yPos = ladder.Item.SimPosition.Y - ladder.Item.RectHeight * 0.5f;
}
break;
}
}
if (AnimController.FloorY < yPos) { return; }
}
Vector2 pos = DrawPosition; Vector2 pos = DrawPosition;
pos.Y += hudInfoHeight; pos.Y += hudInfoHeight;
@@ -694,7 +723,7 @@ namespace Barotrauma
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
cursorPos, cursorPos,
new Vector2(item.First.DrawPosition.X, -item.First.DrawPosition.Y), new Vector2(item.First.DrawPosition.X, -item.First.DrawPosition.Y),
ToolBox.GradientLerp(item.Second, Color.Red, Color.Orange, Color.Green), width: 2); ToolBox.GradientLerp(item.Second, GUI.Style.Red, GUI.Style.Orange, GUI.Style.Green), width: 2);
} }
} }
return; return;
@@ -724,7 +753,7 @@ namespace Barotrauma
Color nameColor = Color.White; Color nameColor = Color.White;
if (Controlled != null && TeamID != Controlled.TeamID) if (Controlled != null && TeamID != Controlled.TeamID)
{ {
nameColor = TeamID == TeamType.FriendlyNPC ? Color.SkyBlue : Color.Red; nameColor = TeamID == TeamType.FriendlyNPC ? Color.SkyBlue : GUI.Style.Red;
} }
GUI.Font.DrawString(spriteBatch, name, namePos + new Vector2(1.0f / cam.Zoom, 1.0f / cam.Zoom), Color.Black, 0.0f, Vector2.Zero, 1.0f / cam.Zoom, SpriteEffects.None, 0.001f); GUI.Font.DrawString(spriteBatch, name, namePos + new Vector2(1.0f / cam.Zoom, 1.0f / cam.Zoom), Color.Black, 0.0f, Vector2.Zero, 1.0f / cam.Zoom, SpriteEffects.None, 0.001f);
GUI.Font.DrawString(spriteBatch, name, namePos, nameColor * hudInfoAlpha, 0.0f, Vector2.Zero, 1.0f / cam.Zoom, SpriteEffects.None, 0.0f); GUI.Font.DrawString(spriteBatch, name, namePos, nameColor * hudInfoAlpha, 0.0f, Vector2.Zero, 1.0f / cam.Zoom, SpriteEffects.None, 0.0f);
@@ -744,7 +773,7 @@ namespace Barotrauma
Vector2 healthBarPos = new Vector2(pos.X - 50, -pos.Y); Vector2 healthBarPos = new Vector2(pos.X - 50, -pos.Y);
GUI.DrawProgressBar(spriteBatch, healthBarPos, new Vector2(100.0f, 15.0f), GUI.DrawProgressBar(spriteBatch, healthBarPos, new Vector2(100.0f, 15.0f),
CharacterHealth.DisplayedVitality / MaxVitality, CharacterHealth.DisplayedVitality / MaxVitality,
Color.Lerp(Color.Red, Color.Green, CharacterHealth.DisplayedVitality / MaxVitality) * 0.8f * hudInfoAlpha, Color.Lerp(GUI.Style.Red, GUI.Style.Green, CharacterHealth.DisplayedVitality / MaxVitality) * 0.8f * hudInfoAlpha,
new Color(0.5f, 0.57f, 0.6f, 1.0f) * hudInfoAlpha); new Color(0.5f, 0.57f, 0.6f, 1.0f) * hudInfoAlpha);
} }
} }
@@ -171,6 +171,7 @@ namespace Barotrauma
if (GUI.DisableHUD) return; if (GUI.DisableHUD) return;
character.CharacterHealth.Alignment = Alignment.Right; character.CharacterHealth.Alignment = Alignment.Right;
GUI.InfoAreaBackground.Draw(spriteBatch, Vector2.Zero);
if (GameMain.GameSession?.CrewManager != null) if (GameMain.GameSession?.CrewManager != null)
{ {
@@ -198,54 +199,17 @@ namespace Barotrauma
float alpha = Math.Min((1000.0f - dist) / 1000.0f * 2.0f, 1.0f); float alpha = Math.Min((1000.0f - dist) / 1000.0f * 2.0f, 1.0f);
if (alpha <= 0.0f) continue; if (alpha <= 0.0f) continue;
GUI.DrawIndicator(spriteBatch, drawPos, cam, 100.0f, GUI.BrokenIcon, GUI.DrawIndicator(spriteBatch, drawPos, cam, 100.0f, GUI.BrokenIcon,
Color.Lerp(Color.DarkRed, Color.Orange * 0.5f, brokenItem.Condition / brokenItem.MaxCondition) * alpha); Color.Lerp(GUI.Style.Red, GUI.Style.Orange * 0.5f, brokenItem.Condition / brokenItem.MaxCondition) * alpha);
} }
if (!character.IsUnconscious && character.Stun <= 0.0f) if (!character.IsUnconscious && character.Stun <= 0.0f)
{ {
if (character.FocusedCharacter != null && character.FocusedCharacter.CanBeSelected) if (character.FocusedCharacter != null && character.FocusedCharacter.CanBeSelected)
{ {
Vector2 startPos = character.DrawPosition + (character.FocusedCharacter.DrawPosition - character.DrawPosition) * 0.7f; DrawCharacterHoverTexts(spriteBatch, cam, character);
startPos = cam.WorldToScreen(startPos);
string focusName = character.FocusedCharacter.DisplayName;
if (character.FocusedCharacter.Info != null)
{
focusName = character.FocusedCharacter.Info.DisplayName;
}
Vector2 textPos = startPos;
Vector2 offset = GUI.Font.MeasureString(focusName);
textPos -= new Vector2(offset.X / 2, offset.Y);
Color nameColor = Color.White;
if (character.TeamID != character.FocusedCharacter.TeamID)
{
nameColor = character.FocusedCharacter.TeamID == Character.TeamType.FriendlyNPC ? Color.SkyBlue : Color.Red;
}
GUI.DrawString(spriteBatch, textPos, focusName, nameColor, Color.Black * 0.7f, 2);
textPos.Y += offset.Y;
if (character.FocusedCharacter.CanBeDragged)
{
GUI.DrawString(spriteBatch, textPos, GetCachedHudText("GrabHint", GameMain.Config.KeyBindText(InputType.Grab)),
Color.LightGreen, Color.Black, 2, GUI.SmallFont);
textPos.Y += offset.Y;
}
if (character.FocusedCharacter.CharacterHealth.UseHealthWindow && character.CanInteractWith(character.FocusedCharacter, 160f, false))
{
GUI.DrawString(spriteBatch, textPos, GetCachedHudText("HealHint", GameMain.Config.KeyBindText(InputType.Health)),
Color.LightGreen, Color.Black, 2, GUI.SmallFont);
textPos.Y += offset.Y;
}
if (!string.IsNullOrEmpty(character.FocusedCharacter.customInteractHUDText))
{
GUI.DrawString(spriteBatch, textPos, character.FocusedCharacter.customInteractHUDText, Color.LightGreen, Color.Black, 2, GUI.SmallFont);
textPos.Y += offset.Y;
}
} }
float circleSize = 1.0f; float circleSize;
if (character.FocusedItem != null) if (character.FocusedItem != null)
{ {
if (focusedItem != character.FocusedItem) if (focusedItem != character.FocusedItem)
@@ -278,9 +242,11 @@ namespace Barotrauma
int dir = Math.Sign(focusedItem.WorldPosition.X - character.WorldPosition.X); int dir = Math.Sign(focusedItem.WorldPosition.X - character.WorldPosition.X);
Vector2 offset = GUI.Font.MeasureString(focusedItem.Name); Vector2 textSize = GUI.Font.MeasureString(focusedItem.Name);
Vector2 largeTextSize = GUI.SubHeadingFont.MeasureString(focusedItem.Name);
Vector2 startPos = cam.WorldToScreen(focusedItem.DrawPosition); Vector2 startPos = cam.WorldToScreen(focusedItem.DrawPosition);
startPos.Y -= (hudTexts.Count + 1) * offset.Y; startPos.Y -= (hudTexts.Count + 1) * textSize.Y;
if (focusedItem.Sprite != null) if (focusedItem.Sprite != null)
{ {
startPos.X += (int)(circleSize * 0.4f * dir); startPos.X += (int)(circleSize * 0.4f * dir);
@@ -288,17 +254,19 @@ namespace Barotrauma
} }
Vector2 textPos = startPos; Vector2 textPos = startPos;
if (dir == -1) textPos.X -= offset.X; if (dir == -1) { textPos.X -= largeTextSize.X; }
float alpha = MathHelper.Clamp((focusedItemOverlayTimer - ItemOverlayDelay) * 2.0f, 0.0f, 1.0f); float alpha = MathHelper.Clamp((focusedItemOverlayTimer - ItemOverlayDelay) * 2.0f, 0.0f, 1.0f);
GUI.DrawString(spriteBatch, textPos, focusedItem.Name, Color.White * alpha, Color.Black * alpha * 0.7f, 2); GUI.DrawString(spriteBatch, textPos, focusedItem.Name, GUI.Style.TextColor * alpha, Color.Black * alpha * 0.7f, 2, font: GUI.SubHeadingFont);
textPos.Y += offset.Y; startPos.X += dir * 10.0f * GUI.Scale;
textPos.X += dir * 10.0f * GUI.Scale;
textPos.Y += largeTextSize.Y;
foreach (ColoredText coloredText in hudTexts) foreach (ColoredText coloredText in hudTexts)
{ {
if (dir == -1) textPos.X = (int)(startPos.X - GUI.SmallFont.MeasureString(coloredText.Text).X); if (dir == -1) textPos.X = (int)(startPos.X - GUI.SmallFont.MeasureString(coloredText.Text).X);
GUI.DrawString(spriteBatch, textPos, coloredText.Text, coloredText.Color * alpha, Color.Black * alpha * 0.7f, 2, GUI.SmallFont); GUI.DrawString(spriteBatch, textPos, coloredText.Text, coloredText.Color * alpha, Color.Black * alpha * 0.7f, 2, GUI.SmallFont);
textPos.Y += offset.Y; textPos.Y += textSize.Y;
} }
} }
} }
@@ -336,11 +304,12 @@ namespace Barotrauma
if (character.Info != null) if (character.Info != null)
{ {
character.Info.DrawPortrait(spriteBatch, HUDLayoutSettings.PortraitArea.Location.ToVector2(), targetWidth: HUDLayoutSettings.PortraitArea.Width); character.Info.DrawPortrait(spriteBatch, HUDLayoutSettings.PortraitArea.Location.ToVector2(), targetWidth: HUDLayoutSettings.PortraitArea.Width);
character.Info.DrawJobIcon(spriteBatch);
} }
mouseOnPortrait = HUDLayoutSettings.PortraitArea.Contains(PlayerInput.MousePosition); mouseOnPortrait = HUDLayoutSettings.PortraitArea.Contains(PlayerInput.MousePosition);
if (mouseOnPortrait) if (mouseOnPortrait)
{ {
GUI.UIGlow.Draw(spriteBatch, HUDLayoutSettings.PortraitArea, Color.LightGreen * 0.5f); GUI.UIGlow.Draw(spriteBatch, HUDLayoutSettings.PortraitArea, GUI.Style.Green * 0.5f);
} }
} }
if (ShouldDrawInventory(character)) if (ShouldDrawInventory(character))
@@ -384,7 +353,60 @@ namespace Barotrauma
GUIComponent.DrawToolTip( GUIComponent.DrawToolTip(
spriteBatch, spriteBatch,
character.Info?.Job == null ? character.DisplayName : character.Name + " (" + character.Info.Job.Name + ")", character.Info?.Job == null ? character.DisplayName : character.Name + " (" + character.Info.Job.Name + ")",
HUDLayoutSettings.PortraitArea); HUDLayoutSettings.PortraitTooltipArea);
}
}
private static void DrawCharacterHoverTexts(SpriteBatch spriteBatch, Camera cam, Character character)
{
foreach (Item item in character.Inventory.Items)
{
var statusHUD = item?.GetComponent<StatusHUD>();
if (statusHUD != null && statusHUD.IsActive && statusHUD.VisibleCharacters.Contains(character.FocusedCharacter))
{
return;
}
}
Vector2 startPos = character.DrawPosition + (character.FocusedCharacter.DrawPosition - character.DrawPosition) * 0.7f;
startPos = cam.WorldToScreen(startPos);
string focusName = character.FocusedCharacter.DisplayName;
if (character.FocusedCharacter.Info != null)
{
focusName = character.FocusedCharacter.Info.DisplayName;
}
Vector2 textPos = startPos;
Vector2 textSize = GUI.Font.MeasureString(focusName);
Vector2 largeTextSize = GUI.SubHeadingFont.MeasureString(focusName);
textPos -= new Vector2(textSize.X / 2, textSize.Y);
Color nameColor = GUI.Style.TextColor;
if (character.TeamID != character.FocusedCharacter.TeamID)
{
nameColor = character.FocusedCharacter.TeamID == Character.TeamType.FriendlyNPC ? Color.SkyBlue : GUI.Style.Red;
}
GUI.DrawString(spriteBatch, textPos, focusName, nameColor, Color.Black * 0.7f, 2, GUI.SubHeadingFont);
textPos.X += 10.0f * GUI.Scale;
textPos.Y += GUI.SubHeadingFont.MeasureString(focusName).Y;
if (character.FocusedCharacter.CanBeDragged)
{
GUI.DrawString(spriteBatch, textPos, GetCachedHudText("GrabHint", GameMain.Config.KeyBindText(InputType.Grab)),
GUI.Style.Green, Color.Black, 2, GUI.SmallFont);
textPos.Y += largeTextSize.Y;
}
if (character.FocusedCharacter.CharacterHealth.UseHealthWindow && character.CanInteractWith(character.FocusedCharacter, 160f, false))
{
GUI.DrawString(spriteBatch, textPos, GetCachedHudText("HealHint", GameMain.Config.KeyBindText(InputType.Health)),
GUI.Style.Green, Color.Black, 2, GUI.SmallFont);
textPos.Y += textSize.Y;
}
if (!string.IsNullOrEmpty(character.FocusedCharacter.customInteractHUDText))
{
GUI.DrawString(spriteBatch, textPos, character.FocusedCharacter.customInteractHUDText, GUI.Style.Green, Color.Black, 2, GUI.SmallFont);
textPos.Y += textSize.Y;
} }
} }
@@ -12,7 +12,7 @@ namespace Barotrauma
{ {
public GUIFrame CreateInfoFrame(GUIFrame frame) public GUIFrame CreateInfoFrame(GUIFrame frame)
{ {
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.7f), frame.RectTransform, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.1f) }) var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), frame.RectTransform, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.1f) })
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.03f RelativeSpacing = 0.03f
@@ -103,7 +103,7 @@ namespace Barotrauma
{ {
GUI.AddMessage( GUI.AddMessage(
"+" + ((int)((newLevel - prevLevel) * 100.0f)).ToString() + " XP", "+" + ((int)((newLevel - prevLevel) * 100.0f)).ToString() + " XP",
Color.Green, GUI.Style.Green,
textPopupPos, textPopupPos,
Vector2.UnitY * 10.0f); Vector2.UnitY * 10.0f);
} }
@@ -111,7 +111,7 @@ namespace Barotrauma
{ {
GUI.AddMessage( GUI.AddMessage(
"+10 XP", "+10 XP",
Color.Green, GUI.Style.Green,
textPopupPos, textPopupPos,
Vector2.UnitY * 10.0f); Vector2.UnitY * 10.0f);
} }
@@ -121,7 +121,7 @@ namespace Barotrauma
GUI.AddMessage( GUI.AddMessage(
TextManager.GetWithVariables("SkillIncreased", new string[3] { "[name]", "[skillname]", "[newlevel]" }, TextManager.GetWithVariables("SkillIncreased", new string[3] { "[name]", "[skillname]", "[newlevel]" },
new string[3] { Name, TextManager.Get("SkillName." + skillIdentifier), ((int)newLevel).ToString() }, new string[3] { Name, TextManager.Get("SkillName." + skillIdentifier), ((int)newLevel).ToString() },
new bool[3] { false, true, false }), Color.Green); new bool[3] { false, true, false }), GUI.Style.Green);
} }
} }
@@ -160,7 +160,7 @@ namespace Barotrauma
sprite.SourceRect = new Rectangle(location, sprite.SourceRect.Size); sprite.SourceRect = new Rectangle(location, sprite.SourceRect.Size);
} }
public void DrawPortrait(SpriteBatch spriteBatch, Vector2 screenPos, float targetWidth) public void DrawPortrait(SpriteBatch spriteBatch, Vector2 screenPos, float targetWidth, bool flip = false)
{ {
float backgroundScale = 1; float backgroundScale = 1;
if (PortraitBackground != null) if (PortraitBackground != null)
@@ -177,13 +177,13 @@ namespace Barotrauma
{ {
Portrait.SourceRect = new Rectangle(CalculateOffset(Portrait, Head.SheetIndex.Value.ToPoint()), Portrait.SourceRect.Size); Portrait.SourceRect = new Rectangle(CalculateOffset(Portrait, Head.SheetIndex.Value.ToPoint()), Portrait.SourceRect.Size);
} }
Portrait.Draw(spriteBatch, screenPos + offset, scale: scale, spriteEffect: SpriteEffects.FlipHorizontally); Portrait.Draw(spriteBatch, screenPos + offset, scale: scale, spriteEffect: flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None);
if (AttachmentSprites != null) if (AttachmentSprites != null)
{ {
float depthStep = 0.000001f; float depthStep = 0.000001f;
foreach (var attachment in AttachmentSprites) foreach (var attachment in AttachmentSprites)
{ {
DrawAttachmentSprite(spriteBatch, attachment, Portrait, screenPos + offset, scale, depthStep, SpriteEffects.FlipHorizontally); DrawAttachmentSprite(spriteBatch, attachment, Portrait, screenPos + offset, scale, depthStep, flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None);
depthStep += depthStep; depthStep += depthStep;
} }
} }
@@ -213,6 +213,12 @@ namespace Barotrauma
} }
} }
public void DrawJobIcon(SpriteBatch spriteBatch)
{
if (jobIcon == null) return;
jobIcon.Draw(spriteBatch, jobIconPos, Job.Prefab.UIColor, scale: .5f * GUI.Scale);
}
private void DrawAttachmentSprite(SpriteBatch spriteBatch, WearableSprite attachment, Sprite head, Vector2 drawPos, float scale, float depthStep, SpriteEffects spriteEffects = SpriteEffects.None) private void DrawAttachmentSprite(SpriteBatch spriteBatch, WearableSprite attachment, Sprite head, Vector2 drawPos, float scale, float depthStep, SpriteEffects spriteEffects = SpriteEffects.None)
{ {
if (attachment.InheritSourceRect) if (attachment.InheritSourceRect)
@@ -288,6 +288,7 @@ namespace Barotrauma
GameAnalyticsManager.AddErrorEventOnce("CharacterNetworking.ClientRead:NoInventory" + ID, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg); GameAnalyticsManager.AddErrorEventOnce("CharacterNetworking.ClientRead:NoInventory" + ID, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
//read anyway to prevent messing up reading the rest of the message //read anyway to prevent messing up reading the rest of the message
UInt16 lastEventID = msg.ReadUInt16();
byte itemCount = msg.ReadByte(); byte itemCount = msg.ReadByte();
for (int i = 0; i < itemCount; i++) for (int i = 0; i < itemCount; i++)
{ {
@@ -41,7 +41,7 @@ namespace Barotrauma
private Submarine parentSub; private Submarine parentSub;
public HUDProgressBar(Vector2 worldPosition, Submarine parentSubmarine = null) public HUDProgressBar(Vector2 worldPosition, Submarine parentSubmarine = null)
: this(worldPosition, parentSubmarine, Color.Red, Color.Green) : this(worldPosition, parentSubmarine, GUI.Style.Red, GUI.Style.Green)
{ {
} }
@@ -14,20 +14,20 @@ namespace Barotrauma
{ {
if (prevStrength % 10.0f > 0.05f && Strength % 10.0f < 0.05f) if (prevStrength % 10.0f > 0.05f && Strength % 10.0f < 0.05f)
{ {
GUI.AddMessage(TextManager.Get("HuskDormant"), Color.Red); GUI.AddMessage(TextManager.Get("HuskDormant"), GUI.Style.Red);
} }
} }
else if (Strength < Prefab.MaxStrength) else if (Strength < Prefab.MaxStrength)
{ {
if (state == InfectionState.Dormant && Character.Controlled == character) if (state == InfectionState.Dormant && Character.Controlled == character)
{ {
GUI.AddMessage(TextManager.Get("HuskCantSpeak"), Color.Red); GUI.AddMessage(TextManager.Get("HuskCantSpeak"), GUI.Style.Red);
} }
} }
else if (state != InfectionState.Active && Character.Controlled == character) else if (state != InfectionState.Active && Character.Controlled == character)
{ {
GUI.AddMessage(TextManager.GetWithVariable("HuskActivate", "[Attack]", GameMain.Config.KeyBindText(InputType.Attack)), GUI.AddMessage(TextManager.GetWithVariable("HuskActivate", "[Attack]", GameMain.Config.KeyBindText(InputType.Attack)),
Color.Red); GUI.Style.Red);
} }
} }
} }
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,8 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System.Linq; using System.Linq;
using System; using System;
using System.Xml.Linq;
using System.Collections.Generic;
namespace Barotrauma namespace Barotrauma
{ {
@@ -8,7 +10,7 @@ namespace Barotrauma
{ {
public GUIButton CreateInfoFrame(int variant) public GUIButton CreateInfoFrame(int variant)
{ {
int width = 500, height = 400; int width = 500, height = 450;
GUIButton backFrame = new GUIButton(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker"); GUIButton backFrame = new GUIButton(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker");
GUIFrame frame = new GUIFrame(new RectTransform(new Point(width, height), backFrame.RectTransform, Anchor.Center)); GUIFrame frame = new GUIFrame(new RectTransform(new Point(width, height), backFrame.RectTransform, Anchor.Center));
@@ -48,5 +50,75 @@ namespace Barotrauma
return backFrame; return backFrame;
} }
public class OutfitPreview
{
/// <summary>
/// Pair.First = sprite, Pair.Second = draw offset
/// </summary>
public readonly List<Pair<Sprite, Vector2>> Sprites;
public Vector2 Dimensions;
public OutfitPreview()
{
Sprites = new List<Pair<Sprite, Vector2>>();
Dimensions = Vector2.One;
}
public void AddSprite(Sprite sprite, Vector2 drawOffset)
{
Sprites.Add(new Pair<Sprite, Vector2>(sprite, drawOffset));
}
}
public List<OutfitPreview> GetJobOutfitSprites(Gender gender, bool useInventoryIcon, out Vector2 maxDimensions)
{
List<OutfitPreview> outfitPreviews = new List<OutfitPreview>();
maxDimensions = Vector2.One;
var equipIdentifiers = Element.GetChildElements("ItemSet").Elements().Where(e => e.GetAttributeBool("outfit", false)).Select(e => e.GetAttributeString("identifier", ""));
var outfitPrefabs = ItemPrefab.Prefabs.Where(itemPrefab => equipIdentifiers.Contains(itemPrefab.Identifier)).ToList();
if (!outfitPrefabs.Any()) { return null; }
for (int i = 0; i < outfitPrefabs.Count; i++)
{
var outfitPreview = new OutfitPreview();
if (!ItemSets.TryGetValue(i, out var itemSetElement)) { continue; }
var previewElement = itemSetElement.GetChildElement("PreviewSprites");
if (previewElement == null || useInventoryIcon)
{
if (outfitPrefabs[i] is ItemPrefab prefab && prefab.InventoryIcon != null)
{
outfitPreview.AddSprite(prefab.InventoryIcon, Vector2.Zero);
outfitPreview.Dimensions = prefab.InventoryIcon.SourceRect.Size.ToVector2();
maxDimensions.X = MathHelper.Max(maxDimensions.X, outfitPreview.Dimensions.X);
maxDimensions.Y = MathHelper.Max(maxDimensions.Y, outfitPreview.Dimensions.Y);
}
outfitPreviews.Add(outfitPreview);
continue;
}
var children = previewElement.Elements().ToList();
for (int n = 0; n < children.Count; n++)
{
XElement spriteElement = children[n];
string spriteTexture = spriteElement.GetAttributeString("texture", "").Replace("[GENDER]", (gender == Gender.Female) ? "female" : "male");
var sprite = new Sprite(spriteElement, file: spriteTexture);
sprite.size = new Vector2(sprite.SourceRect.Width, sprite.SourceRect.Height);
outfitPreview.AddSprite(sprite, children[n].GetAttributeVector2("offset", Vector2.Zero));
}
outfitPreview.Dimensions = previewElement.GetAttributeVector2("dims", Vector2.One);
maxDimensions.X = MathHelper.Max(maxDimensions.X, outfitPreview.Dimensions.X);
maxDimensions.Y = MathHelper.Max(maxDimensions.Y, outfitPreview.Dimensions.Y);
outfitPreviews.Add(outfitPreview);
}
return outfitPreviews;
}
} }
} }
@@ -81,7 +81,7 @@ namespace Barotrauma
//{ //{
// var pos = ConvertUnits.ToDisplayUnits(mouthPos.Value); // var pos = ConvertUnits.ToDisplayUnits(mouthPos.Value);
// pos.Y = -pos.Y; // pos.Y = -pos.Y;
// ShapeExtensions.DrawPoint(spriteBatch, pos, Color.Red, size: 5); // ShapeExtensions.DrawPoint(spriteBatch, pos, GUI.Style.Red, size: 5);
//} //}
return; return;
// A debug visualisation on the bezier curve between limbs. // A debug visualisation on the bezier curve between limbs.
@@ -98,7 +98,7 @@ namespace Barotrauma
//GUI.DrawLine(spriteBatch, start, end, Color.White); //GUI.DrawLine(spriteBatch, start, end, Color.White);
//GUI.DrawLine(spriteBatch, start, control, Color.Black); //GUI.DrawLine(spriteBatch, start, control, Color.Black);
//GUI.DrawLine(spriteBatch, control, end, Color.Black); //GUI.DrawLine(spriteBatch, control, end, Color.Black);
GUI.DrawBezierWithDots(spriteBatch, start, end, control, 1000, Color.Red); GUI.DrawBezierWithDots(spriteBatch, start, end, control, 1000, GUI.Style.Red);
} }
} }
@@ -433,14 +433,17 @@ namespace Barotrauma
SoundPlayer.PlayDamageSound(damageSoundType, Math.Max(damage, bleedingDamage), WorldPosition); SoundPlayer.PlayDamageSound(damageSoundType, Math.Max(damage, bleedingDamage), WorldPosition);
} }
// Always spawn damage particles // spawn damage particles
float damageParticleAmount = Math.Min(damage / 10, 1.0f) * damageMultiplier; float damageParticleAmount = Math.Min(damage / 10, 1.0f) * damageMultiplier;
foreach (ParticleEmitter emitter in character.DamageEmitters) if (damageParticleAmount > 0.001f)
{ {
if (inWater && emitter.Prefab.ParticlePrefab.DrawTarget == ParticlePrefab.DrawTargetType.Air) continue; foreach (ParticleEmitter emitter in character.DamageEmitters)
if (!inWater && emitter.Prefab.ParticlePrefab.DrawTarget == ParticlePrefab.DrawTargetType.Water) continue; {
if (inWater && emitter.Prefab.ParticlePrefab.DrawTarget == ParticlePrefab.DrawTargetType.Air) continue;
if (!inWater && emitter.Prefab.ParticlePrefab.DrawTarget == ParticlePrefab.DrawTargetType.Water) continue;
emitter.Emit(1.0f, WorldPosition, character.CurrentHull, amountMultiplier: damageParticleAmount); emitter.Emit(1.0f, WorldPosition, character.CurrentHull, amountMultiplier: damageParticleAmount);
}
} }
if (bleedingDamage > 0) if (bleedingDamage > 0)
@@ -631,7 +634,7 @@ namespace Barotrauma
if (pullJoint != null) if (pullJoint != null)
{ {
Vector2 pos = ConvertUnits.ToDisplayUnits(pullJoint.WorldAnchorB); Vector2 pos = ConvertUnits.ToDisplayUnits(pullJoint.WorldAnchorB);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 5, 5), Color.Red, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X, (int)-pos.Y, 5, 5), GUI.Style.Red, true);
} }
var bodyDrawPos = body.DrawPosition; var bodyDrawPos = body.DrawPosition;
bodyDrawPos.Y = -bodyDrawPos.Y; bodyDrawPos.Y = -bodyDrawPos.Y;
@@ -645,11 +648,11 @@ namespace Barotrauma
var front = ConvertUnits.ToDisplayUnits(body.FarseerBody.GetWorldPoint(localFront)); var front = ConvertUnits.ToDisplayUnits(body.FarseerBody.GetWorldPoint(localFront));
front.Y = -front.Y; front.Y = -front.Y;
GUI.DrawLine(spriteBatch, bodyDrawPos, front, Color.Yellow, width: 2); GUI.DrawLine(spriteBatch, bodyDrawPos, front, Color.Yellow, width: 2);
GUI.DrawLine(spriteBatch, from, to, Color.Red, width: 1); GUI.DrawLine(spriteBatch, from, to, GUI.Style.Red, width: 1);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)from.X, (int)from.Y, 12, 12), Color.White, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)from.X, (int)from.Y, 12, 12), Color.White, true);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)to.X, (int)to.Y, 12, 12), Color.White, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)to.X, (int)to.Y, 12, 12), Color.White, true);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)from.X, (int)from.Y, 10, 10), Color.Blue, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)from.X, (int)from.Y, 10, 10), Color.Blue, true);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)to.X, (int)to.Y, 10, 10), Color.Red, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)to.X, (int)to.Y, 10, 10), GUI.Style.Red, true);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)front.X, (int)front.Y, 10, 10), Color.Yellow, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)front.X, (int)front.Y, 10, 10), Color.Yellow, true);
//Vector2 mainLimbFront = ConvertUnits.ToDisplayUnits(ragdoll.MainLimb.body.FarseerBody.GetWorldPoint(ragdoll.MainLimb.body.GetFrontLocal(MathHelper.ToRadians(limbParams.Orientation)))); //Vector2 mainLimbFront = ConvertUnits.ToDisplayUnits(ragdoll.MainLimb.body.FarseerBody.GetWorldPoint(ragdoll.MainLimb.body.GetFrontLocal(MathHelper.ToRadians(limbParams.Orientation))));
@@ -748,8 +751,8 @@ namespace Barotrauma
//{ //{
// width = (int)Math.Round(width / cam.Zoom); // width = (int)Math.Round(width / cam.Zoom);
//} //}
//GUI.DrawLine(spriteBatch, startPos, startPos + Vector2.Normalize(up) * size, Color.Red, width: width); //GUI.DrawLine(spriteBatch, startPos, startPos + Vector2.Normalize(up) * size, GUI.Style.Red, width: width);
Color color = modifier.DamageMultiplier > 1 ? Color.Red : Color.GreenYellow; Color color = modifier.DamageMultiplier > 1 ? GUI.Style.Red : GUI.Style.Green;
float size = ConvertUnits.ToDisplayUnits(body.GetSize().Length() / 2); float size = ConvertUnits.ToDisplayUnits(body.GetSize().Length() / 2);
if (isScreenSpace) if (isScreenSpace)
{ {
@@ -787,12 +787,9 @@ namespace Barotrauma
commands.Add(new Command("save|savesub", "save [submarine name]: Save the currently loaded submarine using the specified name.", (string[] args) => commands.Add(new Command("save|savesub", "save [submarine name]: Save the currently loaded submarine using the specified name.", (string[] args) =>
{ {
if (args.Length < 1) return; if (args.Length < 1) { return; }
if (GameMain.SubEditorScreen.CharacterMode) GameMain.SubEditorScreen.SetMode(SubEditorScreen.Mode.Default);
{
GameMain.SubEditorScreen.SetCharacterMode(false);
}
string fileName = string.Join(" ", args); string fileName = string.Join(" ", args);
if (fileName.Contains("../")) if (fileName.Contains("../"))
@@ -27,14 +27,14 @@ namespace Barotrauma
{ {
GUI.DrawString(spriteBatch, new Vector2(10, y), "EventManager", Color.White, Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(10, y), "EventManager", Color.White, Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 20), "Event cooldown: " + eventCoolDown, Color.White, Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 20), "Event cooldown: " + eventCoolDown, Color.White, Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 35), "Current intensity: " + (int)(currentIntensity * 100), Color.Lerp(Color.White, Color.Red, currentIntensity), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 35), "Current intensity: " + (int)(currentIntensity * 100), Color.Lerp(Color.White, GUI.Style.Red, currentIntensity), Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 50), "Target intensity: " + (int)(targetIntensity * 100), Color.Lerp(Color.White, Color.Red, targetIntensity), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 50), "Target intensity: " + (int)(targetIntensity * 100), Color.Lerp(Color.White, GUI.Style.Red, targetIntensity), Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 65), "AvgHealth: " + (int)(avgCrewHealth * 100), Color.Lerp(Color.Red, Color.Green, avgCrewHealth), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 65), "AvgHealth: " + (int)(avgCrewHealth * 100), Color.Lerp(GUI.Style.Red, GUI.Style.Green, avgCrewHealth), Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 80), "AvgHullIntegrity: " + (int)(avgHullIntegrity * 100), Color.Lerp(Color.Red, Color.Green, avgHullIntegrity), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 80), "AvgHullIntegrity: " + (int)(avgHullIntegrity * 100), Color.Lerp(GUI.Style.Red, GUI.Style.Green, avgHullIntegrity), Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 95), "FloodingAmount: " + (int)(floodingAmount * 100), Color.Lerp(Color.Green, Color.Red, floodingAmount), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 95), "FloodingAmount: " + (int)(floodingAmount * 100), Color.Lerp(GUI.Style.Green, GUI.Style.Red, floodingAmount), Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 110), "FireAmount: " + (int)(fireAmount * 100), Color.Lerp(Color.Green, Color.Red, fireAmount), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 110), "FireAmount: " + (int)(fireAmount * 100), Color.Lerp(GUI.Style.Green, GUI.Style.Red, fireAmount), Color.Black * 0.6f, 0, GUI.SmallFont);
GUI.DrawString(spriteBatch, new Vector2(15, y + 125), "EnemyDanger: " + (int)(enemyDanger * 100), Color.Lerp(Color.Green, Color.Red, enemyDanger), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 125), "EnemyDanger: " + (int)(enemyDanger * 100), Color.Lerp(GUI.Style.Green, GUI.Style.Red, enemyDanger), Color.Black * 0.6f, 0, GUI.SmallFont);
#if DEBUG #if DEBUG
if (PlayerInput.KeyDown(Microsoft.Xna.Framework.Input.Keys.LeftAlt) && if (PlayerInput.KeyDown(Microsoft.Xna.Framework.Input.Keys.LeftAlt) &&
@@ -61,8 +61,8 @@ namespace Barotrauma
Rectangle graphRect = new Rectangle(15, y + 150, 150, 50); Rectangle graphRect = new Rectangle(15, y + 150, 150, 50);
GUI.DrawRectangle(spriteBatch, graphRect, Color.Black * 0.5f, true); GUI.DrawRectangle(spriteBatch, graphRect, Color.Black * 0.5f, true);
intensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, Color.Red, currentIntensity)); intensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, GUI.Style.Red, currentIntensity));
targetIntensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, Color.Red, targetIntensity) * 0.5f); targetIntensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, GUI.Style.Red, targetIntensity) * 0.5f);
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
new Vector2(graphRect.Right, graphRect.Y + graphRect.Height * (1.0f - eventThreshold)), new Vector2(graphRect.Right, graphRect.Y + graphRect.Height * (1.0f - eventThreshold)),
@@ -30,8 +30,7 @@ namespace Barotrauma
_toggleOpen = GameMain.Config.ChatOpen = value; _toggleOpen = GameMain.Config.ChatOpen = value;
foreach (GUIComponent child in ToggleButton.Children) foreach (GUIComponent child in ToggleButton.Children)
{ {
child.SpriteEffects = _toggleOpen == (HUDLayoutSettings.ChatBoxAlignment == Alignment.Right) ? child.SpriteEffects = _toggleOpen ? SpriteEffects.FlipHorizontally : SpriteEffects.None;
SpriteEffects.FlipHorizontally : SpriteEffects.None;
} }
} }
} }
@@ -58,6 +57,11 @@ namespace Barotrauma
private GUIButton showNewMessagesButton; private GUIButton showNewMessagesButton;
private GUIFrame hideableElements;
public const int ToggleButtonWidthRaw = 30;
private int popupMessageOffset;
public ChatBox(GUIComponent parent, bool isSinglePlayer) public ChatBox(GUIComponent parent, bool isSinglePlayer)
{ {
this.IsSinglePlayer = isSinglePlayer; this.IsSinglePlayer = isSinglePlayer;
@@ -69,9 +73,12 @@ namespace Barotrauma
screenResolution = new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight); screenResolution = new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight);
int toggleButtonWidth = (int)(30 * GUI.Scale); int toggleButtonWidth = (int)(ToggleButtonWidthRaw * GUI.Scale);
GUIFrame = new GUIFrame(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ChatBoxArea, parent.RectTransform), style: null); GUIFrame = new GUIFrame(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ChatBoxArea, parent.RectTransform), style: null);
var chatBoxHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.875f), GUIFrame.RectTransform), style: "ChatBox");
hideableElements = new GUIFrame(new RectTransform(Vector2.One, GUIFrame.RectTransform), style: null);
var chatBoxHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.875f), hideableElements.RectTransform), style: "ChatBox");
chatBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.95f), chatBoxHolder.RectTransform, Anchor.CenterRight), style: null); chatBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.95f), chatBoxHolder.RectTransform, Anchor.CenterRight), style: null);
ToggleButton = new GUIButton(new RectTransform(new Point(toggleButtonWidth, HUDLayoutSettings.ChatBoxArea.Height), parent.RectTransform), ToggleButton = new GUIButton(new RectTransform(new Point(toggleButtonWidth, HUDLayoutSettings.ChatBoxArea.Height), parent.RectTransform),
@@ -83,7 +90,7 @@ namespace Barotrauma
return true; return true;
}; };
InputBox = new GUITextBox(new RectTransform(new Vector2(0.925f, 0.125f), GUIFrame.RectTransform, Anchor.BottomLeft), InputBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.125f), hideableElements.RectTransform, Anchor.BottomLeft),
style: "ChatTextBox") style: "ChatTextBox")
{ {
Font = GUI.SmallFont, Font = GUI.SmallFont,
@@ -98,12 +105,14 @@ namespace Barotrauma
//gui.Text = ""; //gui.Text = "";
}; };
var chatSendButton = new GUIButton(new RectTransform(new Vector2(0.075f, 0.125f), GUIFrame.RectTransform, Anchor.BottomRight) { RelativeOffset = new Vector2(0.0f, -0.01f) }, ">"); var chatSendButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.7f), InputBox.RectTransform, Anchor.CenterRight, scaleBasis: ScaleBasis.BothHeight), style: "GUIButtonToggleRight");
chatSendButton.OnClicked += (GUIButton btn, object userdata) => chatSendButton.OnClicked += (GUIButton btn, object userdata) =>
{ {
InputBox.OnEnterPressed(InputBox, InputBox.Text); InputBox.OnEnterPressed(InputBox, InputBox.Text);
return true; return true;
}; };
chatSendButton.RectTransform.AbsoluteOffset = new Point((int)(InputBox.Rect.Height * 0.15f), 0);
InputBox.TextBlock.RectTransform.MaxSize = new Point((int)(InputBox.Rect.Width - chatSendButton.Rect.Width * 1.25f), int.MaxValue);
showNewMessagesButton = new GUIButton(new RectTransform(new Vector2(1f, 0.125f), GUIFrame.RectTransform, Anchor.BottomCenter) { RelativeOffset = new Vector2(0.0f, -0.125f) }, TextManager.Get("chat.shownewmessages")); showNewMessagesButton = new GUIButton(new RectTransform(new Vector2(1f, 0.125f), GUIFrame.RectTransform, Anchor.BottomCenter) { RelativeOffset = new Vector2(0.0f, -0.125f) }, TextManager.Get("chat.shownewmessages"));
showNewMessagesButton.OnClicked += (GUIButton btn, object userdata) => showNewMessagesButton.OnClicked += (GUIButton btn, object userdata) =>
@@ -278,6 +287,11 @@ namespace Barotrauma
GUI.PlayUISound(soundType); GUI.PlayUISound(soundType);
} }
public void SetVisibility(bool visible)
{
GUIFrame.Parent.Visible = visible;
}
private IEnumerable<object> UpdateMessageAnimation(GUIComponent message, float animDuration) private IEnumerable<object> UpdateMessageAnimation(GUIComponent message, float animDuration)
{ {
float timer = 0.0f; float timer = 0.0f;
@@ -301,18 +315,14 @@ namespace Barotrauma
HUDLayoutSettings.ChatBoxArea.Y / (float)GameMain.GraphicsHeight); HUDLayoutSettings.ChatBoxArea.Y / (float)GameMain.GraphicsHeight);
GUIFrame.RectTransform.NonScaledSize = HUDLayoutSettings.ChatBoxArea.Size; GUIFrame.RectTransform.NonScaledSize = HUDLayoutSettings.ChatBoxArea.Size;
int toggleButtonWidth = (int)(30 * GUI.Scale); int toggleButtonWidth = (int)(ToggleButtonWidthRaw * GUI.Scale);
//make room for the toggle button
if (HUDLayoutSettings.ChatBoxAlignment == Alignment.Left)
{
GUIFrame.RectTransform.AbsoluteOffset += new Point(toggleButtonWidth, 0);
}
GUIFrame.RectTransform.NonScaledSize -= new Point(toggleButtonWidth, 0); GUIFrame.RectTransform.NonScaledSize -= new Point(toggleButtonWidth, 0);
GUIFrame.RectTransform.AbsoluteOffset += new Point(toggleButtonWidth, 0);
ToggleButton.RectTransform.NonScaledSize = new Point(toggleButtonWidth, HUDLayoutSettings.ChatBoxArea.Height); ToggleButton.RectTransform.NonScaledSize = new Point(toggleButtonWidth, HUDLayoutSettings.ChatBoxArea.Height);
ToggleButton.RectTransform.AbsoluteOffset = HUDLayoutSettings.ChatBoxAlignment == Alignment.Left ? ToggleButton.RectTransform.AbsoluteOffset = new Point(HUDLayoutSettings.ChatBoxArea.Left - toggleButtonWidth, HUDLayoutSettings.ChatBoxArea.Y);
new Point(HUDLayoutSettings.ChatBoxArea.X, HUDLayoutSettings.ChatBoxArea.Y) :
new Point(HUDLayoutSettings.ChatBoxArea.Right - toggleButtonWidth, HUDLayoutSettings.ChatBoxArea.Y); popupMessageOffset = ToggleButton.Rect.Width + GameMain.GameSession.CrewManager.ReportButtonFrame.Rect.Width + GUIFrame.Rect.Width;
} }
public void Update(float deltaTime) public void Update(float deltaTime)
@@ -347,7 +357,6 @@ namespace Barotrauma
var popupMsg = popupMessages.Count > 0 ? popupMessages.Peek() : null; var popupMsg = popupMessages.Count > 0 ? popupMessages.Peek() : null;
if (popupMsg != null) if (popupMsg != null)
{ {
int offset = -popupMsg.Rect.Width - ToggleButton.Rect.Width * 2 - (int)(50 * GUI.Scale) - (GUIFrame.Rect.X - GameMain.GraphicsWidth);
popupMsg.Visible = true; popupMsg.Visible = true;
//popup messages appear and disappear faster when there's more pending messages //popup messages appear and disappear faster when there's more pending messages
popupMessageTimer += deltaTime * popupMessages.Count * popupMessages.Count; popupMessageTimer += deltaTime * popupMessages.Count * popupMessages.Count;
@@ -355,7 +364,7 @@ namespace Barotrauma
{ {
//move the message out of the screen and delete it //move the message out of the screen and delete it
popupMsg.RectTransform.ScreenSpaceOffset = popupMsg.RectTransform.ScreenSpaceOffset =
new Point((int)MathHelper.SmoothStep(offset, 10, (popupMessageTimer - PopupMessageDuration) * 5.0f), 0); new Point((int)MathHelper.SmoothStep(popupMessageOffset, 10, (popupMessageTimer - PopupMessageDuration) * 5.0f), 0);
if (popupMessageTimer > PopupMessageDuration + 1.0f) if (popupMessageTimer > PopupMessageDuration + 1.0f)
{ {
popupMessageTimer = 0.0f; popupMessageTimer = 0.0f;
@@ -366,15 +375,16 @@ namespace Barotrauma
else else
{ {
//move the message on the screen //move the message on the screen
popupMsg.RectTransform.ScreenSpaceOffset = new Point( popupMsg.RectTransform.ScreenSpaceOffset = new Point(
(int)MathHelper.SmoothStep(0, offset, popupMessageTimer * 5.0f), 0); (int)MathHelper.SmoothStep(0, popupMessageOffset, popupMessageTimer * 5.0f), 0);
} }
} }
} }
openState = MathHelper.Clamp(openState, 0.0f, 1.0f); openState = MathHelper.Clamp(openState, 0.0f, 1.0f);
int hiddenBoxOffset = GUIFrame.Rect.Width + ToggleButton.Rect.Width; int hiddenBoxOffset = -(GUIFrame.Rect.Width);
GUIFrame.RectTransform.AbsoluteOffset = GUIFrame.RectTransform.AbsoluteOffset =
new Point((int)MathHelper.SmoothStep(hiddenBoxOffset * (HUDLayoutSettings.ChatBoxAlignment == Alignment.Left ? -1 : 1), 0, openState), 0); new Point((int)MathHelper.SmoothStep(hiddenBoxOffset, 0, openState), 0);
hideableElements.Visible = openState > 0.0f;
} }
} }
} }
@@ -5,28 +5,66 @@ using System.Xml.Linq;
namespace Barotrauma namespace Barotrauma
{ {
public enum TransitionMode
{
Linear,
Smooth,
Smoother,
EaseIn,
EaseOut,
Exponential
}
public enum SpriteFallBackState
{
None,
Hover,
Pressed,
Selected,
HoverSelected,
Toggle
}
public class GUIComponentStyle public class GUIComponentStyle
{ {
public readonly Vector4 Padding; public readonly Vector4 Padding;
public readonly Color Color; public readonly Color Color;
public readonly Color textColor;
public readonly Color HoverColor; public readonly Color HoverColor;
public readonly Color SelectedColor; public readonly Color SelectedColor;
public readonly Color PressedColor; public readonly Color PressedColor;
public readonly Color DisabledColor;
public readonly Color TextColor;
public readonly Color HoverTextColor;
public readonly Color SelectedTextColor;
public readonly Color DisabledTextColor;
public readonly float SpriteCrossFadeTime;
public readonly float ColorCrossFadeTime;
public readonly TransitionMode TransitionMode;
public readonly string Font;
public readonly bool ForceUpperCase;
public readonly Color OutlineColor; public readonly Color OutlineColor;
public readonly XElement Element; public readonly XElement Element;
public readonly Dictionary<GUIComponent.ComponentState, List<UISprite>> Sprites; public readonly Dictionary<GUIComponent.ComponentState, List<UISprite>> Sprites;
public SpriteFallBackState FallBackState;
public Dictionary<string, GUIComponentStyle> ChildStyles; public Dictionary<string, GUIComponentStyle> ChildStyles;
public GUIComponentStyle(XElement element) public readonly GUIStyle Style;
public int? Width { get; private set; }
public int? Height { get; private set; }
public GUIComponentStyle(XElement element, GUIStyle style)
{ {
Style = style;
Element = element; Element = element;
Sprites = new Dictionary<GUIComponent.ComponentState, List<UISprite>>(); Sprites = new Dictionary<GUIComponent.ComponentState, List<UISprite>>();
@@ -38,14 +76,33 @@ namespace Barotrauma
ChildStyles = new Dictionary<string, GUIComponentStyle>(); ChildStyles = new Dictionary<string, GUIComponentStyle>();
Padding = element.GetAttributeVector4("padding", Vector4.Zero); Padding = element.GetAttributeVector4("padding", Vector4.Zero);
Color = element.GetAttributeColor("color", Color.Transparent); Color = element.GetAttributeColor("color", Color.Transparent);
textColor = element.GetAttributeColor("textcolor", Color.Black);
HoverColor = element.GetAttributeColor("hovercolor", Color); HoverColor = element.GetAttributeColor("hovercolor", Color);
SelectedColor = element.GetAttributeColor("selectedcolor", Color); SelectedColor = element.GetAttributeColor("selectedcolor", Color);
DisabledColor = element.GetAttributeColor("disabledcolor", Color);
PressedColor = element.GetAttributeColor("pressedcolor", Color); PressedColor = element.GetAttributeColor("pressedcolor", Color);
OutlineColor = element.GetAttributeColor("outlinecolor", Color.Transparent); OutlineColor = element.GetAttributeColor("outlinecolor", Color.Transparent);
TextColor = element.GetAttributeColor("textcolor", Color.Black);
HoverTextColor = element.GetAttributeColor("hovertextcolor", TextColor);
DisabledTextColor = element.GetAttributeColor("disabledtextcolor", TextColor);
SelectedTextColor = element.GetAttributeColor("selectedtextcolor", TextColor);
SpriteCrossFadeTime = element.GetAttributeFloat("spritefadetime", SpriteCrossFadeTime);
ColorCrossFadeTime = element.GetAttributeFloat("colorfadetime", ColorCrossFadeTime);
if (Enum.TryParse(element.GetAttributeString("colortransition", string.Empty), ignoreCase: true, out TransitionMode transition))
{
TransitionMode = transition;
}
if (Enum.TryParse(element.GetAttributeString("fallbackstate", GUIComponent.ComponentState.None.ToString()), ignoreCase: true, out SpriteFallBackState s))
{
FallBackState = s;
}
Font = element.GetAttributeString("font", "");
ForceUpperCase = element.GetAttributeBool("forceuppercase", false);
foreach (XElement subElement in element.Elements()) foreach (XElement subElement in element.Elements())
{ {
switch (subElement.Name.ToString().ToLowerInvariant()) switch (subElement.Name.ToString().ToLowerInvariant())
@@ -59,6 +116,11 @@ namespace Barotrauma
string stateStr = subElement.GetAttributeString("state", "None"); string stateStr = subElement.GetAttributeString("state", "None");
Enum.TryParse(stateStr, out spriteState); Enum.TryParse(stateStr, out spriteState);
Sprites[spriteState].Add(newSprite); Sprites[spriteState].Add(newSprite);
//use the same sprite for Hover and HoverSelected if latter is not specified
if (spriteState == GUIComponent.ComponentState.HoverSelected && !Sprites.ContainsKey(GUIComponent.ComponentState.HoverSelected))
{
Sprites[GUIComponent.ComponentState.HoverSelected].Add(newSprite);
}
} }
else else
{ {
@@ -68,11 +130,34 @@ namespace Barotrauma
} }
} }
break; break;
case "size":
break;
default: default:
ChildStyles.Add(subElement.Name.ToString().ToLowerInvariant(), new GUIComponentStyle(subElement)); ChildStyles.Add(subElement.Name.ToString().ToLowerInvariant(), new GUIComponentStyle(subElement, style));
break; break;
} }
} }
GetSize(element);
}
public void GetSize(XElement element)
{
Point size = new Point(0, 0);
foreach (XElement subElement in element.Elements())
{
if (subElement.Name.ToString().ToLowerInvariant() != "size") { continue; }
Point maxResolution = subElement.GetAttributePoint("maxresolution", new Point(int.MaxValue, int.MaxValue));
if (GameMain.GraphicsWidth <= maxResolution.X && GameMain.GraphicsHeight <= maxResolution.Y)
{
size = new Point(
subElement.GetAttributeInt("width", 0),
subElement.GetAttributeInt("height", 0));
break;
}
}
if (size.X > 0) { Width = size.X; }
if (size.Y > 0) { Height = size.Y; }
} }
} }
} }
@@ -32,13 +32,11 @@ namespace Barotrauma
private static GUIFrame window; private static GUIFrame window;
private static GUIListBox sidebar; private static GUIListBox sidebar;
private static GUIListBox fileList; private static GUIListBox fileList;
private static GUIButton moveToParentButton;
private static GUITextBox directoryBox; private static GUITextBox directoryBox;
private static GUITextBox filterBox; private static GUITextBox filterBox;
private static GUITextBox fileBox; private static GUITextBox fileBox;
private static GUIDropDown fileTypeDropdown; private static GUIDropDown fileTypeDropdown;
private static GUIButton openButton; private static GUIButton openButton;
private static GUIButton cancelButton;
private static FileSystemWatcher fileSystemWatcher; private static FileSystemWatcher fileSystemWatcher;
@@ -46,7 +44,7 @@ namespace Barotrauma
private static readonly string[] ignoredDrivePrefixes = new string[] private static readonly string[] ignoredDrivePrefixes = new string[]
{ {
"/sys/","/snap/" "/sys/", "/snap/"
}; };
private static string currentDirectory; private static string currentDirectory;
@@ -62,14 +60,14 @@ namespace Barotrauma
List<string> dirs = new List<string>(); List<string> dirs = new List<string>();
for (int i = 0; i < dirSplit.Length; i++) for (int i = 0; i < dirSplit.Length; i++)
{ {
if (dirSplit[i].Trim()=="..") if (dirSplit[i].Trim() == "..")
{ {
if (dirs.Count > 1) if (dirs.Count > 1)
{ {
dirs.RemoveAt(dirs.Count - 1); dirs.RemoveAt(dirs.Count - 1);
} }
} }
else if (dirSplit[i].Trim()!=".") else if (dirSplit[i].Trim() != ".")
{ {
dirs.Add(dirSplit[i]); dirs.Add(dirSplit[i]);
} }
@@ -80,9 +78,11 @@ namespace Barotrauma
currentDirectory += "/"; currentDirectory += "/";
} }
fileSystemWatcher?.Dispose(); fileSystemWatcher?.Dispose();
fileSystemWatcher = new FileSystemWatcher(currentDirectory); fileSystemWatcher = new FileSystemWatcher(currentDirectory)
fileSystemWatcher.Filter = "*"; {
fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; Filter = "*",
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName
};
fileSystemWatcher.Created += OnFileSystemChanges; fileSystemWatcher.Created += OnFileSystemChanges;
fileSystemWatcher.Deleted += OnFileSystemChanges; fileSystemWatcher.Deleted += OnFileSystemChanges;
fileSystemWatcher.Renamed += OnFileSystemChanges; fileSystemWatcher.Renamed += OnFileSystemChanges;
@@ -103,8 +103,10 @@ namespace Barotrauma
{ {
case WatcherChangeTypes.Created: case WatcherChangeTypes.Created:
{ {
var itemFrame = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), fileList.Content.RectTransform), e.Name); var itemFrame = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), fileList.Content.RectTransform), e.Name)
itemFrame.UserData = (bool?)Directory.Exists(e.FullPath); {
UserData = (bool?)Directory.Exists(e.FullPath)
};
if ((itemFrame.UserData as bool?) ?? false) if ((itemFrame.UserData as bool?) ?? false)
{ {
itemFrame.Text += "/"; itemFrame.Text += "/";
@@ -164,7 +166,7 @@ namespace Barotrauma
window = new GUIFrame(new RectTransform(Vector2.One * 0.8f, backgroundFrame.RectTransform, Anchor.Center)); window = new GUIFrame(new RectTransform(Vector2.One * 0.8f, backgroundFrame.RectTransform, Anchor.Center));
var horizontalLayout = new GUILayoutGroup(new RectTransform(Vector2.One*0.9f, window.RectTransform, Anchor.Center), true); var horizontalLayout = new GUILayoutGroup(new RectTransform(Vector2.One * 0.9f, window.RectTransform, Anchor.Center), true);
sidebar = new GUIListBox(new RectTransform(new Vector2(0.29f, 1.0f), horizontalLayout.RectTransform)); sidebar = new GUIListBox(new RectTransform(new Vector2(0.29f, 1.0f), horizontalLayout.RectTransform));
var drives = DriveInfo.GetDrives(); var drives = DriveInfo.GetDrives();
@@ -186,8 +188,8 @@ namespace Barotrauma
new GUIFrame(new RectTransform(new Vector2(0.01f, 1.0f), horizontalLayout.RectTransform), style: null); new GUIFrame(new RectTransform(new Vector2(0.01f, 1.0f), horizontalLayout.RectTransform), style: null);
var fileListLayout = new GUILayoutGroup(new RectTransform(new Vector2(0.7f, 1.0f), horizontalLayout.RectTransform)); var fileListLayout = new GUILayoutGroup(new RectTransform(new Vector2(0.7f, 1.0f), horizontalLayout.RectTransform));
var firstRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), fileListLayout.RectTransform), true); var firstRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), fileListLayout.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft);
moveToParentButton = new GUIButton(new RectTransform(new Vector2(0.05f, 1.0f), firstRow.RectTransform), "^") new GUIButton(new RectTransform(new Vector2(0.05f, 1.0f), firstRow.RectTransform), "^")
{ {
OnClicked = MoveToParentDirectory OnClicked = MoveToParentDirectory
}; };
@@ -212,6 +214,8 @@ namespace Barotrauma
{ {
OverflowClip = true OverflowClip = true
}; };
firstRow.RectTransform.MinSize = new Point(0, firstRow.RectTransform.Children.Max(c => c.MinSize.Y));
filterBox.OnTextChanged += (txtbox, txt) => filterBox.OnTextChanged += (txtbox, txt) =>
{ {
RefreshFileList(); RefreshFileList();
@@ -220,50 +224,54 @@ namespace Barotrauma
//spacing between rows //spacing between rows
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), fileListLayout.RectTransform), style: null); new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), fileListLayout.RectTransform), style: null);
fileList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.85f), fileListLayout.RectTransform)); fileList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.85f), fileListLayout.RectTransform))
fileList.OnSelected = (child, userdata) =>
{ {
if (userdata == null) { return false; } OnSelected = (child, userdata) =>
fileBox.Text = (child as GUITextBlock).Text;
if (PlayerInput.DoubleClicked())
{ {
bool isDir = (userdata as bool?).Value; if (userdata == null) { return false; }
if (isDir)
{
CurrentDirectory += (child as GUITextBlock).Text;
}
else
{
OnFileSelected?.Invoke(CurrentDirectory + (child as GUITextBlock).Text);
Open = false;
}
}
return true; var fileName = (child as GUITextBlock).Text;
fileBox.Text = fileName;
if (PlayerInput.DoubleClicked())
{
bool isDir = (userdata as bool?).Value;
if (isDir)
{
CurrentDirectory += fileName;
}
else
{
OnFileSelected?.Invoke(CurrentDirectory + fileName);
Open = false;
}
}
return true;
}
}; };
//spacing between rows //spacing between rows
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), fileListLayout.RectTransform), style: null); new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), fileListLayout.RectTransform), style: null);
var thirdRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), fileListLayout.RectTransform), true); var thirdRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), fileListLayout.RectTransform), true);
fileBox = new GUITextBox(new RectTransform(new Vector2(0.7f, 1.0f), thirdRow.RectTransform)); fileBox = new GUITextBox(new RectTransform(new Vector2(0.7f, 1.0f), thirdRow.RectTransform))
fileBox.OnEnterPressed = (tb, txt) => openButton?.OnClicked?.Invoke(openButton, null) ?? false;
fileTypeDropdown = new GUIDropDown(new RectTransform(new Vector2(0.3f, 1.0f), thirdRow.RectTransform), dropAbove: true);
fileTypeDropdown.OnSelected = (child, userdata) =>
{ {
currentFileTypePattern = (child as GUITextBlock).UserData as string; OnEnterPressed = (tb, txt) => openButton?.OnClicked?.Invoke(openButton, null) ?? false
RefreshFileList(); };
return true; fileTypeDropdown = new GUIDropDown(new RectTransform(new Vector2(0.3f, 1.0f), thirdRow.RectTransform), dropAbove: true)
{
OnSelected = (child, userdata) =>
{
currentFileTypePattern = (child as GUITextBlock).UserData as string;
RefreshFileList();
return true;
}
}; };
fileTypeDropdown.Select(4); fileTypeDropdown.Select(4);
//spacing between rows //spacing between rows
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), fileListLayout.RectTransform), style: null); new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), fileListLayout.RectTransform), style: null);
var fourthRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), fileListLayout.RectTransform), true); var fourthRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), fileListLayout.RectTransform), true);
@@ -271,7 +279,7 @@ namespace Barotrauma
//padding for open/cancel buttons //padding for open/cancel buttons
new GUIFrame(new RectTransform(new Vector2(0.7f, 1.0f), fourthRow.RectTransform), style: null); new GUIFrame(new RectTransform(new Vector2(0.7f, 1.0f), fourthRow.RectTransform), style: null);
openButton = new GUIButton(new RectTransform(new Vector2(0.15f, 1.0f), fourthRow.RectTransform), "Open") openButton = new GUIButton(new RectTransform(new Vector2(0.15f, 1.0f), fourthRow.RectTransform), TextManager.Get("opensubbutton"))
{ {
OnClicked = (btn, obj) => OnClicked = (btn, obj) =>
{ {
@@ -279,13 +287,13 @@ namespace Barotrauma
{ {
CurrentDirectory += fileBox.Text; CurrentDirectory += fileBox.Text;
} }
if (!File.Exists(CurrentDirectory+fileBox.Text)) { return false; } if (!File.Exists(CurrentDirectory + fileBox.Text)) { return false; }
OnFileSelected?.Invoke(CurrentDirectory + fileBox.Text); OnFileSelected?.Invoke(CurrentDirectory + fileBox.Text);
Open = false; Open = false;
return false; return false;
} }
}; };
cancelButton = new GUIButton(new RectTransform(new Vector2(0.15f, 1.0f), fourthRow.RectTransform), "Cancel") new GUIButton(new RectTransform(new Vector2(0.15f, 1.0f), fourthRow.RectTransform), TextManager.Get("cancel"))
{ {
OnClicked = (btn, obj) => OnClicked = (btn, obj) =>
{ {
@@ -306,7 +314,7 @@ namespace Barotrauma
public static void AddFileTypeFilter(string name, string pattern) public static void AddFileTypeFilter(string name, string pattern)
{ {
if (backgroundFrame == null) { Init(); } if (backgroundFrame == null) { Init(); }
fileTypeDropdown.AddItem(name + " ("+pattern+")", pattern); fileTypeDropdown.AddItem(name + " (" + pattern + ")", pattern);
} }
public static void SelectFileTypeFilter(string pattern) public static void SelectFileTypeFilter(string pattern)
@@ -322,21 +330,28 @@ namespace Barotrauma
try try
{ {
var directories = Directory.EnumerateDirectories(currentDirectory, "*"+filterBox.Text+"*"); var directories = Directory.EnumerateDirectories(currentDirectory, "*" + filterBox.Text + "*");
foreach (var directory in directories) foreach (var directory in directories)
{ {
string txt = directory; string txt = directory;
if (txt.StartsWith(currentDirectory)) { txt = txt.Substring(currentDirectory.Length); } if (txt.StartsWith(currentDirectory)) { txt = txt.Substring(currentDirectory.Length); }
if (!txt.EndsWith("/")) { txt += "/"; } if (!txt.EndsWith("/")) { txt += "/"; }
var itemFrame = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), fileList.Content.RectTransform), txt); var itemFrame = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), fileList.Content.RectTransform), txt)
itemFrame.UserData = (bool?)true; {
UserData = (bool?)true
};
var folderIcon = new GUIImage(new RectTransform(new Point((int)(itemFrame.Rect.Height * 0.8f)), itemFrame.RectTransform, Anchor.CenterLeft)
{
AbsoluteOffset = new Point((int)(itemFrame.Rect.Height * 0.25f), 0)
}, style: "OpenButton", scaleToFit: true);
itemFrame.Padding = new Vector4(folderIcon.Rect.Width * 1.5f, itemFrame.Padding.Y, itemFrame.Padding.Z, itemFrame.Padding.W);
} }
IEnumerable<string> files = null; IEnumerable<string> files = null;
foreach (string pattern in currentFileTypePattern.Split(',')) foreach (string pattern in currentFileTypePattern.Split(','))
{ {
string patternTrimmed = pattern.Trim(); string patternTrimmed = pattern.Trim();
patternTrimmed = "*"+filterBox.Text+"*"+patternTrimmed; patternTrimmed = "*" + filterBox.Text + "*" + patternTrimmed;
if (files == null) if (files == null)
{ {
files = Directory.EnumerateFiles(currentDirectory, patternTrimmed); files = Directory.EnumerateFiles(currentDirectory, patternTrimmed);
@@ -351,8 +366,10 @@ namespace Barotrauma
{ {
string txt = file; string txt = file;
if (txt.StartsWith(currentDirectory)) { txt = txt.Substring(currentDirectory.Length); } if (txt.StartsWith(currentDirectory)) { txt = txt.Substring(currentDirectory.Length); }
var itemFrame = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), fileList.Content.RectTransform), txt); var itemFrame = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), fileList.Content.RectTransform), txt)
itemFrame.UserData = (bool?)false; {
UserData = (bool?)false
};
} }
} }
catch (Exception e) catch (Exception e)
@@ -124,12 +124,13 @@ namespace Barotrauma
public static ScalableFont UnscaledSmallFont => Style?.UnscaledSmallFont; public static ScalableFont UnscaledSmallFont => Style?.UnscaledSmallFont;
public static ScalableFont SmallFont => Style?.SmallFont; public static ScalableFont SmallFont => Style?.SmallFont;
public static ScalableFont LargeFont => Style?.LargeFont; public static ScalableFont LargeFont => Style?.LargeFont;
public static ScalableFont VideoTitleFont => Style?.VideoTitleFont; public static ScalableFont SubHeadingFont => Style?.SubHeadingFont;
public static ScalableFont ObjectiveTitleFont => Style?.ObjectiveTitleFont; public static ScalableFont DigitalFont => Style?.DigitalFont;
public static ScalableFont ObjectiveNameFont => Style?.ObjectiveNameFont;
public static ScalableFont CJKFont { get; private set; } public static ScalableFont CJKFont { get; private set; }
public static UISprite UIGlow => Style.UIGlow; public static UISprite UIGlow => Style.UIGlow;
public static UISprite UIGlowCircular => Style.UIGlowCircular;
public static Sprite SubmarineIcon public static Sprite SubmarineIcon
{ {
@@ -169,6 +170,8 @@ namespace Barotrauma
get { return timerIcon; } get { return timerIcon; }
} }
public static Sprite InfoAreaBackground;
public static bool SettingsMenuOpen public static bool SettingsMenuOpen
{ {
get { return settingsMenuOpen; } get { return settingsMenuOpen; }
@@ -267,6 +270,7 @@ namespace Barotrauma
lockIcon = new Sprite("Content/UI/UI_Atlas.png", new Rectangle(996, 677, 21, 25), new Vector2(0.5f, 0.5f)); lockIcon = new Sprite("Content/UI/UI_Atlas.png", new Rectangle(996, 677, 21, 25), new Vector2(0.5f, 0.5f));
checkmarkIcon = new Sprite("Content/UI/UI_Atlas.png", new Rectangle(932, 398, 33, 28), new Vector2(0.5f, 0.5f)); checkmarkIcon = new Sprite("Content/UI/UI_Atlas.png", new Rectangle(932, 398, 33, 28), new Vector2(0.5f, 0.5f));
timerIcon = new Sprite("Content/UI/UI_Atlas.png", new Rectangle(997, 653, 18, 21), new Vector2(0.5f, 0.5f)); timerIcon = new Sprite("Content/UI/UI_Atlas.png", new Rectangle(997, 653, 18, 21), new Vector2(0.5f, 0.5f));
InfoAreaBackground = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(290, 320, 400, 300), new Vector2(0.0f, 0.0f));
} }
/// <summary> /// <summary>
@@ -329,9 +333,9 @@ namespace Barotrauma
DrawString(spriteBatch, new Vector2(300, y), DrawString(spriteBatch, new Vector2(300, y),
"Draw - Avg: " + GameMain.PerformanceCounter.DrawTimeGraph.Average().ToString("0.00") + " ms" + "Draw - Avg: " + GameMain.PerformanceCounter.DrawTimeGraph.Average().ToString("0.00") + " ms" +
" Max: " + GameMain.PerformanceCounter.DrawTimeGraph.LargestValue().ToString("0.00") + " ms", " Max: " + GameMain.PerformanceCounter.DrawTimeGraph.LargestValue().ToString("0.00") + " ms",
Color.Green, Color.Black * 0.8f, font: SmallFont); GUI.Style.Green, Color.Black * 0.8f, font: SmallFont);
y += 15; y += 15;
GameMain.PerformanceCounter.DrawTimeGraph.Draw(spriteBatch, new Rectangle(300, y, 170, 50), null, 0, Color.Green); GameMain.PerformanceCounter.DrawTimeGraph.Draw(spriteBatch, new Rectangle(300, y, 170, 50), null, 0, GUI.Style.Green);
y += 50; y += 50;
DrawString(spriteBatch, new Vector2(300, y), DrawString(spriteBatch, new Vector2(300, y),
@@ -340,26 +344,26 @@ namespace Barotrauma
Color.LightBlue, Color.Black * 0.8f, font: SmallFont); Color.LightBlue, Color.Black * 0.8f, font: SmallFont);
y += 15; y += 15;
GameMain.PerformanceCounter.UpdateTimeGraph.Draw(spriteBatch, new Rectangle(300, y, 170, 50), null, 0, Color.LightBlue); GameMain.PerformanceCounter.UpdateTimeGraph.Draw(spriteBatch, new Rectangle(300, y, 170, 50), null, 0, Color.LightBlue);
GameMain.PerformanceCounter.UpdateIterationsGraph.Draw(spriteBatch, new Rectangle(300, y, 170, 50), 20, 0, Color.Red); GameMain.PerformanceCounter.UpdateIterationsGraph.Draw(spriteBatch, new Rectangle(300, y, 170, 50), 20, 0, GUI.Style.Red);
y += 50; y += 50;
foreach (string key in GameMain.PerformanceCounter.GetSavedIdentifiers) foreach (string key in GameMain.PerformanceCounter.GetSavedIdentifiers)
{ {
float elapsedMillisecs = GameMain.PerformanceCounter.GetAverageElapsedMillisecs(key); float elapsedMillisecs = GameMain.PerformanceCounter.GetAverageElapsedMillisecs(key);
DrawString(spriteBatch, new Vector2(300, y), DrawString(spriteBatch, new Vector2(300, y),
key + ": " + elapsedMillisecs.ToString("0.00"), key + ": " + elapsedMillisecs.ToString("0.00"),
Color.Lerp(Color.LightGreen, Color.Red, elapsedMillisecs / 10.0f), Color.Black * 0.5f, 0, SmallFont); Color.Lerp(Color.LightGreen, GUI.Style.Red, elapsedMillisecs / 10.0f), Color.Black * 0.5f, 0, SmallFont);
y += 15; y += 15;
} }
if (Settings.EnableDiagnostics) if (Settings.EnableDiagnostics)
{ {
DrawString(spriteBatch, new Vector2(320, y), "ContinuousPhysicsTime: " + GameMain.World.ContinuousPhysicsTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, Color.Red, (float)GameMain.World.ContinuousPhysicsTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont); DrawString(spriteBatch, new Vector2(320, y), "ContinuousPhysicsTime: " + GameMain.World.ContinuousPhysicsTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, GUI.Style.Red, (float)GameMain.World.ContinuousPhysicsTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont);
DrawString(spriteBatch, new Vector2(320, y + 15), "ControllersUpdateTime: " + GameMain.World.ControllersUpdateTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, Color.Red, (float)GameMain.World.ControllersUpdateTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont); DrawString(spriteBatch, new Vector2(320, y + 15), "ControllersUpdateTime: " + GameMain.World.ControllersUpdateTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, GUI.Style.Red, (float)GameMain.World.ControllersUpdateTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont);
DrawString(spriteBatch, new Vector2(320, y + 30), "AddRemoveTime: " + GameMain.World.AddRemoveTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, Color.Red, (float)GameMain.World.AddRemoveTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont); DrawString(spriteBatch, new Vector2(320, y + 30), "AddRemoveTime: " + GameMain.World.AddRemoveTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, GUI.Style.Red, (float)GameMain.World.AddRemoveTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont);
DrawString(spriteBatch, new Vector2(320, y + 45), "NewContactsTime: " + GameMain.World.NewContactsTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, Color.Red, (float)GameMain.World.NewContactsTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont); DrawString(spriteBatch, new Vector2(320, y + 45), "NewContactsTime: " + GameMain.World.NewContactsTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, GUI.Style.Red, (float)GameMain.World.NewContactsTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont);
DrawString(spriteBatch, new Vector2(320, y + 60), "ContactsUpdateTime: " + GameMain.World.ContactsUpdateTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, Color.Red, (float)GameMain.World.ContactsUpdateTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont); DrawString(spriteBatch, new Vector2(320, y + 60), "ContactsUpdateTime: " + GameMain.World.ContactsUpdateTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, GUI.Style.Red, (float)GameMain.World.ContactsUpdateTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont);
DrawString(spriteBatch, new Vector2(320, y + 75), "SolveUpdateTime: " + GameMain.World.SolveUpdateTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, Color.Red, (float)GameMain.World.SolveUpdateTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont); DrawString(spriteBatch, new Vector2(320, y + 75), "SolveUpdateTime: " + GameMain.World.SolveUpdateTime.TotalMilliseconds, Color.Lerp(Color.LightGreen, GUI.Style.Red, (float)GameMain.World.SolveUpdateTime.TotalMilliseconds / 10.0f), Color.Black * 0.5f, 0, SmallFont);
} }
} }
@@ -389,7 +393,7 @@ namespace Barotrauma
DrawString(spriteBatch, new Vector2(10, 90), DrawString(spriteBatch, new Vector2(10, 90),
"Particle count: " + GameMain.ParticleManager.ParticleCount + "/" + GameMain.ParticleManager.MaxParticles, "Particle count: " + GameMain.ParticleManager.ParticleCount + "/" + GameMain.ParticleManager.MaxParticles,
Color.Lerp(Color.Green, Color.Red, (GameMain.ParticleManager.ParticleCount / (float)GameMain.ParticleManager.MaxParticles)), Color.Black * 0.5f, 0, SmallFont); Color.Lerp(GUI.Style.Green, GUI.Style.Red, (GameMain.ParticleManager.ParticleCount / (float)GameMain.ParticleManager.MaxParticles)), Color.Black * 0.5f, 0, SmallFont);
DrawString(spriteBatch, new Vector2(10, 115), DrawString(spriteBatch, new Vector2(10, 115),
"Loaded sprites: " + Sprite.LoadedSprites.Count() + "\n(" + Sprite.LoadedSprites.Select(s => s.FilePath).Distinct().Count() + " unique textures)", "Loaded sprites: " + Sprite.LoadedSprites.Count() + "\n(" + Sprite.LoadedSprites.Select(s => s.FilePath).Distinct().Count() + " unique textures)",
@@ -472,10 +476,6 @@ namespace Barotrauma
"Ctrl+S to show sound debug info", Color.White, Color.Black * 0.5f, 0, SmallFont); "Ctrl+S to show sound debug info", Color.White, Color.Black * 0.5f, 0, SmallFont);
} }
if (PlayerInput.KeyDown(Keys.LeftControl) && PlayerInput.KeyHit(Keys.S))
{
debugDrawSounds = !debugDrawSounds;
}
if (debugDrawEvents) if (debugDrawEvents)
{ {
@@ -488,13 +488,12 @@ namespace Barotrauma
DrawString(spriteBatch, new Vector2(10, 300), DrawString(spriteBatch, new Vector2(10, 300),
"Ctrl+E to show EventManager debug info", Color.White, Color.Black * 0.5f, 0, SmallFont); "Ctrl+E to show EventManager debug info", Color.White, Color.Black * 0.5f, 0, SmallFont);
} }
if (PlayerInput.KeyDown(Keys.LeftControl) && PlayerInput.KeyHit(Keys.E))
{
debugDrawEvents = !debugDrawEvents;
}
if (MouseOn != null) if (MouseOn != null)
{ {
DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth - 500, 20), $"Selected UI Element: {MouseOn.GetType().ToString()}", Color.LightGreen, Color.Black * 0.5f, 0, SmallFont); DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth - 500, 20),
$"Selected UI Element: {MouseOn.GetType().Name} ({ (MouseOn.Style?.Element.Name.LocalName ?? "no style") }, {MouseOn.Rect})",
Color.LightGreen, Color.Black * 0.5f, 0, SmallFont);
} }
} }
@@ -744,19 +743,27 @@ namespace Barotrauma
{ {
inventoryIndex = updateList.IndexOf(CharacterHUD.HUDFrame); inventoryIndex = updateList.IndexOf(CharacterHUD.HUDFrame);
} }
for (var i = updateList.Count - 1; i > inventoryIndex; i--)
if (!PlayerInput.PrimaryMouseButtonHeld() && !PlayerInput.PrimaryMouseButtonClicked())
{ {
var c = updateList[i]; for (var i = updateList.Count - 1; i > inventoryIndex; i--)
if (!c.CanBeFocused) { continue; }
if (c.MouseRect.Contains(PlayerInput.MousePosition))
{ {
if ((!PlayerInput.PrimaryMouseButtonHeld() && !PlayerInput.PrimaryMouseButtonClicked()) || c == prevMouseOn) var c = updateList[i];
if (!c.CanBeFocused) { continue; }
if (c.MouseRect.Contains(PlayerInput.MousePosition))
{ {
MouseOn = c; if ((!PlayerInput.PrimaryMouseButtonHeld() && !PlayerInput.PrimaryMouseButtonClicked()) || c == prevMouseOn)
{
MouseOn = c;
}
break;
} }
break;
} }
} }
else
{
MouseOn = prevMouseOn;
}
MouseCursor = UpdateMouseCursorState(MouseOn); MouseCursor = UpdateMouseCursorState(MouseOn);
return MouseOn; return MouseOn;
@@ -845,8 +852,11 @@ namespace Barotrauma
// Children in list boxes can be interacted with despite not having // Children in list boxes can be interacted with despite not having
// a GUIButton inside of them so instead of hard coding we check if // a GUIButton inside of them so instead of hard coding we check if
// the children can be interacted with by checking their hover state // the children can be interacted with by checking their hover state
if (parent is GUIListBox) if (parent is GUIListBox listBox)
{ {
if (listBox.DraggedElement != null) { return CursorState.Dragging; }
if (listBox.CanDragElements) { return CursorState.Move; }
var hoverParent = c; var hoverParent = c;
while (true) while (true)
{ {
@@ -958,6 +968,15 @@ namespace Barotrauma
public static void Update(float deltaTime) public static void Update(float deltaTime)
{ {
if (PlayerInput.KeyDown(Keys.LeftControl) && PlayerInput.KeyHit(Keys.S))
{
debugDrawSounds = !debugDrawSounds;
}
if (PlayerInput.KeyDown(Keys.LeftControl) && PlayerInput.KeyHit(Keys.E))
{
debugDrawEvents = !debugDrawEvents;
}
HandlePersistingElements(deltaTime); HandlePersistingElements(deltaTime);
RefreshUpdateList(); RefreshUpdateList();
UpdateMouseOn(); UpdateMouseOn();
@@ -1279,7 +1298,7 @@ namespace Barotrauma
public static void DrawSineWithDots(SpriteBatch spriteBatch, Vector2 from, Vector2 dir, float amplitude, float length, float scale, int pointCount, Color color, int dotSize = 2) public static void DrawSineWithDots(SpriteBatch spriteBatch, Vector2 from, Vector2 dir, float amplitude, float length, float scale, int pointCount, Color color, int dotSize = 2)
{ {
Vector2 up = dir.Right(); Vector2 up = dir.Right();
//DrawLine(spriteBatch, from, from + dir, Color.Red); //DrawLine(spriteBatch, from, from + dir, GUI.Style.Red);
//DrawLine(spriteBatch, from, from + up * dir.Length(), Color.Blue); //DrawLine(spriteBatch, from, from + up * dir.Length(), Color.Blue);
for (int i = 0; i < pointCount; i++) for (int i = 0; i < pointCount; i++)
{ {
@@ -1814,15 +1833,15 @@ namespace Barotrauma
PauseMenu = new GUIFrame(new RectTransform(Vector2.One, Canvas), style: null, color: Color.Black * 0.5f); PauseMenu = new GUIFrame(new RectTransform(Vector2.One, Canvas), style: null, color: Color.Black * 0.5f);
var pauseMenuInner = new GUIFrame(new RectTransform(new Vector2(0.13f, 0.35f), PauseMenu.RectTransform, Anchor.Center) { MinSize = new Point(200, 300) }); var pauseMenuInner = new GUIFrame(new RectTransform(new Vector2(0.13f, 0.3f), PauseMenu.RectTransform, Anchor.Center) { MinSize = new Point(250, 300) });
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.85f, 0.8f), pauseMenuInner.RectTransform, Anchor.Center) { RelativeOffset = new Vector2(0.0f, 0.05f) }) var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.7f, 0.6f), pauseMenuInner.RectTransform, Anchor.Center))
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.05f RelativeSpacing = 0.05f
}; };
var button = new GUIButton(new RectTransform(new Vector2(0.12f, 0.12f), buttonContainer.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(-0.05f, -0.13f) }, var button = new GUIButton(new RectTransform(new Vector2(0.1f, 0.1f), pauseMenuInner.RectTransform, Anchor.TopRight) { AbsoluteOffset = new Point((int)(15 * GUI.Scale)) },
"", style: "GUIBugButton") "", style: "GUIBugButton")
{ {
IgnoreLayoutGroups = true, IgnoreLayoutGroups = true,
@@ -1830,12 +1849,12 @@ namespace Barotrauma
OnClicked = (btn, userdata) => { GameMain.Instance.ShowBugReporter(); return true; } OnClicked = (btn, userdata) => { GameMain.Instance.ShowBugReporter(); return true; }
}; };
button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuResume"), style: "GUIButtonLarge") button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuResume"))
{ {
OnClicked = TogglePauseMenu OnClicked = TogglePauseMenu
}; };
button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuSettings"), style: "GUIButtonLarge") button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuSettings"))
{ {
OnClicked = (btn, userData) => OnClicked = (btn, userData) =>
{ {
@@ -1849,7 +1868,7 @@ namespace Barotrauma
{ {
if (GameMain.GameSession.GameMode is SinglePlayerCampaign spMode) if (GameMain.GameSession.GameMode is SinglePlayerCampaign spMode)
{ {
button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuRetry"), style: "GUIButtonLarge"); button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuRetry"));
button.OnClicked += (btn, userData) => button.OnClicked += (btn, userData) =>
{ {
var msgBox = new GUIMessageBox("", TextManager.Get("PauseMenuRetryVerification"), new string[] { TextManager.Get("Yes"), TextManager.Get("Cancel") }) var msgBox = new GUIMessageBox("", TextManager.Get("PauseMenuRetryVerification"), new string[] { TextManager.Get("Yes"), TextManager.Get("Cancel") })
@@ -1875,7 +1894,7 @@ namespace Barotrauma
} }
else if (!GameMain.GameSession.GameMode.IsSinglePlayer && GameMain.Client != null && GameMain.Client.HasPermission(ClientPermissions.ManageRound)) else if (!GameMain.GameSession.GameMode.IsSinglePlayer && GameMain.Client != null && GameMain.Client.HasPermission(ClientPermissions.ManageRound))
{ {
new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), text: TextManager.Get("EndRound"), style: "GUIButtonLarge") new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), text: TextManager.Get("EndRound"))
{ {
OnClicked = (btn, userdata) => OnClicked = (btn, userdata) =>
{ {
@@ -1910,7 +1929,7 @@ namespace Barotrauma
{ {
if (GameMain.GameSession.GameMode is SinglePlayerCampaign spMode) if (GameMain.GameSession.GameMode is SinglePlayerCampaign spMode)
{ {
button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuSaveQuit"), style: "GUIButtonLarge") button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuSaveQuit"))
{ {
UserData = "save" UserData = "save"
}; };
@@ -1919,7 +1938,7 @@ namespace Barotrauma
} }
} }
button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuQuit"), style: "GUIButtonLarge"); button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), buttonContainer.RectTransform), TextManager.Get("PauseMenuQuit"));
button.OnClicked += (btn, userData) => button.OnClicked += (btn, userData) =>
{ {
var quitButton = button; var quitButton = button;
@@ -20,9 +20,7 @@ namespace Barotrauma
public OnButtonDownHandler OnButtonDown; public OnButtonDownHandler OnButtonDown;
public bool CanBeSelected = true; public bool CanBeSelected = true;
private Color? defaultTextColor;
public override bool Enabled public override bool Enabled
{ {
get get
@@ -33,13 +31,7 @@ namespace Barotrauma
set set
{ {
if (value == enabled) { return; } if (value == enabled) { return; }
enabled = value; enabled = frame.Enabled = textBlock.Enabled = value;
if (color.A == 0)
{
if (defaultTextColor == null) { defaultTextColor = TextBlock.TextColor; }
TextBlock.TextColor = enabled ? defaultTextColor.Value : defaultTextColor.Value * 0.5f;
}
frame.Color = enabled ? color : Color.Gray * 0.7f;
} }
} }
@@ -105,6 +97,11 @@ namespace Barotrauma
set { textBlock.TextColor = value; } set { textBlock.TextColor = value; }
} }
public Color HoverTextColor
{
get { return textBlock.HoverTextColor; }
set { textBlock.HoverTextColor = value; }
}
public override float FlashTimer public override float FlashTimer
{ {
@@ -115,12 +112,12 @@ namespace Barotrauma
{ {
get get
{ {
return (textBlock==null) ? GUI.Font : textBlock.Font; return (textBlock == null) ? GUI.Font : textBlock.Font;
} }
set set
{ {
base.Font = value; base.Font = value;
if (textBlock != null) textBlock.Font = value; if (textBlock != null) textBlock.Font = value;
} }
} }
@@ -149,28 +146,28 @@ namespace Barotrauma
} }
} }
public bool Selected { get; set; } public GUIButton(RectTransform rectT, string text = "", Alignment textAlignment = Alignment.Center, string style = "", Color? color = null) : base(style, rectT)
public GUIButton(RectTransform rectT, string text = "", Alignment textAlignment = Alignment.Center, string style = "", Color? color = null, ScalableFont font = null) : base(style, rectT)
{ {
CanBeFocused = true; CanBeFocused = true;
HoverCursor = CursorState.Hand; HoverCursor = CursorState.Hand;
frame = new GUIFrame(new RectTransform(Vector2.One, rectT), style) { CanBeFocused = false };
if (style != null) { GUI.Style.Apply(frame, style == "" ? "GUIButton" : style); }
if (color.HasValue) if (color.HasValue)
{ {
this.color = color.Value; this.color = frame.Color = color.Value;
} }
frame = new GUIFrame(new RectTransform(Vector2.One, rectT), style) { CanBeFocused = false }; textBlock = new GUITextBlock(new RectTransform(Vector2.One, rectT, Anchor.Center), text, textAlignment: textAlignment, style: null)
if (style != null) GUI.Style.Apply(frame, style == "" ? "GUIButton" : style);
textBlock = new GUITextBlock(new RectTransform(Vector2.One, rectT), text, textAlignment: textAlignment, style: null, font: font)
{ {
TextColor = this.style == null ? Color.Black : this.style.textColor, TextColor = this.style == null ? Color.Black : this.style.TextColor,
HoverTextColor = this.style == null ? Color.Black : this.style.HoverTextColor,
SelectedTextColor = this.style == null ? Color.Black : this.style.SelectedTextColor,
CanBeFocused = false CanBeFocused = false
}; };
if (rectT.Rect.Height == 0 && !string.IsNullOrEmpty(text)) if (rectT.Rect.Height == 0 && !string.IsNullOrEmpty(text))
{ {
RectTransform.Resize(new Point(RectTransform.Rect.Width, (int)Font.MeasureString(textBlock.Text).Y)); RectTransform.Resize(new Point(RectTransform.Rect.Width, (int)Font.MeasureString(textBlock.Text).Y));
RectTransform.MinSize = textBlock.RectTransform.MinSize = new Point(0, Rect.Height); RectTransform.MinSize = textBlock.RectTransform.MinSize = new Point(0, System.Math.Max(rectT.MinSize.Y, Rect.Height));
TextBlock.SetTextPos(); TextBlock.SetTextPos();
} }
GUI.Style.Apply(textBlock, "", this); GUI.Style.Apply(textBlock, "", this);
@@ -181,12 +178,12 @@ namespace Barotrauma
{ {
base.ApplyStyle(style); base.ApplyStyle(style);
if (frame != null) frame.ApplyStyle(style); if (frame != null) { frame.ApplyStyle(style); }
} }
public override void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, Vector2? flashRectInflate = null) public override void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, bool useCircularFlash = false, Vector2? flashRectInflate = null)
{ {
Frame.Flash(color, flashDuration, useRectangleFlash, flashRectInflate); Frame.Flash(color, flashDuration, useRectangleFlash, useCircularFlash, flashRectInflate);
} }
protected override void Draw(SpriteBatch spriteBatch) protected override void Draw(SpriteBatch spriteBatch)
@@ -200,7 +197,9 @@ namespace Barotrauma
base.Update(deltaTime); base.Update(deltaTime);
if (Rect.Contains(PlayerInput.MousePosition) && CanBeSelected && CanBeFocused && Enabled && GUI.IsMouseOn(this)) if (Rect.Contains(PlayerInput.MousePosition) && CanBeSelected && CanBeFocused && Enabled && GUI.IsMouseOn(this))
{ {
state = ComponentState.Hover; State = Selected ?
ComponentState.HoverSelected :
ComponentState.Hover;
if (PlayerInput.PrimaryMouseButtonDown()) if (PlayerInput.PrimaryMouseButtonDown())
{ {
OnButtonDown?.Invoke(); OnButtonDown?.Invoke();
@@ -211,12 +210,12 @@ namespace Barotrauma
{ {
if (OnPressed()) if (OnPressed())
{ {
state = ComponentState.Pressed; State = ComponentState.Pressed;
} }
} }
else else
{ {
state = ComponentState.Pressed; State = ComponentState.Pressed;
} }
} }
else if (PlayerInput.PrimaryMouseButtonClicked()) else if (PlayerInput.PrimaryMouseButtonClicked())
@@ -224,28 +223,26 @@ namespace Barotrauma
GUI.PlayUISound(GUISoundType.Click); GUI.PlayUISound(GUISoundType.Click);
if (OnClicked != null) if (OnClicked != null)
{ {
if (OnClicked(this, UserData) && CanBeSelected) if (OnClicked(this, UserData))
{ {
state = ComponentState.Selected; State = ComponentState.Selected;
} }
} }
else else
{ {
Selected = !Selected; Selected = !Selected;
// state = state == ComponentState.Selected ? ComponentState.None : ComponentState.Selected; }
}
} }
} }
else else
{ {
state = Selected ? ComponentState.Selected : ComponentState.None; State = Selected ? ComponentState.Selected : ComponentState.None;
} }
foreach (GUIComponent child in Children) foreach (GUIComponent child in Children)
{ {
child.State = state; child.State = State;
} }
//frame.State = state;
} }
} }
} }
@@ -0,0 +1,26 @@
using Microsoft.Xna.Framework;
namespace Barotrauma
{
public class GUIColorSettings
{
// Inventory
public static Color InventorySlotColor = new Color(78, 114, 88);
public static Color EquipmentSlotColor = new Color(72, 58, 25);
public static Color EquipmentSlotIconColor = new Color(99, 70, 64);
// Health HUD
public static Color BuffColorLow = Color.LightGreen;
public static Color BuffColorMedium = Color.Green;
public static Color BuffColorHigh = Color.DarkGreen;
public static Color DebuffColorLow = Color.DarkSalmon;
public static Color DebuffColorMedium = Color.Red;
public static Color DebuffColorHigh = Color.DarkRed;
public static Color HealthBarColorLow = Color.Red;
public static Color HealthBarColorMedium = Color.Orange;
public static Color HealthBarColorHigh = new Color(78, 114, 88);
}
}
@@ -15,11 +15,11 @@ namespace Barotrauma
{ {
#region Hierarchy #region Hierarchy
public GUIComponent Parent => RectTransform.Parent?.GUIComponent; public GUIComponent Parent => RectTransform.Parent?.GUIComponent;
public CursorState HoverCursor = CursorState.Default; public CursorState HoverCursor = CursorState.Default;
public IEnumerable<GUIComponent> Children => RectTransform.Children.Select(c => c.GUIComponent); public IEnumerable<GUIComponent> Children => RectTransform.Children.Select(c => c.GUIComponent);
public T GetChild<T>() where T : GUIComponent public T GetChild<T>() where T : GUIComponent
{ {
return Children.FirstOrDefault(c => c is T) as T; return Children.FirstOrDefault(c => c is T) as T;
@@ -30,6 +30,19 @@ namespace Barotrauma
return GetAllChildren().FirstOrDefault(c => c is T) as T; return GetAllChildren().FirstOrDefault(c => c is T) as T;
} }
public IEnumerable<T> GetAllChildren<T>() where T : GUIComponent
{
return GetAllChildren().Where(c => c is T).Select(c => c as T);
}
/// <summary>
/// Returns all child elements in the hierarchy.
/// </summary>
public IEnumerable<GUIComponent> GetAllChildren()
{
return RectTransform.GetAllChildren().Select(c => c.GUIComponent);
}
public GUIComponent GetChild(int index) public GUIComponent GetChild(int index)
{ {
if (index < 0 || index >= CountChildren) return null; if (index < 0 || index >= CountChildren) return null;
@@ -51,15 +64,6 @@ namespace Barotrauma
return null; return null;
} }
/// <summary>
/// Returns all child elements in the hierarchy.
/// If the component has RectTransform, it's more efficient to use RectTransform.GetChildren and access the GUIComponent property directly.
/// </summary>
public IEnumerable<GUIComponent> GetAllChildren()
{
return RectTransform.GetAllChildren().Select(c => c.GUIComponent);
}
public bool IsParentOf(GUIComponent component, bool recursive = true) public bool IsParentOf(GUIComponent component, bool recursive = true)
{ {
if (component == null) { return false; } if (component == null) { return false; }
@@ -134,31 +138,30 @@ namespace Barotrauma
public int UpdateOrder { get; set; } public int UpdateOrder { get; set; }
public Action<GUIComponent> OnAddedToGUIUpdateList; public Action<GUIComponent> OnAddedToGUIUpdateList;
/// <summary>
/// Launched at the beginning of the Draw method. Note: if the method is overridden, the event might not be called! public enum ComponentState { None, Hover, Pressed, Selected, HoverSelected };
public enum ComponentState { None, Hover, Pressed, Selected };
protected Alignment alignment; protected Alignment alignment;
protected GUIComponentStyle style; protected GUIComponentStyle style;
protected object userData; protected object userData;
public bool CanBeFocused; public bool CanBeFocused;
protected Color color; protected Color color;
protected Color hoverColor; protected Color hoverColor;
protected Color selectedColor; protected Color selectedColor;
protected Color disabledColor;
protected Color pressedColor; protected Color pressedColor;
private CoroutineHandle pulsateCoroutine; private CoroutineHandle pulsateCoroutine;
protected ComponentState state;
protected Color flashColor; protected Color flashColor;
protected float flashDuration = 1.5f; protected float flashDuration = 1.5f;
// TODO: We should use an enum for the flash modes, but it would require a bit of refactoring, because Flash method is use in so many places.
private bool useRectangleFlash; private bool useRectangleFlash;
private bool useCircularFlash;
public virtual float FlashTimer public virtual float FlashTimer
{ {
get { return flashTimer; } get { return flashTimer; }
@@ -166,7 +169,20 @@ namespace Barotrauma
protected float flashTimer; protected float flashTimer;
private Vector2 flashRectInflate; private Vector2 flashRectInflate;
public bool IgnoreLayoutGroups; private bool ignoreLayoutGroups;
public bool IgnoreLayoutGroups
{
get { return ignoreLayoutGroups; }
set
{
if (ignoreLayoutGroups == value) { return; }
ignoreLayoutGroups = value;
if (Parent is GUILayoutGroup layoutGroup)
{
layoutGroup.NeedsToRecalculate = true;
}
}
}
public virtual ScalableFont Font public virtual ScalableFont Font
{ {
@@ -210,7 +226,7 @@ namespace Barotrauma
get { return enabled; } get { return enabled; }
set { enabled = value; } set { enabled = value; }
} }
private static GUITextBlock toolTipBlock; private static GUITextBlock toolTipBlock;
public Vector2 Center public Vector2 Center
@@ -270,10 +286,31 @@ namespace Barotrauma
public virtual Color OutlineColor { get; set; } public virtual Color OutlineColor { get; set; }
public ComponentState State protected ComponentState _state;
protected ComponentState _previousState;
protected bool selected;
public virtual bool Selected
{ {
get { return state; } get { return selected; }
set { state = value; } set
{
selected = value;
Children.ForEach(c => c.Selected = value);
}
}
public virtual ComponentState State
{
get { return _state; }
set
{
if (_state != value)
{
spriteFadeTimer = SpriteCrossFadeTime;
colorFadeTimer = ColorCrossFadeTime;
_previousState = _state;
}
_state = value;
}
} }
public object UserData public object UserData
@@ -304,6 +341,11 @@ namespace Barotrauma
get { return selectedColor; } get { return selectedColor; }
set { selectedColor = value; } set { selectedColor = value; }
} }
public virtual Color DisabledColor
{
get { return disabledColor; }
set { disabledColor = value; }
}
public virtual Color PressedColor public virtual Color PressedColor
{ {
@@ -311,6 +353,14 @@ namespace Barotrauma
set { pressedColor = value; } set { pressedColor = value; }
} }
public TransitionMode ColorTransition { get; private set; }
public SpriteFallBackState FallBackState { get; private set; }
public float SpriteCrossFadeTime { get; private set; }
public float ColorCrossFadeTime { get; private set; }
private float spriteFadeTimer;
private float colorFadeTimer;
public bool ExternalHighlight = false; public bool ExternalHighlight = false;
private RectTransform rectTransform; private RectTransform rectTransform;
@@ -331,23 +381,26 @@ namespace Barotrauma
/// <summary> /// <summary>
/// This is the new constructor. /// This is the new constructor.
/// </summary> /// </summary>
protected GUIComponent(string style, RectTransform rectT) : this(style) protected GUIComponent(string style, RectTransform rectT)
{ {
RectTransform = rectT; RectTransform = rectT;
Visible = true;
OutlineColor = Color.Transparent;
Font = GUI.Font;
CanBeFocused = true;
if (style != null) { GUI.Style.Apply(this, style); }
} }
protected GUIComponent(string style) protected GUIComponent(string style)
{ {
Visible = true; Visible = true;
OutlineColor = Color.Transparent; OutlineColor = Color.Transparent;
Font = GUI.Font; Font = GUI.Font;
CanBeFocused = true;
CanBeFocused = true; //TODO: change default to false? if (style != null) { GUI.Style.Apply(this, style); }
if (style != null)
GUI.Style.Apply(this, style);
} }
#region Updating #region Updating
@@ -402,6 +455,14 @@ namespace Barotrauma
{ {
flashTimer -= deltaTime; flashTimer -= deltaTime;
} }
if (spriteFadeTimer > 0)
{
spriteFadeTimer -= deltaTime;
}
if (colorFadeTimer > 0)
{
colorFadeTimer -= deltaTime;
}
} }
/// <summary> /// <summary>
@@ -448,34 +509,114 @@ namespace Barotrauma
RectTransform.Children.ForEach(c => c.GUIComponent.DrawManually(spriteBatch, recursive, recursive)); RectTransform.Children.ForEach(c => c.GUIComponent.DrawManually(spriteBatch, recursive, recursive));
} }
protected virtual Color GetCurrentColor(ComponentState state) protected Color _currentColor;
protected virtual Color GetColor(ComponentState state)
{ {
switch (state) if (!Enabled) { return DisabledColor; }
return state switch
{ {
case ComponentState.Hover: ComponentState.Hover => HoverColor,
return HoverColor; ComponentState.Pressed => PressedColor,
case ComponentState.Pressed: ComponentState.Selected => SelectedColor,
return PressedColor; _ => Color,
case ComponentState.Selected: };
return SelectedColor; }
default:
return Color; private float GetEasing(TransitionMode easing, float t)
} {
return easing switch
{
TransitionMode.Smooth => MathUtils.SmoothStep(t),
TransitionMode.Smoother => MathUtils.SmootherStep(t),
TransitionMode.EaseIn => MathUtils.EaseIn(t),
TransitionMode.EaseOut => MathUtils.EaseOut(t),
TransitionMode.Exponential => t * t,
TransitionMode.Linear => t,
_ => t,
};
}
protected Color GetBlendedColor(Color targetColor, ref Color blendedColor)
{
blendedColor = ColorCrossFadeTime > 0 ? Color.Lerp(blendedColor, targetColor, MathUtils.InverseLerp(ColorCrossFadeTime, 0, GetEasing(ColorTransition, colorFadeTimer))) : targetColor;
return blendedColor;
} }
protected virtual void Draw(SpriteBatch spriteBatch) protected virtual void Draw(SpriteBatch spriteBatch)
{ {
if (!Visible) return; if (!Visible) return;
var rect = Rect; var rect = Rect;
Color currColor = GetCurrentColor(state);
if (currColor.A > 0.0f && (sprites == null || !sprites.Any())) GUI.DrawRectangle(spriteBatch, rect, currColor * (currColor.A / 255.0f), true);
if (sprites != null && sprites[state] != null && currColor.A > 0.0f) GetBlendedColor(GetColor(State), ref _currentColor);
if (_currentColor.A > 0.0f && (sprites == null || !sprites.Any()))
{ {
foreach (UISprite uiSprite in sprites[state]) GUI.DrawRectangle(spriteBatch, rect, _currentColor * (_currentColor.A / 255.0f), true);
}
if (sprites != null && _currentColor.A > 0)
{
if (!sprites.TryGetValue(_previousState, out List<UISprite> previousSprites) || previousSprites.None())
{ {
uiSprite.Draw(spriteBatch, rect, currColor * (currColor.A / 255.0f), SpriteEffects); switch (FallBackState)
{
case SpriteFallBackState.Toggle:
sprites.TryGetValue(Selected ? ComponentState.Selected : ComponentState.None, out previousSprites);
break;
default:
if (Enum.TryParse(FallBackState.ToString(), ignoreCase: true, out ComponentState fallBackState))
{
sprites.TryGetValue(fallBackState, out previousSprites);
}
break;
}
}
// Handle fallbacks when some of the sprites are not defined
if (!sprites.TryGetValue(State, out List<UISprite> currentSprites) || currentSprites.None())
{
switch (FallBackState)
{
case SpriteFallBackState.Toggle:
sprites.TryGetValue(Selected ? ComponentState.Selected : ComponentState.None, out currentSprites);
break;
default:
if (Enum.TryParse(FallBackState.ToString(), ignoreCase: true, out ComponentState fallBackState))
{
sprites.TryGetValue(fallBackState, out currentSprites);
}
break;
}
}
if (_previousState != State && currentSprites != previousSprites)
{
if (previousSprites != null && previousSprites.Any())
{
// Draw the previous sprites(s) only while cross fading out
Color previousColor = GetColor(_previousState);
foreach (UISprite uiSprite in previousSprites)
{
float alphaMultiplier = SpriteCrossFadeTime > 0 && (uiSprite.CrossFadeOut || currentSprites != null && currentSprites.Any(s => s.CrossFadeIn))
? MathUtils.InverseLerp(0, SpriteCrossFadeTime, GetEasing(uiSprite.TransitionMode, spriteFadeTimer)) : 0;
if (alphaMultiplier > 0)
{
uiSprite.Draw(spriteBatch, rect, previousColor * alphaMultiplier, SpriteEffects);
}
}
}
}
if (currentSprites != null && currentSprites.Any())
{
// Draw the current sprite(s)
foreach (UISprite uiSprite in currentSprites)
{
float alphaMultiplier = SpriteCrossFadeTime > 0 && (uiSprite.CrossFadeIn || previousSprites != null && previousSprites.Any(s => s.CrossFadeOut))
? MathUtils.InverseLerp(SpriteCrossFadeTime, 0, GetEasing(uiSprite.TransitionMode, spriteFadeTimer)) : (_currentColor.A / 255.0f);
if (alphaMultiplier > 0)
{
uiSprite.Draw(spriteBatch, rect, _currentColor * alphaMultiplier, SpriteEffects);
}
}
} }
} }
@@ -490,15 +631,16 @@ namespace Barotrauma
//MathHelper.Pi * 0.8f -> the curve goes from 144 deg to 0, //MathHelper.Pi * 0.8f -> the curve goes from 144 deg to 0,
//i.e. quickly bumps up from almost full brightness to full and then fades out //i.e. quickly bumps up from almost full brightness to full and then fades out
if (!useRectangleFlash) if (useRectangleFlash)
{ {
GUI.UIGlow.Draw(spriteBatch, GUI.DrawRectangle(spriteBatch, flashRect, flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f), true);
flashRect,
flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f));
} }
else else
{ {
GUI.DrawRectangle(spriteBatch, flashRect, flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f), true); var glow = useCircularFlash ? GUI.UIGlowCircular : GUI.UIGlow;
glow.Draw(spriteBatch,
flashRect,
flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f));
} }
} }
} }
@@ -551,13 +693,14 @@ namespace Barotrauma
color = new Color(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, a); color = new Color(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, a);
} }
public virtual void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, Vector2? flashRectInflate = null) public virtual void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, bool useCircularFlash = false, Vector2? flashRectInflate = null)
{ {
flashTimer = flashDuration; flashTimer = flashDuration;
this.flashRectInflate = flashRectInflate ?? Vector2.Zero; this.flashRectInflate = flashRectInflate ?? Vector2.Zero;
this.useRectangleFlash = useRectangleFlash; this.useRectangleFlash = useRectangleFlash;
this.useCircularFlash = useCircularFlash;
this.flashDuration = flashDuration; this.flashDuration = flashDuration;
flashColor = (color == null) ? Color.Red : (Color)color; flashColor = (color == null) ? GUI.Style.Red : (Color)color;
} }
public void FadeOut(float duration, bool removeAfter) public void FadeOut(float duration, bool removeAfter)
@@ -611,16 +754,37 @@ namespace Barotrauma
public virtual void ApplyStyle(GUIComponentStyle style) public virtual void ApplyStyle(GUIComponentStyle style)
{ {
if (style == null) return; if (style == null) { return; }
color = style.Color; color = style.Color;
_currentColor = color;
hoverColor = style.HoverColor; hoverColor = style.HoverColor;
selectedColor = style.SelectedColor; selectedColor = style.SelectedColor;
pressedColor = style.PressedColor; pressedColor = style.PressedColor;
disabledColor = style.DisabledColor;
sprites = style.Sprites; sprites = style.Sprites;
OutlineColor = style.OutlineColor; OutlineColor = style.OutlineColor;
SpriteCrossFadeTime = style.SpriteCrossFadeTime;
ColorCrossFadeTime = style.ColorCrossFadeTime;
ColorTransition = style.TransitionMode;
FallBackState = style.FallBackState;
if (rectTransform != null)
{
if (style.Width.HasValue)
{
RectTransform.MinSize = new Point(style.Width.Value, RectTransform.MinSize.Y);
RectTransform.MaxSize = new Point(style.Width.Value, RectTransform.MaxSize.Y);
if (rectTransform.IsFixedSize) { RectTransform.Resize(new Point(style.Width.Value, rectTransform.NonScaledSize.Y)); }
}
if (style.Height.HasValue)
{
RectTransform.MinSize = new Point(RectTransform.MinSize.X, style.Height.Value);
RectTransform.MaxSize = new Point(RectTransform.MaxSize.X, style.Height.Value);
if (rectTransform.IsFixedSize) { RectTransform.Resize(new Point(rectTransform.NonScaledSize.X, style.Height.Value)); }
}
}
this.style = style; this.style = style;
} }
@@ -779,14 +943,8 @@ namespace Barotrauma
case "largefont": case "largefont":
font = GUI.LargeFont; font = GUI.LargeFont;
break; break;
case "videotitlefont": case "subheading":
font = GUI.VideoTitleFont; font = GUI.SubHeadingFont;
break;
case "objectivetitlefont":
font = GUI.ObjectiveTitleFont;
break;
case "objectivenamefont":
font = GUI.ObjectiveNameFont;
break; break;
} }
@@ -13,8 +13,9 @@ namespace Barotrauma
public OnSelectedHandler OnSelected; public OnSelectedHandler OnSelected;
public OnSelectedHandler OnDropped; public OnSelectedHandler OnDropped;
private GUIButton button; private readonly GUIButton button;
private GUIListBox listBox; private readonly GUIImage icon;
private readonly GUIListBox listBox;
private RectTransform currentHighestParent; private RectTransform currentHighestParent;
private List<RectTransform> parentHierarchy = new List<RectTransform>(); private List<RectTransform> parentHierarchy = new List<RectTransform>();
@@ -41,7 +42,11 @@ namespace Barotrauma
public bool ButtonEnabled public bool ButtonEnabled
{ {
get { return button.Enabled; } get { return button.Enabled; }
set { button.Enabled = value; } set
{
button.Enabled = value;
if (icon != null) { icon.Enabled = value; }
}
} }
public GUIComponent SelectedComponent public GUIComponent SelectedComponent
@@ -49,6 +54,7 @@ namespace Barotrauma
get { return listBox.SelectedComponent; } get { return listBox.SelectedComponent; }
} }
// TODO: fix implicit hiding
public bool Selected public bool Selected
{ {
get get
@@ -157,17 +163,25 @@ namespace Barotrauma
OnClicked = OnClicked OnClicked = OnClicked
}; };
GUI.Style.Apply(button, "", this); GUI.Style.Apply(button, "", this);
button.TextBlock.SetTextPos();
Anchor listAnchor = dropAbove ? Anchor.TopCenter : Anchor.BottomCenter; Anchor listAnchor = dropAbove ? Anchor.TopCenter : Anchor.BottomCenter;
Pivot listPivot = dropAbove ? Pivot.BottomCenter : Pivot.TopCenter; Pivot listPivot = dropAbove ? Pivot.BottomCenter : Pivot.TopCenter;
listBox = new GUIListBox(new RectTransform(new Point(Rect.Width, Rect.Height * MathHelper.Clamp(elementCount, 2, 10)), rectT, listAnchor, listPivot) listBox = new GUIListBox(new RectTransform(new Point(Rect.Width, Rect.Height * MathHelper.Clamp(elementCount, 2, 10)), rectT, listAnchor, listPivot)
{ IsFixedSize = false }, style: null) { IsFixedSize = false }, style: null)
{ {
Enabled = !selectMultiple, Enabled = !selectMultiple,
OnSelected = SelectItem OnSelected = SelectItem
}; };
GUI.Style.Apply(listBox.Content, "GUIListBox", this); GUI.Style.Apply(listBox, "GUIListBox", this);
GUI.Style.Apply(listBox.ContentBackground, "GUIListBox", this);
if (button.Style.ChildStyles.ContainsKey("dropdownicon"))
{
icon = new GUIImage(new RectTransform(new Vector2(0.6f, 0.6f), button.RectTransform, Anchor.CenterRight, scaleBasis: ScaleBasis.BothHeight) { AbsoluteOffset = new Point(5, 0) }, null, scaleToFit: true);
icon.ApplyStyle(button.Style.ChildStyles["dropdownicon"]);
}
currentHighestParent = FindHighestParent(); currentHighestParent = FindHighestParent();
currentHighestParent.GUIComponent.OnAddedToGUIUpdateList += AddListBoxToGUIUpdateList; currentHighestParent.GUIComponent.OnAddedToGUIUpdateList += AddListBoxToGUIUpdateList;
@@ -253,6 +267,7 @@ namespace Barotrauma
i++; i++;
} }
button.Text = string.Join(", ", texts); button.Text = string.Join(", ", texts);
// TODO: The callback is called at least twice, remove this?
OnSelected?.Invoke(tb.Parent, tb.Parent.UserData); OnSelected?.Invoke(tb.Parent, tb.Parent.UserData);
return true; return true;
} }
@@ -300,6 +315,7 @@ namespace Barotrauma
button.Text = textBlock.Text; button.Text = textBlock.Text;
} }
Dropped = false; Dropped = false;
// TODO: OnSelected can be called multiple times and when it shouldn't be called -> turn into an event so that nobody else can call it.
OnSelected?.Invoke(component, component.UserData); OnSelected?.Invoke(component, component.UserData);
return true; return true;
} }
@@ -8,6 +8,7 @@ namespace Barotrauma
{ {
public GUIFrame(RectTransform rectT, string style = "", Color? color = null) : base(style, rectT) public GUIFrame(RectTransform rectT, string style = "", Color? color = null) : base(style, rectT)
{ {
Enabled = true;
if (color.HasValue) if (color.HasValue)
{ {
this.color = color.Value; this.color = color.Value;
@@ -18,7 +19,7 @@ namespace Barotrauma
{ {
if (!Visible) return; if (!Visible) return;
Color currColor = GetCurrentColor(state); Color currColor = GetColor(State);
if (sprites == null || !sprites.Any(s => s.Value.Any())) GUI.DrawRectangle(spriteBatch, Rect, currColor * (currColor.A/255.0f), true); if (sprites == null || !sprites.Any(s => s.Value.Any())) GUI.DrawRectangle(spriteBatch, Rect, currColor * (currColor.A/255.0f), true);
base.Draw(spriteBatch); base.Draw(spriteBatch);
@@ -87,7 +87,7 @@ namespace Barotrauma
} }
if (style == null) if (style == null)
{ {
color = hoverColor = selectedColor = pressedColor = Color.White; color = hoverColor = selectedColor = pressedColor = disabledColor = Color.White;
} }
if (!scaleToFit) if (!scaleToFit)
{ {
@@ -97,15 +97,17 @@ namespace Barotrauma
{ {
rectT.SizeChanged += RecalculateScale; rectT.SizeChanged += RecalculateScale;
} }
Enabled = true;
} }
protected override void Draw(SpriteBatch spriteBatch) protected override void Draw(SpriteBatch spriteBatch)
{ {
if (!Visible) return; if (!Visible) return;
if (Parent != null) { state = Parent.State; } if (Parent != null) { State = Parent.State; }
if (OverrideState != null) { state = OverrideState.Value; } if (OverrideState != null) { State = OverrideState.Value; }
Color currColor = GetCurrentColor(state);
Color currentColor = GetColor(State);
if (BlendState != null) if (BlendState != null)
{ {
@@ -115,23 +117,23 @@ namespace Barotrauma
if (style != null) if (style != null)
{ {
foreach (UISprite uiSprite in style.Sprites[state]) foreach (UISprite uiSprite in style.Sprites[State])
{ {
if (Math.Abs(Rotation) > float.Epsilon) if (Math.Abs(Rotation) > float.Epsilon)
{ {
float scale = Math.Min(Rect.Width / uiSprite.Sprite.size.X, Rect.Height / uiSprite.Sprite.size.Y); float scale = Math.Min(Rect.Width / uiSprite.Sprite.size.X, Rect.Height / uiSprite.Sprite.size.Y);
spriteBatch.Draw(uiSprite.Sprite.Texture, Rect.Center.ToVector2(), uiSprite.Sprite.SourceRect, currColor * (currColor.A / 255.0f), Rotation, uiSprite.Sprite.size / 2, spriteBatch.Draw(uiSprite.Sprite.Texture, Rect.Center.ToVector2(), uiSprite.Sprite.SourceRect, currentColor * (currentColor.A / 255.0f), Rotation, uiSprite.Sprite.size / 2,
Scale * scale, SpriteEffects, 0.0f); Scale * scale, SpriteEffects, 0.0f);
} }
else else
{ {
uiSprite.Draw(spriteBatch, Rect, currColor * (currColor.A / 255.0f), SpriteEffects); uiSprite.Draw(spriteBatch, Rect, currentColor * (currentColor.A / 255.0f), SpriteEffects);
} }
} }
} }
else if (sprite?.Texture != null) else if (sprite?.Texture != null)
{ {
spriteBatch.Draw(sprite.Texture, Rect.Center.ToVector2(), sourceRect, currColor * (currColor.A / 255.0f), Rotation, sprite.size / 2, spriteBatch.Draw(sprite.Texture, Rect.Center.ToVector2(), sourceRect, currentColor * (currentColor.A / 255.0f), Rotation, sprite.size / 2,
Scale, SpriteEffects, 0.0f); Scale, SpriteEffects, 0.0f);
} }
@@ -68,6 +68,10 @@ namespace Barotrauma
public bool NeedsToRecalculate public bool NeedsToRecalculate
{ {
get { return needsToRecalculate; } get { return needsToRecalculate; }
set
{
if (value) { needsToRecalculate = true; }
}
} }
public GUILayoutGroup(RectTransform rectT, bool isHorizontal = false, Anchor childAnchor = Anchor.TopLeft) : base(null, rectT) public GUILayoutGroup(RectTransform rectT, bool isHorizontal = false, Anchor childAnchor = Anchor.TopLeft) : base(null, rectT)
@@ -86,20 +90,49 @@ namespace Barotrauma
float stretchFactor = 1.0f; float stretchFactor = 1.0f;
if (stretch && RectTransform.Children.Count() > 0) if (stretch && RectTransform.Children.Count() > 0)
{ {
foreach (RectTransform child in RectTransform.Children)
{
if (child.GUIComponent.IgnoreLayoutGroups) { continue; }
if (child.ScaleBasis == ScaleBasis.BothHeight) { child.MinSize = new Point(child.Rect.Height, child.MinSize.Y); }
if (child.ScaleBasis == ScaleBasis.BothWidth) { child.MinSize = new Point(child.MinSize.X, child.Rect.Width); }
if (child.ScaleBasis == ScaleBasis.Smallest)
{
if (Rect.Width < Rect.Height)
{
child.MinSize = new Point(child.MinSize.X, child.Rect.Width);
}
else
{
child.MinSize = new Point(child.Rect.Height, child.MinSize.Y);
}
}
if (child.ScaleBasis == ScaleBasis.Largest)
{
if (Rect.Width > Rect.Height)
{
child.MinSize = new Point(child.MinSize.X, child.Rect.Width);
}
else
{
child.MinSize = new Point(child.Rect.Height, child.MinSize.Y);
}
}
}
float minSize = RectTransform.Children float minSize = RectTransform.Children
.Where(c => !c.GUIComponent.IgnoreLayoutGroups) .Where(c => !c.GUIComponent.IgnoreLayoutGroups)
.Sum(c => isHorizontal ? c.MinSize.X : c.MinSize.Y); .Sum(c => isHorizontal ? (c.IsFixedSize ? c.NonScaledSize.X : c.MinSize.X) : (c.IsFixedSize ? c.NonScaledSize.Y : c.MinSize.Y));
float totalSize = RectTransform.Children float totalSize = RectTransform.Children
.Where(c => !c.GUIComponent.IgnoreLayoutGroups) .Where(c => !c.GUIComponent.IgnoreLayoutGroups)
.Sum(c => isHorizontal ? .Sum(c => isHorizontal ?
MathHelper.Clamp(c.Rect.Width, c.MinSize.X, c.MaxSize.X) : (c.IsFixedSize ? c.Rect.Width : MathHelper.Clamp(c.Rect.Width, c.MinSize.X, c.MaxSize.X)) :
MathHelper.Clamp(c.Rect.Height, c.MinSize.Y, c.MaxSize.Y)); (c.IsFixedSize ? c.Rect.Height : MathHelper.Clamp(c.Rect.Height, c.MinSize.Y, c.MaxSize.Y)));
float thisSize = (isHorizontal ? Rect.Width : Rect.Height); float thisSize = (isHorizontal ? Rect.Width : Rect.Height);
totalSize += totalSize +=
(RectTransform.Children.Count() - 1) * (RectTransform.Children.Count(c => !c.GUIComponent.IgnoreLayoutGroups) - 1) *
(absoluteSpacing + relativeSpacing * thisSize); (absoluteSpacing + relativeSpacing * thisSize);
stretchFactor = totalSize <= 0.0f || minSize >= thisSize ? stretchFactor = totalSize <= 0.0f || minSize >= thisSize ?
@@ -117,20 +150,34 @@ namespace Barotrauma
{ {
child.RelativeOffset = new Vector2(relPos, child.RelativeOffset.Y); child.RelativeOffset = new Vector2(relPos, child.RelativeOffset.Y);
child.AbsoluteOffset = new Point(absPos, child.AbsoluteOffset.Y); child.AbsoluteOffset = new Point(absPos, child.AbsoluteOffset.Y);
absPos += (int)Math.Max((child.Rect.Width + absoluteSpacing) * stretchFactor, child.MinSize.X); if (child.IsFixedSize)
if (stretch)
{ {
child.RelativeSize = new Vector2(child.RelativeSize.X * stretchFactor, child.RelativeSize.Y); absPos += child.NonScaledSize.X + absoluteSpacing;
}
else
{
absPos += (int)(MathHelper.Clamp(child.Rect.Width * stretchFactor, child.MinSize.X, child.MaxSize.X) + (absoluteSpacing * stretchFactor));
if (stretch)
{
child.RelativeSize = new Vector2(child.RelativeSize.X * stretchFactor, child.RelativeSize.Y);
}
} }
} }
else else
{ {
child.RelativeOffset = new Vector2(child.RelativeOffset.X, relPos); child.RelativeOffset = new Vector2(child.RelativeOffset.X, relPos);
child.AbsoluteOffset = new Point(child.AbsoluteOffset.X, absPos); child.AbsoluteOffset = new Point(child.AbsoluteOffset.X, absPos);
absPos += (int)Math.Max((child.Rect.Height + absoluteSpacing) * stretchFactor, child.MinSize.Y); if (child.IsFixedSize)
if (stretch)
{ {
child.RelativeSize = new Vector2(child.RelativeSize.X, child.RelativeSize.Y * stretchFactor); absPos += child.NonScaledSize.Y + absoluteSpacing;
}
else
{
absPos += (int)(MathHelper.Clamp(child.Rect.Height * stretchFactor, child.MinSize.Y, child.MaxSize.Y) + (absoluteSpacing * stretchFactor));
if (stretch)
{
child.RelativeSize = new Vector2(child.RelativeSize.X, child.RelativeSize.Y * stretchFactor);
}
} }
} }
relPos += relativeSpacing * stretchFactor; relPos += relativeSpacing * stretchFactor;
@@ -22,8 +22,16 @@ namespace Barotrauma
public delegate void OnRearrangedHandler(GUIListBox listBox, object obj); public delegate void OnRearrangedHandler(GUIListBox listBox, object obj);
public OnRearrangedHandler OnRearranged; public OnRearrangedHandler OnRearranged;
public GUIScrollBar ScrollBar { get; private set; } /// <summary>
/// A frame drawn behind the content of the listbox
/// </summary>
public GUIFrame ContentBackground { get; private set; }
/// <summary>
/// A frame that contains the contents of the listbox. The frame itself is not rendered.
/// </summary>
public GUIFrame Content { get; private set; } public GUIFrame Content { get; private set; }
public GUIScrollBar ScrollBar { get; private set; }
private Dictionary<GUIComponent, bool> childVisible = new Dictionary<GUIComponent, bool>(); private Dictionary<GUIComponent, bool> childVisible = new Dictionary<GUIComponent, bool>();
@@ -33,7 +41,7 @@ namespace Barotrauma
private bool dimensionsNeedsRecalculation; private bool dimensionsNeedsRecalculation;
// TODO: Define in styles? // TODO: Define in styles?
private int scrollBarSize = 20; private int scrollBarSize = 25;
public bool SelectMultiple; public bool SelectMultiple;
@@ -53,6 +61,18 @@ namespace Barotrauma
} }
} }
private Vector4? overridePadding;
public Vector4 Padding
{
get
{
if (overridePadding.HasValue) { return overridePadding.Value; }
if (Style == null) { return Vector4.Zero; }
return Style.Padding;
}
set { overridePadding = value; }
}
public GUIComponent SelectedComponent public GUIComponent SelectedComponent
{ {
get get
@@ -61,6 +81,7 @@ namespace Barotrauma
} }
} }
// TODO: fix implicit hiding
public bool Selected { get; set; } public bool Selected { get; set; }
public List<GUIComponent> AllSelected public List<GUIComponent> AllSelected
@@ -148,14 +169,20 @@ namespace Barotrauma
private Rectangle draggedReferenceRectangle; private Rectangle draggedReferenceRectangle;
private Point draggedReferenceOffset; private Point draggedReferenceOffset;
public GUIComponent DraggedElement => draggedElement;
public GUIListBox(RectTransform rectT, bool isHorizontal = false, Color? color = null, string style = "") : base(style, rectT) public GUIListBox(RectTransform rectT, bool isHorizontal = false, Color? color = null, string style = "") : base(style, rectT)
{ {
CanBeFocused = true; CanBeFocused = true;
selected = new List<GUIComponent>(); selected = new List<GUIComponent>();
Content = new GUIFrame(new RectTransform(Vector2.One, rectT), style) ContentBackground = new GUIFrame(new RectTransform(Vector2.One, rectT), style)
{ {
CanBeFocused = false CanBeFocused = false
}; };
Content = new GUIFrame(new RectTransform(Vector2.One, ContentBackground.RectTransform), style: null)
{
CanBeFocused = false
};
Content.RectTransform.ChildrenChanged += (_) => Content.RectTransform.ChildrenChanged += (_) =>
{ {
scrollBarNeedsRecalculation = true; scrollBarNeedsRecalculation = true;
@@ -163,7 +190,7 @@ namespace Barotrauma
}; };
if (style != null) if (style != null)
{ {
GUI.Style.Apply(Content, "", this); GUI.Style.Apply(ContentBackground, "", this);
} }
if (color.HasValue) if (color.HasValue)
{ {
@@ -173,15 +200,17 @@ namespace Barotrauma
Anchor anchor; Anchor anchor;
if (isHorizontal) if (isHorizontal)
{ {
size = new Point(Rect.Width, scrollBarSize); size = new Point((int)(Rect.Width - Padding.X - Padding.Z), (int)(scrollBarSize * GUI.Scale));
anchor = Anchor.BottomLeft; anchor = Anchor.BottomCenter;
} }
else else
{ {
size = new Point(scrollBarSize, Rect.Height); size = new Point((int)(scrollBarSize * GUI.Scale), (int)(Rect.Height - Padding.Y - Padding.W));
anchor = Anchor.TopRight; anchor = Anchor.CenterRight;
} }
ScrollBar = new GUIScrollBar(new RectTransform(size, rectT, anchor), isHorizontal: isHorizontal); ScrollBar = new GUIScrollBar(new RectTransform(size, rectT, anchor)
{ AbsoluteOffset = isHorizontal ? new Point(0, (int)Padding.W) : new Point((int)Padding.Z, 0) },
isHorizontal: isHorizontal);
UpdateScrollBarSize(); UpdateScrollBarSize();
Enabled = true; Enabled = true;
ScrollBar.BarScroll = 0.0f; ScrollBar.BarScroll = 0.0f;
@@ -193,9 +222,18 @@ namespace Barotrauma
private void UpdateDimensions() private void UpdateDimensions()
{ {
dimensionsNeedsRecalculation = false; dimensionsNeedsRecalculation = false;
ContentBackground.RectTransform.Resize(Rect.Size);
bool reduceScrollbarSize = KeepSpaceForScrollBar ? ScrollBarEnabled : ScrollBarVisible; bool reduceScrollbarSize = KeepSpaceForScrollBar ? ScrollBarEnabled : ScrollBarVisible;
Content.RectTransform.Resize(reduceScrollbarSize ? CalculateFrameSize(ScrollBar.IsHorizontal, scrollBarSize) : Rect.Size); Point contentSize = reduceScrollbarSize ? CalculateFrameSize(ScrollBar.IsHorizontal, scrollBarSize) : Rect.Size;
ScrollBar.RectTransform.Resize(ScrollBar.IsHorizontal ? new Point(Rect.Width, scrollBarSize) : new Point(scrollBarSize, Rect.Height)); Content.RectTransform.Resize(new Point((int)(contentSize.X - Padding.X - Padding.Z), (int)(contentSize.Y - Padding.Y - Padding.W)));
Content.RectTransform.AbsoluteOffset = new Point((int)Padding.X, (int)Padding.Y);
ScrollBar.RectTransform.Resize(ScrollBar.IsHorizontal ?
new Point((int)(Rect.Width - Padding.X - Padding.Z), (int)(scrollBarSize * GUI.Scale)) :
new Point((int)(scrollBarSize * GUI.Scale), (int)(Rect.Height - Padding.Y - Padding.W)));
ScrollBar.RectTransform.AbsoluteOffset = ScrollBar.IsHorizontal ?
new Point(0, (int)Padding.W) :
new Point((int)Padding.Z, 0);
UpdateScrollBarSize();
} }
public void Select(object userData, bool force = false, bool autoScroll = true) public void Select(object userData, bool force = false, bool autoScroll = true)
@@ -380,7 +418,7 @@ namespace Barotrauma
{ {
foreach (GUIComponent child in Children) foreach (GUIComponent child in Children)
{ {
if (child == Content || child == ScrollBar) { continue; } if (child == Content || child == ScrollBar || child == ContentBackground) { continue; }
child.AddToGUIUpdateList(ignoreChildren, order); child.AddToGUIUpdateList(ignoreChildren, order);
} }
} }
@@ -411,7 +449,7 @@ namespace Barotrauma
OnAddedToGUIUpdateList?.Invoke(this); OnAddedToGUIUpdateList?.Invoke(this);
return; return;
} }
Content.AddToGUIUpdateList(true, order);
int lastVisible = 0; int lastVisible = 0;
for (int i = 0; i < Content.CountChildren; i++) for (int i = 0; i < Content.CountChildren; i++)
{ {
@@ -516,7 +554,11 @@ namespace Barotrauma
GUIComponent child = Content.GetChild(childIndex); GUIComponent child = Content.GetChild(childIndex);
bool wasSelected = true; bool wasSelected = true;
if (OnSelected != null) wasSelected = force || OnSelected(child, child.UserData); if (OnSelected != null)
{
// TODO: The callback is called twice, fix this!
wasSelected = force || OnSelected(child, child.UserData);
}
if (!wasSelected) { return; } if (!wasSelected) { return; }
@@ -638,10 +680,10 @@ namespace Barotrauma
totalSize += Content.CountChildren * Spacing; totalSize += Content.CountChildren * Spacing;
} }
float minScrollBarSize = 20.0f;
ScrollBar.BarSize = ScrollBar.IsHorizontal ? ScrollBar.BarSize = ScrollBar.IsHorizontal ?
Math.Max(Math.Min(Content.Rect.Width / (float)totalSize, 1.0f), 5.0f / Content.Rect.Width) : Math.Max(Math.Min(Content.Rect.Width / (float)totalSize, 1.0f), minScrollBarSize / Content.Rect.Width) :
Math.Max(Math.Min(Content.Rect.Height / (float)totalSize, 1.0f), 5.0f / Content.Rect.Height); Math.Max(Math.Min(Content.Rect.Height / (float)totalSize, 1.0f), minScrollBarSize / Content.Rect.Height);
} }
public override void ClearChildren() public override void ClearChildren()
@@ -668,8 +710,8 @@ namespace Barotrauma
{ {
if (!Visible) { return; } if (!Visible) { return; }
Content.DrawManually(spriteBatch, alsoChildren: false); ContentBackground.DrawManually(spriteBatch, alsoChildren: false);
Rectangle prevScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle; Rectangle prevScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle;
RasterizerState prevRasterizerState = spriteBatch.GraphicsDevice.RasterizerState; RasterizerState prevRasterizerState = spriteBatch.GraphicsDevice.RasterizerState;
if (HideChildrenOutsideFrame) if (HideChildrenOutsideFrame)
@@ -90,7 +90,7 @@ namespace Barotrauma
Content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.85f), InnerFrame.RectTransform, Anchor.Center)) { AbsoluteSpacing = 5 }; Content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.85f), InnerFrame.RectTransform, Anchor.Center)) { AbsoluteSpacing = 5 };
Header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), Header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform),
headerText, textAlignment: Alignment.Center, wrap: true); headerText, font: GUI.SubHeadingFont, textAlignment: Alignment.Center, wrap: true);
GUI.Style.Apply(Header, "", this); GUI.Style.Apply(Header, "", this);
Header.RectTransform.MinSize = new Point(0, Header.Rect.Height); Header.RectTransform.MinSize = new Point(0, Header.Rect.Height);
@@ -103,21 +103,28 @@ namespace Barotrauma
Text.RectTransform.IsFixedSize = true; Text.RectTransform.IsFixedSize = true;
} }
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), Content.RectTransform, Anchor.BottomCenter, maxSize: new Point(1000, 50)), var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), Content.RectTransform, Anchor.BottomCenter), childAnchor: Anchor.TopCenter)
isHorizontal: true, childAnchor: buttons.Length > 1 ? Anchor.BottomLeft : Anchor.Center)
{ {
AbsoluteSpacing = 5, AbsoluteSpacing = 5,
IgnoreLayoutGroups = true IgnoreLayoutGroups = true
}; };
int buttonSize = 35;
var buttonStyle = GUI.Style.GetComponentStyle("GUIButton");
if (buttonStyle != null && buttonStyle.Height.HasValue)
{
buttonSize = buttonStyle.Height.Value;
}
buttonContainer.RectTransform.NonScaledSize = buttonContainer.RectTransform.MinSize = buttonContainer.RectTransform.MaxSize = buttonContainer.RectTransform.NonScaledSize = buttonContainer.RectTransform.MinSize = buttonContainer.RectTransform.MaxSize =
new Point(buttonContainer.Rect.Width, (int)(30 * GUI.Scale)); new Point(buttonContainer.Rect.Width, (int)((buttonSize + 5) * buttons.Length));
buttonContainer.RectTransform.IsFixedSize = true; buttonContainer.RectTransform.IsFixedSize = true;
if (height == 0) if (height == 0)
{ {
height += Header.Rect.Height + Content.AbsoluteSpacing; height += Header.Rect.Height + Content.AbsoluteSpacing;
height += (Text == null ? 0 : Text.Rect.Height) + Content.AbsoluteSpacing; height += (Text == null ? 0 : Text.Rect.Height) + Content.AbsoluteSpacing;
height += buttonContainer.Rect.Height; height += buttonContainer.Rect.Height + 20;
if (minSize.HasValue) { height = Math.Max(height, minSize.Value.Y); } if (minSize.HasValue) { height = Math.Max(height, minSize.Value.Y); }
InnerFrame.RectTransform.NonScaledSize = InnerFrame.RectTransform.NonScaledSize =
@@ -129,7 +136,7 @@ namespace Barotrauma
Buttons = new List<GUIButton>(buttons.Length); Buttons = new List<GUIButton>(buttons.Length);
for (int i = 0; i < buttons.Length; i++) for (int i = 0; i < buttons.Length; i++)
{ {
var button = new GUIButton(new RectTransform(new Vector2(Math.Min(0.9f / buttons.Length, 0.5f), 1.0f), buttonContainer.RectTransform), buttons[i], style: "GUIButtonLarge"); var button = new GUIButton(new RectTransform(new Vector2(0.6f, 1.0f / buttons.Length), buttonContainer.RectTransform), buttons[i]);
Buttons.Add(button); Buttons.Add(button);
} }
} }
@@ -157,7 +164,7 @@ namespace Barotrauma
Buttons = new List<GUIButton>(1) Buttons = new List<GUIButton>(1)
{ {
new GUIButton(new RectTransform(new Vector2(0.5f, 0.5f), buttonContainer.RectTransform, Anchor.Center), new GUIButton(new RectTransform(new Vector2(0.5f, 0.5f), buttonContainer.RectTransform, Anchor.Center),
style: GUI.Style.GetComponentStyle("GUIButtonSolidHorizontalArrow") != null ? "GUIButtonSolidHorizontalArrow" : "GUIButtonHorizontalArrow") style: "GUIButtonHorizontalArrow")
{ {
OnClicked = Close OnClicked = Close
} }
@@ -16,8 +16,8 @@ namespace Barotrauma
public OnValueChangedHandler OnValueChanged; public OnValueChangedHandler OnValueChanged;
public GUITextBox TextBox { get; private set; } public GUITextBox TextBox { get; private set; }
public GUIButton PlusButton { get; private set; }
public GUIButton MinusButton { get; private set; } private GUIButton plusButton, minusButton;
private NumberType inputType; private NumberType inputType;
public NumberType InputType public NumberType InputType
@@ -25,10 +25,17 @@ namespace Barotrauma
get { return inputType; } get { return inputType; }
set set
{ {
if (inputType == value) { return; }
inputType = value; inputType = value;
PlusButton.Visible = inputType == NumberType.Int || if (inputType == NumberType.Int ||
(inputType == NumberType.Float && MinValueFloat > float.MinValue && MaxValueFloat < float.MaxValue); (inputType == NumberType.Float && MinValueFloat > float.MinValue && MaxValueFloat < float.MaxValue))
MinusButton.Visible = PlusButton.Visible; {
ShowPlusMinusButtons();
}
else
{
HidePlusMinusButtons();
}
} }
} }
@@ -40,9 +47,15 @@ namespace Barotrauma
{ {
minValueFloat = value; minValueFloat = value;
ClampFloatValue(); ClampFloatValue();
PlusButton.Visible = inputType == NumberType.Int || if (inputType == NumberType.Int ||
(inputType == NumberType.Float && MinValueFloat > float.MinValue && MaxValueFloat < float.MaxValue); (inputType == NumberType.Float && MinValueFloat > float.MinValue && MaxValueFloat < float.MaxValue))
MinusButton.Visible = PlusButton.Visible; {
ShowPlusMinusButtons();
}
else
{
HidePlusMinusButtons();
}
} }
} }
public float? MaxValueFloat public float? MaxValueFloat
@@ -52,9 +65,15 @@ namespace Barotrauma
{ {
maxValueFloat = value; maxValueFloat = value;
ClampFloatValue(); ClampFloatValue();
PlusButton.Visible = inputType == NumberType.Int || if (inputType == NumberType.Int ||
(inputType == NumberType.Float && MinValueFloat > float.MinValue && MaxValueFloat < float.MaxValue); (inputType == NumberType.Float && MinValueFloat > float.MinValue && MaxValueFloat < float.MaxValue))
MinusButton.Visible = PlusButton.Visible; {
ShowPlusMinusButtons();
}
else
{
HidePlusMinusButtons();
}
} }
} }
@@ -124,14 +143,14 @@ namespace Barotrauma
get => base.Enabled; get => base.Enabled;
set set
{ {
PlusButton.Enabled = true; plusButton.Enabled = true;
MinusButton.Enabled = true; minusButton.Enabled = true;
if (InputType == NumberType.Int) { ClampIntValue(); } else { ClampFloatValue(); } if (InputType == NumberType.Int) { ClampIntValue(); } else { ClampFloatValue(); }
TextBox.Enabled = value; TextBox.Enabled = value;
if (!value) if (!value)
{ {
PlusButton.Enabled = false; plusButton.Enabled = false;
MinusButton.Enabled = false; minusButton.Enabled = false;
} }
} }
} }
@@ -163,37 +182,31 @@ namespace Barotrauma
public GUINumberInput(RectTransform rectT, NumberType inputType, string style = "", Alignment textAlignment = Alignment.Center, float? relativeButtonAreaWidth = null) : base(style, rectT) public GUINumberInput(RectTransform rectT, NumberType inputType, string style = "", Alignment textAlignment = Alignment.Center, float? relativeButtonAreaWidth = null) : base(style, rectT)
{ {
LayoutGroup = new GUILayoutGroup(new RectTransform(Vector2.One, rectT), isHorizontal: true) { Stretch = true }; LayoutGroup = new GUILayoutGroup(new RectTransform(Vector2.One, rectT), isHorizontal: true, childAnchor: Anchor.CenterLeft) { Stretch = true };
float _relativeButtonAreaWidth = relativeButtonAreaWidth ?? MathHelper.Clamp(Rect.Height / (float)Rect.Width, 0.1f, 0.5f); float _relativeButtonAreaWidth = relativeButtonAreaWidth ?? MathHelper.Clamp(Rect.Height / (float)Rect.Width, 0.1f, 0.25f);
TextBox = new GUITextBox(new RectTransform(new Vector2(1.0f - _relativeButtonAreaWidth, 1.0f), LayoutGroup.RectTransform), textAlignment: textAlignment, style: style) TextBox = new GUITextBox(new RectTransform(new Vector2(1.0f - _relativeButtonAreaWidth, 1.0f), LayoutGroup.RectTransform), textAlignment: textAlignment, style: "GUITextBoxNoIcon")
{ {
ClampText = false, ClampText = false
// For some reason the caret in the number inputs is dimmer than it should.
// It should not be rendered behind anything, as I first suspected.
// Therefore this hack.
CaretColor = Color.White
}; };
TextBox.CaretColor = TextBox.TextColor;
TextBox.OnTextChanged += TextChanged; TextBox.OnTextChanged += TextChanged;
var buttonArea = new GUIFrame(new RectTransform(new Vector2(_relativeButtonAreaWidth, 1.0f), LayoutGroup.RectTransform, Anchor.CenterRight), style: null); var buttonArea = new GUIFrame(new RectTransform(new Vector2(_relativeButtonAreaWidth, 1.0f), LayoutGroup.RectTransform, Anchor.CenterRight), style: null);
/*if (!relativeButtonAreaWidth.HasValue) plusButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.5f), buttonArea.RectTransform), style: null);
{ GUI.Style.Apply(plusButton, "PlusButton", this);
// Not sure what's the point of this plusButton.OnButtonDown += () =>
buttonArea.RectTransform.MinSize = new Point(Rect.Height, 0);
}*/
PlusButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.5f), buttonArea.RectTransform), "+", font: GUI.GlobalFont);
PlusButton.OnButtonDown += () =>
{ {
pressedTimer = pressedDelay; pressedTimer = pressedDelay;
return true; return true;
}; };
PlusButton.OnClicked += (button, data) => plusButton.OnClicked += (button, data) =>
{ {
IncreaseValue(); IncreaseValue();
return true; return true;
}; };
PlusButton.OnPressed += () => plusButton.OnPressed += () =>
{ {
if (!IsPressedTimerRunning) if (!IsPressedTimerRunning)
{ {
@@ -201,20 +214,20 @@ namespace Barotrauma
} }
return true; return true;
}; };
PlusButton.Visible = inputType == NumberType.Int;
MinusButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.5f), buttonArea.RectTransform, Anchor.BottomRight), "-", font: GUI.GlobalFont); minusButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.5f), buttonArea.RectTransform, Anchor.BottomRight), style: null);
MinusButton.OnButtonDown += () => GUI.Style.Apply(minusButton, "MinusButton", this);
minusButton.OnButtonDown += () =>
{ {
pressedTimer = pressedDelay; pressedTimer = pressedDelay;
return true; return true;
}; };
MinusButton.OnClicked += (button, data) => minusButton.OnClicked += (button, data) =>
{ {
ReduceValue(); ReduceValue();
return true; return true;
}; };
MinusButton.OnPressed += () => minusButton.OnPressed += () =>
{ {
if (!IsPressedTimerRunning) if (!IsPressedTimerRunning)
{ {
@@ -222,7 +235,11 @@ namespace Barotrauma
} }
return true; return true;
}; };
MinusButton.Visible = inputType == NumberType.Int;
if (inputType != NumberType.Int)
{
HidePlusMinusButtons();
}
if (inputType == NumberType.Int) if (inputType == NumberType.Int)
{ {
@@ -257,6 +274,23 @@ namespace Barotrauma
break; break;
} }
RectTransform.MinSize = TextBox.RectTransform.MinSize;
LayoutGroup.Recalculate();
}
private void HidePlusMinusButtons()
{
plusButton.Parent.Visible = false;
plusButton.Parent.IgnoreLayoutGroups = true;
TextBox.RectTransform.RelativeSize = Vector2.One;
LayoutGroup.Recalculate();
}
private void ShowPlusMinusButtons()
{
plusButton.Parent.Visible = true;
plusButton.Parent.IgnoreLayoutGroups = false;
TextBox.RectTransform.RelativeSize = new Vector2(1.0f - plusButton.Parent.RectTransform.RelativeSize.X, 1.0f);
LayoutGroup.Recalculate(); LayoutGroup.Recalculate();
} }
@@ -336,12 +370,12 @@ namespace Barotrauma
if (MinValueFloat != null) if (MinValueFloat != null)
{ {
floatValue = Math.Max(floatValue, MinValueFloat.Value); floatValue = Math.Max(floatValue, MinValueFloat.Value);
MinusButton.Enabled = floatValue > MinValueFloat; minusButton.Enabled = floatValue > MinValueFloat;
} }
if (MaxValueFloat != null) if (MaxValueFloat != null)
{ {
floatValue = Math.Min(floatValue, MaxValueFloat.Value); floatValue = Math.Min(floatValue, MaxValueFloat.Value);
PlusButton.Enabled = floatValue < MaxValueFloat; plusButton.Enabled = floatValue < MaxValueFloat;
} }
} }
@@ -350,12 +384,12 @@ namespace Barotrauma
if (MinValueInt != null) if (MinValueInt != null)
{ {
intValue = Math.Max(intValue, MinValueInt.Value); intValue = Math.Max(intValue, MinValueInt.Value);
MinusButton.Enabled = intValue > MinValueInt; minusButton.Enabled = intValue > MinValueInt;
} }
if (MaxValueInt != null) if (MaxValueInt != null)
{ {
intValue = Math.Min(intValue, MaxValueInt.Value); intValue = Math.Min(intValue, MaxValueInt.Value);
PlusButton.Enabled = intValue < MaxValueInt; plusButton.Enabled = intValue < MaxValueInt;
} }
} }
@@ -10,6 +10,7 @@ namespace Barotrauma
private GUIFrame frame, slider; private GUIFrame frame, slider;
private float barSize; private float barSize;
private bool showFrame;
public delegate float ProgressGetterHandler(); public delegate float ProgressGetterHandler();
public ProgressGetterHandler ProgressGetter; public ProgressGetterHandler ProgressGetter;
@@ -38,7 +39,7 @@ namespace Barotrauma
} }
} }
public GUIProgressBar(RectTransform rectT, float barSize, Color? color = null, string style = "") : base(style, rectT) public GUIProgressBar(RectTransform rectT, float barSize, Color? color = null, string style = "", bool showFrame = true) : base(style, rectT)
{ {
if (color.HasValue) if (color.HasValue)
{ {
@@ -49,12 +50,14 @@ namespace Barotrauma
GUI.Style.Apply(frame, "", this); GUI.Style.Apply(frame, "", this);
slider = new GUIFrame(new RectTransform(Vector2.One, rectT)); slider = new GUIFrame(new RectTransform(Vector2.One, rectT));
GUI.Style.Apply(slider, "Slider", this); GUI.Style.Apply(slider, "Slider", this);
this.showFrame = showFrame;
this.barSize = barSize; this.barSize = barSize;
Enabled = true;
} }
protected override void Draw(SpriteBatch spriteBatch) protected override void Draw(SpriteBatch spriteBatch)
{ {
if (!Visible) return; if (!Visible) { return; }
if (ProgressGetter != null) if (ProgressGetter != null)
{ {
@@ -73,20 +76,31 @@ namespace Barotrauma
} }
Rectangle sliderRect = new Rectangle( Rectangle sliderRect = new Rectangle(
frame.Rect.X, frame.Rect.X + (int)style.Padding.X,
(int)(frame.Rect.Y + (isHorizontal ? 0 : frame.Rect.Height * (1.0f - barSize))), (int)(frame.Rect.Y + (int)style.Padding.Y + (isHorizontal ? 0 : frame.Rect.Height * (1.0f - barSize))),
isHorizontal ? (int)((frame.Rect.Width) * barSize) : frame.Rect.Width, isHorizontal ? (int)((frame.Rect.Width - style.Padding.X - style.Padding.Z) * barSize) : frame.Rect.Width,
isHorizontal ? (int)(frame.Rect.Height) : (int)(frame.Rect.Height * barSize)); isHorizontal ? (int)(frame.Rect.Height - style.Padding.Y - style.Padding.W) : (int)(frame.Rect.Height * barSize));
frame.Visible = true; sliderRect.Width = Math.Max(sliderRect.Width, 1);
sliderRect.Height = Math.Max(sliderRect.Height, 1);
slider.RectTransform.AbsoluteOffset = new Point((int)style.Padding.X, (int)style.Padding.Y);
slider.RectTransform.MaxSize = new Point(
(int)(Rect.Width - style.Padding.X + style.Padding.Z),
(int)(Rect.Height - style.Padding.Y + style.Padding.W));
frame.Visible = showFrame;
slider.Visible = true; slider.Visible = true;
if (AutoDraw)
if (showFrame)
{ {
frame.DrawAuto(spriteBatch); if (AutoDraw)
} {
else frame.DrawAuto(spriteBatch);
{ }
frame.DrawManually(spriteBatch); else
{
frame.DrawManually(spriteBatch);
}
} }
Rectangle prevScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle; Rectangle prevScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle;
@@ -97,7 +111,7 @@ namespace Barotrauma
spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState, rasterizerState: GameMain.ScissorTestEnable); spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState, rasterizerState: GameMain.ScissorTestEnable);
} }
Color currColor = GetCurrentColor(state); Color currColor = GetColor(State);
slider.Color = currColor; slider.Color = currColor;
if (AutoDraw) if (AutoDraw)
@@ -54,8 +54,9 @@ namespace Barotrauma
} }
} }
private int? selected; // intentional hiding?
public int? Selected private new int? selected;
public new int? Selected
{ {
get get
{ {
@@ -64,7 +65,7 @@ namespace Barotrauma
set set
{ {
OnSelect?.Invoke(this, value); OnSelect?.Invoke(this, value);
if (selected != null && selected.Equals(value)) return; if (selected != null && selected.Equals(value)) { return; }
selected = value; selected = value;
foreach (KeyValuePair<int, GUITickBox> radioButton in radioButtons) foreach (KeyValuePair<int, GUITickBox> radioButton in radioButtons)
{ {
@@ -72,7 +73,10 @@ namespace Barotrauma
{ {
radioButton.Value.Selected = true; radioButton.Value.Selected = true;
} }
else if (radioButton.Value.Selected) radioButton.Value.Selected = false; else if (radioButton.Value.Selected)
{
radioButton.Value.Selected = false;
}
} }
} }
} }
@@ -80,7 +80,11 @@ namespace Barotrauma
{ {
enabled = value; enabled = value;
Bar.Enabled = value; Bar.Enabled = value;
if (!enabled) Bar.Selected = false; Children.ForEach(c => c.Enabled = value);
if (!enabled)
{
Bar.Selected = false;
}
} }
} }
@@ -196,7 +200,8 @@ namespace Barotrauma
Frame = new GUIFrame(new RectTransform(Vector2.One, rectT)); Frame = new GUIFrame(new RectTransform(Vector2.One, rectT));
GUI.Style.Apply(Frame, IsHorizontal ? "GUIFrameHorizontal" : "GUIFrameVertical", this); GUI.Style.Apply(Frame, IsHorizontal ? "GUIFrameHorizontal" : "GUIFrameVertical", this);
this.barSize = barSize; this.barSize = barSize;
Bar = new GUIButton(new RectTransform(Vector2.One, rectT, IsHorizontal ? Anchor.CenterLeft : Anchor.TopCenter), color: color);
Bar = new GUIButton(new RectTransform(Vector2.One, rectT, IsHorizontal ? Anchor.CenterLeft : Anchor.TopCenter), color: color, style: null);
switch (style) switch (style)
{ {
@@ -21,16 +21,50 @@ namespace Barotrauma
public ScalableFont UnscaledSmallFont { get; private set; } public ScalableFont UnscaledSmallFont { get; private set; }
public ScalableFont SmallFont { get; private set; } public ScalableFont SmallFont { get; private set; }
public ScalableFont LargeFont { get; private set; } public ScalableFont LargeFont { get; private set; }
public ScalableFont VideoTitleFont { get; private set; } public ScalableFont SubHeadingFont { get; private set; }
public ScalableFont ObjectiveTitleFont { get; private set; } public ScalableFont DigitalFont { get; private set; }
public ScalableFont ObjectiveNameFont { get; private set; }
public Dictionary<ScalableFont, bool> ForceFontUpperCase
{
get;
private set;
} = new Dictionary<ScalableFont, bool>();
public readonly Sprite[] CursorSprite = new Sprite[7]; public readonly Sprite[] CursorSprite = new Sprite[7];
public UISprite UIGlow { get; private set; } public UISprite UIGlow { get; private set; }
public UISprite UIGlowCircular { get; private set; }
public SpriteSheet FocusIndicator { get; private set; } public SpriteSheet FocusIndicator { get; private set; }
/// <summary>
/// General green color used for elements whose colors are set from code
/// </summary>
public Color Green { get; private set; } = Color.LightGreen;
/// <summary>
/// General red color used for elements whose colors are set from code
/// </summary>
public Color Orange { get; private set; } = Color.Orange;
/// <summary>
/// General red color used for elements whose colors are set from code
/// </summary>
public Color Red { get; private set; } = Color.Red;
/// <summary>
/// General blue color used for elements whose colors are set from code
/// </summary>
public Color Blue { get; private set; } = Color.Blue;
public Color TextColor { get; private set; } = Color.White * 0.8f;
public Color TextColorBright { get; private set; } = Color.White * 0.9f;
public Color TextColorDark { get; private set; } = Color.Black * 0.9f;
public Color TextColorDim { get; private set; } = Color.White * 0.6f;
public static Point ItemFrameMargin = new Point(50, 56);
public static Point ItemFrameOffset = new Point(0, 3);
public GUIStyle(XElement element, GraphicsDevice graphicsDevice) public GUIStyle(XElement element, GraphicsDevice graphicsDevice)
{ {
this.graphicsDevice = graphicsDevice; this.graphicsDevice = graphicsDevice;
@@ -48,38 +82,71 @@ namespace Barotrauma
CursorSprite[index] = new Sprite(children); CursorSprite[index] = new Sprite(children);
} }
break; break;
case "green":
Green = subElement.GetAttributeColor("color", Green);
break;
case "orange":
Orange = subElement.GetAttributeColor("color", Orange);
break;
case "red":
Red = subElement.GetAttributeColor("color", Red);
break;
case "blue":
Blue = subElement.GetAttributeColor("color", Blue);
break;
case "textcolordark":
TextColorDark = subElement.GetAttributeColor("color", TextColorDark);
break;
case "TextColorBright":
TextColorBright = subElement.GetAttributeColor("color", TextColorBright);
break;
case "textcolordim":
TextColorDim = subElement.GetAttributeColor("color", TextColorDim);
break;
case "textcolornormal":
case "textcolor":
TextColor = subElement.GetAttributeColor("color", TextColor);
break;
case "uiglow": case "uiglow":
UIGlow = new UISprite(subElement); UIGlow = new UISprite(subElement);
break; break;
case "uiglowcircular":
UIGlowCircular = new UISprite(subElement);
break;
case "focusindicator": case "focusindicator":
FocusIndicator = new SpriteSheet(subElement); FocusIndicator = new SpriteSheet(subElement);
break; break;
case "font": case "font":
Font = LoadFont(subElement, graphicsDevice); Font = LoadFont(subElement, graphicsDevice);
ForceFontUpperCase[Font] = subElement.GetAttributeBool("forceuppercase", false);
break; break;
case "globalfont": case "globalfont":
GlobalFont = LoadFont(subElement, graphicsDevice); GlobalFont = LoadFont(subElement, graphicsDevice);
ForceFontUpperCase[GlobalFont] = subElement.GetAttributeBool("forceuppercase", false);
break; break;
case "unscaledsmallfont": case "unscaledsmallfont":
UnscaledSmallFont = LoadFont(subElement, graphicsDevice); UnscaledSmallFont = LoadFont(subElement, graphicsDevice);
ForceFontUpperCase[UnscaledSmallFont] = subElement.GetAttributeBool("forceuppercase", false);
break; break;
case "smallfont": case "smallfont":
SmallFont = LoadFont(subElement, graphicsDevice); SmallFont = LoadFont(subElement, graphicsDevice);
ForceFontUpperCase[SmallFont] = subElement.GetAttributeBool("forceuppercase", false);
break; break;
case "largefont": case "largefont":
LargeFont = LoadFont(subElement, graphicsDevice); LargeFont = LoadFont(subElement, graphicsDevice);
ForceFontUpperCase[LargeFont] = subElement.GetAttributeBool("forceuppercase", false);
break;
case "digitalfont":
DigitalFont = LoadFont(subElement, graphicsDevice);
ForceFontUpperCase[DigitalFont] = subElement.GetAttributeBool("forceuppercase", false);
break; break;
case "objectivetitle": case "objectivetitle":
ObjectiveTitleFont = LoadFont(subElement, graphicsDevice); case "subheading":
break; SubHeadingFont = LoadFont(subElement, graphicsDevice);
case "objectivename": ForceFontUpperCase[SubHeadingFont] = subElement.GetAttributeBool("forceuppercase", false);
ObjectiveNameFont = LoadFont(subElement, graphicsDevice);
break;
case "videotitle":
VideoTitleFont = LoadFont(subElement, graphicsDevice);
break; break;
default: default:
GUIComponentStyle componentStyle = new GUIComponentStyle(subElement); GUIComponentStyle componentStyle = new GUIComponentStyle(subElement, this);
componentStyles.Add(subElement.Name.ToString().ToLowerInvariant(), componentStyle); componentStyles.Add(subElement.Name.ToString().ToLowerInvariant(), componentStyle);
break; break;
} }
@@ -91,7 +158,7 @@ namespace Barotrauma
DebugConsole.NewMessage("Global font not defined in the current UI style file. The global font is used to render western symbols when using Chinese/Japanese/Korean localization. Using default font instead...", Color.Orange); DebugConsole.NewMessage("Global font not defined in the current UI style file. The global font is used to render western symbols when using Chinese/Japanese/Korean localization. Using default font instead...", Color.Orange);
} }
GameMain.Instance.OnResolutionChanged += () => { RescaleFonts(); }; GameMain.Instance.OnResolutionChanged += () => { RescaleElements(); };
} }
/// <summary> /// <summary>
@@ -114,7 +181,7 @@ namespace Barotrauma
} }
private void RescaleFonts() private void RescaleElements()
{ {
if (configElement == null) { return; } if (configElement == null) { return; }
if (configElement.Elements() == null) { return; } if (configElement.Elements() == null) { return; }
@@ -135,19 +202,21 @@ namespace Barotrauma
LargeFont.Size = GetFontSize(subElement); LargeFont.Size = GetFontSize(subElement);
break; break;
case "objectivetitle": case "objectivetitle":
if (ObjectiveTitleFont == null) { continue; } case "subheading":
ObjectiveTitleFont.Size = GetFontSize(subElement); if (SubHeadingFont == null) { continue; }
break; SubHeadingFont.Size = GetFontSize(subElement);
case "objectivename":
if (ObjectiveNameFont == null) { continue; }
ObjectiveNameFont.Size = GetFontSize(subElement);
break;
case "videotitle":
if (VideoTitleFont == null) { continue; }
VideoTitleFont.Size = GetFontSize(subElement);
break; break;
} }
} }
foreach (var componentStyle in componentStyles.Values)
{
componentStyle.GetSize(componentStyle.Element);
foreach (var childStyle in componentStyle.ChildStyles.Values)
{
childStyle.GetSize(childStyle.Element);
}
}
} }
private ScalableFont LoadFont(XElement element, GraphicsDevice graphicsDevice) private ScalableFont LoadFont(XElement element, GraphicsDevice graphicsDevice)
@@ -16,8 +16,8 @@ namespace Barotrauma
protected Vector2 textPos; protected Vector2 textPos;
protected Vector2 origin; protected Vector2 origin;
protected Color textColor; protected Color textColor, disabledTextColor, selectedTextColor;
private string wrappedText; private string wrappedText;
private string censoredText; private string censoredText;
@@ -63,8 +63,12 @@ namespace Barotrauma
} }
set set
{ {
if (base.Font == value) return; if (base.Font == value) { return; }
base.Font = originalFont = value; base.Font = originalFont = value;
if (text != null && GUI.Style.ForceFontUpperCase.ContainsKey(Font) && GUI.Style.ForceFontUpperCase[Font])
{
Text = text.ToUpper();
}
SetTextPos(); SetTextPos();
} }
} }
@@ -74,11 +78,12 @@ namespace Barotrauma
get { return text; } get { return text; }
set set
{ {
string newText = forceUpperCase ? value?.ToUpper() : value; string newText = forceUpperCase || (GUI.Style.ForceFontUpperCase.ContainsKey(Font) && GUI.Style.ForceFontUpperCase[Font]) || (style != null && style.ForceUpperCase) ?
value?.ToUpper() :
value;
if (Text == newText) { return; } if (Text == newText) { return; }
//reset scale, it gets recalculated in SetTextPos //reset scale, it gets recalculated in SetTextPos
if (autoScale) { textScale = 1.0f; } if (autoScale) { textScale = 1.0f; }
@@ -155,7 +160,9 @@ namespace Barotrauma
if (forceUpperCase == value) { return; } if (forceUpperCase == value) { return; }
forceUpperCase = value; forceUpperCase = value;
if (forceUpperCase) if (forceUpperCase ||
(style != null && style.ForceUpperCase) ||
(GUI.Style.ForceFontUpperCase.ContainsKey(Font) && GUI.Style.ForceFontUpperCase[Font]))
{ {
Text = text?.ToUpper(); Text = text?.ToUpper();
} }
@@ -179,6 +186,19 @@ namespace Barotrauma
set { textColor = value; } set { textColor = value; }
} }
private Color? hoverTextColor;
public Color HoverTextColor
{
get { return hoverTextColor ?? textColor; }
set { hoverTextColor = value; }
}
public Color SelectedTextColor
{
get { return selectedTextColor; }
set { selectedTextColor = value; }
}
public Alignment TextAlignment public Alignment TextAlignment
{ {
get { return textAlignment; } get { return textAlignment; }
@@ -218,7 +238,7 @@ namespace Barotrauma
} }
if (textColor.HasValue) if (textColor.HasValue)
{ {
this.textColor = textColor.Value; OverrideTextColor(textColor.Value);
} }
//if the text is in chinese/korean/japanese and we're not using a CJK-compatible font, //if the text is in chinese/korean/japanese and we're not using a CJK-compatible font,
@@ -242,6 +262,7 @@ namespace Barotrauma
RectTransform.ScaleChanged += SetTextPos; RectTransform.ScaleChanged += SetTextPos;
RectTransform.SizeChanged += SetTextPos; RectTransform.SizeChanged += SetTextPos;
Enabled = true;
Censor = false; Censor = false;
} }
public GUITextBlock(RectTransform rectT, List<ColorData> colorData, string text, Color? textColor = null, ScalableFont font = null, Alignment textAlignment = Alignment.Left, bool wrap = false, string style = "", Color? color = null, bool playerInput = false) public GUITextBlock(RectTransform rectT, List<ColorData> colorData, string text, Color? textColor = null, ScalableFont font = null, Alignment textAlignment = Alignment.Left, bool wrap = false, string style = "", Color? color = null, bool playerInput = false)
@@ -257,13 +278,33 @@ namespace Barotrauma
RectTransform.Resize(new Point(RectTransform.Rect.Width, (int)Font.MeasureString(wrappedText).Y + padding)); RectTransform.Resize(new Point(RectTransform.Rect.Width, (int)Font.MeasureString(wrappedText).Y + padding));
} }
public override void ApplyStyle(GUIComponentStyle style) public override void ApplyStyle(GUIComponentStyle componentStyle)
{ {
if (style == null) return; if (componentStyle == null) { return; }
base.ApplyStyle(style); base.ApplyStyle(componentStyle);
padding = style.Padding; padding = componentStyle.Padding;
textColor = style.textColor; textColor = componentStyle.TextColor;
hoverTextColor = componentStyle.HoverTextColor;
disabledTextColor = componentStyle.DisabledTextColor;
selectedTextColor = componentStyle.SelectedTextColor;
switch (componentStyle.Font)
{
case "font":
Font = componentStyle.Style.Font;
break;
case "smallfont":
Font = componentStyle.Style.SmallFont;
break;
case "largefont":
Font = componentStyle.Style.LargeFont;
break;
case "objectivetitle":
case "subheading":
Font = componentStyle.Style.SubHeadingFont;
break;
}
} }
public void SetTextPos() public void SetTextPos()
@@ -293,11 +334,14 @@ namespace Barotrauma
overflowClipActive = TextSize.X > rect.Width - padding.X - padding.Z; overflowClipActive = TextSize.X > rect.Width - padding.X - padding.Z;
} }
Vector2 minSize = new Vector2(
Math.Max(rect.Width - padding.X - padding.Z, 5.0f),
Math.Max(rect.Height - padding.Y - padding.W, 5.0f));
if (autoScale && textScale > 0.1f && if (autoScale && textScale > 0.1f &&
(TextSize.X * textScale > rect.Width - padding.X - padding.Z || TextSize.Y * textScale > rect.Height - padding.Y - padding.W)) (TextSize.X * textScale > minSize.X || TextSize.Y * textScale > minSize.Y))
{ {
TextScale = Math.Max(0.1f, Math.Min( TextScale = Math.Max(0.1f, Math.Min(
(rect.Width - padding.X - padding.Z) / TextSize.X, (rect.Width - padding.X - padding.Z) / TextSize.X,
(rect.Height - padding.Y - padding.W) / TextSize.Y)) - 0.01f; (rect.Height - padding.Y - padding.W) / TextSize.Y)) - 0.01f;
return; return;
} }
@@ -358,17 +402,28 @@ namespace Barotrauma
textColor = new Color(textColor.R, textColor.G, textColor.B, a); textColor = new Color(textColor.R, textColor.G, textColor.B, a);
} }
/// <summary>
/// Overrides the color for all the states.
/// </summary>
public void OverrideTextColor(Color color)
{
textColor = color;
hoverTextColor = color;
selectedTextColor = color;
disabledTextColor = color;
}
protected override void Draw(SpriteBatch spriteBatch) protected override void Draw(SpriteBatch spriteBatch)
{ {
if (!Visible) return; if (!Visible) { return; }
Color currColor = GetCurrentColor(state); Color currColor = GetColor(State);
var rect = Rect; var rect = Rect;
base.Draw(spriteBatch); base.Draw(spriteBatch);
if (TextGetter != null) Text = TextGetter(); if (TextGetter != null) { Text = TextGetter(); }
Rectangle prevScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle; Rectangle prevScissorRect = spriteBatch.GraphicsDevice.ScissorRectangle;
if (overflowClipActive) if (overflowClipActive)
@@ -388,19 +443,29 @@ namespace Barotrauma
pos.Y = (int)pos.Y; pos.Y = (int)pos.Y;
} }
Color currentTextColor = State == ComponentState.Hover || State == ComponentState.HoverSelected ? HoverTextColor : TextColor;
if (!enabled)
{
currentTextColor = disabledTextColor;
}
else if (State == ComponentState.Selected)
{
currentTextColor = selectedTextColor;
}
if (!hasColorHighlight) if (!hasColorHighlight)
{ {
Font.DrawString(spriteBatch, Font.DrawString(spriteBatch,
Censor ? censoredText : (Wrap ? wrappedText : text), Censor ? censoredText : (Wrap ? wrappedText : text),
pos, pos,
textColor * (textColor.A / 255.0f), currentTextColor * (currentTextColor.A / 255.0f),
0.0f, origin, TextScale, 0.0f, origin, TextScale,
SpriteEffects.None, textDepth); SpriteEffects.None, textDepth);
} }
else else
{ {
Font.DrawStringWithColors(spriteBatch, Censor ? censoredText : (Wrap ? wrappedText : text), pos, Font.DrawStringWithColors(spriteBatch, Censor ? censoredText : (Wrap ? wrappedText : text), pos,
textColor * (textColor.A / 255.0f), 0.0f, origin, TextScale, SpriteEffects.None, textDepth, colorData); currentTextColor * (currentTextColor.A / 255.0f), 0.0f, origin, TextScale, SpriteEffects.None, textDepth, colorData);
} }
} }
@@ -21,6 +21,7 @@ namespace Barotrauma
private readonly GUIFrame frame; private readonly GUIFrame frame;
private readonly GUITextBlock textBlock; private readonly GUITextBlock textBlock;
private readonly GUIImage icon;
public Func<string, string> textFilterFunction; public Func<string, string> textFilterFunction;
@@ -74,6 +75,7 @@ namespace Barotrauma
set { textBlock.TextGetter = value; } set { textBlock.TextGetter = value; }
} }
// TODO: fix implicit hiding
private bool selected; private bool selected;
public bool Selected public bool Selected
{ {
@@ -103,6 +105,11 @@ namespace Barotrauma
} }
} }
public GUITextBlock TextBlock
{
get { return textBlock; }
}
//should the text be limited to the size of the box //should the text be limited to the size of the box
//ignored when MaxTextLength is set or text wrapping is enabled //ignored when MaxTextLength is set or text wrapping is enabled
public bool ClampText public bool ClampText
@@ -132,7 +139,8 @@ namespace Barotrauma
get { return enabled; } get { return enabled; }
set set
{ {
enabled = value; enabled = frame.Enabled = textBlock.Enabled = value;
if (icon != null) { icon.Enabled = value; }
if (!enabled && Selected) if (!enabled && Selected)
{ {
Deselect(); Deselect();
@@ -228,25 +236,58 @@ namespace Barotrauma
} }
public GUITextBox(RectTransform rectT, string text = "", Color? textColor = null, ScalableFont font = null, public GUITextBox(RectTransform rectT, string text = "", Color? textColor = null, ScalableFont font = null,
Alignment textAlignment = Alignment.Left, bool wrap = false, string style = "", Color? color = null) Alignment textAlignment = Alignment.Left, bool wrap = false, string style = "", Color? color = null, bool createClearButton = false)
: base(style, rectT) : base(style, rectT)
{ {
HoverCursor = CursorState.IBeam; HoverCursor = CursorState.IBeam;
CanBeFocused = true; CanBeFocused = true;
Enabled = true;
this.color = color ?? Color.White; this.color = color ?? Color.White;
frame = new GUIFrame(new RectTransform(Vector2.One, rectT, Anchor.Center), style, color); frame = new GUIFrame(new RectTransform(Vector2.One, rectT, Anchor.Center), style, color);
GUI.Style.Apply(frame, style == "" ? "GUITextBox" : style); GUI.Style.Apply(frame, style == "" ? "GUITextBox" : style);
textBlock = new GUITextBlock(new RectTransform(Vector2.One, frame.RectTransform, Anchor.Center), text, textColor, font, textAlignment, wrap, playerInput: true); textBlock = new GUITextBlock(new RectTransform(Vector2.One, frame.RectTransform, Anchor.CenterLeft), text, textColor, font, textAlignment, wrap, playerInput: true);
GUI.Style.Apply(textBlock, "", this); GUI.Style.Apply(textBlock, "", this);
CaretEnabled = true; CaretEnabled = true;
caretPosDirty = true; caretPosDirty = true;
new GUICustomComponent(new RectTransform(Vector2.One, frame.RectTransform), onDraw: DrawCaretAndSelection);
int clearButtonWidth = 0;
if (createClearButton)
{
var clearButton = new GUIButton(new RectTransform(new Vector2(0.6f, 0.6f), frame.RectTransform, Anchor.CenterRight, scaleBasis: ScaleBasis.BothHeight) { AbsoluteOffset = new Point(5, 0) }, style: "GUICancelButton")
{
OnClicked = (bt, userdata) =>
{
Text = "";
frame.Flash(Color.White);
return true;
}
};
textBlock.RectTransform.MaxSize = new Point(frame.Rect.Width - clearButton.Rect.Height - clearButton.RectTransform.AbsoluteOffset.X * 2, int.MaxValue);
clearButtonWidth = (int)(clearButton.Rect.Width * 1.2f);
}
if (this.style != null && this.style.ChildStyles.ContainsKey("textboxicon"))
{
icon = new GUIImage(new RectTransform(new Vector2(0.6f, 0.6f), frame.RectTransform, Anchor.CenterRight, scaleBasis: ScaleBasis.BothHeight) { AbsoluteOffset = new Point(5 + clearButtonWidth, 0) }, null, scaleToFit: true);
icon.ApplyStyle(this.style.ChildStyles["textboxicon"]);
textBlock.RectTransform.MaxSize = new Point(frame.Rect.Width - icon.Rect.Height - clearButtonWidth - icon.RectTransform.AbsoluteOffset.X * 2, int.MaxValue);
}
Font = textBlock.Font; Font = textBlock.Font;
rectT.SizeChanged += () => { caretPosDirty = true; }; Enabled = true;
rectT.ScaleChanged += () => { caretPosDirty = true; };
rectT.SizeChanged += () =>
{
if (icon != null) { textBlock.RectTransform.MaxSize = new Point(frame.Rect.Width - icon.Rect.Height - icon.RectTransform.AbsoluteOffset.X * 2, int.MaxValue); }
caretPosDirty = true;
};
rectT.ScaleChanged += () =>
{
if (icon != null) { textBlock.RectTransform.MaxSize = new Point(frame.Rect.Width - icon.Rect.Height - icon.RectTransform.AbsoluteOffset.X * 2, int.MaxValue); }
caretPosDirty = true;
};
} }
private bool SetText(string text, bool store = true) private bool SetText(string text, bool store = true)
@@ -441,9 +482,9 @@ namespace Barotrauma
OnDeselected?.Invoke(this, Keys.None); OnDeselected?.Invoke(this, Keys.None);
} }
public override void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, Vector2? flashRectOffset = null) public override void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, bool useCircularFlash = false, Vector2? flashRectOffset = null)
{ {
textBlock.Flash(color, flashDuration, useRectangleFlash, flashRectOffset); frame.Flash(color, flashDuration, useRectangleFlash, useCircularFlash, flashRectOffset);
} }
protected override void Update(float deltaTime) protected override void Update(float deltaTime)
@@ -451,10 +492,10 @@ namespace Barotrauma
if (!Visible) return; if (!Visible) return;
if (flashTimer > 0.0f) flashTimer -= deltaTime; if (flashTimer > 0.0f) flashTimer -= deltaTime;
if (!Enabled) return; if (!Enabled) { return; }
if (MouseRect.Contains(PlayerInput.MousePosition) && (GUI.MouseOn == null || GUI.IsMouseOn(this))) if (MouseRect.Contains(PlayerInput.MousePosition) && (GUI.MouseOn == null || (!(GUI.MouseOn is GUIButton) && GUI.IsMouseOn(this))))
{ {
state = ComponentState.Hover; State = ComponentState.Hover;
if (PlayerInput.PrimaryMouseButtonDown()) if (PlayerInput.PrimaryMouseButtonDown())
{ {
Select(); Select();
@@ -481,7 +522,7 @@ namespace Barotrauma
{ {
if ((PlayerInput.LeftButtonClicked() || PlayerInput.RightButtonClicked()) && selected) Deselect(); if ((PlayerInput.LeftButtonClicked() || PlayerInput.RightButtonClicked()) && selected) Deselect();
isSelecting = false; isSelecting = false;
state = ComponentState.None; State = ComponentState.None;
} }
if (!isSelecting) if (!isSelecting)
{ {
@@ -492,14 +533,14 @@ namespace Barotrauma
{ {
if (textBlock.OverflowClipActive) if (textBlock.OverflowClipActive)
{ {
if (CaretScreenPos.X < Rect.X + textBlock.Padding.X) if (CaretScreenPos.X < textBlock.Rect.X + textBlock.Padding.X)
{ {
textBlock.TextPos = new Vector2(textBlock.TextPos.X + ((Rect.X + textBlock.Padding.X) - CaretScreenPos.X), textBlock.TextPos.Y); textBlock.TextPos = new Vector2(textBlock.TextPos.X + ((textBlock.Rect.X + textBlock.Padding.X) - CaretScreenPos.X), textBlock.TextPos.Y);
CalculateCaretPos(); CalculateCaretPos();
} }
else if (CaretScreenPos.X > Rect.Right - textBlock.Padding.Z) else if (CaretScreenPos.X > textBlock.Rect.Right - textBlock.Padding.Z)
{ {
textBlock.TextPos = new Vector2(textBlock.TextPos.X - (CaretScreenPos.X - (Rect.Right - textBlock.Padding.Z)), textBlock.TextPos.Y); textBlock.TextPos = new Vector2(textBlock.TextPos.X - (CaretScreenPos.X - (textBlock.Rect.Right - textBlock.Padding.Z)), textBlock.TextPos.Y);
CalculateCaretPos(); CalculateCaretPos();
} }
} }
@@ -513,7 +554,7 @@ namespace Barotrauma
if (GUI.KeyboardDispatcher.Subscriber == this) if (GUI.KeyboardDispatcher.Subscriber == this)
{ {
state = ComponentState.Selected; State = ComponentState.Selected;
Character.DisableControls = true; Character.DisableControls = true;
if (OnEnterPressed != null && PlayerInput.KeyHit(Keys.Enter)) if (OnEnterPressed != null && PlayerInput.KeyHit(Keys.Enter))
{ {
@@ -525,16 +566,12 @@ namespace Barotrauma
Deselect(); Deselect();
} }
textBlock.State = state; textBlock.State = State;
} }
protected override void Draw(SpriteBatch spriteBatch) private void DrawCaretAndSelection(SpriteBatch spriteBatch, GUICustomComponent customComponent)
{ {
if (!Visible) return; if (!Visible) { return; }
base.Draw(spriteBatch);
// Frame is not used in the old system.
frame?.DrawManually(spriteBatch);
textBlock.DrawManually(spriteBatch);
if (Selected) if (Selected)
{ {
if (caretVisible ) if (caretVisible )
@@ -552,9 +589,9 @@ namespace Barotrauma
//GUI.DrawString(spriteBatch, new Vector2(100, 20), selectionStartIndex.ToString(), Color.White, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(100, 20), selectionStartIndex.ToString(), Color.White, Color.Black);
//GUI.DrawString(spriteBatch, new Vector2(140, 20), selectionEndIndex.ToString(), Color.White, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(140, 20), selectionEndIndex.ToString(), Color.White, Color.Black);
//GUI.DrawString(spriteBatch, new Vector2(100, 40), selectedText.ToString(), Color.Yellow, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(100, 40), selectedText.ToString(), Color.Yellow, Color.Black);
//GUI.DrawString(spriteBatch, new Vector2(100, 60), $"caret index: {CaretIndex.ToString()}", Color.Red, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(100, 60), $"caret index: {CaretIndex.ToString()}", GUI.Style.Red, Color.Black);
//GUI.DrawString(spriteBatch, new Vector2(100, 80), $"caret pos: {caretPos.ToString()}", Color.Red, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(100, 80), $"caret pos: {caretPos.ToString()}", GUI.Style.Red, Color.Black);
//GUI.DrawString(spriteBatch, new Vector2(100, 100), $"caret screen pos: {CaretScreenPos.ToString()}", Color.Red, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(100, 100), $"caret screen pos: {CaretScreenPos.ToString()}", GUI.Style.Red, Color.Black);
//GUI.DrawString(spriteBatch, new Vector2(100, 120), $"text start pos: {(textBlock.TextPos - textBlock.Origin).ToString()}", Color.White, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(100, 120), $"text start pos: {(textBlock.TextPos - textBlock.Origin).ToString()}", Color.White, Color.Black);
//GUI.DrawString(spriteBatch, new Vector2(100, 140), $"cursor pos: {PlayerInput.MousePosition.ToString()}", Color.White, Color.Black); //GUI.DrawString(spriteBatch, new Vector2(100, 140), $"cursor pos: {PlayerInput.MousePosition.ToString()}", Color.White, Color.Black);
} }
@@ -805,7 +842,7 @@ namespace Barotrauma
} }
} }
} }
IEnumerable<GUITextBox> GetAndSortTextBoxes(GUIComponent parent) => parent.GetAllChildren().Select(c => c as GUITextBox).Where(t => t != null).OrderBy(t => t.Rect.Y).ThenBy(t => t.Rect.X); IEnumerable<GUITextBox> GetAndSortTextBoxes(GUIComponent parent) => parent.GetAllChildren<GUITextBox>().OrderBy(t => t.Rect.Y).ThenBy(t => t.Rect.X);
GUITextBox SelectNextTextBox(GUIListBox listBox) GUITextBox SelectNextTextBox(GUIListBox listBox)
{ {
var textBoxes = GetAndSortTextBoxes(listBox.SelectedComponent); var textBoxes = GetAndSortTextBoxes(listBox.SelectedComponent);
@@ -18,14 +18,12 @@ namespace Barotrauma
private GUIRadioButtonGroup radioButtonGroup; private GUIRadioButtonGroup radioButtonGroup;
private bool selected; public override bool Selected
public bool Selected
{ {
get { return selected; } get { return selected; }
set set
{ {
if (value == selected) return; if (value == selected) { return; }
if (radioButtonGroup != null && radioButtonGroup.SelectedRadioButton == this) if (radioButtonGroup != null && radioButtonGroup.SelectedRadioButton == this)
{ {
selected = true; selected = true;
@@ -33,8 +31,7 @@ namespace Barotrauma
} }
selected = value; selected = value;
state = (selected) ? ComponentState.Selected : ComponentState.None; State = selected ? ComponentState.Selected : ComponentState.None;
box.State = state;
if (value && radioButtonGroup != null) if (value && radioButtonGroup != null)
{ {
radioButtonGroup.SelectRadioButton(this); radioButtonGroup.SelectRadioButton(this);
@@ -44,7 +41,18 @@ namespace Barotrauma
} }
} }
private Color? defaultTextColor; public override ComponentState State
{
get
{
return base.State;
}
set
{
base.State = value;
box.State = TextBlock.State = value;
}
}
public override bool Enabled public override bool Enabled
{ {
@@ -56,12 +64,7 @@ namespace Barotrauma
set set
{ {
if (value == enabled) { return; } if (value == enabled) { return; }
enabled = value; enabled = box.Enabled = TextBlock.Enabled = value;
if (color.A == 0)
{
if (defaultTextColor == null) { defaultTextColor = TextBlock.TextColor; }
TextBlock.TextColor = enabled ? defaultTextColor.Value : defaultTextColor.Value * 0.5f;
}
} }
} }
@@ -126,11 +129,6 @@ namespace Barotrauma
set { text.Text = value; } set { text.Text = value; }
} }
public Color? DefaultTextColor
{
get { return defaultTextColor; }
}
public GUITickBox(RectTransform rectT, string label, ScalableFont font = null, string style = "") : base(null, rectT) public GUITickBox(RectTransform rectT, string label, ScalableFont font = null, string style = "") : base(null, rectT)
{ {
CanBeFocused = true; CanBeFocused = true;
@@ -138,9 +136,9 @@ namespace Barotrauma
layoutGroup = new GUILayoutGroup(new RectTransform(Vector2.One, rectT), true); layoutGroup = new GUILayoutGroup(new RectTransform(Vector2.One, rectT), true);
box = new GUIFrame(new RectTransform(Vector2.One, layoutGroup.RectTransform, scaleBasis: ScaleBasis.BothHeight) box = new GUIFrame(new RectTransform(Vector2.One, layoutGroup.RectTransform, Anchor.CenterLeft, scaleBasis: ScaleBasis.BothHeight)
{ {
IsFixedSize = false IsFixedSize = true
}, string.Empty, Color.DarkGray) }, string.Empty, Color.DarkGray)
{ {
HoverColor = Color.Gray, HoverColor = Color.Gray,
@@ -148,12 +146,20 @@ namespace Barotrauma
CanBeFocused = false CanBeFocused = false
}; };
GUI.Style.Apply(box, style == "" ? "GUITickBox" : style); GUI.Style.Apply(box, style == "" ? "GUITickBox" : style);
if (box.RectTransform.MinSize.Y > 0)
{
RectTransform.MinSize = box.RectTransform.MinSize;
RectTransform.MaxSize = box.RectTransform.MaxSize;
RectTransform.Resize(new Point(RectTransform.NonScaledSize.X, RectTransform.MinSize.Y));
box.RectTransform.MinSize = new Point(box.RectTransform.MinSize.Y);
box.RectTransform.Resize(box.RectTransform.MinSize);
}
Vector2 textBlockScale = new Vector2((float)(Rect.Width - Rect.Height) / (float)Math.Max(Rect.Width, 1.0), 1.0f); Vector2 textBlockScale = new Vector2((float)(Rect.Width - Rect.Height) / (float)Math.Max(Rect.Width, 1.0), 1.0f);
text = new GUITextBlock(new RectTransform(textBlockScale, layoutGroup.RectTransform), label, font: font, textAlignment: Alignment.CenterLeft) text = new GUITextBlock(new RectTransform(textBlockScale, layoutGroup.RectTransform, Anchor.CenterLeft), label, font: font, textAlignment: Alignment.CenterLeft)
{ {
CanBeFocused = false CanBeFocused = false
}; };
GUI.Style.Apply(text, "GUIButtonHorizontal", this); GUI.Style.Apply(text, "GUITextBlock", this);
Enabled = true; Enabled = true;
ResizeBox(); ResizeBox();
@@ -171,21 +177,26 @@ namespace Barotrauma
{ {
Vector2 textBlockScale = new Vector2(Math.Max(Rect.Width - box.Rect.Width, 0.0f) / Math.Max(Rect.Width, 1.0f), 1.0f); Vector2 textBlockScale = new Vector2(Math.Max(Rect.Width - box.Rect.Width, 0.0f) / Math.Max(Rect.Width, 1.0f), 1.0f);
text.RectTransform.RelativeSize = textBlockScale; text.RectTransform.RelativeSize = textBlockScale;
box.RectTransform.MinSize = new Point(Rect.Height);
box.RectTransform.Resize(box.RectTransform.MinSize);
text.SetTextPos(); text.SetTextPos();
} }
protected override void Update(float deltaTime) protected override void Update(float deltaTime)
{ {
if (!Visible) return; if (!Visible) { return; }
base.Update(deltaTime); base.Update(deltaTime);
if (GUI.MouseOn == this && Enabled) if (GUI.MouseOn == this && Enabled)
{ {
box.State = ComponentState.Hover; State = Selected ?
ComponentState.HoverSelected :
ComponentState.Hover;
if (PlayerInput.PrimaryMouseButtonHeld()) if (PlayerInput.PrimaryMouseButtonHeld())
{ {
box.State = ComponentState.Selected; State = ComponentState.Selected;
} }
if (PlayerInput.PrimaryMouseButtonClicked()) if (PlayerInput.PrimaryMouseButtonClicked())
@@ -200,14 +211,13 @@ namespace Barotrauma
} }
} }
} }
else if (selected)
{
State = ComponentState.Selected;
}
else else
{ {
box.State = ComponentState.None; State = ComponentState.None;
}
if (selected)
{
box.State = ComponentState.Selected;
} }
} }
} }
@@ -45,11 +45,6 @@ namespace Barotrauma
get; private set; get; private set;
} }
public static Alignment ChatBoxAlignment
{
get; private set;
}
public static Rectangle ObjectiveAnchor public static Rectangle ObjectiveAnchor
{ {
get; private set; get; private set;
@@ -60,6 +55,10 @@ namespace Barotrauma
get; private set; get; private set;
} }
/*public static Rectangle HealthBarAreaRight
{
get; private set;
}*/
public static Rectangle HealthBarAreaLeft public static Rectangle HealthBarAreaLeft
{ {
get; private set; get; private set;
@@ -69,26 +68,17 @@ namespace Barotrauma
get; private set; get; private set;
} }
public static Rectangle HealthBarAreaRight
{
get; private set;
}
public static Rectangle AfflictionAreaRight
{
get; private set;
}
public static Rectangle HealthWindowAreaLeft public static Rectangle HealthWindowAreaLeft
{ {
get; private set; get; private set;
} }
public static Rectangle HealthWindowAreaRight public static Rectangle PortraitArea
{ {
get; private set; get; private set;
} }
public static Rectangle PortraitArea public static Rectangle PortraitTooltipArea
{ {
get; private set; get; private set;
} }
@@ -125,74 +115,66 @@ namespace Barotrauma
//slice from the top of the screen for misc buttons (info, end round, server controls) //slice from the top of the screen for misc buttons (info, end round, server controls)
ButtonAreaTop = new Rectangle(Padding, Padding, GameMain.GraphicsWidth - Padding * 2, (int)(50 * GUI.Scale)); ButtonAreaTop = new Rectangle(Padding, Padding, GameMain.GraphicsWidth - Padding * 2, (int)(50 * GUI.Scale));
int crewAreaHeight = (int)Math.Max(GameMain.GraphicsHeight * 0.22f, 150); int portraitSize = (int)(125 * GUI.Scale);
CrewArea = new Rectangle(Padding, ButtonAreaTop.Bottom + Padding, GameMain.GraphicsWidth - InventoryAreaUpper.Width - Padding * 3, crewAreaHeight); PortraitArea = new Rectangle(Padding * 2, Padding * 2, portraitSize, portraitSize);
PortraitTooltipArea = new Rectangle(PortraitArea.X + portraitSize / 2 + Padding, PortraitArea.Top - portraitSize, portraitSize, portraitSize);
int portraitSize = (int)(100 * GUI.Scale);
PortraitArea = new Rectangle(GameMain.GraphicsWidth - portraitSize - Padding, GameMain.GraphicsHeight - portraitSize - Padding, portraitSize, portraitSize);
//horizontal slices at the corners of the screen for health bar and affliction icons //horizontal slices at the corners of the screen for health bar and affliction icons
int healthBarWidth = (int)Math.Max(250 * GUI.Scale, 150); int healthBarWidth = (int)Math.Max(250 * GUI.Scale, 150);
int healthBarHeight = (int)Math.Max(20 * GUI.Scale, 15); int healthBarHeight = (int)Math.Max(15f * GUI.Scale, 12.5f);
int afflictionAreaHeight = (int)(60 * GUI.Scale); int afflictionAreaHeight = (int)(50 * GUI.Scale);
HealthBarAreaLeft = new Rectangle(Padding, GameMain.GraphicsHeight - healthBarHeight - Padding, healthBarWidth, healthBarHeight); HealthBarAreaLeft = new Rectangle(PortraitArea.X, PortraitArea.Y + Padding / 2 + portraitSize, healthBarWidth, healthBarHeight);
AfflictionAreaLeft = new Rectangle(Padding, HealthBarAreaLeft.Y - afflictionAreaHeight - Padding, healthBarWidth, afflictionAreaHeight); AfflictionAreaLeft = new Rectangle(Padding, HealthBarAreaLeft.Y - afflictionAreaHeight - Padding, healthBarWidth, afflictionAreaHeight);
HealthBarAreaRight = new Rectangle(PortraitArea.X - Padding - healthBarWidth, Math.Min(PortraitArea.Y + Padding * 3, inventoryTopY - healthBarHeight), healthBarWidth, HealthBarAreaLeft.Height); //HealthBarAreaRight = new Rectangle(Padding, GameMain.GraphicsHeight - healthBarHeight - Padding, healthBarWidth, healthBarHeight);
if (HealthBarAreaRight.Y + healthBarHeight * 0.75f < PortraitArea.Y) /*if (HealthBarAreaRight.Y + healthBarHeight * 0.75f < PortraitArea.Y)
{ {
HealthBarAreaRight = new Rectangle(GameMain.GraphicsWidth - Padding - healthBarWidth, HealthBarAreaRight.Y, HealthBarAreaRight.Width, HealthBarAreaRight.Height); HealthBarAreaRight = new Rectangle(GameMain.GraphicsWidth - Padding - healthBarWidth, HealthBarAreaRight.Y, HealthBarAreaRight.Width, HealthBarAreaRight.Height);
} }*/
AfflictionAreaRight = new Rectangle(HealthBarAreaRight.X, HealthBarAreaRight.Y - Padding - afflictionAreaHeight, healthBarWidth, afflictionAreaHeight); //AfflictionAreaRight = new Rectangle(HealthBarAreaRight.X, HealthBarAreaRight.Y + healthBarHeight + Padding, healthBarWidth, afflictionAreaHeight);
int messageAreaWidth = GameMain.GraphicsWidth / 3; int messageAreaWidth = GameMain.GraphicsWidth / 3;
MessageAreaTop = new Rectangle((GameMain.GraphicsWidth - messageAreaWidth) / 2, ButtonAreaTop.Bottom, messageAreaWidth, ButtonAreaTop.Height); MessageAreaTop = new Rectangle((GameMain.GraphicsWidth - messageAreaWidth) / 2, ButtonAreaTop.Bottom, messageAreaWidth, ButtonAreaTop.Height);
CrewArea = new Rectangle(HealthBarAreaLeft.Right + Padding, MessageAreaTop.Bottom + Padding,
GameMain.GraphicsWidth - HealthBarAreaLeft.Right - 2 * Padding, (int)(0.6f * portraitSize));
//slice for the upper slots of the inventory (clothes, id card, headset) //slice for the upper slots of the inventory (clothes, id card, headset)
int inventoryAreaUpperWidth = (int)(GameMain.GraphicsWidth * 0.2f); int inventoryAreaUpperWidth = (int)(GameMain.GraphicsWidth * 0.2f);
int inventoryAreaUpperHeight = (int)(GameMain.GraphicsHeight * 0.2f); int inventoryAreaUpperHeight = (int)(GameMain.GraphicsHeight * 0.2f);
InventoryAreaUpper = new Rectangle(GameMain.GraphicsWidth - inventoryAreaUpperWidth - Padding, CrewArea.Y, inventoryAreaUpperWidth, inventoryAreaUpperHeight); InventoryAreaUpper = new Rectangle(GameMain.GraphicsWidth - inventoryAreaUpperWidth - Padding, CrewArea.Y, inventoryAreaUpperWidth, inventoryAreaUpperHeight);
//chatbox between upper and lower inventory areas, can be on either side depending on the alignment int toggleButtonWidth = (int)(ChatBox.ToggleButtonWidthRaw * GUI.Scale);
ChatBoxAlignment = Alignment.Right; int chatBoxWidth = (int)(475 * GUI.Scale);
int chatBoxWidth = (int)(500 * GUI.Scale); int chatBoxHeight = (int)Math.Max(GameMain.GraphicsHeight * 0.22f, 150);
int chatBoxHeight = crewAreaHeight; ChatBoxArea = new Rectangle(Padding + toggleButtonWidth, GameMain.GraphicsHeight - Padding - chatBoxHeight, chatBoxWidth, chatBoxHeight);
ChatBoxArea = ChatBoxAlignment == Alignment.Left ?
new Rectangle(Padding, CrewArea.Y, chatBoxWidth, chatBoxHeight) :
new Rectangle(GameMain.GraphicsWidth - Padding - chatBoxWidth, CrewArea.Y, chatBoxWidth, chatBoxHeight);
int objectiveAnchorWidth = (int)(250 * GUI.Scale); int objectiveAnchorWidth = (int)(250 * GUI.Scale);
int objectiveAnchorOffsetY = (int)(100 * GUI.Scale); int objectiveAnchorOffsetY = (int)(150 * GUI.Scale);
ObjectiveAnchor = new Rectangle(GameMain.GraphicsWidth - Padding - objectiveAnchorWidth, CrewArea.Y + crewAreaHeight + objectiveAnchorOffsetY, objectiveAnchorWidth, 0); ObjectiveAnchor = new Rectangle(Padding, ChatBoxArea.Y - objectiveAnchorOffsetY, objectiveAnchorWidth, 0);
int lowerAreaHeight = (int)Math.Min(GameMain.GraphicsHeight * 0.25f, 280); int lowerAreaHeight = (int)Math.Min(GameMain.GraphicsHeight * 0.25f, 280);
InventoryAreaLower = new Rectangle(Padding, GameMain.GraphicsHeight - lowerAreaHeight, GameMain.GraphicsWidth - Padding * 2, lowerAreaHeight); InventoryAreaLower = new Rectangle(Padding, GameMain.GraphicsHeight - lowerAreaHeight, GameMain.GraphicsWidth - Padding * 2, lowerAreaHeight);
int healthWindowY = CrewArea.Bottom + Padding; int healthWindowWidth = (int)(GameMain.GraphicsWidth * 0.5f);
Rectangle healthWindowArea = ChatBoxAlignment == Alignment.Left ? int healthWindowHeight = (int)(GameMain.GraphicsWidth * 0.5f * 0.65f);
new Rectangle(ChatBoxArea.Right + Padding, healthWindowY, GameMain.GraphicsWidth - ChatBoxArea.Width - inventoryAreaUpperWidth, GameMain.GraphicsHeight - healthWindowY - lowerAreaHeight / 2) : int healthWindowX = GameMain.GraphicsWidth / 2 - healthWindowWidth / 2;
new Rectangle(Padding - ChatBoxArea.Width, healthWindowY, GameMain.GraphicsWidth - ChatBoxArea.Width - inventoryAreaUpperWidth, GameMain.GraphicsHeight - healthWindowY - lowerAreaHeight / 2); int healthWindowY = GameMain.GraphicsHeight / 2 - healthWindowHeight / 2;
int healthWindowPadding = Padding * 3; HealthWindowAreaLeft = new Rectangle(healthWindowX, healthWindowY, healthWindowWidth, healthWindowHeight);
HealthWindowAreaLeft = new Rectangle(healthWindowPadding, healthWindowY, GameMain.GraphicsWidth / 2 - healthWindowPadding, GameMain.GraphicsHeight - healthWindowY - lowerAreaHeight);
HealthWindowAreaRight = new Rectangle(GameMain.GraphicsWidth / 2, healthWindowY, GameMain.GraphicsWidth / 2 - healthWindowPadding, GameMain.GraphicsHeight - healthWindowY - lowerAreaHeight);
} }
public static void Draw(SpriteBatch spriteBatch) public static void Draw(SpriteBatch spriteBatch)
{ {
GUI.DrawRectangle(spriteBatch, ButtonAreaTop, Color.White * 0.5f); GUI.DrawRectangle(spriteBatch, ButtonAreaTop, Color.White * 0.5f);
GUI.DrawRectangle(spriteBatch, MessageAreaTop, Color.Orange * 0.5f); GUI.DrawRectangle(spriteBatch, MessageAreaTop, GUI.Style.Orange * 0.5f);
GUI.DrawRectangle(spriteBatch, InventoryAreaUpper, Color.Yellow * 0.5f); GUI.DrawRectangle(spriteBatch, InventoryAreaUpper, Color.Yellow * 0.5f);
GUI.DrawRectangle(spriteBatch, CrewArea, Color.Blue * 0.5f); GUI.DrawRectangle(spriteBatch, CrewArea, Color.Blue * 0.5f);
GUI.DrawRectangle(spriteBatch, ChatBoxArea, Color.Cyan * 0.5f); GUI.DrawRectangle(spriteBatch, ChatBoxArea, Color.Cyan * 0.5f);
GUI.DrawRectangle(spriteBatch, HealthBarAreaLeft, Color.Red * 0.5f); GUI.DrawRectangle(spriteBatch, HealthBarAreaLeft, Color.Red * 0.5f);
GUI.DrawRectangle(spriteBatch, AfflictionAreaLeft, Color.Red * 0.5f); GUI.DrawRectangle(spriteBatch, AfflictionAreaLeft, Color.Red * 0.5f);
GUI.DrawRectangle(spriteBatch, HealthBarAreaRight, Color.Red * 0.5f);
GUI.DrawRectangle(spriteBatch, AfflictionAreaRight, Color.Red * 0.5f);
GUI.DrawRectangle(spriteBatch, InventoryAreaLower, Color.Yellow * 0.5f); GUI.DrawRectangle(spriteBatch, InventoryAreaLower, Color.Yellow * 0.5f);
GUI.DrawRectangle(spriteBatch, HealthWindowAreaLeft, Color.Red * 0.5f); GUI.DrawRectangle(spriteBatch, HealthWindowAreaLeft, Color.Red * 0.5f);
GUI.DrawRectangle(spriteBatch, HealthWindowAreaRight, Color.Red * 0.5f);
} }
} }
@@ -194,7 +194,18 @@ namespace Barotrauma
string loadText; string loadText;
if (LoadState == 100.0f) if (LoadState == 100.0f)
{ {
loadText = TextManager.Get("PressAnyKey"); #if DEBUG
if (GameMain.Config.AutomaticQuickStartEnabled && GameMain.FirstLoad)
{
loadText = "QUICKSTARTING ...";
}
else
{
#endif
loadText = TextManager.Get("PressAnyKey");
#if DEBUG
}
#endif
} }
else else
{ {
@@ -23,7 +23,9 @@ namespace Barotrauma
public enum ScaleBasis public enum ScaleBasis
{ {
Normal, BothWidth, BothHeight Normal,
BothWidth, BothHeight,
Smallest, Largest
} }
public class RectTransform public class RectTransform
@@ -56,7 +58,7 @@ namespace Barotrauma
} }
} }
private List<RectTransform> children = new List<RectTransform>(); private readonly List<RectTransform> children = new List<RectTransform>();
public IEnumerable<RectTransform> Children => children; public IEnumerable<RectTransform> Children => children;
public int CountChildren => children.Count; public int CountChildren => children.Count;
@@ -291,7 +293,11 @@ namespace Barotrauma
} }
} }
private ScaleBasis scaleBasis; public ScaleBasis ScaleBasis
{
get;
private set;
}
public bool IsLastChild public bool IsLastChild
{ {
@@ -330,7 +336,7 @@ namespace Barotrauma
public RectTransform(Vector2 relativeSize, RectTransform parent, Anchor anchor = Anchor.TopLeft, Pivot? pivot = null, Point? minSize = null, Point? maxSize = null, ScaleBasis scaleBasis = ScaleBasis.Normal) public RectTransform(Vector2 relativeSize, RectTransform parent, Anchor anchor = Anchor.TopLeft, Pivot? pivot = null, Point? minSize = null, Point? maxSize = null, ScaleBasis scaleBasis = ScaleBasis.Normal)
{ {
Init(parent, anchor, pivot); Init(parent, anchor, pivot);
this.scaleBasis = scaleBasis; this.ScaleBasis = scaleBasis;
this.relativeSize = relativeSize; this.relativeSize = relativeSize;
this.minSize = minSize; this.minSize = minSize;
this.maxSize = maxSize; this.maxSize = maxSize;
@@ -348,7 +354,7 @@ namespace Barotrauma
public RectTransform(Point absoluteSize, RectTransform parent = null, Anchor anchor = Anchor.TopLeft, Pivot? pivot = null) public RectTransform(Point absoluteSize, RectTransform parent = null, Anchor anchor = Anchor.TopLeft, Pivot? pivot = null)
{ {
Init(parent, anchor, pivot); Init(parent, anchor, pivot);
this.scaleBasis = ScaleBasis.Normal; this.ScaleBasis = ScaleBasis.Normal;
this.nonScaledSize = absoluteSize; this.nonScaledSize = absoluteSize;
RecalculateScale(); RecalculateScale();
RecalculateRelativeSize(); RecalculateRelativeSize();
@@ -364,8 +370,14 @@ namespace Barotrauma
Enum.TryParse(element.GetAttributeString("pivot", anchor.ToString()), out Pivot pivot); Enum.TryParse(element.GetAttributeString("pivot", anchor.ToString()), out Pivot pivot);
Point? minSize = null, maxSize = null; Point? minSize = null, maxSize = null;
if (element.Attribute("minsize") != null) minSize = element.GetAttributePoint("minsize", Point.Zero); if (element.Attribute("minsize") != null)
//if (element.Attribute("maxsize") != null) maxSize = element.GetAttributePoint("maxsize", new Point(1000, 1000)); {
minSize = element.GetAttributePoint("minsize", Point.Zero);
}
if (element.Attribute("maxsize") != null)
{
maxSize = element.GetAttributePoint("maxsize", new Point(1000, 1000));
}
RectTransform rectTransform; RectTransform rectTransform;
if (element.Attribute("absolutesize") != null) if (element.Attribute("absolutesize") != null)
@@ -426,14 +438,36 @@ namespace Barotrauma
protected void RecalculateAbsoluteSize() protected void RecalculateAbsoluteSize()
{ {
Point size = NonScaledParentRect.Size; Point size = NonScaledParentRect.Size;
if (scaleBasis == ScaleBasis.BothWidth) if (ScaleBasis == ScaleBasis.BothWidth)
{ {
size.Y = size.X; size.Y = size.X;
} }
else if (scaleBasis == ScaleBasis.BothHeight) else if (ScaleBasis == ScaleBasis.BothHeight)
{ {
size.X = size.Y; size.X = size.Y;
} }
else if (ScaleBasis == ScaleBasis.Smallest)
{
if (size.X < size.Y)
{
size.Y = size.X;
}
else
{
size.X = size.Y;
}
}
else if (ScaleBasis == ScaleBasis.Largest)
{
if (size.X > size.Y)
{
size.Y = size.X;
}
else
{
size.X = size.Y;
}
}
nonScaledSize = size.Multiply(RelativeSize).Clamp(MinSize, MaxSize); nonScaledSize = size.Multiply(RelativeSize).Clamp(MinSize, MaxSize);
recalculateRect = true; recalculateRect = true;
SizeChanged?.Invoke(); SizeChanged?.Invoke();
@@ -573,7 +607,7 @@ namespace Barotrauma
/// </summary> /// </summary>
public IEnumerable<RectTransform> GetAllChildren() public IEnumerable<RectTransform> GetAllChildren()
{ {
return children.SelectManyRecursive(c => c.children); return children.Concat(children.SelectManyRecursive(c => c.children));
} }
public int GetChildIndex(RectTransform rectT) public int GetChildIndex(RectTransform rectT)
@@ -37,11 +37,23 @@ namespace Barotrauma
private set; private set;
} }
public bool CrossFadeIn { get; private set; } = true;
public bool CrossFadeOut { get; private set; } = true;
public TransitionMode TransitionMode { get; private set; }
public UISprite(XElement element) public UISprite(XElement element)
{ {
Sprite = new Sprite(element); Sprite = new Sprite(element);
MaintainAspectRatio = element.GetAttributeBool("maintainaspectratio", false); MaintainAspectRatio = element.GetAttributeBool("maintainaspectratio", false);
Tile = element.GetAttributeBool("tile", true); Tile = element.GetAttributeBool("tile", true);
CrossFadeIn = element.GetAttributeBool("crossfadein", CrossFadeIn);
CrossFadeOut = element.GetAttributeBool("crossfadeout", CrossFadeOut);
string transitionMode = element.GetAttributeString("transition", string.Empty);
if (Enum.TryParse(transitionMode, ignoreCase: true, out TransitionMode transition))
{
TransitionMode = transition;
}
Vector4 sliceVec = element.GetAttributeVector4("slice", Vector4.Zero); Vector4 sliceVec = element.GetAttributeVector4("slice", Vector4.Zero);
if (sliceVec != Vector4.Zero) if (sliceVec != Vector4.Zero)
@@ -86,43 +98,30 @@ namespace Barotrauma
{ {
Vector2 pos = new Vector2(rect.X, rect.Y); Vector2 pos = new Vector2(rect.X, rect.Y);
int centerWidth = Math.Max(rect.Width - Slices[0].Width - Slices[2].Width, 0);
int centerHeight = Math.Max(rect.Height - Slices[0].Height - Slices[8].Height, 0);
Vector2 scale = Vector2.One; Vector2 scale = Vector2.One;
if (centerHeight == 0)
{ scale.Y = MathHelper.Clamp((float)rect.Height / (Slices[0].Height + Slices[6].Height), 0, 1);
scale.Y = MathHelper.Clamp((float)rect.Height / (Slices[0].Height + Slices[3].Height + Slices[6].Height), 0, 1);
centerHeight = rect.Height - (int)((Slices[0].Height + Slices[6].Height) * scale.Y); scale.X = MathHelper.Clamp((float)rect.Width / (Slices[0].Width + Slices[2].Width), 0, 1);
}
else scale.X = scale.Y = Math.Min(scale.X, scale.Y);
{ int centerHeight = rect.Height - (int)((Slices[0].Height + Slices[6].Height) * scale.Y);
scale.Y = MathHelper.Clamp((float)rect.Height / (Slices[0].Height + Slices[6].Height), 0, 1); int centerWidth = rect.Width - (int)((Slices[0].Width + Slices[2].Width) * scale.X);
centerHeight = (int)(centerHeight * scale.Y);
}
if (centerWidth == 0)
{
scale.X = MathHelper.Clamp((float)rect.Height / (Slices[0].Width + Slices[1].Width + Slices[2].Width), 0, 1);
centerWidth = rect.Width - (int)((Slices[0].Width + Slices[2].Width) * scale.X);
}
else
{
scale.X = MathHelper.Clamp((float)rect.Width / (Slices[0].Width + Slices[2].Width), 0, 1);
centerWidth = (int)(centerWidth * scale.X);
}
for (int x = 0; x < 3; x++) for (int x = 0; x < 3; x++)
{ {
float width = (x == 1 ? centerWidth : Slices[x].Width * scale.X); int width = (int)(x == 1 ? centerWidth : Slices[x].Width * scale.X);
if (width <= 0) { continue; }
for (int y = 0; y < 3; y++) for (int y = 0; y < 3; y++)
{ {
float height = (y == 1 ? centerHeight : Slices[x + y * 3].Height * scale.Y); int height = (int)(y == 1 ? centerHeight : Slices[x + y * 3].Height * scale.Y);
if (height <= 0) { continue; }
spriteBatch.Draw(Sprite.Texture, spriteBatch.Draw(Sprite.Texture,
new Rectangle((int)pos.X, (int)pos.Y, (int)width, (int)height), new Rectangle((int)pos.X, (int)pos.Y, width, height),
Slices[x + y * 3], Slices[x + y * 3],
color); color);
pos.Y += height; pos.Y += height;
} }
pos.X += width; pos.X += width;
@@ -75,13 +75,13 @@ namespace Barotrauma
} }
videoView = new GUICustomComponent(new RectTransform(Point.Zero, videoFrame.RectTransform, Anchor.Center), (spriteBatch, guiCustomComponent) => { DrawVideo(spriteBatch, guiCustomComponent.Rect); }); videoView = new GUICustomComponent(new RectTransform(Point.Zero, videoFrame.RectTransform, Anchor.Center), (spriteBatch, guiCustomComponent) => { DrawVideo(spriteBatch, guiCustomComponent.Rect); });
title = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft), string.Empty, font: GUI.VideoTitleFont, textColor: new Color(253, 174, 0), textAlignment: Alignment.Left); title = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft), string.Empty, font: GUI.LargeFont, textColor: new Color(253, 174, 0), textAlignment: Alignment.Left);
textContent = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft), string.Empty, font: GUI.Font, textAlignment: Alignment.TopLeft); textContent = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft), string.Empty, font: GUI.Font, textAlignment: Alignment.TopLeft);
objectiveTitle = new GUITextBlock(new RectTransform(new Vector2(1f, 0f), textFrame.RectTransform, Anchor.TopCenter, Pivot.TopCenter), string.Empty, font: GUI.ObjectiveTitleFont, textAlignment: Alignment.CenterRight, textColor: Color.White); objectiveTitle = new GUITextBlock(new RectTransform(new Vector2(1f, 0f), textFrame.RectTransform, Anchor.TopCenter, Pivot.TopCenter), string.Empty, font: GUI.SubHeadingFont, textAlignment: Alignment.CenterRight, textColor: Color.White);
objectiveTitle.Text = TextManager.Get("Tutorial.NewObjective"); objectiveTitle.Text = TextManager.Get("Tutorial.NewObjective");
objectiveText = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopCenter, Pivot.TopCenter), string.Empty, font: GUI.ObjectiveNameFont, textColor: new Color(4, 180, 108), textAlignment: Alignment.CenterRight); objectiveText = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopCenter, Pivot.TopCenter), string.Empty, font: GUI.SubHeadingFont, textColor: new Color(4, 180, 108), textAlignment: Alignment.CenterRight);
objectiveTitle.Visible = objectiveText.Visible = false; objectiveTitle.Visible = objectiveText.Visible = false;
} }
@@ -41,7 +41,7 @@ namespace Barotrauma
/// </summary> /// </summary>
public bool isFilled; public bool isFilled;
public int inputAreaMargin; public int inputAreaMargin;
public Color color = Color.Red; public Color color = GUI.Style.Red;
public Color? secondaryColor; public Color? secondaryColor;
public Color textColor = Color.White; public Color textColor = Color.White;
public Color textBackgroundColor = Color.Black * 0.5f; public Color textBackgroundColor = Color.Black * 0.5f;
@@ -171,6 +171,10 @@ namespace Barotrauma
private const GraphicsProfile GfxProfile = GraphicsProfile.Reach; private const GraphicsProfile GfxProfile = GraphicsProfile.Reach;
#if DEBUG
public static bool FirstLoad = true;
#endif
public GameMain(string[] args) public GameMain(string[] args)
{ {
Content.RootDirectory = "Content"; Content.RootDirectory = "Content";
@@ -391,7 +395,7 @@ namespace Barotrauma
float baseVolume = MathHelper.Clamp(Config.SoundVolume * 2.0f, 0.0f, 1.0f); float baseVolume = MathHelper.Clamp(Config.SoundVolume * 2.0f, 0.0f, 1.0f);
pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_UTG.webm", baseVolume * 0.5f)); pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_UTG.webm", baseVolume * 0.5f));
pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_FF.webm", baseVolume)); pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_FF.webm", baseVolume));
pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_Daedalic.webm", baseVolume * 0.15f)); pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_Daedalic.webm", baseVolume * 0.1f));
} }
//if not loading in a separate thread, wait for the splash screens to finish before continuing the loading //if not loading in a separate thread, wait for the splash screens to finish before continuing the loading
@@ -702,6 +706,15 @@ namespace Barotrauma
loadingScreenOpen = false; loadingScreenOpen = false;
} }
#if DEBUG
if (TitleScreen.LoadState >= 100.0f && !TitleScreen.PlayingSplashScreen && Config.AutomaticQuickStartEnabled && FirstLoad)
{
loadingScreenOpen = false;
FirstLoad = false;
MainMenuScreen.QuickStart();
}
#endif
if (!hasLoaded && !CoroutineManager.IsCoroutineRunning(loadingCoroutine)) if (!hasLoaded && !CoroutineManager.IsCoroutineRunning(loadingCoroutine))
{ {
string errMsg = "Loading was interrupted due to an error"; string errMsg = "Loading was interrupted due to an error";
@@ -778,7 +791,8 @@ namespace Barotrauma
//open the pause menu if not controlling a character OR if the character has no UIs active that can be closed with ESC //open the pause menu if not controlling a character OR if the character has no UIs active that can be closed with ESC
else if ((Character.Controlled == null || !itemHudActive()) else if ((Character.Controlled == null || !itemHudActive())
//TODO: do we need to check Inventory.SelectedSlot? //TODO: do we need to check Inventory.SelectedSlot?
&& Inventory.SelectedSlot == null && CharacterHealth.OpenHealthWindow == null) && Inventory.SelectedSlot == null && CharacterHealth.OpenHealthWindow == null
&& !CrewManager.IsCommandInterfaceOpen)
{ {
// Otherwise toggle pausing, unless another window/interface is open. // Otherwise toggle pausing, unless another window/interface is open.
GUI.TogglePauseMenu(); GUI.TogglePauseMenu();
File diff suppressed because it is too large Load Diff
@@ -35,8 +35,8 @@ namespace Barotrauma
CanBeFocused = false CanBeFocused = false
}; };
var newCampaignContainer = new GUIFrame(new RectTransform(Vector2.One, campaignContainer.RectTransform, Anchor.BottomLeft), style: null); var newCampaignContainer = new GUIFrame(new RectTransform(new Vector2(0.95f, 0.95f), campaignContainer.RectTransform, Anchor.Center), style: null);
var loadCampaignContainer = new GUIFrame(new RectTransform(Vector2.One, campaignContainer.RectTransform, Anchor.BottomLeft), style: null); var loadCampaignContainer = new GUIFrame(new RectTransform(new Vector2(0.95f, 0.95f), campaignContainer.RectTransform, Anchor.Center), style: null);
var campaignSetupUI = new CampaignSetupUI(true, newCampaignContainer, loadCampaignContainer, null, saveFiles); var campaignSetupUI = new CampaignSetupUI(true, newCampaignContainer, loadCampaignContainer, null, saveFiles);
@@ -156,13 +156,14 @@ namespace Barotrauma.Tutorials
do { yield return null; } while (!captain_medicObjectiveSensor.MotionDetected); do { yield return null; } while (!captain_medicObjectiveSensor.MotionDetected);
GameMain.GameSession?.CrewManager.AddSinglePlayerChatMessage(captain_medic.Info.DisplayName, TextManager.Get("Captain.Radio.Medic"), ChatMessageType.Radio, null); GameMain.GameSession?.CrewManager.AddSinglePlayerChatMessage(captain_medic.Info.DisplayName, TextManager.Get("Captain.Radio.Medic"), ChatMessageType.Radio, null);
yield return new WaitForSeconds(2f, false); yield return new WaitForSeconds(2f, false);
GameMain.GameSession.CrewManager.ToggleCrewAreaOpen = true; GameMain.GameSession.CrewManager.ToggleCrewListOpen = true;
GameMain.GameSession.CrewManager.AddCharacter(captain_medic); GameMain.GameSession.CrewManager.AddCharacter(captain_medic);
TriggerTutorialSegment(0); TriggerTutorialSegment(0, GameMain.Config.KeyBindText(InputType.Command));
do do
{ {
yield return null; yield return null;
GameMain.GameSession.CrewManager.HighlightOrderButton(captain_medic, "follow", highlightColor, new Vector2(5, 5)); // TODO: Rework order highlighting for new command UI
// GameMain.GameSession.CrewManager.HighlightOrderButton(captain_medic, "follow", highlightColor, new Vector2(5, 5));
} }
while (!HasOrder(captain_medic, "follow")); while (!HasOrder(captain_medic, "follow"));
SetDoorAccess(tutorial_submarineDoor, tutorial_submarineDoorLight, true); SetDoorAccess(tutorial_submarineDoor, tutorial_submarineDoorLight, true);
@@ -172,34 +173,37 @@ namespace Barotrauma.Tutorials
do { yield return null; } while (!captain_enteredSubmarineSensor.MotionDetected); do { yield return null; } while (!captain_enteredSubmarineSensor.MotionDetected);
yield return new WaitForSeconds(3f, false); yield return new WaitForSeconds(3f, false);
captain_mechanic.AIController.Enabled = captain_security.AIController.Enabled = captain_engineer.AIController.Enabled = true; captain_mechanic.AIController.Enabled = captain_security.AIController.Enabled = captain_engineer.AIController.Enabled = true;
TriggerTutorialSegment(1); TriggerTutorialSegment(1, GameMain.Config.KeyBindText(InputType.Command));
GameMain.GameSession.CrewManager.AddCharacter(captain_mechanic); GameMain.GameSession.CrewManager.AddCharacter(captain_mechanic);
do do
{ {
yield return null; yield return null;
GameMain.GameSession.CrewManager.HighlightOrderButton(captain_mechanic, "repairsystems", highlightColor, new Vector2(5, 5)); // TODO: Rework order highlighting for new command UI
// GameMain.GameSession.CrewManager.HighlightOrderButton(captain_mechanic, "repairsystems", highlightColor, new Vector2(5, 5));
//HighlightOrderOption("jobspecific"); //HighlightOrderOption("jobspecific");
} }
while (!HasOrder(captain_mechanic, "repairsystems")); while (!HasOrder(captain_mechanic, "repairsystems"));
RemoveCompletedObjective(segments[1]); RemoveCompletedObjective(segments[1]);
yield return new WaitForSeconds(2f, false); yield return new WaitForSeconds(2f, false);
TriggerTutorialSegment(2); TriggerTutorialSegment(2, GameMain.Config.KeyBindText(InputType.Command));
GameMain.GameSession.CrewManager.AddCharacter(captain_security); GameMain.GameSession.CrewManager.AddCharacter(captain_security);
do do
{ {
yield return null; yield return null;
GameMain.GameSession.CrewManager.HighlightOrderButton(captain_security, "operateweapons", highlightColor, new Vector2(5, 5)); // TODO: Rework order highlighting for new command UI
// GameMain.GameSession.CrewManager.HighlightOrderButton(captain_security, "operateweapons", highlightColor, new Vector2(5, 5));
HighlightOrderOption("fireatwill"); HighlightOrderOption("fireatwill");
} }
while (!HasOrder(captain_security, "operateweapons", "fireatwill")); while (!HasOrder(captain_security, "operateweapons", "fireatwill"));
RemoveCompletedObjective(segments[2]); RemoveCompletedObjective(segments[2]);
yield return new WaitForSeconds(4f, false); yield return new WaitForSeconds(4f, false);
TriggerTutorialSegment(3); TriggerTutorialSegment(3, GameMain.Config.KeyBindText(InputType.Command));
GameMain.GameSession.CrewManager.AddCharacter(captain_engineer); GameMain.GameSession.CrewManager.AddCharacter(captain_engineer);
do do
{ {
yield return null; yield return null;
GameMain.GameSession.CrewManager.HighlightOrderButton(captain_engineer, "operatereactor", highlightColor, new Vector2(5, 5)); // TODO: Rework order highlighting for new command UI
// GameMain.GameSession.CrewManager.HighlightOrderButton(captain_engineer, "operatereactor", highlightColor, new Vector2(5, 5));
HighlightOrderOption("powerup"); HighlightOrderOption("powerup");
} }
while (!HasOrder(captain_engineer, "operatereactor", "powerup")); while (!HasOrder(captain_engineer, "operatereactor", "powerup"));
@@ -225,10 +229,9 @@ namespace Barotrauma.Tutorials
{ {
if (IsSelectedItem(captain_navConsole.Item)) if (IsSelectedItem(captain_navConsole.Item))
{ {
if (captain_sonar.ActiveTickBox.Box.FlashTimer <= 0) if (captain_sonar.SonarModeSwitch.Frame.FlashTimer <= 0)
{ {
captain_sonar.ActiveTickBox.Box.Flash(highlightColor, 1.5f, false, new Vector2(2.5f, 2.5f)); captain_sonar.SonarModeSwitch.Frame.Flash(highlightColor, 1.5f, false, false, new Vector2(2.5f, 2.5f));
//captain_sonar.ActiveTickBox.Box.Pulsate(Vector2.One, Vector2.One * 1.5f, 1.5f);
} }
} }
yield return null; yield return null;
@@ -55,6 +55,22 @@ namespace Barotrauma.Tutorials
radioSpeakerName = TextManager.Get("Tutorial.Radio.Speaker"); radioSpeakerName = TextManager.Get("Tutorial.Radio.Speaker");
doctor = Character.Controlled; doctor = Character.Controlled;
var bandages = FindOrGiveItem(doctor, "antibleeding1");
bandages.Unequip(doctor);
doctor.Inventory.RemoveItem(bandages);
var syringegun = FindOrGiveItem(doctor, "syringegun");
syringegun.Unequip(doctor);
doctor.Inventory.RemoveItem(syringegun);
var antibiotics = FindOrGiveItem(doctor, "antibiotics");
antibiotics.Unequip(doctor);
doctor.Inventory.RemoveItem(antibiotics);
var morphine = FindOrGiveItem(doctor, "antidama1");
morphine.Unequip(doctor);
doctor.Inventory.RemoveItem(morphine);
doctor_suppliesCabinet = Item.ItemList.Find(i => i.HasTag("doctor_suppliescabinet"))?.GetComponent<ItemContainer>(); doctor_suppliesCabinet = Item.ItemList.Find(i => i.HasTag("doctor_suppliescabinet"))?.GetComponent<ItemContainer>();
doctor_medBayCabinet = Item.ItemList.Find(i => i.HasTag("doctor_medbaycabinet"))?.GetComponent<ItemContainer>(); doctor_medBayCabinet = Item.ItemList.Find(i => i.HasTag("doctor_medbaycabinet"))?.GetComponent<ItemContainer>();
@@ -175,7 +191,7 @@ namespace Barotrauma.Tutorials
yield return new WaitForSeconds(2.0f); yield return new WaitForSeconds(2.0f);
}*/ }*/
TriggerTutorialSegment(0, GameMain.Config.KeyBindText(InputType.Select), GameMain.Config.KeyBindText(InputType.Deselect)); // Medical supplies objective TriggerTutorialSegment(0, GameMain.Config.KeyBindText(InputType.Select), GameMain.Config.KeyBindText(InputType.Deselect), GameMain.Config.KeyBindText(InputType.ToggleInventory)); // Medical supplies objective
do do
{ {
@@ -254,17 +270,18 @@ namespace Barotrauma.Tutorials
GameMain.GameSession.CrewManager.AllowCharacterSwitch = false; GameMain.GameSession.CrewManager.AllowCharacterSwitch = false;
GameMain.GameSession.CrewManager.AddCharacter(doctor); GameMain.GameSession.CrewManager.AddCharacter(doctor);
GameMain.GameSession.CrewManager.AddCharacter(patient1); GameMain.GameSession.CrewManager.AddCharacter(patient1);
GameMain.GameSession.CrewManager.ToggleCrewAreaOpen = true; GameMain.GameSession.CrewManager.ToggleCrewListOpen = true;
patient1.CharacterHealth.UseHealthWindow = false; patient1.CharacterHealth.UseHealthWindow = false;
yield return new WaitForSeconds(3.0f, false); yield return new WaitForSeconds(3.0f, false);
patient1.AIController.Enabled = true; patient1.AIController.Enabled = true;
doctor.RemoveActiveObjectiveEntity(patient1); doctor.RemoveActiveObjectiveEntity(patient1);
TriggerTutorialSegment(3); // Get the patient to medbay TriggerTutorialSegment(3, GameMain.Config.KeyBindText(InputType.Command)); // Get the patient to medbay
while (patient1.CurrentOrder == null || patient1.CurrentOrder.Identifier != "follow") while (patient1.CurrentOrder == null || patient1.CurrentOrder.Identifier != "follow")
{ {
GameMain.GameSession.CrewManager.HighlightOrderButton(patient1, "follow", highlightColor, new Vector2(5, 5)); // TODO: Rework order highlighting for new command UI
// GameMain.GameSession.CrewManager.HighlightOrderButton(patient1, "follow", highlightColor, new Vector2(5, 5));
yield return null; yield return null;
} }
@@ -127,7 +127,7 @@ namespace Barotrauma.Tutorials
engineer_reactor = Item.ItemList.Find(i => i.HasTag("engineer_reactor")).GetComponent<Reactor>(); engineer_reactor = Item.ItemList.Find(i => i.HasTag("engineer_reactor")).GetComponent<Reactor>();
engineer_reactor.FireDelay = engineer_reactor.MeltdownDelay = float.PositiveInfinity; engineer_reactor.FireDelay = engineer_reactor.MeltdownDelay = float.PositiveInfinity;
engineer_reactor.FuelConsumptionRate = 0.0f; engineer_reactor.FuelConsumptionRate = 0.0f;
engineer_reactor.OnOffSwitch.BarScroll = 1f; engineer_reactor.PowerOn = true;
reactorOperatedProperly = false; reactorOperatedProperly = false;
engineer_secondDoor = Item.ItemList.Find(i => i.HasTag("engineer_seconddoor")).GetComponent<Door>(); ; engineer_secondDoor = Item.ItemList.Find(i => i.HasTag("engineer_seconddoor")).GetComponent<Door>(); ;
@@ -195,7 +195,7 @@ namespace Barotrauma.Tutorials
engineer_submarineJunctionBox_2 = Item.ItemList.Find(i => i.HasTag("engineer_submarinejunctionbox_2")); engineer_submarineJunctionBox_2 = Item.ItemList.Find(i => i.HasTag("engineer_submarinejunctionbox_2"));
engineer_submarineJunctionBox_3 = Item.ItemList.Find(i => i.HasTag("engineer_submarinejunctionbox_3")); engineer_submarineJunctionBox_3 = Item.ItemList.Find(i => i.HasTag("engineer_submarinejunctionbox_3"));
engineer_submarineReactor = Item.ItemList.Find(i => i.HasTag("engineer_submarinereactor")).GetComponent<Reactor>(); engineer_submarineReactor = Item.ItemList.Find(i => i.HasTag("engineer_submarinereactor")).GetComponent<Reactor>();
engineer_submarineReactor.OnOffSwitch.BarScrollValue = .25f; engineer_submarineReactor.PowerOn = true;
engineer_submarineReactor.IsActive = engineer_submarineReactor.AutoTemp = false; engineer_submarineReactor.IsActive = engineer_submarineReactor.AutoTemp = false;
engineer_submarineJunctionBox_1.Indestructible = false; engineer_submarineJunctionBox_1.Indestructible = false;
@@ -235,7 +235,7 @@ namespace Barotrauma.Tutorials
do { yield return null; } while (!engineer_equipmentObjectiveSensor.MotionDetected); do { yield return null; } while (!engineer_equipmentObjectiveSensor.MotionDetected);
GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Engineer.Radio.Equipment"), ChatMessageType.Radio, null); GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Engineer.Radio.Equipment"), ChatMessageType.Radio, null);
yield return new WaitForSeconds(0.5f, false); yield return new WaitForSeconds(0.5f, false);
TriggerTutorialSegment(0, GameMain.Config.KeyBindText(InputType.Select), GameMain.Config.KeyBindText(InputType.Deselect)); // Retrieve equipment TriggerTutorialSegment(0, GameMain.Config.KeyBindText(InputType.Select), GameMain.Config.KeyBindText(InputType.Deselect), GameMain.Config.KeyBindText(InputType.ToggleInventory)); // Retrieve equipment
bool firstSlotRemoved = false; bool firstSlotRemoved = false;
bool secondSlotRemoved = false; bool secondSlotRemoved = false;
bool thirdSlotRemoved = false; bool thirdSlotRemoved = false;
@@ -289,19 +289,19 @@ namespace Barotrauma.Tutorials
{ {
if (IsSelectedItem(engineer_reactor.Item)) if (IsSelectedItem(engineer_reactor.Item))
{ {
engineer_reactor.AutoTempSlider.BarScrollValue = 1.0f; engineer_reactor.AutoTemp = false;
if (engineer_reactor.OnOffSwitch.FlashTimer <= 0) if (engineer_reactor.PowerButton.FlashTimer <= 0)
{ {
engineer_reactor.OnOffSwitch.Flash(highlightColor, 1.5f, false); engineer_reactor.PowerButton.Flash(highlightColor, 1.5f, false);
} }
} }
yield return null; yield return null;
} while (engineer_reactor.OnOffSwitch.BarScroll > 0.45f); } while (!engineer_reactor.PowerOn);
do do
{ {
if (IsSelectedItem(engineer_reactor.Item) && engineer_reactor.Item.OwnInventory.slots != null) if (IsSelectedItem(engineer_reactor.Item) && engineer_reactor.Item.OwnInventory.slots != null)
{ {
engineer_reactor.AutoTempSlider.BarScrollValue = 1.0f; engineer_reactor.AutoTemp = false;
HighlightInventorySlot(engineer.Inventory, "fuelrod", highlightColor, 0.5f, 0.5f, 0f); HighlightInventorySlot(engineer.Inventory, "fuelrod", highlightColor, 0.5f, 0.5f, 0f);
for (int i = 0; i < engineer_reactor.Item.OwnInventory.slots.Length; i++) for (int i = 0; i < engineer_reactor.Item.OwnInventory.slots.Length; i++)
@@ -316,7 +316,7 @@ namespace Barotrauma.Tutorials
{ {
if (IsSelectedItem(engineer_reactor.Item)) if (IsSelectedItem(engineer_reactor.Item))
{ {
engineer_reactor.AutoTempSlider.BarScrollValue = 1.0f; engineer_reactor.AutoTemp = false;
if (engineer_reactor.FissionRateScrollBar.FlashTimer <= 0) if (engineer_reactor.FissionRateScrollBar.FlashTimer <= 0)
{ {
engineer_reactor.FissionRateScrollBar.Flash(highlightColor, 1.5f); engineer_reactor.FissionRateScrollBar.Flash(highlightColor, 1.5f);
@@ -335,9 +335,9 @@ namespace Barotrauma.Tutorials
{ {
if (IsSelectedItem(engineer_reactor.Item)) if (IsSelectedItem(engineer_reactor.Item))
{ {
if (engineer_reactor.AutoTempSlider.FlashTimer <= 0) if (engineer_reactor.AutoTempSwitch.FlashTimer <= 0)
{ {
engineer_reactor.AutoTempSlider.Flash(highlightColor, 1.5f, false, new Vector2(10, 10)); engineer_reactor.AutoTempSwitch.Flash(highlightColor, 1.5f, false, false, new Vector2(10, 10));
} }
} }
yield return null; yield return null;
@@ -348,7 +348,7 @@ namespace Barotrauma.Tutorials
{ {
yield return new WaitForSeconds(0.1f, false); yield return new WaitForSeconds(0.1f, false);
wait -= 0.1f; wait -= 0.1f;
engineer_reactor.AutoTempSlider.BarScrollValue = 0.0f; engineer_reactor.AutoTemp = true;
} while (wait > 0.0f); } while (wait > 0.0f);
engineer.SelectedConstruction = null; engineer.SelectedConstruction = null;
engineer_reactor.CanBeSelected = false; engineer_reactor.CanBeSelected = false;
@@ -254,7 +254,7 @@ namespace Barotrauma.Tutorials
yield return new WaitForSeconds(0.0f, false); yield return new WaitForSeconds(0.0f, false);
GameMain.GameSession?.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Mechanic.Radio.Equipment"), ChatMessageType.Radio, null); GameMain.GameSession?.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Mechanic.Radio.Equipment"), ChatMessageType.Radio, null);
do { yield return null; } while (!mechanic_equipmentObjectiveSensor.MotionDetected); do { yield return null; } while (!mechanic_equipmentObjectiveSensor.MotionDetected);
TriggerTutorialSegment(1, GameMain.Config.KeyBindText(InputType.Select), GameMain.Config.KeyBindText(InputType.Deselect)); // Equipment & inventory objective TriggerTutorialSegment(1, GameMain.Config.KeyBindText(InputType.Select), GameMain.Config.KeyBindText(InputType.Deselect), GameMain.Config.KeyBindText(InputType.ToggleInventory)); // Equipment & inventory objective
SetHighlight(mechanic_equipmentCabinet.Item, true); SetHighlight(mechanic_equipmentCabinet.Item, true);
bool firstSlotRemoved = false; bool firstSlotRemoved = false;
bool secondSlotRemoved = false; bool secondSlotRemoved = false;
@@ -296,7 +296,7 @@ namespace Barotrauma.Tutorials
// Room 3 // Room 3
do { yield return null; } while (!mechanic_weldingObjectiveSensor.MotionDetected); do { yield return null; } while (!mechanic_weldingObjectiveSensor.MotionDetected);
TriggerTutorialSegment(2, GameMain.Config.KeyBindText(InputType.Aim), GameMain.Config.KeyBindText(InputType.Shoot)); // Welding objective TriggerTutorialSegment(2, GameMain.Config.KeyBindText(InputType.Aim), GameMain.Config.KeyBindText(InputType.Shoot), GameMain.Config.KeyBindText(InputType.ToggleInventory)); // Welding objective
do do
{ {
if (!mechanic.HasEquippedItem("divingmask")) if (!mechanic.HasEquippedItem("divingmask"))
@@ -323,9 +323,9 @@ namespace Barotrauma.Tutorials
yield return null; yield return null;
if (IsSelectedItem(mechanic_workingPump.Item)) if (IsSelectedItem(mechanic_workingPump.Item))
{ {
if (mechanic_workingPump.IsActiveSlider.FlashTimer <= 0) if (mechanic_workingPump.PowerButton.FlashTimer <= 0)
{ {
mechanic_workingPump.IsActiveSlider.Flash(uiHighlightColor, 1.5f, true); mechanic_workingPump.PowerButton.Flash(uiHighlightColor, 1.5f, true);
} }
} }
} while (mechanic_workingPump.FlowPercentage >= 0 || !mechanic_workingPump.IsActive); // Highlight until draining } while (mechanic_workingPump.FlowPercentage >= 0 || !mechanic_workingPump.IsActive); // Highlight until draining
@@ -554,9 +554,9 @@ namespace Barotrauma.Tutorials
{ {
if (IsSelectedItem(mechanic_brokenPump.Item)) if (IsSelectedItem(mechanic_brokenPump.Item))
{ {
if (mechanic_brokenPump.IsActiveSlider.FlashTimer <= 0) if (mechanic_brokenPump.PowerButton.FlashTimer <= 0)
{ {
mechanic_brokenPump.IsActiveSlider.Flash(uiHighlightColor, 1.5f, true); mechanic_brokenPump.PowerButton.Flash(uiHighlightColor, 1.5f, true);
} }
} }
} }
@@ -252,12 +252,12 @@ namespace Barotrauma.Tutorials
{ {
HighlightInventorySlot(officer.Inventory, "bodyarmor", highlightColor, .5f, .5f, 0f); HighlightInventorySlot(officer.Inventory, "bodyarmor", highlightColor, .5f, .5f, 0f);
} }
if (!officer.HasEquippedItem("ballistichelmet")) if (!officer.HasEquippedItem("ballistichelmet1"))
{ {
HighlightInventorySlot(officer.Inventory, "ballistichelmet", highlightColor, .5f, .5f, 0f); HighlightInventorySlot(officer.Inventory, "ballistichelmet1", highlightColor, .5f, .5f, 0f);
} }
yield return new WaitForSeconds(1f, false); yield return new WaitForSeconds(1f, false);
} while (!officer.HasEquippedItem("stunbaton") || !officer.HasEquippedItem("bodyarmor") || !officer.HasEquippedItem("ballistichelmet")); } while (!officer.HasEquippedItem("stunbaton") || !officer.HasEquippedItem("bodyarmor") || !officer.HasEquippedItem("ballistichelmet1"));
RemoveCompletedObjective(segments[1]); RemoveCompletedObjective(segments[1]);
SetDoorAccess(officer_firstDoor, officer_firstDoorLight, true); SetDoorAccess(officer_firstDoor, officer_firstDoorLight, true);
@@ -31,8 +31,8 @@ namespace Barotrauma.Tutorials
protected Color highlightColor = Color.OrangeRed; protected Color highlightColor = Color.OrangeRed;
protected Color uiHighlightColor = new Color(150, 50, 0); protected Color uiHighlightColor = new Color(150, 50, 0);
protected Color buttonHighlightColor = new Color(255, 100, 0); protected Color buttonHighlightColor = new Color(255, 100, 0);
protected Color inaccessibleColor = Color.Red; protected Color inaccessibleColor = GUI.Style.Red;
protected Color accessibleColor = Color.Green; protected Color accessibleColor = GUI.Style.Green;
public ScenarioTutorial(XElement element) : base(element) public ScenarioTutorial(XElement element) : base(element)
{ {
@@ -372,9 +372,10 @@ namespace Barotrauma.Tutorials
private void CreateObjectiveGUI(TutorialSegment segment, int index, TutorialContentTypes type) private void CreateObjectiveGUI(TutorialSegment segment, int index, TutorialContentTypes type)
{ {
Point replayButtonSize = new Point((int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).X), (int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).Y * 1.45f)); string objectiveText = TextManager.ParseInputTypes(segment.Objective);
Point replayButtonSize = new Point((int)(GUI.LargeFont.MeasureString(objectiveText).X), (int)(GUI.LargeFont.MeasureString(objectiveText).Y * 1.45f));
segment.ReplayButton = new GUIButton(new RectTransform(replayButtonSize, objectiveFrame.RectTransform, Anchor.TopRight, Pivot.TopRight) { AbsoluteOffset = new Point(0, (replayButtonSize.Y + (int)(20f * GUI.Scale)) * index) }, style: null); segment.ReplayButton = new GUIButton(new RectTransform(replayButtonSize, objectiveFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft) { AbsoluteOffset = new Point(0, (replayButtonSize.Y + (int)(20f * GUI.Scale)) * index) }, style: null);
segment.ReplayButton.OnClicked += (GUIButton btn, object userdata) => segment.ReplayButton.OnClicked += (GUIButton btn, object userdata) =>
{ {
if (type == TutorialContentTypes.Video) if (type == TutorialContentTypes.Video)
@@ -389,13 +390,15 @@ namespace Barotrauma.Tutorials
}; };
string objectiveTitleText = TextManager.ParseInputTypes(objectiveTranslated); string objectiveTitleText = TextManager.ParseInputTypes(objectiveTranslated);
int yOffset = (int)((GUI.ObjectiveNameFont.MeasureString(objectiveTitleText).Y / 2f + 5)); int yOffset = (int)((GUI.SubHeadingFont.MeasureString(objectiveTitleText).Y + 5));
segment.LinkedTitle = new GUITextBlock(new RectTransform(new Point((int)GUI.ObjectiveTitleFont.MeasureString(objectiveTitleText).X, yOffset), segment.ReplayButton.RectTransform, Anchor.CenterRight, Pivot.BottomRight) /*{ AbsoluteOffset = new Point((int)(-10 * GUI.Scale), 0) }*/, segment.LinkedTitle = new GUITextBlock(new RectTransform(new Point((int)GUI.SubHeadingFont.MeasureString(objectiveTitleText).X, yOffset), segment.ReplayButton.RectTransform, Anchor.CenterLeft, Pivot.BottomLeft) /*{ AbsoluteOffset = new Point((int)(-10 * GUI.Scale), 0) }*/,
objectiveTitleText, textColor: Color.White, font: GUI.ObjectiveTitleFont, textAlignment: Alignment.CenterRight); objectiveTitleText, textColor: Color.White, font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
{
ForceUpperCase = true
};
string objectiveText = TextManager.ParseInputTypes(segment.Objective); segment.LinkedText = new GUITextBlock(new RectTransform(new Point((int)GUI.LargeFont.MeasureString(objectiveText).X, yOffset), segment.ReplayButton.RectTransform, Anchor.CenterLeft, Pivot.TopLeft) /*{ AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) }*/,
segment.LinkedText = new GUITextBlock(new RectTransform(new Point((int)GUI.ObjectiveNameFont.MeasureString(objectiveText).X, yOffset), segment.ReplayButton.RectTransform, Anchor.CenterRight, Pivot.TopRight) /*{ AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) }*/, objectiveText, textColor: new Color(4, 180, 108), font: GUI.LargeFont, textAlignment: Alignment.CenterLeft);
objectiveText, textColor: new Color(4, 180, 108), font: GUI.ObjectiveNameFont, textAlignment: Alignment.CenterRight);
segment.LinkedTitle.Color = segment.LinkedTitle.HoverColor = segment.LinkedTitle.PressedColor = segment.LinkedTitle.SelectedColor = Color.Transparent; segment.LinkedTitle.Color = segment.LinkedTitle.HoverColor = segment.LinkedTitle.PressedColor = segment.LinkedTitle.SelectedColor = Color.Transparent;
segment.LinkedText.Color = segment.LinkedText.HoverColor = segment.LinkedText.PressedColor = segment.LinkedText.SelectedColor = Color.Transparent; segment.LinkedText.Color = segment.LinkedText.HoverColor = segment.LinkedText.PressedColor = segment.LinkedText.SelectedColor = Color.Transparent;
@@ -449,19 +452,19 @@ namespace Barotrauma.Tutorials
RectTransform rectTA; RectTransform rectTA;
if (objectiveTextWidth > objectiveTitleWidth) if (objectiveTextWidth > objectiveTitleWidth)
{ {
rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft); rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomRight, Pivot.BottomRight);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - (int)(10 * GUI.Scale), 0); rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - (int)(25 * GUI.Scale), 0);
} }
else else
{ {
rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft); rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomRight, Pivot.BottomRight);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - (int)(10 * GUI.Scale) - (objectiveTitleWidth - objectiveTextWidth), 0); rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - (int)(25 * GUI.Scale) - (objectiveTitleWidth - objectiveTextWidth), 0);
} }
GUIImage checkmark = new GUIImage(rectTA, "CheckMark"); GUIImage checkmark = new GUIImage(rectTA, "CheckMark");
checkmark.Color = checkmark.SelectedColor = checkmark.HoverColor = checkmark.PressedColor = color; checkmark.Color = checkmark.SelectedColor = checkmark.HoverColor = checkmark.PressedColor = color;
RectTransform rectTB = new RectTransform(new Vector2(1.1f, .8f), segment.LinkedText.RectTransform, Anchor.Center, Pivot.Center); RectTransform rectTB = new RectTransform(new Vector2(1.0f, .8f), segment.LinkedText.RectTransform, Anchor.Center, Pivot.Center);
GUIImage stroke = new GUIImage(rectTB, "Stroke"); GUIImage stroke = new GUIImage(rectTB, "Stroke");
stroke.Color = stroke.SelectedColor = stroke.HoverColor = stroke.PressedColor = color; stroke.Color = stroke.SelectedColor = stroke.HoverColor = stroke.PressedColor = color;
@@ -493,14 +496,6 @@ namespace Barotrauma.Tutorials
protected GUIComponent CreateInfoFrame(string title, string text, int width = 300, int height = 80, string anchorStr = "", bool hasButton = false, Action callback = null, Action showVideo = null) protected GUIComponent CreateInfoFrame(string title, string text, int width = 300, int height = 80, string anchorStr = "", bool hasButton = false, Action callback = null, Action showVideo = null)
{ {
if (hasButton) height += 60; if (hasButton) height += 60;
string wrappedText = ToolBox.WrapText(text, width, GUI.Font);
height += (int)(GUI.Font.MeasureString(wrappedText).Y + 50);
if (title.Length > 0)
{
height += 35;
}
Anchor anchor = Anchor.TopRight; Anchor anchor = Anchor.TopRight;
@@ -509,12 +504,23 @@ namespace Barotrauma.Tutorials
Enum.TryParse(anchorStr, out anchor); Enum.TryParse(anchorStr, out anchor);
} }
var background = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center), "InnerFrame", new Color(0, 0, 0, 1f)); width = (int)(width * GUI.Scale);
height = (int)(height * GUI.Scale);
var infoBlock = new GUIFrame(new RectTransform(new Point((int)(width * GUI.Scale), (int)(height * GUI.Scale)), background.RectTransform, anchor) { AbsoluteOffset = new Point(20) }); string wrappedText = ToolBox.WrapText(text, width, GUI.Font);
infoBlock.Flash(Color.Green); height += (int)GUI.Font.MeasureString(wrappedText).Y;
var infoContent = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), infoBlock.RectTransform, Anchor.Center)) if (title.Length > 0)
{
height += (int)GUI.Font.MeasureString(title).Y + (int)(150 * GUI.Scale);
}
var background = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center), style: null, Color.Black * 0.5f);
var infoBlock = new GUIFrame(new RectTransform(new Point(width, height), background.RectTransform, anchor));
infoBlock.Flash(GUI.Style.Green);
var infoContent = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), infoBlock.RectTransform, Anchor.Center))
{ {
Stretch = true, Stretch = true,
AbsoluteSpacing = 5 AbsoluteSpacing = 5
@@ -523,7 +529,7 @@ namespace Barotrauma.Tutorials
if (title.Length > 0) if (title.Length > 0)
{ {
var titleBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContent.RectTransform), var titleBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContent.RectTransform),
title, font: GUI.VideoTitleFont, textAlignment: Alignment.Center, textColor: new Color(253, 174, 0)); title, font: GUI.LargeFont, textAlignment: Alignment.Center, textColor: new Color(253, 174, 0));
titleBlock.RectTransform.IsFixedSize = true; titleBlock.RectTransform.IsFixedSize = true;
} }
@@ -543,15 +549,15 @@ namespace Barotrauma.Tutorials
if (hasButton) if (hasButton)
{ {
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.3f), infoContent.RectTransform) { MinSize = new Point(0, 30), MaxSize = new Point((int) infoContent.Rect.X, 60) }, isHorizontal: true) var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), infoContent.RectTransform), isHorizontal: true)
{ {
Stretch = true,
RelativeSpacing = 0.1f RelativeSpacing = 0.1f
}; };
buttonContainer.RectTransform.IsFixedSize = true; buttonContainer.RectTransform.IsFixedSize = true;
if (showVideo != null) if (showVideo != null)
{ {
buttonContainer.Stretch = true;
var videoButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonContainer.RectTransform), var videoButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonContainer.RectTransform),
TextManager.Get("Video"), style: "GUIButtonLarge") TextManager.Get("Video"), style: "GUIButtonLarge")
{ {
@@ -562,8 +568,13 @@ namespace Barotrauma.Tutorials
} }
}; };
} }
else
{
buttonContainer.Stretch = false;
buttonContainer.ChildAnchor = Anchor.Center;
}
var okButton = new GUIButton(new RectTransform(new Vector2(0.6f, 1.0f), buttonContainer.RectTransform), var okButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonContainer.RectTransform),
TextManager.Get("OK"), style: "GUIButtonLarge") TextManager.Get("OK"), style: "GUIButtonLarge")
{ {
OnClicked = CloseInfoFrame OnClicked = CloseInfoFrame
@@ -1,21 +1,19 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
namespace Barotrauma namespace Barotrauma
{ {
partial class GameSession partial class GameSession
{ {
private InfoFrameTab selectedTab; private InfoFrameTab selectedTab;
private GUIButton infoFrame; private GUIFrame infoFrame;
private readonly List<GUIButton> tabButtons = new List<GUIButton>();
private GUIFrame infoFrameContent; private GUIFrame infoFrameContent;
public RoundSummary RoundSummary { get; private set; }
private RoundSummary roundSummary;
public RoundSummary RoundSummary
{
get { return roundSummary; }
}
private bool ToggleInfoFrame() private bool ToggleInfoFrame()
{ {
if (GameMain.NetworkMember != null && GameMain.NetLobbyScreen != null) if (GameMain.NetworkMember != null && GameMain.NetLobbyScreen != null)
@@ -40,7 +38,9 @@ namespace Barotrauma
{ {
int width = 600, height = 400; int width = 600, height = 400;
infoFrame = new GUIButton(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker"); tabButtons.Clear();
infoFrame = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker");
var innerFrame = new GUIFrame(new RectTransform(new Vector2(0.5f, 0.35f), infoFrame.RectTransform, Anchor.Center) { MinSize = new Point(width, height), RelativeOffset = new Vector2(0.0f, 0.033f) }); var innerFrame = new GUIFrame(new RectTransform(new Vector2(0.5f, 0.35f), infoFrame.RectTransform, Anchor.Center) { MinSize = new Point(width, height), RelativeOffset = new Vector2(0.0f, 0.033f) });
@@ -56,12 +56,14 @@ namespace Barotrauma
UserData = InfoFrameTab.Crew, UserData = InfoFrameTab.Crew,
OnClicked = SelectInfoFrameTab OnClicked = SelectInfoFrameTab
}; };
tabButtons.Add(crewButton);
var missionButton = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), buttonArea.RectTransform), TextManager.Get("Mission"), style: "GUITabButton") var missionButton = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), buttonArea.RectTransform), TextManager.Get("Mission"), style: "GUITabButton")
{ {
UserData = InfoFrameTab.Mission, UserData = InfoFrameTab.Mission,
OnClicked = SelectInfoFrameTab OnClicked = SelectInfoFrameTab
}; };
tabButtons.Add(missionButton);
if (GameMain.NetworkMember != null) if (GameMain.NetworkMember != null)
{ {
@@ -70,6 +72,7 @@ namespace Barotrauma
UserData = InfoFrameTab.MyCharacter, UserData = InfoFrameTab.MyCharacter,
OnClicked = SelectInfoFrameTab OnClicked = SelectInfoFrameTab
}; };
tabButtons.Add(myCharacterButton);
} }
/*TODO: fix /*TODO: fix
@@ -89,6 +92,7 @@ namespace Barotrauma
selectedTab = (InfoFrameTab)userData; selectedTab = (InfoFrameTab)userData;
CreateInfoFrame(); CreateInfoFrame();
tabButtons.ForEach(tb => tb.Selected = (InfoFrameTab)tb.UserData == selectedTab);
switch (selectedTab) switch (selectedTab)
{ {
@@ -19,6 +19,9 @@ namespace Barotrauma
Graphics, Graphics,
Audio, Audio,
Controls, Controls,
#if DEBUG
Debug
#endif
} }
private readonly Point MinSupportedResolution = new Point(1024, 540); private readonly Point MinSupportedResolution = new Point(1024, 540);
@@ -57,6 +60,7 @@ namespace Barotrauma
keyMapping[(int)InputType.CrewOrders] = new KeyOrMouse(Keys.C); keyMapping[(int)InputType.CrewOrders] = new KeyOrMouse(Keys.C);
keyMapping[(int)InputType.Voice] = new KeyOrMouse(Keys.V); keyMapping[(int)InputType.Voice] = new KeyOrMouse(Keys.V);
keyMapping[(int)InputType.Command] = new KeyOrMouse(MouseButton.MiddleMouse);
if (Language == "French") if (Language == "French")
{ {
@@ -64,6 +68,7 @@ namespace Barotrauma
keyMapping[(int)InputType.Down] = new KeyOrMouse(Keys.S); keyMapping[(int)InputType.Down] = new KeyOrMouse(Keys.S);
keyMapping[(int)InputType.Left] = new KeyOrMouse(Keys.Q); keyMapping[(int)InputType.Left] = new KeyOrMouse(Keys.Q);
keyMapping[(int)InputType.Right] = new KeyOrMouse(Keys.D); keyMapping[(int)InputType.Right] = new KeyOrMouse(Keys.D);
keyMapping[(int)InputType.ToggleInventory] = new KeyOrMouse(Keys.A);
keyMapping[(int)InputType.SelectNextCharacter] = new KeyOrMouse(Keys.X); keyMapping[(int)InputType.SelectNextCharacter] = new KeyOrMouse(Keys.X);
keyMapping[(int)InputType.SelectPreviousCharacter] = new KeyOrMouse(Keys.W); keyMapping[(int)InputType.SelectPreviousCharacter] = new KeyOrMouse(Keys.W);
@@ -74,6 +79,7 @@ namespace Barotrauma
keyMapping[(int)InputType.Down] = new KeyOrMouse(Keys.S); keyMapping[(int)InputType.Down] = new KeyOrMouse(Keys.S);
keyMapping[(int)InputType.Left] = new KeyOrMouse(Keys.A); keyMapping[(int)InputType.Left] = new KeyOrMouse(Keys.A);
keyMapping[(int)InputType.Right] = new KeyOrMouse(Keys.D); keyMapping[(int)InputType.Right] = new KeyOrMouse(Keys.D);
keyMapping[(int)InputType.ToggleInventory] = new KeyOrMouse(Keys.Q);
keyMapping[(int)InputType.SelectNextCharacter] = new KeyOrMouse(Keys.Z); keyMapping[(int)InputType.SelectNextCharacter] = new KeyOrMouse(Keys.Z);
keyMapping[(int)InputType.SelectPreviousCharacter] = new KeyOrMouse(Keys.X); keyMapping[(int)InputType.SelectPreviousCharacter] = new KeyOrMouse(Keys.X);
@@ -227,7 +233,7 @@ namespace Barotrauma
} }
label = text.Text.Substring(0, index); label = text.Text.Substring(0, index);
} }
text.Text = label + " " + barScroll * 100 + "%"; text.Text = label + " " + (int)(barScroll * 100) + "%";
return true; return true;
} }
@@ -256,26 +262,35 @@ namespace Barotrauma
settingsHolder = settingsFrameContent.RectTransform; settingsHolder = settingsFrameContent.RectTransform;
} }
Vector2 tickBoxScale = Vector2.One * 0.05f; Vector2 textBlockScale = new Vector2(1.0f, 0.05f);
Vector2 tickBoxScale = new Vector2(1.0f, 0.05f);
var settingsFramePadding = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), settingsHolder, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.05f) }) { RelativeSpacing = 0.01f, IsHorizontal = true }; var settingsFramePadding = new GUIFrame(new RectTransform(new Vector2(0.95f, 0.93f), settingsHolder, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.05f) }, style: null);
var buttonArea = new GUIFrame(new RectTransform(new Vector2(0.6f, 0.06f), settingsFramePadding.RectTransform, Anchor.BottomRight) { RelativeOffset = new Vector2(0.07f, 0.0f) }, style: null)
{
IgnoreLayoutGroups = true
};
/// General tab -------------------------------------------------------------- /// General tab --------------------------------------------------------------
var leftPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.25f, 1.0f), settingsFramePadding.RectTransform, Anchor.TopLeft)); var leftPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.25f, 0.93f), settingsFramePadding.RectTransform))
{
Stretch = true,
RelativeSpacing = 0.01f
};
var settingsTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftPanel.RectTransform), var settingsTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftPanel.RectTransform),
TextManager.Get("Settings"), textAlignment: Alignment.TopLeft, font: GUI.LargeFont) TextManager.Get("Settings"), textAlignment: Alignment.TopLeft, font: GUI.LargeFont)
{ ForceUpperCase = true }; { ForceUpperCase = true };
var generalLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), leftPanel.RectTransform, Anchor.TopLeft)); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftPanel.RectTransform), TextManager.Get("ContentPackages"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), generalLayoutGroup.RectTransform), TextManager.Get("ContentPackages")); var corePackageDropdown = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftPanel.RectTransform))
{
ButtonEnabled = ContentPackage.List.Count(cp => cp.CorePackage) > 1
};
var corePackageDropdown = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), generalLayoutGroup.RectTransform)); contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.70f), leftPanel.RectTransform))
corePackageDropdown.ButtonEnabled = ContentPackage.List.Count(cp => cp.CorePackage) > 1;
contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.70f), generalLayoutGroup.RectTransform))
{ {
OnSelected = (gc, obj) => false, OnSelected = (gc, obj) => false,
ScrollBarVisible = true ScrollBarVisible = true
@@ -292,7 +307,7 @@ namespace Barotrauma
if (!contentPackage.IsCompatible()) if (!contentPackage.IsCompatible())
{ {
frame.UserData = null; frame.UserData = null;
text.TextColor = Color.Red * 0.6f; text.TextColor = GUI.Style.Red * 0.6f;
frame.ToolTip = text.ToolTip = frame.ToolTip = text.ToolTip =
TextManager.GetWithVariables(contentPackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage", TextManager.GetWithVariables(contentPackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage",
new string[3] { "[packagename]", "[packageversion]", "[gameversion]" }, new string[3] { contentPackage.Name, contentPackage.GameVersion.ToString(), GameMain.Version.ToString() }); new string[3] { "[packagename]", "[packageversion]", "[gameversion]" }, new string[3] { contentPackage.Name, contentPackage.GameVersion.ToString(), GameMain.Version.ToString() });
@@ -300,7 +315,7 @@ namespace Barotrauma
else if (contentPackage.CorePackage && !contentPackage.ContainsRequiredCorePackageFiles(out List<ContentType> missingContentTypes)) else if (contentPackage.CorePackage && !contentPackage.ContainsRequiredCorePackageFiles(out List<ContentType> missingContentTypes))
{ {
frame.UserData = null; frame.UserData = null;
text.TextColor = Color.Red * 0.6f; text.TextColor = GUI.Style.Red * 0.6f;
frame.ToolTip = text.ToolTip = frame.ToolTip = text.ToolTip =
TextManager.GetWithVariables("ContentPackageMissingCoreFiles", new string[2] { "[packagename]", "[missingfiletypes]" }, TextManager.GetWithVariables("ContentPackageMissingCoreFiles", new string[2] { "[packagename]", "[missingfiletypes]" },
new string[2] { contentPackage.Name, string.Join(", ", missingContentTypes) }, new bool[2] { false, true }); new string[2] { contentPackage.Name, string.Join(", ", missingContentTypes) }, new bool[2] { false, true });
@@ -330,7 +345,19 @@ namespace Barotrauma
{ {
UserData = contentPackage UserData = contentPackage
}; };
var tickBox = new GUITickBox(new RectTransform(Vector2.One, frame.RectTransform, scaleBasis: ScaleBasis.BothHeight), contentPackage.Name,
var frameContent = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), frame.RectTransform, Anchor.Center), isHorizontal: true, childAnchor: Anchor.CenterLeft)
{
Stretch = true,
RelativeSpacing = 0.02f
};
var dragIndicator = new GUIButton(new RectTransform(new Vector2(0.1f, 0.5f), frameContent.RectTransform, scaleBasis: ScaleBasis.BothHeight),
style: "GUIDragIndicator")
{
CanBeFocused = false
};
var tickBox = new GUITickBox(new RectTransform(Vector2.One, frameContent.RectTransform), contentPackage.Name,
style: "GUITickBox") style: "GUITickBox")
{ {
UserData = contentPackage, UserData = contentPackage,
@@ -338,10 +365,11 @@ namespace Barotrauma
OnSelected = SelectContentPackage, OnSelected = SelectContentPackage,
Enabled = CanHotswapPackages(false) Enabled = CanHotswapPackages(false)
}; };
frame.RectTransform.MinSize = new Point(0, (int)(tickBox.RectTransform.MinSize.Y / frameContent.RectTransform.RelativeSize.Y));
if (!contentPackage.IsCompatible()) if (!contentPackage.IsCompatible())
{ {
tickBox.Enabled = false; tickBox.Enabled = false;
tickBox.TextColor = Color.Red * 0.6f; tickBox.TextColor = GUI.Style.Red * 0.6f;
tickBox.ToolTip = tickBox.TextBlock.ToolTip = tickBox.ToolTip = tickBox.TextBlock.ToolTip =
TextManager.GetWithVariables(contentPackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage", TextManager.GetWithVariables(contentPackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage",
new string[3] { "[packagename]", "[packageversion]", "[gameversion]" }, new string[3] { contentPackage.Name, contentPackage.GameVersion.ToString(), GameMain.Version.ToString() }); new string[3] { "[packagename]", "[packageversion]", "[gameversion]" }, new string[3] { contentPackage.Name, contentPackage.GameVersion.ToString(), GameMain.Version.ToString() });
@@ -353,15 +381,13 @@ namespace Barotrauma
TextManager.GetWithVariable("ContentPackageHasErrors", "[packagename]", contentPackage.Name) + TextManager.GetWithVariable("ContentPackageHasErrors", "[packagename]", contentPackage.Name) +
"\n" + string.Join("\n", contentPackage.ErrorMessages); "\n" + string.Join("\n", contentPackage.ErrorMessages);
} }
tickBox.TextBlock.CanBeFocused = true;
} }
contentPackageList.CanDragElements = CanHotswapPackages(false); contentPackageList.CanDragElements = CanHotswapPackages(false);
contentPackageList.CanBeFocused = CanHotswapPackages(false); contentPackageList.CanBeFocused = CanHotswapPackages(false);
contentPackageList.OnRearranged = OnContentPackagesRearranged; contentPackageList.OnRearranged = OnContentPackagesRearranged;
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.045f), generalLayoutGroup.RectTransform), TextManager.Get("Language")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.045f), leftPanel.RectTransform), TextManager.Get("Language"), font: GUI.SubHeadingFont);
var languageDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.045f), generalLayoutGroup.RectTransform)); var languageDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.045f), leftPanel.RectTransform));
foreach (string language in TextManager.AvailableLanguages) foreach (string language in TextManager.AvailableLanguages)
{ {
languageDD.AddItem(TextManager.GetTranslatedLanguageName(language), language); languageDD.AddItem(TextManager.GetTranslatedLanguageName(language), language);
@@ -396,28 +422,48 @@ namespace Barotrauma
return true; return true;
}; };
var rightPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.99f - leftPanel.RectTransform.RelativeSize.X, 0.95f), // right panel --------------------------------------
settingsFramePadding.RectTransform, Anchor.TopLeft));
var rightPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.99f - leftPanel.RectTransform.RelativeSize.X, leftPanel.RectTransform.RelativeSize.Y),
settingsFramePadding.RectTransform, Anchor.TopRight))
{
Stretch = true
};
var tabButtonHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), rightPanel.RectTransform, Anchor.TopCenter), isHorizontal: true); var tabButtonHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), rightPanel.RectTransform, Anchor.TopCenter), isHorizontal: true);
var paddedFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), rightPanel.RectTransform, Anchor.Center), style: null); var paddedFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), rightPanel.RectTransform, Anchor.Center), style: null);
tabs = new GUIFrame[Enum.GetValues(typeof(Tab)).Length]; tabs = new GUIFrame[Enum.GetValues(typeof(Tab)).Length];
tabButtons = new GUIButton[tabs.Length]; tabButtons = new GUIButton[tabs.Length];
foreach (Tab tab in Enum.GetValues(typeof(Tab))) foreach (Tab tab in Enum.GetValues(typeof(Tab)))
{ {
tabs[(int)tab] = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.91f), paddedFrame.RectTransform), style: "InnerFrame") tabs[(int)tab] = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), paddedFrame.RectTransform), style: "InnerFrame")
{ {
UserData = tab UserData = tab
}; };
tabButtons[(int)tab] = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tabButtonHolder.RectTransform),
TextManager.Get("SettingsTab." + tab.ToString()), style: "GUITabButton") #if DEBUG
if (tab != Tab.Debug)
{ {
UserData = tab, #endif
OnClicked = (bt, userdata) => { SelectTab((Tab)userdata); return true; } tabButtons[(int)tab] = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tabButtonHolder.RectTransform),
}; TextManager.Get("SettingsTab." + tab.ToString()), style: "GUITabButton")
{
UserData = tab,
OnClicked = (bt, userdata) => { SelectTab((Tab)userdata); return true; }
};
#if DEBUG
}
else
{
tabButtons[(int)tab] = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tabButtonHolder.RectTransform), "Debug", style: "GUITabButton")
{
UserData = tab,
OnClicked = (bt, userdata) => { SelectTab((Tab)userdata); return true; }
};
}
#endif
} }
new GUIButton(new RectTransform(new Vector2(0.05f, 0.75f), tabButtonHolder.RectTransform, Anchor.BottomRight) { RelativeOffset = new Vector2(0.0f, 0.2f) }, style: "GUIBugButton") new GUIButton(new RectTransform(new Vector2(0.05f, 0.75f), tabButtonHolder.RectTransform, Anchor.BottomRight) { RelativeOffset = new Vector2(0.0f, 0.2f) }, style: "GUIBugButton")
@@ -426,7 +472,6 @@ namespace Barotrauma
OnClicked = (btn, userdata) => { GameMain.Instance.ShowBugReporter(); return true; } OnClicked = (btn, userdata) => { GameMain.Instance.ShowBugReporter(); return true; }
}; };
var buttonArea = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.08f), paddedFrame.RectTransform, Anchor.BottomCenter), style: null);
/// Graphics tab -------------------------------------------------------------- /// Graphics tab --------------------------------------------------------------
@@ -437,7 +482,7 @@ namespace Barotrauma
{ RelativeOffset = new Vector2(0.025f, 0.02f) }) { RelativeOffset = new Vector2(0.025f, 0.02f) })
{ RelativeSpacing = 0.01f }; { RelativeSpacing = 0.01f };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), TextManager.Get("Resolution")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), TextManager.Get("Resolution"), font: GUI.SubHeadingFont);
var resolutionDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform)) var resolutionDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform))
{ {
ButtonEnabled = GameMain.Config.WindowMode != WindowMode.BorderlessWindowed ButtonEnabled = GameMain.Config.WindowMode != WindowMode.BorderlessWindowed
@@ -446,7 +491,7 @@ namespace Barotrauma
var supportedDisplayModes = UpdateResolutionDD(resolutionDD); var supportedDisplayModes = UpdateResolutionDD(resolutionDD);
resolutionDD.OnSelected = SelectResolution; resolutionDD.OnSelected = SelectResolution;
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), TextManager.Get("DisplayMode")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), TextManager.Get("DisplayMode"), font: GUI.SubHeadingFont);
var displayModeDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform)); var displayModeDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform));
displayModeDD.AddItem(TextManager.Get("Fullscreen"), WindowMode.Fullscreen); displayModeDD.AddItem(TextManager.Get("Fullscreen"), WindowMode.Fullscreen);
@@ -486,7 +531,7 @@ namespace Barotrauma
return true; return true;
}; };
GUITickBox vsyncTickBox = new GUITickBox(new RectTransform(tickBoxScale, leftColumn.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("EnableVSync")) GUITickBox vsyncTickBox = new GUITickBox(new RectTransform(tickBoxScale, leftColumn.RectTransform), TextManager.Get("EnableVSync"))
{ {
ToolTip = TextManager.Get("EnableVSyncToolTip"), ToolTip = TextManager.Get("EnableVSyncToolTip"),
OnSelected = (GUITickBox box) => OnSelected = (GUITickBox box) =>
@@ -502,19 +547,21 @@ namespace Barotrauma
}; };
GUITickBox pauseOnFocusLostBox = new GUITickBox(new RectTransform(tickBoxScale, leftColumn.RectTransform, scaleBasis: ScaleBasis.BothHeight), GUITickBox pauseOnFocusLostBox = new GUITickBox(new RectTransform(tickBoxScale, leftColumn.RectTransform),
TextManager.Get("PauseOnFocusLost")); TextManager.Get("PauseOnFocusLost"))
pauseOnFocusLostBox.Selected = PauseOnFocusLost;
pauseOnFocusLostBox.ToolTip = TextManager.Get("PauseOnFocusLostToolTip");
pauseOnFocusLostBox.OnSelected = (tickBox) =>
{ {
PauseOnFocusLost = tickBox.Selected; Selected = PauseOnFocusLost,
UnsavedSettings = true; ToolTip = TextManager.Get("PauseOnFocusLostToolTip"),
return true; OnSelected = (tickBox) =>
{
PauseOnFocusLost = tickBox.Selected;
UnsavedSettings = true;
return true;
}
}; };
GUITextBlock particleLimitText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("ParticleLimit")); GUITextBlock particleLimitText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("ParticleLimit"), font: GUI.SubHeadingFont);
GUIScrollBar particleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), GUIScrollBar particleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), style: "GUISlider",
barSize: 0.1f) barSize: 0.1f)
{ {
UserData = particleLimitText, UserData = particleLimitText,
@@ -529,7 +576,7 @@ namespace Barotrauma
}; };
particleScrollBar.OnMoved(particleScrollBar, particleScrollBar.BarScroll); particleScrollBar.OnMoved(particleScrollBar, particleScrollBar.BarScroll);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("LosEffect")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("LosEffect"), font: GUI.SubHeadingFont);
var losModeDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform)); var losModeDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform));
losModeDD.AddItem(TextManager.Get("LosModeNone"), LosMode.None); losModeDD.AddItem(TextManager.Get("LosModeNone"), LosMode.None);
losModeDD.AddItem(TextManager.Get("LosModeTransparent"), LosMode.Transparent); losModeDD.AddItem(TextManager.Get("LosModeTransparent"), LosMode.Transparent);
@@ -547,12 +594,12 @@ namespace Barotrauma
return true; return true;
}; };
GUITextBlock LightText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("LightMapScale")) GUITextBlock LightText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("LightMapScale"), font: GUI.SubHeadingFont)
{ {
ToolTip = TextManager.Get("LightMapScaleToolTip") ToolTip = TextManager.Get("LightMapScaleToolTip")
}; };
GUIScrollBar lightScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), GUIScrollBar lightScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform),
barSize: 0.1f) style: "GUISlider", barSize: 0.1f)
{ {
UserData = LightText, UserData = LightText,
ToolTip = TextManager.Get("LightMapScaleToolTip"), ToolTip = TextManager.Get("LightMapScaleToolTip"),
@@ -567,7 +614,7 @@ namespace Barotrauma
}; };
lightScrollBar.OnMoved(lightScrollBar, lightScrollBar.BarScroll); lightScrollBar.OnMoved(lightScrollBar, lightScrollBar.BarScroll);
/*new GUITickBox(new RectTransform(tickBoxScale, rightColumn.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("SpecularLighting")) /*new GUITickBox(new RectTransform(tickBoxScale, rightColumn.RectTransform), TextManager.Get("SpecularLighting"))
{ {
ToolTip = TextManager.Get("SpecularLightingToolTip"), ToolTip = TextManager.Get("SpecularLightingToolTip"),
Selected = SpecularityEnabled, Selected = SpecularityEnabled,
@@ -579,7 +626,7 @@ namespace Barotrauma
} }
};*/ };*/
new GUITickBox(new RectTransform(tickBoxScale, rightColumn.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("ChromaticAberration")) new GUITickBox(new RectTransform(tickBoxScale, rightColumn.RectTransform), TextManager.Get("ChromaticAberration"))
{ {
ToolTip = TextManager.Get("ChromaticAberrationToolTip"), ToolTip = TextManager.Get("ChromaticAberrationToolTip"),
Selected = ChromaticAberrationEnabled, Selected = ChromaticAberrationEnabled,
@@ -591,9 +638,9 @@ namespace Barotrauma
} }
}; };
GUITextBlock HUDScaleText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("HUDScale")); GUITextBlock HUDScaleText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("HUDScale"), font: GUI.SubHeadingFont);
GUIScrollBar HUDScaleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), GUIScrollBar HUDScaleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform),
barSize: 0.1f) style: "GUISlider", barSize: 0.1f)
{ {
UserData = HUDScaleText, UserData = HUDScaleText,
BarScroll = (HUDScale - MinHUDScale) / (MaxHUDScale - MinHUDScale), BarScroll = (HUDScale - MinHUDScale) / (MaxHUDScale - MinHUDScale),
@@ -609,8 +656,9 @@ namespace Barotrauma
}; };
HUDScaleScrollBar.OnMoved(HUDScaleScrollBar, HUDScaleScrollBar.BarScroll); HUDScaleScrollBar.OnMoved(HUDScaleScrollBar, HUDScaleScrollBar.BarScroll);
GUITextBlock inventoryScaleText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("InventoryScale")); GUITextBlock inventoryScaleText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("InventoryScale"), font: GUI.SubHeadingFont);
GUIScrollBar inventoryScaleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), barSize: 0.1f) GUIScrollBar inventoryScaleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform),
style: "GUISlider", barSize: 0.1f)
{ {
UserData = inventoryScaleText, UserData = inventoryScaleText,
BarScroll = (InventoryScale - MinInventoryScale) / (MaxInventoryScale - MinInventoryScale), BarScroll = (InventoryScale - MinInventoryScale) / (MaxInventoryScale - MinInventoryScale),
@@ -627,13 +675,15 @@ namespace Barotrauma
/// Audio tab ---------------------------------------------------------------- /// Audio tab ----------------------------------------------------------------
var audioSliders = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.3f), tabs[(int)Tab.Audio].RectTransform, Anchor.TopCenter) var audioContent = new GUILayoutGroup(new RectTransform(new Vector2(0.97f, 0.97f), tabs[(int)Tab.Audio].RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter)
{ RelativeOffset = new Vector2(0.0f, 0.02f) }) {
{ RelativeSpacing = 0.01f }; Stretch = true,
RelativeSpacing = 0.01f
GUITextBlock soundVolumeText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), audioSliders.RectTransform), TextManager.Get("SoundVolume")); };
GUIScrollBar soundScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.15f), audioSliders.RectTransform),
barSize: 0.05f) GUITextBlock soundVolumeText = new GUITextBlock(new RectTransform(textBlockScale, audioContent.RectTransform), TextManager.Get("SoundVolume"), font: GUI.SubHeadingFont);
GUIScrollBar soundScrollBar = new GUIScrollBar(new RectTransform(textBlockScale, audioContent.RectTransform),
style: "GUISlider", barSize: 0.05f)
{ {
UserData = soundVolumeText, UserData = soundVolumeText,
BarScroll = SoundVolume, BarScroll = SoundVolume,
@@ -647,9 +697,9 @@ namespace Barotrauma
}; };
soundScrollBar.OnMoved(soundScrollBar, soundScrollBar.BarScroll); soundScrollBar.OnMoved(soundScrollBar, soundScrollBar.BarScroll);
GUITextBlock musicVolumeText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), audioSliders.RectTransform), TextManager.Get("MusicVolume")); GUITextBlock musicVolumeText = new GUITextBlock(new RectTransform(textBlockScale, audioContent.RectTransform), TextManager.Get("MusicVolume"), font: GUI.SubHeadingFont);
GUIScrollBar musicScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.15f), audioSliders.RectTransform), GUIScrollBar musicScrollBar = new GUIScrollBar(new RectTransform(textBlockScale, audioContent.RectTransform),
barSize: 0.05f) style: "GUISlider", barSize: 0.05f)
{ {
UserData = musicVolumeText, UserData = musicVolumeText,
BarScroll = MusicVolume, BarScroll = MusicVolume,
@@ -663,9 +713,9 @@ namespace Barotrauma
}; };
musicScrollBar.OnMoved(musicScrollBar, musicScrollBar.BarScroll); musicScrollBar.OnMoved(musicScrollBar, musicScrollBar.BarScroll);
GUITextBlock voiceChatVolumeText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), audioSliders.RectTransform), TextManager.Get("VoiceChatVolume")); GUITextBlock voiceChatVolumeText = new GUITextBlock(new RectTransform(textBlockScale, audioContent.RectTransform), TextManager.Get("VoiceChatVolume"), font: GUI.SubHeadingFont);
GUIScrollBar voiceChatScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.15f), audioSliders.RectTransform), GUIScrollBar voiceChatScrollBar = new GUIScrollBar(new RectTransform(textBlockScale, audioContent.RectTransform),
barSize: 0.05f) style: "GUISlider", barSize: 0.05f)
{ {
UserData = voiceChatVolumeText, UserData = voiceChatVolumeText,
BarScroll = VoiceChatVolume, BarScroll = VoiceChatVolume,
@@ -679,45 +729,43 @@ namespace Barotrauma
}; };
voiceChatScrollBar.OnMoved(voiceChatScrollBar, voiceChatScrollBar.BarScroll); voiceChatScrollBar.OnMoved(voiceChatScrollBar, voiceChatScrollBar.BarScroll);
var tickBoxes = new GUILayoutGroup(new RectTransform(new Vector2(0.28f, 0.15f), tabs[(int)Tab.Audio].RectTransform, Anchor.TopLeft) GUITickBox muteOnFocusLostBox = new GUITickBox(new RectTransform(tickBoxScale, audioContent.RectTransform), TextManager.Get("MuteOnFocusLost"))
{ RelativeOffset = new Vector2(0.02f, 0.32f) })
{ RelativeSpacing = 0.01f };
GUITickBox muteOnFocusLostBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, tickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("MuteOnFocusLost"));
muteOnFocusLostBox.Selected = MuteOnFocusLost;
muteOnFocusLostBox.ToolTip = TextManager.Get("MuteOnFocusLostToolTip");
muteOnFocusLostBox.OnSelected = (tickBox) =>
{ {
MuteOnFocusLost = tickBox.Selected; Selected = MuteOnFocusLost,
UnsavedSettings = true; ToolTip = TextManager.Get("MuteOnFocusLostToolTip"),
return true; OnSelected = (tickBox) =>
{
MuteOnFocusLost = tickBox.Selected;
UnsavedSettings = true;
return true;
}
}; };
GUITickBox dynamicRangeCompressionTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, tickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("DynamicRangeCompression")); GUITickBox dynamicRangeCompressionTickBox = new GUITickBox(new RectTransform(tickBoxScale, audioContent.RectTransform), TextManager.Get("DynamicRangeCompression"))
dynamicRangeCompressionTickBox.Selected = DynamicRangeCompressionEnabled;
dynamicRangeCompressionTickBox.ToolTip = TextManager.Get("DynamicRangeCompressionToolTip");
dynamicRangeCompressionTickBox.OnSelected = (tickBox) =>
{ {
DynamicRangeCompressionEnabled = tickBox.Selected; Selected = DynamicRangeCompressionEnabled,
UnsavedSettings = true; ToolTip = TextManager.Get("DynamicRangeCompressionToolTip"),
return true; OnSelected = (tickBox) =>
{
DynamicRangeCompressionEnabled = tickBox.Selected;
UnsavedSettings = true;
return true;
}
}; };
GUITickBox voipAttenuationTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, tickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("VoipAttenuation")); GUITickBox voipAttenuationTickBox = new GUITickBox(new RectTransform(tickBoxScale, audioContent.RectTransform), TextManager.Get("VoipAttenuation"))
voipAttenuationTickBox.Selected = VoipAttenuationEnabled;
voipAttenuationTickBox.ToolTip = TextManager.Get("VoipAttenuationToolTip");
voipAttenuationTickBox.OnSelected = (tickBox) =>
{ {
VoipAttenuationEnabled = tickBox.Selected; Selected = VoipAttenuationEnabled,
UnsavedSettings = true; ToolTip = TextManager.Get("VoipAttenuationToolTip"),
return true; OnSelected = (tickBox) =>
{
VoipAttenuationEnabled = tickBox.Selected;
UnsavedSettings = true;
return true;
}
}; };
var voipSettings = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.35f), tabs[(int)Tab.Audio].RectTransform, Anchor.TopCenter) new GUITextBlock(new RectTransform(textBlockScale, audioContent.RectTransform), TextManager.Get("VoiceChat"), font: GUI.SubHeadingFont);
{ RelativeOffset = new Vector2(0.0f, 0.47f) })
{ RelativeSpacing = 0.01f };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), voipSettings.RectTransform), TextManager.Get("VoiceChat"));
CaptureDeviceNames = Alc.GetStringList((IntPtr)null, Alc.CaptureDeviceSpecifier); CaptureDeviceNames = Alc.GetStringList((IntPtr)null, Alc.CaptureDeviceSpecifier);
foreach (string name in CaptureDeviceNames) foreach (string name in CaptureDeviceNames)
@@ -725,14 +773,16 @@ namespace Barotrauma
DebugConsole.NewMessage(name + " " + name.Length.ToString(), Color.Lime); DebugConsole.NewMessage(name + " " + name.Length.ToString(), Color.Lime);
} }
GUITickBox directionalVoiceChat = new GUITickBox(new RectTransform(tickBoxScale / 0.4f, voipSettings.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("DirectionalVoiceChat")); GUITickBox directionalVoiceChat = new GUITickBox(new RectTransform(tickBoxScale, audioContent.RectTransform), TextManager.Get("DirectionalVoiceChat"))
directionalVoiceChat.Selected = UseDirectionalVoiceChat;
directionalVoiceChat.ToolTip = TextManager.Get("DirectionalVoiceChatToolTip");
directionalVoiceChat.OnSelected = (tickBox) =>
{ {
UseDirectionalVoiceChat = tickBox.Selected; Selected = UseDirectionalVoiceChat,
UnsavedSettings = true; ToolTip = TextManager.Get("DirectionalVoiceChatToolTip"),
return true; OnSelected = (tickBox) =>
{
UseDirectionalVoiceChat = tickBox.Selected;
UnsavedSettings = true;
return true;
}
}; };
if (string.IsNullOrWhiteSpace(VoiceCaptureDevice) || !(CaptureDeviceNames?.Contains(VoiceCaptureDevice) ?? false)) if (string.IsNullOrWhiteSpace(VoiceCaptureDevice) || !(CaptureDeviceNames?.Contains(VoiceCaptureDevice) ?? false))
@@ -744,7 +794,7 @@ namespace Barotrauma
VoiceSetting = VoiceMode.Disabled; VoiceSetting = VoiceMode.Disabled;
} }
#if (!OSX) #if (!OSX)
var deviceList = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.15f), voipSettings.RectTransform), TrimAudioDeviceName(VoiceCaptureDevice), CaptureDeviceNames.Count); var deviceList = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.15f), audioContent.RectTransform), TrimAudioDeviceName(VoiceCaptureDevice), CaptureDeviceNames.Count);
if (CaptureDeviceNames?.Count > 0) if (CaptureDeviceNames?.Count > 0)
{ {
foreach (string name in CaptureDeviceNames) foreach (string name in CaptureDeviceNames)
@@ -763,15 +813,15 @@ namespace Barotrauma
else else
{ {
deviceList.AddItem(TextManager.Get("VoipNoDevices") ?? "N/A", null); deviceList.AddItem(TextManager.Get("VoipNoDevices") ?? "N/A", null);
deviceList.ButtonTextColor = Color.Red; deviceList.ButtonTextColor = GUI.Style.Red;
deviceList.ButtonEnabled = false; deviceList.ButtonEnabled = false;
deviceList.Select(0); deviceList.Select(0);
} }
#else #else
var defaultDeviceGroup = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.3f), voipSettings.RectTransform), true, Anchor.CenterLeft); var defaultDeviceGroup = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.3f), audioContent.RectTransform), true, Anchor.CenterLeft);
var currentDeviceTextBlock = new GUITextBlock(new RectTransform(new Vector2(.7f, 0.75f), null), var currentDeviceTextBlock = new GUITextBlock(new RectTransform(new Vector2(.7f, 0.75f), null),
TextManager.AddPunctuation(':', TextManager.Get("CurrentDevice"), TrimAudioDeviceName(VoiceCaptureDevice))) TextManager.AddPunctuation(':', TextManager.Get("CurrentDevice"), TrimAudioDeviceName(VoiceCaptureDevice)), font: GUI.SubHeadingFont)
{ {
ToolTip = TextManager.Get("CurrentDeviceToolTip.OSX"), ToolTip = TextManager.Get("CurrentDeviceToolTip.OSX"),
TextAlignment = Alignment.CenterLeft TextAlignment = Alignment.CenterLeft
@@ -795,7 +845,7 @@ namespace Barotrauma
else else
{ {
currentDeviceTextBlock.Text = TextManager.Get("VoipNoDevices") ?? "N/A"; currentDeviceTextBlock.Text = TextManager.Get("VoipNoDevices") ?? "N/A";
currentDeviceTextBlock.Flash(Color.Red); currentDeviceTextBlock.Flash(GUI.Style.Red);
} }
return true; return true;
@@ -807,16 +857,16 @@ namespace Barotrauma
#endif #endif
var voiceModeCount = Enum.GetNames(typeof(VoiceMode)).Length; var voiceModeCount = Enum.GetNames(typeof(VoiceMode)).Length;
var voiceModeDropDown = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.15f), voipSettings.RectTransform), elementCount: voiceModeCount); var voiceModeDropDown = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.15f), audioContent.RectTransform), elementCount: voiceModeCount);
for (int i = 0; i < voiceModeCount; i++) for (int i = 0; i < voiceModeCount; i++)
{ {
var voiceMode = "VoiceMode." + ((VoiceMode)i).ToString(); var voiceMode = "VoiceMode." + ((VoiceMode)i).ToString();
voiceModeDropDown.AddItem(TextManager.Get(voiceMode), userData: i, toolTip: TextManager.Get(voiceMode + "ToolTip")); voiceModeDropDown.AddItem(TextManager.Get(voiceMode), userData: i, toolTip: TextManager.Get(voiceMode + "ToolTip"));
} }
var micVolumeText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), voipSettings.RectTransform), TextManager.Get("MicrophoneVolume")); var micVolumeText = new GUITextBlock(new RectTransform(textBlockScale, audioContent.RectTransform), TextManager.Get("MicrophoneVolume"), font: GUI.SubHeadingFont);
var micVolumeSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.15f), voipSettings.RectTransform), var micVolumeSlider = new GUIScrollBar(new RectTransform(textBlockScale, audioContent.RectTransform),
barSize: 0.05f) style: "GUISlider", barSize: 0.05f)
{ {
UserData = micVolumeText, UserData = micVolumeText,
BarScroll = (float)Math.Sqrt(MathUtils.InverseLerp(0.2f, MaxMicrophoneVolume, MicrophoneVolume)), BarScroll = (float)Math.Sqrt(MathUtils.InverseLerp(0.2f, MaxMicrophoneVolume, MicrophoneVolume)),
@@ -832,14 +882,13 @@ namespace Barotrauma
}; };
micVolumeSlider.OnMoved(micVolumeSlider, micVolumeSlider.BarScroll); micVolumeSlider.OnMoved(micVolumeSlider, micVolumeSlider.BarScroll);
var extraVoiceSettingsContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.25f), audioContent.RectTransform, Anchor.BottomCenter), style: null);
var extraVoiceSettingsContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.6f), voipSettings.RectTransform, Anchor.BottomCenter), style: null);
var voiceActivityGroup = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), extraVoiceSettingsContainer.RectTransform)) var voiceActivityGroup = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), extraVoiceSettingsContainer.RectTransform))
{ {
Visible = VoiceSetting != VoiceMode.Disabled Visible = VoiceSetting != VoiceMode.Disabled
}; };
GUITextBlock noiseGateText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), voiceActivityGroup.RectTransform), TextManager.Get("NoiseGateThreshold")) GUITextBlock noiseGateText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), voiceActivityGroup.RectTransform), TextManager.Get("NoiseGateThreshold"), font: GUI.SubHeadingFont)
{ {
Visible = VoiceSetting == VoiceMode.Activity, Visible = VoiceSetting == VoiceMode.Activity,
TextGetter = () => TextGetter = () =>
@@ -854,7 +903,7 @@ namespace Barotrauma
if (VoiceSetting == VoiceMode.Activity) if (VoiceSetting == VoiceMode.Activity)
{ {
dbMeter.Color = VoipCapture.Instance.LastdB > NoiseGateThreshold ? Color.Lime : Color.Orange; //TODO: i'm a filthy hack dbMeter.Color = VoipCapture.Instance.LastdB > NoiseGateThreshold ? GUI.Style.Green : GUI.Style.Orange; //TODO: i'm a filthy hack
} }
else else
{ {
@@ -864,7 +913,8 @@ namespace Barotrauma
float scrollVal = double.IsNegativeInfinity(VoipCapture.Instance.LastdB) ? 0.0f : ((float)VoipCapture.Instance.LastdB + 100.0f) / 100.0f; float scrollVal = double.IsNegativeInfinity(VoipCapture.Instance.LastdB) ? 0.0f : ((float)VoipCapture.Instance.LastdB + 100.0f) / 100.0f;
return scrollVal * scrollVal; return scrollVal * scrollVal;
}; };
var noiseGateSlider = new GUIScrollBar(new RectTransform(Vector2.One, dbMeter.RectTransform, Anchor.Center), color: Color.White, barSize: 0.03f); var noiseGateSlider = new GUIScrollBar(new RectTransform(Vector2.One, dbMeter.RectTransform, Anchor.Center), color: Color.White,
style: "GUISlider", barSize: 0.03f);
noiseGateSlider.Frame.Visible = false; noiseGateSlider.Frame.Visible = false;
noiseGateSlider.Step = 0.01f; noiseGateSlider.Step = 0.01f;
noiseGateSlider.Range = new Vector2(-100.0f, 0.0f); noiseGateSlider.Range = new Vector2(-100.0f, 0.0f);
@@ -887,7 +937,7 @@ namespace Barotrauma
{ {
Visible = VoiceSetting == VoiceMode.PushToTalk Visible = VoiceSetting == VoiceMode.PushToTalk
}; };
new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), voiceInputContainer.RectTransform), TextManager.Get("InputType.Voice")); new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), voiceInputContainer.RectTransform), TextManager.Get("InputType.Voice"), font: GUI.SubHeadingFont);
var voiceKeyBox = new GUITextBox(new RectTransform(new Vector2(0.4f, 1.0f), voiceInputContainer.RectTransform, Anchor.TopRight), text: KeyBindText(InputType.Voice)) var voiceKeyBox = new GUITextBox(new RectTransform(new Vector2(0.4f, 1.0f), voiceInputContainer.RectTransform, Anchor.TopRight), text: KeyBindText(InputType.Voice))
{ {
SelectedColor = Color.Gold * 0.3f, SelectedColor = Color.Gold * 0.3f,
@@ -953,12 +1003,12 @@ namespace Barotrauma
{ RelativeOffset = new Vector2(0.0f, 0.02f) }) { RelativeOffset = new Vector2(0.0f, 0.02f) })
{ RelativeSpacing = 0.01f }; { RelativeSpacing = 0.01f };
GUITextBlock aimAssistText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), controlsLayoutGroup.RectTransform), TextManager.Get("AimAssist")) GUITextBlock aimAssistText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), controlsLayoutGroup.RectTransform), TextManager.Get("AimAssist"), font: GUI.SubHeadingFont)
{ {
ToolTip = TextManager.Get("AimAssistToolTip") ToolTip = TextManager.Get("AimAssistToolTip")
}; };
GUIScrollBar aimAssistSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), controlsLayoutGroup.RectTransform), GUIScrollBar aimAssistSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), controlsLayoutGroup.RectTransform),
barSize: 0.05f) style: "GUISlider", barSize: 0.05f)
{ {
UserData = aimAssistText, UserData = aimAssistText,
BarScroll = MathUtils.InverseLerp(0.0f, 5.0f, AimAssistAmount), BarScroll = MathUtils.InverseLerp(0.0f, 5.0f, AimAssistAmount),
@@ -973,7 +1023,7 @@ namespace Barotrauma
}; };
aimAssistSlider.OnMoved(aimAssistSlider, aimAssistSlider.BarScroll); aimAssistSlider.OnMoved(aimAssistSlider, aimAssistSlider.BarScroll);
new GUITickBox(new RectTransform(tickBoxScale, controlsLayoutGroup.RectTransform, scaleBasis: ScaleBasis.BothHeight), TextManager.Get("EnableMouseLook")) new GUITickBox(new RectTransform(tickBoxScale, controlsLayoutGroup.RectTransform), TextManager.Get("EnableMouseLook"))
{ {
ToolTip = TextManager.Get("EnableMouseLookToolTip"), ToolTip = TextManager.Get("EnableMouseLookToolTip"),
Selected = EnableMouseLook, Selected = EnableMouseLook,
@@ -999,11 +1049,11 @@ namespace Barotrauma
{ {
var inputContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.06f),(i <= (inputNames.Length / 2.2f) ? inputColumnLeft : inputColumnRight).RectTransform)) var inputContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.06f),(i <= (inputNames.Length / 2.2f) ? inputColumnLeft : inputColumnRight).RectTransform))
{ Stretch = true, IsHorizontal = true, RelativeSpacing = 0.01f, Color = new Color(12, 14, 15, 215) }; { Stretch = true, IsHorizontal = true, RelativeSpacing = 0.01f, Color = new Color(12, 14, 15, 215) };
var inputName = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), inputContainer.RectTransform, Anchor.TopLeft) { MinSize = new Point(150, 0) }, var inputName = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), inputContainer.RectTransform, Anchor.TopLeft) { MinSize = new Point(100, 0) },
TextManager.Get("InputType." + ((InputType)i)), font: GUI.SmallFont) { ForceUpperCase = true }; TextManager.Get("InputType." + ((InputType)i)), font: GUI.SmallFont) { ForceUpperCase = true };
inputNameBlocks.Add(inputName); inputNameBlocks.Add(inputName);
var keyBox = new GUITextBox(new RectTransform(new Vector2(0.4f, 1.0f), inputContainer.RectTransform), var keyBox = new GUITextBox(new RectTransform(new Vector2(0.4f, 1.0f), inputContainer.RectTransform),
text: KeyBindText((InputType)i), font: GUI.SmallFont) text: KeyBindText((InputType)i), font: GUI.SmallFont, style: "GUITextBoxNoIcon")
{ {
UserData = i UserData = i
}; };
@@ -1020,12 +1070,15 @@ namespace Barotrauma
GUITextBlock.AutoScaleAndNormalize(inputNameBlocks); GUITextBlock.AutoScaleAndNormalize(inputNameBlocks);
var resetControlsHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.07f), controlsLayoutGroup.RectTransform), isHorizontal: true) var resetControlsArea = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.07f), controlsLayoutGroup.RectTransform), style: null);
var resetControlsHolder = new GUILayoutGroup(new RectTransform(new Vector2(buttonArea.RectTransform.RelativeSize.X / controlsLayoutGroup.RectTransform.RelativeSize.X / rightPanel.RectTransform.RelativeSize.X, 1.0f), resetControlsArea.RectTransform, Anchor.Center),
isHorizontal: true, childAnchor: Anchor.CenterLeft)
{ {
RelativeSpacing = 0.02f Stretch = true,
}; RelativeSpacing = 0.05f
}; resetControlsHolder.CanBeFocused = true;
var defaultBindingsButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetDefaultBindings")) var defaultBindingsButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetDefaultBindings"), style: "GUIButtonSmall")
{ {
ToolTip = TextManager.Get("SetDefaultBindingsToolTip"), ToolTip = TextManager.Get("SetDefaultBindingsToolTip"),
OnClicked = (button, data) => OnClicked = (button, data) =>
@@ -1035,7 +1088,7 @@ namespace Barotrauma
} }
}; };
var legacyBindingsButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetLegacyBindings")) var legacyBindingsButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetLegacyBindings"), style: "GUIButtonSmall")
{ {
ToolTip = TextManager.Get("SetLegacyBindingsToolTip"), ToolTip = TextManager.Get("SetLegacyBindingsToolTip"),
OnClicked = (button, data) => OnClicked = (button, data) =>
@@ -1050,17 +1103,13 @@ namespace Barotrauma
GUITextBlock.AutoScaleAndNormalize(defaultBindingsButton.TextBlock, legacyBindingsButton.TextBlock); GUITextBlock.AutoScaleAndNormalize(defaultBindingsButton.TextBlock, legacyBindingsButton.TextBlock);
}; };
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.02f), generalLayoutGroup.RectTransform), style: null);
new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomLeft), new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomLeft),
TextManager.Get("Cancel"), style: "GUIButtonLarge") TextManager.Get("Cancel"))
{ {
IgnoreLayoutGroups = true, IgnoreLayoutGroups = true,
OnClicked = (x, y) => OnClicked = (x, y) =>
{ {
void ExitSettings() static void ExitSettings()
{ {
if (Screen.Selected == GameMain.MainMenuScreen) { GameMain.MainMenuScreen.ReturnToMainMenu(null, null); } if (Screen.Selected == GameMain.MainMenuScreen) { GameMain.MainMenuScreen.ReturnToMainMenu(null, null); }
GUI.SettingsMenuOpen = false; GUI.SettingsMenuOpen = false;
@@ -1091,7 +1140,7 @@ namespace Barotrauma
}; };
new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomCenter), new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomCenter),
TextManager.Get("Reset"), style: "GUIButtonLarge") TextManager.Get("Reset"))
{ {
IgnoreLayoutGroups = true, IgnoreLayoutGroups = true,
OnClicked = (button, data) => OnClicked = (button, data) =>
@@ -1126,13 +1175,50 @@ namespace Barotrauma
}; };
applyButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomRight), applyButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomRight),
TextManager.Get("ApplySettingsButton"), style: "GUIButtonLarge") TextManager.Get("ApplySettingsButton"))
{ {
IgnoreLayoutGroups = true, IgnoreLayoutGroups = true,
Enabled = false Enabled = false
}; };
applyButton.OnClicked = ApplyClicked; applyButton.OnClicked = ApplyClicked;
#if DEBUG
/// Debug tab ----------------------------------------------------------------
var debugTickBoxes = new GUILayoutGroup(new RectTransform(new Vector2(0.28f, 0.15f), tabs[(int)Tab.Debug].RectTransform, Anchor.TopLeft)
{ RelativeOffset = new Vector2(0.02f, 0.02f) })
{ RelativeSpacing = 0.01f };
var automaticQuickStartTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Enable automatic quickstart", style: "GUITickBox");
automaticQuickStartTickBox.Selected = AutomaticQuickStartEnabled;
automaticQuickStartTickBox.ToolTip = "Will the game automatically move on to Quickstart when the game is launched";
automaticQuickStartTickBox.OnSelected = (tickBox) =>
{
AutomaticQuickStartEnabled = tickBox.Selected;
UnsavedSettings = true;
return true;
};
var showSplashScreenTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Show splash screen", style: "GUITickBox");
showSplashScreenTickBox.Selected = EnableSplashScreen;
showSplashScreenTickBox.ToolTip = "Are the splash screens shown when the game is launched";
showSplashScreenTickBox.OnSelected = (tickBox) =>
{
EnableSplashScreen = tickBox.Selected;
UnsavedSettings = true;
return true;
};
var verboseLoggingTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Enable verbose logging", style: "GUITickBox");
verboseLoggingTickBox.Selected = VerboseLogging;
verboseLoggingTickBox.ToolTip = "Should verbose logging be used";
verboseLoggingTickBox.OnSelected = (tickBox) =>
{
VerboseLogging = tickBox.Selected;
UnsavedSettings = true;
return true;
};
#endif
UnsavedSettings = false; // Reset unsaved settings to false once the UI has been created UnsavedSettings = false; // Reset unsaved settings to false once the UI has been created
SelectTab(selectedTab); SelectTab(selectedTab);
} }
@@ -1418,7 +1504,7 @@ namespace Barotrauma
{ {
SaveNewPlayerConfig(); SaveNewPlayerConfig();
SettingsFrame.Flash(Color.Green); SettingsFrame.Flash(GUI.Style.Green);
if (GameMain.WindowMode != GameMain.Config.WindowMode || GameMain.Config.GraphicsWidth != GameMain.GraphicsWidth || GameMain.Config.GraphicsHeight != GameMain.GraphicsHeight) if (GameMain.WindowMode != GameMain.Config.WindowMode || GameMain.Config.GraphicsWidth != GameMain.GraphicsWidth || GameMain.Config.GraphicsHeight != GameMain.GraphicsHeight)
{ {
@@ -98,9 +98,10 @@ namespace Barotrauma
limbSlotIcons.Add(InvSlotType.Headset, new Sprite("Content/UI/IconAtlas.png", new Rectangle(384 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2))); limbSlotIcons.Add(InvSlotType.Headset, new Sprite("Content/UI/IconAtlas.png", new Rectangle(384 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.InnerClothes, new Sprite("Content/UI/IconAtlas.png", new Rectangle(512 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2))); limbSlotIcons.Add(InvSlotType.InnerClothes, new Sprite("Content/UI/IconAtlas.png", new Rectangle(512 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.Card, new Sprite("Content/UI/IconAtlas.png", new Rectangle(640 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2))); limbSlotIcons.Add(InvSlotType.Card, new Sprite("Content/UI/IconAtlas.png", new Rectangle(640 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.Head, new Sprite("Content/UI/IconAtlas.png", new Rectangle(896 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.LeftHand, new Sprite("Content/UI/IconAtlas.png", new Rectangle(640 + margin, 383 + margin, 128 - margin * 2, 128 - margin * 2))); limbSlotIcons.Add(InvSlotType.Head, new Sprite("Content/UI/IconAtlas.png", new Rectangle(896 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.RightHand, new Sprite("Content/UI/IconAtlas.png", new Rectangle(768 + margin, 383 + margin, 128 - margin * 2, 128 - margin * 2))); limbSlotIcons.Add(InvSlotType.LeftHand, new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(640 + margin, 0 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.RightHand, new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(768 + margin, 0 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.OuterClothes, new Sprite("Content/UI/IconAtlas.png", new Rectangle(768 + margin, 896 + margin, 128 - margin * 2, 128 - margin * 2))); limbSlotIcons.Add(InvSlotType.OuterClothes, new Sprite("Content/UI/IconAtlas.png", new Rectangle(768 + margin, 896 + margin, 128 - margin * 2, 128 - margin * 2)));
} }
SlotPositions = new Vector2[SlotTypes.Length]; SlotPositions = new Vector2[SlotTypes.Length];
@@ -146,7 +147,7 @@ namespace Barotrauma
{ {
InventorySlot prevSlot = slots[i]; InventorySlot prevSlot = slots[i];
Sprite slotSprite = slotSpriteSmall; Sprite slotSprite = SlotSpriteSmall;
Rectangle slotRect = new Rectangle( Rectangle slotRect = new Rectangle(
(int)(SlotPositions[i].X), (int)(SlotPositions[i].X),
(int)(SlotPositions[i].Y), (int)(SlotPositions[i].Y),
@@ -243,7 +244,7 @@ namespace Barotrauma
private void SetSlotPositions(Layout layout) private void SetSlotPositions(Layout layout)
{ {
int spacing = (int)(10 * UIScale); int spacing = (int)(10 * UIScale);
Point slotSize = (slotSpriteSmall.size * UIScale).ToPoint(); Point slotSize = (SlotSpriteSmall.size * UIScale).ToPoint();
int bottomOffset = slotSize.Y + spacing * 2 + ContainedIndicatorHeight; int bottomOffset = slotSize.Y + spacing * 2 + ContainedIndicatorHeight;
if (slots == null) CreateSlots(); if (slots == null) CreateSlots();
@@ -258,7 +259,7 @@ namespace Barotrauma
int normalSlotCount = SlotTypes.Count(s => !PersonalSlots.HasFlag(s)); int normalSlotCount = SlotTypes.Count(s => !PersonalSlots.HasFlag(s));
int x = GameMain.GraphicsWidth / 2 - normalSlotCount * (slotSize.X + spacing) / 2; int x = GameMain.GraphicsWidth / 2 - normalSlotCount * (slotSize.X + spacing) / 2;
int upperX = HUDLayoutSettings.PortraitArea.X - slotSize.X * 2; int upperX = GameMain.GraphicsWidth - slotSize.X * 2;
//make sure the rightmost normal slot doesn't overlap with the personal slots //make sure the rightmost normal slot doesn't overlap with the personal slots
x -= Math.Max((x + normalSlotCount * (slotSize.X + spacing)) - (upperX - personalSlotCount * (slotSize.X + spacing)), 0); x -= Math.Max((x + normalSlotCount * (slotSize.X + spacing)) - (upperX - personalSlotCount * (slotSize.X + spacing)), 0);
@@ -631,7 +632,7 @@ namespace Barotrauma
TextManager.Get("QuickUseAction.HoldToUnequip", returnNull: true) ?? TextManager.Get("QuickUseAction.HoldToUnequip", returnNull: true) ??
(GameMain.Config.Language == "English" ? "Hold to unequip" : TextManager.Get("QuickUseAction.Unequip")); (GameMain.Config.Language == "English" ? "Hold to unequip" : TextManager.Get("QuickUseAction.Unequip"));
if (PlayerInput.PrimaryMouseButtonHeld()) if (PlayerInput.LeftButtonHeld())
{ {
slot.QuickUseTimer = Math.Max(0.1f, slot.QuickUseTimer + deltaTime); slot.QuickUseTimer = Math.Max(0.1f, slot.QuickUseTimer + deltaTime);
if (slot.QuickUseTimer >= 1.0f) if (slot.QuickUseTimer >= 1.0f)
@@ -894,7 +895,7 @@ namespace Barotrauma
success = true; success = true;
for (int j = 0; j < capacity; j++) for (int j = 0; j < capacity; j++)
{ {
if (Items[j] == character.SelectedItems[i]) slots[j].ShowBorderHighlight(Color.Green, 0.1f, 0.4f); if (Items[j] == character.SelectedItems[i]) slots[j].ShowBorderHighlight(GUI.Style.Green, 0.1f, 0.4f);
} }
break; break;
} }
@@ -906,7 +907,7 @@ namespace Barotrauma
{ {
for (int i = 0; i < capacity; i++) for (int i = 0; i < capacity; i++)
{ {
if (Items[i] == item) slots[i].ShowBorderHighlight(Color.Green, 0.1f, 0.4f); if (Items[i] == item) slots[i].ShowBorderHighlight(GUI.Style.Green, 0.1f, 0.4f);
} }
} }
@@ -937,8 +938,18 @@ namespace Barotrauma
character.Name, Color.White * 0.9f); character.Name, Color.White * 0.9f);
} }
base.Draw(spriteBatch); for (int i = 0; i < capacity; i++)
{
if (HideSlot(i)) continue;
Rectangle interactRect = slots[i].InteractRect;
interactRect.Location += slots[i].DrawOffset.ToPoint();
//don't draw the item if it's being dragged out of the slot
bool drawItem = draggingItem == null || draggingItem != Items[i] || interactRect.Contains(PlayerInput.MousePosition);
DrawSlot(spriteBatch, this, slots[i], Items[i], i, drawItem, SlotTypes[i]);
}
if (hideButton != null && hideButton.Visible && !Locked) if (hideButton != null && hideButton.Visible && !Locked)
{ {
hideButton.DrawManually(spriteBatch, alsoChildren: true); hideButton.DrawManually(spriteBatch, alsoChildren: true);
@@ -957,7 +968,7 @@ namespace Barotrauma
if (limbSlotIcons.ContainsKey(SlotTypes[i])) if (limbSlotIcons.ContainsKey(SlotTypes[i]))
{ {
var icon = limbSlotIcons[SlotTypes[i]]; var icon = limbSlotIcons[SlotTypes[i]];
icon.Draw(spriteBatch, slots[i].Rect.Center.ToVector2() + slots[i].DrawOffset, Color.White * 0.3f, origin: icon.size / 2, scale: slots[i].Rect.Width / icon.size.X); icon.Draw(spriteBatch, slots[i].Rect.Center.ToVector2() + slots[i].DrawOffset, GUIColorSettings.EquipmentSlotIconColor, origin: icon.size / 2, scale: slots[i].Rect.Width / icon.size.X);
} }
continue; continue;
} }
@@ -54,7 +54,7 @@ namespace Barotrauma.Items.Components
item.SpriteColor * 0.5f, item.SpriteColor * 0.5f,
0.0f, item.Scale, SpriteEffects.None, 0.0f); 0.0f, item.Scale, SpriteEffects.None, 0.0f);
GUI.DrawRectangle(spriteBatch, new Vector2(attachPos.X - 2, -attachPos.Y - 2), Vector2.One * 5, Color.Red, thickness: 3); GUI.DrawRectangle(spriteBatch, new Vector2(attachPos.X - 2, -attachPos.Y - 2), Vector2.One * 5, GUI.Style.Red, thickness: 3);
} }
public void ClientWrite(IWriteMessage msg, object[] extraData = null) public void ClientWrite(IWriteMessage msg, object[] extraData = null)
@@ -117,7 +117,24 @@ namespace Barotrauma.Items.Components
else else
{ {
//if a GUIFrame has been defined, draw the inventory inside it //if a GUIFrame has been defined, draw the inventory inside it
guiCustomComponent = new GUICustomComponent(new RectTransform(new Vector2(0.9f), GuiFrame.RectTransform, Anchor.Center),
var content = new GUIFrame(new RectTransform(GuiFrame.Rect.Size - GUIStyle.ItemFrameMargin, GuiFrame.RectTransform, Anchor.Center) { AbsoluteOffset = GUIStyle.ItemFrameOffset },
style: null)
{
CanBeFocused = false
};
string labelText = GetUILabel();
GUITextBlock label = null;
if (!string.IsNullOrEmpty(labelText))
{
label = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform, Anchor.TopCenter),
labelText, font: GUI.SubHeadingFont, textAlignment: Alignment.Center, wrap: true);
}
float minInventoryAreaSize = 0.5f;
guiCustomComponent = new GUICustomComponent(
new RectTransform(new Vector2(1.0f, label == null ? 1.0f : Math.Max(1.0f - label.RectTransform.RelativeSize.Y, minInventoryAreaSize)), content.RectTransform, Anchor.BottomCenter),
onDraw: (SpriteBatch spriteBatch, GUICustomComponent component) => { Inventory.Draw(spriteBatch); }, onDraw: (SpriteBatch spriteBatch, GUICustomComponent component) => { Inventory.Draw(spriteBatch); },
onUpdate: null) onUpdate: null)
{ {
@@ -127,6 +144,19 @@ namespace Barotrauma.Items.Components
} }
} }
public string GetUILabel()
{
if (UILabel == string.Empty) { return string.Empty; }
if (UILabel != null)
{
return TextManager.Get("UILabel." + UILabel);
}
else
{
return item?.Name;
}
}
public void Draw(SpriteBatch spriteBatch, bool editing = false, float itemDepth = -1) public void Draw(SpriteBatch spriteBatch, bool editing = false, float itemDepth = -1)
{ {
if (hideItems || (item.body != null && !item.body.Enabled)) { return; } if (hideItems || (item.body != null && !item.body.Enabled)) { return; }
@@ -43,9 +43,9 @@ namespace Barotrauma.Items.Components
if (storeOriginalState) if (storeOriginalState)
{ {
crewAreaOriginalState = crewManager.ToggleCrewAreaOpen; crewAreaOriginalState = crewManager.ToggleCrewListOpen;
} }
crewManager.ToggleCrewAreaOpen = value; crewManager.ToggleCrewListOpen = value;
} }
private void ToggleChatBox(bool value, bool storeOriginalState) private void ToggleChatBox(bool value, bool storeOriginalState)
@@ -22,34 +22,68 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), GuiFrame.RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter) var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), GuiFrame.RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter)
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.02f RelativeSpacing = 0.02f
}; };
inputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(0.2f, 0.7f), paddedFrame.RectTransform), style: null); var topFrame = new GUIFrame(new RectTransform(new Vector2(1f, 0.5f), paddedFrame.RectTransform), style: null);
var paddedLine = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.25f), topFrame.RectTransform, Anchor.TopCenter), childAnchor: Anchor.CenterLeft, isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.02f
};
var inputText = new GUITextBlock(new RectTransform(new Vector2(0f, 1.0f), paddedLine.RectTransform), TextManager.Get("uilabel.input"), font: GUI.SubHeadingFont) { Padding = Vector4.Zero };
new GUIFrame(new RectTransform(new Vector2(1f, 1.0f), paddedLine.RectTransform), style: "HorizontalLine");
// Resize GUITextBlock width according to the text length
inputText.RectTransform.Resize(new Point((int)inputText.Font.MeasureString(inputText.Text).X, inputText.RectTransform.Rect.Height));
var inputArea = new GUILayoutGroup(new RectTransform(new Vector2(1f, 1.2f), topFrame.RectTransform, Anchor.CenterLeft), childAnchor: Anchor.BottomLeft, isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.045f
};
inputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(0.7f, 1f), inputArea.RectTransform), style: null);
inputInventoryOverlay = new GUICustomComponent(new RectTransform(Vector2.One, inputInventoryHolder.RectTransform), DrawOverLay, null) inputInventoryOverlay = new GUICustomComponent(new RectTransform(Vector2.One, inputInventoryHolder.RectTransform), DrawOverLay, null)
{ {
CanBeFocused = false CanBeFocused = false
}; };
activateButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.1f), paddedFrame.RectTransform), var buttonContainer = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.75f), inputArea.RectTransform), style: null);
TextManager.Get("DeconstructorDeconstruct")) activateButton = new GUIButton(new RectTransform(new Vector2(0.95f, 0.65f), buttonContainer.RectTransform, Anchor.CenterLeft),
TextManager.Get("DeconstructorDeconstruct"), style: "DeviceButton")
{ {
TextBlock = { AutoScale = true },
OnClicked = ToggleActive OnClicked = ToggleActive
}; };
inSufficientPowerWarning = new GUITextBlock(new RectTransform(Vector2.One, activateButton.RectTransform), TextManager.Get("DeconstructorNoPower"), inSufficientPowerWarning = new GUITextBlock(new RectTransform(Vector2.One, activateButton.RectTransform), TextManager.Get("DeconstructorNoPower"),
textColor: Color.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow") textColor: GUI.Style.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow")
{ {
HoverColor = Color.Black, HoverColor = Color.Black,
IgnoreLayoutGroups = true, IgnoreLayoutGroups = true,
Visible = false, Visible = false,
CanBeFocused = false CanBeFocused = false
}; };
outputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.3f), paddedFrame.RectTransform), style: null);
var bottomFrame = new GUIFrame(new RectTransform(new Vector2(1f, 0.5f), paddedFrame.RectTransform), style: null);
var paddedBottomLine = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.25f), bottomFrame.RectTransform, Anchor.TopCenter), childAnchor: Anchor.CenterLeft, isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.02f
};
var outputText = new GUITextBlock(new RectTransform(new Vector2(0f, 1.0f), paddedBottomLine.RectTransform), TextManager.Get("uilabel.output"), font: GUI.SubHeadingFont) { Padding = Vector4.Zero };
new GUIFrame(new RectTransform(new Vector2(1f, 1.0f), paddedBottomLine.RectTransform), style: "HorizontalLine");
// Resize GUITextBlock width according to the text length
outputText.RectTransform.Resize(new Point((int)outputText.Font.MeasureString(outputText.Text).X, outputText.RectTransform.Rect.Height));
outputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(1f, 1.2f), bottomFrame.RectTransform, Anchor.CenterLeft), style: null);
} }
partial void OnItemLoadedProjSpecific() partial void OnItemLoadedProjSpecific()
@@ -69,7 +103,7 @@ namespace Barotrauma.Items.Components
new Rectangle( new Rectangle(
lastSlot.Rect.X, lastSlot.Rect.Y + (int)(lastSlot.Rect.Height * (1.0f - progressState)), lastSlot.Rect.X, lastSlot.Rect.Y + (int)(lastSlot.Rect.Height * (1.0f - progressState)),
lastSlot.Rect.Width, (int)(lastSlot.Rect.Height * progressState)), lastSlot.Rect.Width, (int)(lastSlot.Rect.Height * progressState)),
Color.Green * 0.5f, isFilled: true); GUI.Style.Green * 0.5f, isFilled: true);
} }
public override void UpdateHUD(Character character, float deltaTime, Camera cam) public override void UpdateHUD(Character character, float deltaTime, Camera cam)
@@ -30,37 +30,45 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
var content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), GuiFrame.RectTransform, Anchor.Center)) var paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.85f, 0.65f), GuiFrame.RectTransform, Anchor.Center)
{ {
Stretch = true, RelativeOffset = new Vector2(0, 0.04f)
RelativeSpacing = 0.05f }, style: null);
};
float indicatorSize = 0.3f; var lightsArea = new GUIFrame(new RectTransform(new Vector2(1, 0.38f), paddedFrame.RectTransform, Anchor.TopLeft), style: null);
powerIndicator = new GUITickBox(new RectTransform(new Vector2(indicatorSize), content.RectTransform), powerIndicator = new GUITickBox(new RectTransform(new Vector2(0.45f, 0.8f), lightsArea.RectTransform, Anchor.Center, Pivot.CenterRight)
TextManager.Get("EnginePowered"), style: "IndicatorLightGreen") {
RelativeOffset = new Vector2(-0.05f, 0)
}, TextManager.Get("EnginePowered"), font: GUI.SubHeadingFont, style: "IndicatorLightGreen")
{ {
CanBeFocused = false CanBeFocused = false
}; };
autoControlIndicator = new GUITickBox(new RectTransform(new Vector2(0.45f, 0.8f), lightsArea.RectTransform, Anchor.Center, Pivot.CenterLeft)
autoControlIndicator = new GUITickBox(new RectTransform(new Vector2(indicatorSize), content.RectTransform), TextManager.Get("PumpAutoControl", fallBackTag: "ReactorAutoControl"), style: "IndicatorLightRed") {
RelativeOffset = new Vector2(0.05f, 0)
}, TextManager.Get("PumpAutoControl", fallBackTag: "ReactorAutoControl"), font: GUI.SubHeadingFont, style: "IndicatorLightYellow")
{ {
CanBeFocused = false CanBeFocused = false
}; };
powerIndicator.TextBlock.Wrap = autoControlIndicator.TextBlock.Wrap = true;
powerIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
autoControlIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
GUITextBlock.AutoScaleAndNormalize(powerIndicator.TextBlock, autoControlIndicator.TextBlock);
var sliderArea = new GUIFrame(new RectTransform(new Vector2(1, 0.6f), paddedFrame.RectTransform, Anchor.BottomLeft), style: null);
string powerLabel = TextManager.Get("EngineForce"); string powerLabel = TextManager.Get("EngineForce");
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), content.RectTransform), "", textAlignment: Alignment.Center) new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), sliderArea.RectTransform, Anchor.TopCenter), "", textColor: GUI.Style.TextColor, font: GUI.SubHeadingFont, textAlignment: Alignment.Center)
{ {
AutoScale = true,
TextGetter = () => { return TextManager.AddPunctuation(':', powerLabel, (int)(targetForce) + " %"); } TextGetter = () => { return TextManager.AddPunctuation(':', powerLabel, (int)(targetForce) + " %"); }
}; };
forceSlider = new GUIScrollBar(new RectTransform(new Vector2(0.95f, 0.45f), sliderArea.RectTransform, Anchor.Center), barSize: 0.1f, style: "DeviceSlider")
forceSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform), barSize: 0.15f, style: "GUISlider")
{ {
Step = 0.05f, Step = 0.05f,
OnMoved = (GUIScrollBar scrollBar, float barScroll) => OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{ {
float newTargetForce = barScroll * 200.0f - 100.0f; float newTargetForce = barScroll * 200.0f - 100.0f;
if (Math.Abs(newTargetForce - targetForce) < 0.01) return false; if (Math.Abs(newTargetForce - targetForce) < 0.01) { return false; }
targetForce = newTargetForce; targetForce = newTargetForce;
@@ -73,16 +81,13 @@ namespace Barotrauma.Items.Components
} }
}; };
var textArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), content.RectTransform), isHorizontal: true) var textsArea = new GUIFrame(new RectTransform(new Vector2(1, 0.25f), sliderArea.RectTransform, Anchor.BottomCenter), style: null);
{ var backwardsLabel = new GUITextBlock(new RectTransform(new Vector2(0.4f, 1.0f), textsArea.RectTransform, Anchor.CenterLeft), TextManager.Get("EngineBackwards"),
Stretch = true textColor: GUI.Style.TextColor, font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft);
}; var forwardsLabel = new GUITextBlock(new RectTransform(new Vector2(0.4f, 1.0f), textsArea.RectTransform, Anchor.CenterRight), TextManager.Get("EngineForwards"),
textColor: GUI.Style.TextColor, font: GUI.SubHeadingFont, textAlignment: Alignment.CenterRight);
GUITextBlock.AutoScaleAndNormalize(backwardsLabel, forwardsLabel);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), textArea.RectTransform), TextManager.Get("EngineBackwards"),
font: GUI.SmallFont, textAlignment: Alignment.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), textArea.RectTransform), TextManager.Get("EngineForwards"),
font: GUI.SmallFont, textAlignment: Alignment.CenterRight);
foreach (XElement subElement in element.Elements()) foreach (XElement subElement in element.Elements())
{ {
switch (subElement.Name.ToString().ToLowerInvariant()) switch (subElement.Name.ToString().ToLowerInvariant())
@@ -113,11 +118,16 @@ namespace Barotrauma.Items.Components
partial void UpdateAnimation(float deltaTime) partial void UpdateAnimation(float deltaTime)
{ {
if (propellerSprite == null) return; if (propellerSprite == null) { return; }
spriteIndex += (force / 100.0f) * AnimSpeed * deltaTime; spriteIndex += (force / 100.0f) * AnimSpeed * deltaTime;
if (spriteIndex < 0) spriteIndex = propellerSprite.FrameCount; if (spriteIndex < 0)
if (spriteIndex >= propellerSprite.FrameCount) spriteIndex = 0.0f; {
spriteIndex = propellerSprite.FrameCount;
}
if (spriteIndex >= propellerSprite.FrameCount)
{
spriteIndex = 0.0f;
}
} }
public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1) public void Draw(SpriteBatch spriteBatch, bool editing, float itemDepth = -1)
@@ -136,7 +146,7 @@ namespace Barotrauma.Items.Components
Vector2 drawPos = item.DrawPosition; Vector2 drawPos = item.DrawPosition;
drawPos += PropellerPos; drawPos += PropellerPos;
drawPos.Y = -drawPos.Y; drawPos.Y = -drawPos.Y;
GUI.DrawRectangle(spriteBatch, drawPos - Vector2.One * 10, Vector2.One * 20, Color.Red); GUI.DrawRectangle(spriteBatch, drawPos - Vector2.One * 10, Vector2.One * 20, GUI.Style.Red);
} }
} }
@@ -13,6 +13,7 @@ namespace Barotrauma.Items.Components
private GUIListBox itemList; private GUIListBox itemList;
private GUIFrame selectedItemFrame; private GUIFrame selectedItemFrame;
private GUIFrame selectedItemReqsFrame;
public GUIButton ActivateButton public GUIButton ActivateButton
{ {
@@ -22,6 +23,7 @@ namespace Barotrauma.Items.Components
private GUITextBox itemFilterBox; private GUITextBox itemFilterBox;
private GUIComponent outputSlot;
private GUIComponent inputInventoryHolder, outputInventoryHolder; private GUIComponent inputInventoryHolder, outputInventoryHolder;
private GUICustomComponent inputInventoryOverlay, outputInventoryOverlay; private GUICustomComponent inputInventoryOverlay, outputInventoryOverlay;
@@ -39,54 +41,81 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific() partial void InitProjSpecific()
{ {
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.95f), GuiFrame.RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter) var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), GuiFrame.RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter)
{ {
Stretch = true,
RelativeSpacing = 0.02f RelativeSpacing = 0.02f
}; };
itemList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.5f), paddedFrame.RectTransform)) var topFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.7f), paddedFrame.RectTransform), "InnerFrameDark");
var paddedItemFrame = new GUIFrame(new RectTransform(new Vector2(0.5f, 1.0f), topFrame.RectTransform), style: null);
var itemListFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), paddedItemFrame.RectTransform, Anchor.Center))
{ {
OnSelected = (GUIComponent component, object userdata) => Stretch = true
};
var filterArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), itemListFrame.RectTransform), isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.02f,
UserData = "filterarea"
};
new GUITextBlock(new RectTransform(new Vector2(0.2f, 0.5f), filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUI.SubHeadingFont)
{
Padding = Vector4.Zero,
AutoScale = true
};
itemFilterBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), createClearButton: true);
itemFilterBox.OnTextChanged += (textBox, text) => { FilterEntities(text); return true; };
itemList = new GUIListBox(new RectTransform(new Vector2(1f, 0.85f), itemListFrame.RectTransform), style: null)
{
OnSelected = (component, userdata) =>
{ {
selectedItem = userdata as FabricationRecipe; selectedItem = userdata as FabricationRecipe;
if (selectedItem != null) { SelectItem(Character.Controlled, selectedItem); } if (selectedItem != null) { SelectItem(Character.Controlled, selectedItem); }
return true; return true;
} }
}; };
new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), topFrame.RectTransform, Anchor.Center), style: "VerticalLine");
var filterArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.06f), paddedFrame.RectTransform), isHorizontal: true) var paddedOutputFrame = new GUIFrame(new RectTransform(new Vector2(0.5f, 1f), topFrame.RectTransform, Anchor.TopRight), style: null);
var outputArea = new GUIFrame(new RectTransform(new Vector2(0.95f, 0.9f), paddedOutputFrame.RectTransform, Anchor.Center), style: null);
// TODO, take off the duct tape and figure out a proper way to do this \/
var scaledFrame = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.55f), outputArea.RectTransform), style: null);
outputSlot = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.5f), outputArea.RectTransform), style: null);
outputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(1.1f, 1.5f), scaledFrame.RectTransform, Anchor.BottomCenter), style: null);
outputInventoryOverlay = new GUICustomComponent(new RectTransform(Vector2.One, outputArea.RectTransform), DrawOutputOverLay) { CanBeFocused = false };
selectedItemFrame = new GUIFrame(new RectTransform(new Vector2(0.6f, 0.5f), outputArea.RectTransform, Anchor.TopRight), style: null);
selectedItemReqsFrame = new GUIFrame(new RectTransform(new Vector2(1f, 0.5f), outputArea.RectTransform, Anchor.BottomLeft), style: null);
var bottomFrame = new GUIFrame(new RectTransform(new Vector2(1f, 0.35f), paddedFrame.RectTransform), style: null);
var paddedLine = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.25f), bottomFrame.RectTransform, Anchor.TopCenter), childAnchor: Anchor.CenterLeft, isHorizontal: true)
{ {
Stretch = true, Stretch = true,
UserData = "filterarea" RelativeSpacing = 0.02f
};
new GUITextBlock(new RectTransform(new Vector2(0.25f, 1.0f), filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUI.Font);
itemFilterBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUI.Font);
itemFilterBox.OnTextChanged += (textBox, text) => { FilterEntities(text); return true; };
var clearButton = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), filterArea.RectTransform), "x")
{
OnClicked = (btn, userdata) => { ClearFilter(); itemFilterBox.Flash(Color.White); return true; }
};
inputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(0.7f, 0.15f), paddedFrame.RectTransform), style: null);
inputInventoryOverlay = new GUICustomComponent(new RectTransform(Vector2.One, inputInventoryHolder.RectTransform), DrawInputOverLay, null)
{
CanBeFocused = false
};
var outputArea = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.25f), paddedFrame.RectTransform), isHorizontal: true);
selectedItemFrame = new GUIFrame(new RectTransform(new Vector2(0.75f, 1.0f), outputArea.RectTransform), style: "InnerFrame");
outputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(0.25f, 1.0f), outputArea.RectTransform), style: null);
outputInventoryOverlay = new GUICustomComponent(new RectTransform(Vector2.One, outputArea.RectTransform), DrawOutputOverLay, null)
{
CanBeFocused = false
}; };
var inputText = new GUITextBlock(new RectTransform(new Vector2(0f, 1.0f), paddedLine.RectTransform), TextManager.Get("uilabel.input"), font: GUI.SubHeadingFont) { Padding = Vector4.Zero };
new GUIFrame(new RectTransform(new Vector2(1f, 1.0f), paddedLine.RectTransform), style: "HorizontalLine");
// Resize GUITextBlock width according to the text length
inputText.RectTransform.Resize(new Point((int)inputText.Font.MeasureString(inputText.Text).X, inputText.RectTransform.Rect.Height));
var inputArea = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 1f), bottomFrame.RectTransform, Anchor.BottomCenter), isHorizontal: true, childAnchor: Anchor.BottomLeft);
inputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(0.8f, 1f), inputArea.RectTransform), style: null);
inputInventoryOverlay = new GUICustomComponent(new RectTransform(Vector2.One, inputInventoryHolder.RectTransform), DrawInputOverLay) { CanBeFocused = false };
CreateRecipes(); CreateRecipes();
activateButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.07f), paddedFrame.RectTransform), var buttonFrame = new GUIFrame(new RectTransform(new Vector2(0.2f, 0.8f), inputArea.RectTransform), style: null);
TextManager.Get("FabricatorCreate"), style: "GUIButtonLarge") activateButton = new GUIButton(new RectTransform(new Vector2(1f, 0.6f), buttonFrame.RectTransform, Anchor.CenterRight),
TextManager.Get("FabricatorCreate"), style: "DeviceButton")
{ {
OnClicked = StartButtonClicked, OnClicked = StartButtonClicked,
UserData = selectedItem, UserData = selectedItem,
@@ -94,7 +123,7 @@ namespace Barotrauma.Items.Components
}; };
inSufficientPowerWarning = new GUITextBlock(new RectTransform(Vector2.One, activateButton.RectTransform), TextManager.Get("FabricatorNoPower"), inSufficientPowerWarning = new GUITextBlock(new RectTransform(Vector2.One, activateButton.RectTransform), TextManager.Get("FabricatorNoPower"),
textColor: Color.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow") textColor: GUI.Style.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow")
{ {
HoverColor = Color.Black, HoverColor = Color.Black,
IgnoreLayoutGroups = true, IgnoreLayoutGroups = true,
@@ -117,7 +146,7 @@ namespace Barotrauma.Items.Components
ToolTip = fi.TargetItem.Description ToolTip = fi.TargetItem.Description
}; };
GUITextBlock textBlock = new GUITextBlock(new RectTransform(Vector2.Zero, frame.RectTransform, Anchor.CenterLeft) { AbsoluteOffset = new Point((int)(50 * GUI.xScale), 0) }, new GUITextBlock(new RectTransform(Vector2.Zero, frame.RectTransform, Anchor.CenterLeft) { AbsoluteOffset = new Point((int)(50 * GUI.xScale), 0) },
fi.DisplayName) fi.DisplayName)
{ {
ToolTip = fi.TargetItem.Description ToolTip = fi.TargetItem.Description
@@ -126,7 +155,7 @@ namespace Barotrauma.Items.Components
var itemIcon = fi.TargetItem.InventoryIcon ?? fi.TargetItem.sprite; var itemIcon = fi.TargetItem.InventoryIcon ?? fi.TargetItem.sprite;
if (itemIcon != null) if (itemIcon != null)
{ {
GUIImage img = new GUIImage(new RectTransform(new Point((int)(30 * GUI.Scale)), frame.RectTransform, Anchor.CenterLeft) { AbsoluteOffset = new Point((int)(3 * GUI.xScale), 0) }, new GUIImage(new RectTransform(new Point((int)(30 * GUI.Scale)), frame.RectTransform, Anchor.CenterLeft) { AbsoluteOffset = new Point((int)(3 * GUI.xScale), 0) },
itemIcon, scaleToFit: true) itemIcon, scaleToFit: true)
{ {
Color = fi.TargetItem.InventoryIconColor, Color = fi.TargetItem.InventoryIconColor,
@@ -166,15 +195,17 @@ namespace Barotrauma.Items.Components
}); });
var sufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform), var sufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform),
TextManager.Get("fabricatorsufficientskills", returnNull: true) ?? "Sufficient skills to fabricate", textColor: Color.LightGreen) TextManager.Get("fabricatorsufficientskills", returnNull: true) ?? "Sufficient skills to fabricate", textColor: GUI.Style.Green, font: GUI.SubHeadingFont)
{ {
AutoScale = true,
CanBeFocused = false CanBeFocused = false
}; };
sufficientSkillsText.RectTransform.SetAsFirstChild(); sufficientSkillsText.RectTransform.SetAsFirstChild();
var insufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform), var insufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform),
TextManager.Get("fabricatorinsufficientskills", returnNull: true) ?? "Insufficient skills to fabricate", textColor: Color.Orange) TextManager.Get("fabricatorinsufficientskills", returnNull: true) ?? "Insufficient skills to fabricate", textColor: Color.Orange, font: GUI.SubHeadingFont)
{ {
AutoScale = true,
CanBeFocused = false CanBeFocused = false
}; };
var firstinSufficient = itemList.Content.Children.FirstOrDefault(c => c.UserData is FabricationRecipe fabricableItem && DegreeOfSuccess(character, fabricableItem.RequiredSkills) < 0.5f); var firstinSufficient = itemList.Content.Children.FirstOrDefault(c => c.UserData is FabricationRecipe fabricableItem && DegreeOfSuccess(character, fabricableItem.RequiredSkills) < 0.5f);
@@ -223,7 +254,7 @@ namespace Barotrauma.Items.Components
{ {
if (item.ParentInventory.slots[availableSlotIndex].HighlightTimer <= 0.0f) if (item.ParentInventory.slots[availableSlotIndex].HighlightTimer <= 0.0f)
{ {
item.ParentInventory.slots[availableSlotIndex].ShowBorderHighlight(Color.LightGreen * 0.5f, 0.5f, 0.5f); item.ParentInventory.slots[availableSlotIndex].ShowBorderHighlight(GUI.Style.Green * 0.5f, 0.5f, 0.5f);
} }
} }
} }
@@ -277,7 +308,7 @@ namespace Barotrauma.Items.Components
new Rectangle( new Rectangle(
slotRect.X, slotRect.Y + (int)(slotRect.Height * (1.0f - progressState)), slotRect.X, slotRect.Y + (int)(slotRect.Height * (1.0f - progressState)),
slotRect.Width, (int)(slotRect.Height * progressState)), slotRect.Width, (int)(slotRect.Height * progressState)),
Color.Green * 0.5f, isFilled: true); GUI.Style.Green * 0.5f, isFilled: true);
} }
itemIcon.Draw( itemIcon.Draw(
@@ -327,8 +358,10 @@ namespace Barotrauma.Items.Components
private bool SelectItem(Character user, FabricationRecipe selectedItem) private bool SelectItem(Character user, FabricationRecipe selectedItem)
{ {
selectedItemFrame.ClearChildren(); selectedItemFrame.ClearChildren();
selectedItemReqsFrame.ClearChildren();
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), selectedItemFrame.RectTransform, Anchor.Center)) { RelativeSpacing = 0.03f, Stretch = true }; var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.9f), selectedItemFrame.RectTransform, Anchor.Center)) { RelativeSpacing = 0.03f };
var paddedReqFrame = new GUILayoutGroup(new RectTransform(new Vector2(1f, 1f), selectedItemReqsFrame.RectTransform, Anchor.Center)) { RelativeSpacing = 0.03f };
/*var itemIcon = selectedItem.TargetItem.InventoryIcon ?? selectedItem.TargetItem.sprite; /*var itemIcon = selectedItem.TargetItem.InventoryIcon ?? selectedItem.TargetItem.sprite;
if (itemIcon != null) if (itemIcon != null)
@@ -340,19 +373,27 @@ namespace Barotrauma.Items.Components
}; };
}*/ }*/
var nameBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), var nameBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
selectedItem.TargetItem.Name, textAlignment: Alignment.CenterLeft); selectedItem.TargetItem.Name, textAlignment: Alignment.CenterLeft, textColor: Color.Aqua, font: GUI.SubHeadingFont)
{
AutoScale = true
};
nameBlock.Padding = new Vector4(0, nameBlock.Padding.Y, nameBlock.Padding.Z, nameBlock.Padding.W);
if (!string.IsNullOrWhiteSpace(selectedItem.TargetItem.Description)) if (!string.IsNullOrWhiteSpace(selectedItem.TargetItem.Description))
{ {
var description = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), var description = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
selectedItem.TargetItem.Description, selectedItem.TargetItem.Description,
font: GUI.SmallFont, wrap: true); font: GUI.SmallFont, wrap: true);
if (description.Rect.Height > paddedFrame.Rect.Height * 0.4f) description.Padding = new Vector4(0, description.Padding.Y, description.Padding.Z, description.Padding.W);
while (description.Rect.Height + nameBlock.Rect.Height > paddedFrame.Rect.Height)
{ {
description.Wrap = false; var lines = description.WrappedText.Split('\n');
description.Text = description.WrappedText.Split('\n').First()+"..."; var newString = string.Join('\n', lines.Take(lines.Length - 1));
nameBlock.ToolTip = description.ToolTip = selectedItem.TargetItem.Description; description.Text = newString.Substring(0, newString.Length - 4) + "...";
description.RectTransform.MaxSize = new Point(int.MaxValue, (int)description.Font.MeasureString(description.Text).Y); description.CalculateHeightFromText();
description.ToolTip = selectedItem.TargetItem.Description;
} }
} }
@@ -364,24 +405,33 @@ namespace Barotrauma.Items.Components
if (selectedItem.RequiredSkills.Any()) if (selectedItem.RequiredSkills.Any())
{ {
string text = TextManager.Get("FabricatorRequiredSkills") + ":\n"; string text = "";
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform),
TextManager.Get("FabricatorRequiredSkills"), textColor: inadequateSkills.Any() ? GUI.Style.Red : GUI.Style.Green, font: GUI.SubHeadingFont)
{
AutoScale = true,
};
foreach (Skill skill in selectedItem.RequiredSkills) foreach (Skill skill in selectedItem.RequiredSkills)
{ {
text += " - " + TextManager.Get("SkillName." + skill.Identifier) + " " + TextManager.Get("Lvl").ToLower() + " " + skill.Level; text += TextManager.Get("SkillName." + skill.Identifier) + " " + TextManager.Get("Lvl").ToLower() + " " + skill.Level;
if (skill != selectedItem.RequiredSkills.Last()) { text += "\n"; } if (skill != selectedItem.RequiredSkills.Last()) { text += "\n"; }
} }
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), text, new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform), text, font: GUI.SmallFont);
textColor: inadequateSkills.Any() ? Color.Red : Color.LightGreen, font: GUI.SmallFont);
} }
float degreeOfSuccess = user == null ? 0.0f : DegreeOfSuccess(user, selectedItem.RequiredSkills); float degreeOfSuccess = user == null ? 0.0f : DegreeOfSuccess(user, selectedItem.RequiredSkills);
if (degreeOfSuccess > 0.5f) { degreeOfSuccess = 1.0f; } if (degreeOfSuccess > 0.5f) { degreeOfSuccess = 1.0f; }
float requiredTime = user == null ? selectedItem.RequiredTime : GetRequiredTime(selectedItem, user); float requiredTime = user == null ? selectedItem.RequiredTime : GetRequiredTime(selectedItem, user);
string requiredTimeText = TextManager.AddPunctuation(':', TextManager.Get("FabricatorRequiredTime"), ToolBox.SecondsToReadableTime(requiredTime));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform),
requiredTimeText, textColor: ToolBox.GradientLerp(degreeOfSuccess, Color.Red, Color.Yellow, Color.LightGreen), font: GUI.SmallFont); TextManager.Get("FabricatorRequiredTime") , textColor: ToolBox.GradientLerp(degreeOfSuccess, GUI.Style.Red, Color.Yellow, GUI.Style.Green), font: GUI.SubHeadingFont)
{
AutoScale = true,
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedReqFrame.RectTransform), ToolBox.SecondsToReadableTime(requiredTime),
font: GUI.SmallFont);
return true; return true;
} }
@@ -413,7 +463,7 @@ namespace Barotrauma.Items.Components
if (selectedItem == null) { return false; } if (selectedItem == null) { return false; }
if (!outputContainer.Inventory.IsEmpty()) if (!outputContainer.Inventory.IsEmpty())
{ {
outputInventoryHolder.Flash(Color.Red); outputSlot.Flash(GUI.Style.Red);
return false; return false;
} }
@@ -19,25 +19,25 @@ namespace Barotrauma.Items.Components
private string noPowerTip = ""; private string noPowerTip = "";
private List<Submarine> displayedSubs = new List<Submarine>(); private readonly List<Submarine> displayedSubs = new List<Submarine>();
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
noPowerTip = TextManager.Get("SteeringNoPowerTip"); noPowerTip = TextManager.Get("SteeringNoPowerTip");
GuiFrame.RectTransform.RelativeOffset = new Vector2(0.05f, 0.0f); GuiFrame.RectTransform.RelativeOffset = new Vector2(0.05f, 0.0f);
new GUICustomComponent(new RectTransform(new Vector2(0.95f, 0.9f), GuiFrame.RectTransform, Anchor.Center), new GUICustomComponent(new RectTransform(GuiFrame.Rect.Size - GUIStyle.ItemFrameMargin, GuiFrame.RectTransform, Anchor.Center) { AbsoluteOffset = GUIStyle.ItemFrameOffset },
DrawHUDBack, null); DrawHUDBack, null);
submarineContainer = new GUIFrame(new RectTransform(new Vector2(0.95f, 0.9f), GuiFrame.RectTransform, Anchor.Center), style: null); submarineContainer = new GUIFrame(new RectTransform(new Vector2(0.95f, 0.9f), GuiFrame.RectTransform, Anchor.Center), style: null);
new GUICustomComponent(new RectTransform(new Vector2(0.95f, 0.9f), GuiFrame.RectTransform, Anchor.Center), new GUICustomComponent(new RectTransform(GuiFrame.Rect.Size - GUIStyle.ItemFrameMargin, GuiFrame.RectTransform, Anchor.Center) { AbsoluteOffset = GUIStyle.ItemFrameOffset },
DrawHUDFront, null) DrawHUDFront, null)
{ {
CanBeFocused = false CanBeFocused = false
}; };
hullInfoFrame = new GUIFrame(new RectTransform(new Vector2(0.13f, 0.13f), GUI.Canvas, minSize: new Point(250, 150)), hullInfoFrame = new GUIFrame(new RectTransform(new Vector2(0.13f, 0.13f), GUI.Canvas, minSize: new Point(250, 150)),
style: "InnerFrame") style: "GUIToolTip")
{ {
CanBeFocused = false CanBeFocused = false
}; };
@@ -120,7 +120,7 @@ namespace Barotrauma.Items.Components
Vector2 textPos = GuiFrame.Rect.Center.ToVector2(); Vector2 textPos = GuiFrame.Rect.Center.ToVector2();
GUI.DrawString(spriteBatch, textPos - textSize / 2, noPowerTip, GUI.DrawString(spriteBatch, textPos - textSize / 2, noPowerTip,
Color.Orange * (float)Math.Abs(Math.Sin(Timing.TotalTime)), Color.Black * 0.8f); GUI.Style.Orange * (float)Math.Abs(Math.Sin(Timing.TotalTime)), Color.Black * 0.8f, font: GUI.SubHeadingFont);
return; return;
} }
@@ -137,7 +137,7 @@ namespace Barotrauma.Items.Components
if (textPos.X - textSize.X / 2 < submarineContainer.Rect.X) if (textPos.X - textSize.X / 2 < submarineContainer.Rect.X)
textPos.X += (submarineContainer.Rect.X - (textPos.X - textSize.X / 2)) + 10 * GUI.xScale; textPos.X += (submarineContainer.Rect.X - (textPos.X - textSize.X / 2)) + 10 * GUI.xScale;
GUI.DrawString(spriteBatch, textPos - textSize / 2, text, GUI.DrawString(spriteBatch, textPos - textSize / 2, text,
Color.Orange * (float)Math.Abs(Math.Sin(Timing.TotalTime)), Color.Black * 0.8f); GUI.Style.Orange * (float)Math.Abs(Math.Sin(Timing.TotalTime)), Color.Black * 0.8f);
break; break;
} }
} }
@@ -213,7 +213,7 @@ namespace Barotrauma.Items.Components
if (ShowHullIntegrity) if (ShowHullIntegrity)
{ {
gapOpenSum = hull.ConnectedGaps.Where(g => !g.IsRoomToRoom).Sum(g => g.Open); gapOpenSum = hull.ConnectedGaps.Where(g => !g.IsRoomToRoom).Sum(g => g.Open);
borderColor = Color.Lerp(neutralColor, Color.Red, Math.Min((float)gapOpenSum, 1.0f)); borderColor = Color.Lerp(neutralColor, GUI.Style.Red, Math.Min((float)gapOpenSum, 1.0f));
} }
float? oxygenAmount = null; float? oxygenAmount = null;
@@ -222,7 +222,7 @@ namespace Barotrauma.Items.Components
oxygenAmount = RequireOxygenDetectors ? hullData.Oxygen : hull.OxygenPercentage; oxygenAmount = RequireOxygenDetectors ? hullData.Oxygen : hull.OxygenPercentage;
GUI.DrawRectangle( GUI.DrawRectangle(
spriteBatch, hullFrame.Rect, spriteBatch, hullFrame.Rect,
Color.Lerp(Color.Red * 0.5f, Color.Green * 0.3f, (float)oxygenAmount / 100.0f), Color.Lerp(GUI.Style.Red * 0.5f, GUI.Style.Green * 0.3f, (float)oxygenAmount / 100.0f),
true); true);
} }
@@ -271,15 +271,15 @@ namespace Barotrauma.Items.Components
waterAmount /= (hullData.LinkedHulls.Count + 1); waterAmount /= (hullData.LinkedHulls.Count + 1);
hullBreachText.Text = gapOpenSum > 0.1f ? TextManager.Get("MiniMapHullBreach") : ""; hullBreachText.Text = gapOpenSum > 0.1f ? TextManager.Get("MiniMapHullBreach") : "";
hullBreachText.TextColor = Color.Red; hullBreachText.TextColor = GUI.Style.Red;
hullAirQualityText.Text = oxygenAmount == null ? TextManager.Get("MiniMapAirQualityUnavailable") : hullAirQualityText.Text = oxygenAmount == null ? TextManager.Get("MiniMapAirQualityUnavailable") :
TextManager.AddPunctuation(':', TextManager.Get("MiniMapAirQuality"), + (int)oxygenAmount + " %"); TextManager.AddPunctuation(':', TextManager.Get("MiniMapAirQuality"), + (int)oxygenAmount + " %");
hullAirQualityText.TextColor = oxygenAmount == null ? Color.Red : Color.Lerp(Color.Red, Color.LightGreen, (float)oxygenAmount / 100.0f); hullAirQualityText.TextColor = oxygenAmount == null ? GUI.Style.Red : Color.Lerp(GUI.Style.Red, Color.LightGreen, (float)oxygenAmount / 100.0f);
hullWaterText.Text = waterAmount == null ? TextManager.Get("MiniMapWaterLevelUnavailable") : hullWaterText.Text = waterAmount == null ? TextManager.Get("MiniMapWaterLevelUnavailable") :
TextManager.AddPunctuation(':', TextManager.Get("MiniMapWaterLevel"), (int)(waterAmount * 100.0f) + " %"); TextManager.AddPunctuation(':', TextManager.Get("MiniMapWaterLevel"), (int)(waterAmount * 100.0f) + " %");
hullWaterText.TextColor = waterAmount == null ? Color.Red : Color.Lerp(Color.LightGreen, Color.Red, (float)waterAmount); hullWaterText.TextColor = waterAmount == null ? GUI.Style.Red : Color.Lerp(Color.LightGreen, GUI.Style.Red, (float)waterAmount);
} }
hullFrame.Color = borderColor; hullFrame.Color = borderColor;
@@ -10,10 +10,10 @@ namespace Barotrauma.Items.Components
{ {
partial class Pump : Powered, IServerSerializable, IClientSerializable partial class Pump : Powered, IServerSerializable, IClientSerializable
{ {
public GUIScrollBar IsActiveSlider { get; private set; } public GUIButton PowerButton { get; private set; }
private GUIScrollBar pumpSpeedSlider; private GUIScrollBar pumpSpeedSlider;
private GUITickBox powerIndicator; private GUITickBox powerLight;
private GUITickBox autoControlIndicator; private GUITickBox autoControlIndicator;
private List<Pair<Vector2, ParticleEmitter>> pumpOutEmitters = new List<Pair<Vector2, ParticleEmitter>>(); private List<Pair<Vector2, ParticleEmitter>> pumpOutEmitters = new List<Pair<Vector2, ParticleEmitter>>();
@@ -40,70 +40,67 @@ namespace Barotrauma.Items.Components
if (GuiFrame == null) { return; } if (GuiFrame == null) { return; }
GUIFrame paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.8f), GuiFrame.RectTransform, Anchor.Center), style: null); GUIFrame paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.85f, 0.65f), GuiFrame.RectTransform, Anchor.Center)
IsActiveSlider = new GUIScrollBar(new RectTransform(new Point((int)(50 * GUI.Scale), (int)(100 * GUI.Scale)), paddedFrame.RectTransform, Anchor.CenterLeft),
barSize: 0.2f, style: "OnOffLever")
{ {
IsBooleanSwitch = true, RelativeOffset = new Vector2(0, 0.04f)
MinValue = 0.25f, }, style: null);
MaxValue = 0.75f
// Power button
float powerButtonSize = 1f;
var powerArea = new GUIFrame(new RectTransform(new Vector2(0.3f, 1) * powerButtonSize, paddedFrame.RectTransform, Anchor.CenterLeft), style: null);
var paddedPowerArea = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.8f), powerArea.RectTransform, Anchor.Center), style: "PowerButtonFrame");
var powerLightArea = new GUIFrame(new RectTransform(new Vector2(0.87f, 0.2f), powerArea.RectTransform, Anchor.TopRight), style: null);
powerLight = new GUITickBox(new RectTransform(Vector2.One, powerLightArea.RectTransform, Anchor.Center),
TextManager.Get("PowerLabel"), font: GUI.SubHeadingFont, style: "IndicatorLightPower")
{
CanBeFocused = false
}; };
var sliderHandle = IsActiveSlider.GetChild<GUIButton>(); powerLight.TextBlock.AutoScale = true;
sliderHandle.RectTransform.NonScaledSize = new Point((int)(84 * GUI.Scale), sliderHandle.Rect.Height); powerLight.TextBlock.OverrideTextColor(GUI.Style.TextColor);
IsActiveSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) => PowerButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.75f), paddedPowerArea.RectTransform, Anchor.TopCenter)
{ {
bool active = scrollBar.BarScroll < 0.5f; RelativeOffset = new Vector2(0, 0.1f)
if (active == IsActive) return false; }, style: "PowerButton")
{
targetLevel = null; OnClicked = (button, data) =>
IsActive = active;
if (!IsActive) currPowerConsumption = 0.0f;
if (GameMain.Client != null)
{ {
correctionTimer = CorrectionDelay; targetLevel = null;
item.CreateClientEvent(this); IsActive = !IsActive;
if (GameMain.Client != null)
{
correctionTimer = CorrectionDelay;
item.CreateClientEvent(this);
}
powerLight.Selected = IsActive;
return true;
} }
return true;
}; };
var rightArea = new GUILayoutGroup(new RectTransform(new Vector2(0.75f, 0.95f), paddedFrame.RectTransform, Anchor.CenterRight)) var rightArea = new GUIFrame(new RectTransform(new Vector2(0.65f, 1), paddedFrame.RectTransform, Anchor.CenterRight), style: null);
{
RelativeSpacing = 0.1f, autoControlIndicator = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.25f), rightArea.RectTransform, Anchor.TopLeft),
Stretch = true TextManager.Get("PumpAutoControl", fallBackTag: "ReactorAutoControl"), font: GUI.SubHeadingFont, style: "IndicatorLightYellow")
};
powerIndicator = new GUITickBox(new RectTransform(new Point((int)(30 * GUI.Scale)), rightArea.RectTransform), TextManager.Get("PumpPowered"), style: "IndicatorLightGreen")
{
CanBeFocused = false
};
autoControlIndicator = new GUITickBox(new RectTransform(new Point((int)(30 * GUI.Scale)), rightArea.RectTransform), TextManager.Get("PumpAutoControl", fallBackTag: "ReactorAutoControl"), style: "IndicatorLightRed")
{ {
CanBeFocused = false CanBeFocused = false
}; };
autoControlIndicator.TextBlock.AutoScale = true;
autoControlIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
var pumpSpeedText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), rightArea.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.0f) }, var sliderArea = new GUIFrame(new RectTransform(new Vector2(1, 0.65f), rightArea.RectTransform, Anchor.BottomLeft), style: null);
"", textAlignment: Alignment.BottomLeft, wrap: true); var pumpSpeedText = new GUITextBlock(new RectTransform(new Vector2(1, 0.3f), sliderArea.RectTransform, Anchor.TopLeft), "",
textColor: GUI.Style.TextColor, textAlignment: Alignment.CenterLeft, wrap: false, font: GUI.SubHeadingFont)
{
AutoScale = true
};
string pumpSpeedStr = TextManager.Get("PumpSpeed"); string pumpSpeedStr = TextManager.Get("PumpSpeed");
pumpSpeedText.TextGetter = () => { return TextManager.AddPunctuation(':', pumpSpeedStr, (int)flowPercentage + " %"); }; pumpSpeedText.TextGetter = () => { return TextManager.AddPunctuation(':', pumpSpeedStr, (int)flowPercentage + " %"); };
pumpSpeedSlider = new GUIScrollBar(new RectTransform(new Vector2(1, 0.35f), sliderArea.RectTransform, Anchor.Center), barSize: 0.1f, style: "DeviceSlider")
var sliderArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.3f), rightArea.RectTransform, Anchor.CenterLeft), isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.01f
};
var outLabel = new GUITextBlock(new RectTransform(new Vector2(0.25f, 1.0f), sliderArea.RectTransform),
TextManager.Get("PumpOut"), textAlignment: Alignment.Center, wrap: false, font: GUI.SmallFont);
pumpSpeedSlider = new GUIScrollBar(new RectTransform(new Vector2(0.5f, 1.0f), sliderArea.RectTransform), barSize: 0.25f, style: "GUISlider")
{ {
Step = 0.05f, Step = 0.05f,
OnMoved = (GUIScrollBar scrollBar, float barScroll) => OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{ {
float newValue = barScroll * 200.0f - 100.0f; float newValue = barScroll * 200.0f - 100.0f;
if (Math.Abs(newValue - FlowPercentage) < 0.1f) return false; if (Math.Abs(newValue - FlowPercentage) < 0.1f) { return false; }
FlowPercentage = newValue; FlowPercentage = newValue;
@@ -115,11 +112,11 @@ namespace Barotrauma.Items.Components
return true; return true;
} }
}; };
var inLabel = new GUITextBlock(new RectTransform(new Vector2(0.25f, 1.0f), sliderArea.RectTransform), var textsArea = new GUIFrame(new RectTransform(new Vector2(1, 0.25f), sliderArea.RectTransform, Anchor.BottomCenter), style: null);
TextManager.Get("PumpIn"), textAlignment: Alignment.Center, wrap: false, font: GUI.SmallFont); var outLabel = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), textsArea.RectTransform, Anchor.CenterLeft), TextManager.Get("PumpOut"),
textColor: GUI.Style.TextColor, textAlignment: Alignment.CenterLeft, wrap: false, font: GUI.SubHeadingFont);
rightArea.Recalculate(); var inLabel = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), textsArea.RectTransform, Anchor.CenterRight), TextManager.Get("PumpIn"),
sliderArea.Recalculate(); textColor: GUI.Style.TextColor, textAlignment: Alignment.CenterRight, wrap: false, font: GUI.SubHeadingFont);
GUITextBlock.AutoScaleAndNormalize(outLabel, inLabel); GUITextBlock.AutoScaleAndNormalize(outLabel, inLabel);
} }
@@ -156,19 +153,36 @@ namespace Barotrauma.Items.Components
} }
} }
private float flickerTimer;
private readonly float flickerFrequency = 1;
public override void UpdateHUD(Character character, float deltaTime, Camera cam) public override void UpdateHUD(Character character, float deltaTime, Camera cam)
{ {
pumpSpeedLockTimer -= deltaTime; pumpSpeedLockTimer -= deltaTime;
isActiveLockTimer -= deltaTime; isActiveLockTimer -= deltaTime;
powerIndicator.Selected = hasPower && IsActive;
autoControlIndicator.Selected = pumpSpeedLockTimer > 0.0f || isActiveLockTimer > 0.0f; autoControlIndicator.Selected = pumpSpeedLockTimer > 0.0f || isActiveLockTimer > 0.0f;
IsActiveSlider.Enabled = isActiveLockTimer <= 0.0f; PowerButton.Enabled = isActiveLockTimer <= 0.0f;
if (HasPower)
{
flickerTimer = 0;
powerLight.Selected = IsActive;
}
else if (IsActive)
{
flickerTimer += deltaTime;
if (flickerTimer > flickerFrequency)
{
flickerTimer = 0;
powerLight.Selected = !powerLight.Selected;
}
}
else
{
flickerTimer = 0;
powerLight.Selected = false;
}
pumpSpeedSlider.Enabled = pumpSpeedLockTimer <= 0.0f && IsActive; pumpSpeedSlider.Enabled = pumpSpeedLockTimer <= 0.0f && IsActive;
if (!PlayerInput.PrimaryMouseButtonHeld()) if (!PlayerInput.PrimaryMouseButtonHeld())
{ {
IsActiveSlider.BarScroll += (IsActive ? -10.0f : 10.0f) * deltaTime;
float pumpSpeedScroll = (FlowPercentage + 100.0f) / 200.0f; float pumpSpeedScroll = (FlowPercentage + 100.0f) / 200.0f;
if (Math.Abs(pumpSpeedScroll - pumpSpeedSlider.BarScroll) > 0.01f) if (Math.Abs(pumpSpeedScroll - pumpSpeedSlider.BarScroll) > 0.01f)
{ {
@@ -1,4 +1,5 @@
using Barotrauma.Networking; using Barotrauma.Extensions;
using Barotrauma.Networking;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System; using System;
@@ -10,21 +11,15 @@ namespace Barotrauma.Items.Components
{ {
partial class Reactor : Powered, IServerSerializable, IClientSerializable partial class Reactor : Powered, IServerSerializable, IClientSerializable
{ {
public GUIScrollBar AutoTempSlider public GUIButton AutoTempSwitch { get; private set; }
{
get { return autoTempSlider; }
}
private GUIScrollBar autoTempSlider;
public GUIScrollBar OnOffSwitch public GUIButton PowerButton { get; private set; }
{ private GUITickBox powerLight;
get { return onOffSwitch; } private GUITickBox autoTempLight;
}
private GUIScrollBar onOffSwitch;
private const int GraphSize = 25; private const int GraphSize = 25;
private float graphTimer; private float graphTimer;
private int updateGraphInterval = 500; private readonly int updateGraphInterval = 500;
private Sprite fissionRateMeter, turbineOutputMeter; private Sprite fissionRateMeter, turbineOutputMeter;
private Sprite meterPointer; private Sprite meterPointer;
@@ -34,21 +29,23 @@ namespace Barotrauma.Items.Components
private Sprite tempRangeIndicator; private Sprite tempRangeIndicator;
private Sprite graphLine; private Sprite graphLine;
//private GUIFrame graph;
public GUIScrollBar FissionRateScrollBar private Color optimalRangeColor = new Color(74,238,104,255);
{ private Color offRangeColor = Color.Orange;
get { return fissionRateScrollBar; } private Color warningColor = Color.Red;
} private Color coldColor = Color.LightBlue;
private GUIScrollBar fissionRateScrollBar; private Color warmColor = Color.Orange;
private Color hotColor = Color.Red;
private Color outputColor = Color.Goldenrod;
private Color loadColor = Color.LightSteelBlue;
public GUIScrollBar TurbineOutputScrollBar public GUIScrollBar FissionRateScrollBar { get; private set; }
{
get { return turbineOutputScrollBar; }
}
private GUIScrollBar turbineOutputScrollBar;
private float[] outputGraph = new float[GraphSize]; public GUIScrollBar TurbineOutputScrollBar { get; private set; }
private float[] loadGraph = new float[GraphSize];
private readonly float[] outputGraph = new float[GraphSize];
private readonly float[] loadGraph = new float[GraphSize];
private GUITickBox criticalHeatWarning; private GUITickBox criticalHeatWarning;
private GUITickBox lowTemperatureWarning; private GUITickBox lowTemperatureWarning;
@@ -56,147 +53,149 @@ namespace Barotrauma.Items.Components
private GUIFrame inventoryContainer; private GUIFrame inventoryContainer;
private GUIComponent leftHUDColumn; private readonly Dictionary<string, GUIButton> warningButtons = new Dictionary<string, GUIButton>();
private GUIComponent midHUDColumn;
private GUIComponent rightHUDColumn;
private GUILayoutGroup sliderControlsContainer; private static readonly string[] warningTexts = new string[]
private Dictionary<string, GUIButton> warningButtons = new Dictionary<string, GUIButton>();
private static string[] warningTexts = new string[]
{ {
"ReactorWarningLowTemp","ReactorWarningOverheating", "ReactorWarningLowTemp", "ReactorWarningLowOutput", "ReactorWarningLowFuel", "ReactorWarningMeltdown",
"ReactorWarningLowOutput", "ReactorWarningHighOutput", "ReactorWarningOverheating", "ReactorWarningHighOutput", "ReactorWarningFuelOut", "ReactorWarningSCRAM"
"ReactorWarningLowFuel", "ReactorWarningFuelOut",
"ReactorWarningMeltdown","ReactorWarningSCRAM"
}; };
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
foreach (XElement subElement in element.Elements()) // TODO: need to recreate the gui when the resolution changes
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "fissionratemeter":
fissionRateMeter = new Sprite(subElement);
break;
case "turbineoutputmeter":
turbineOutputMeter = new Sprite(subElement);
break;
case "meterpointer":
meterPointer = new Sprite(subElement);
break;
case "sectorsprite":
sectorSprite = new Sprite(subElement);
break;
case "tempmeterframe":
tempMeterFrame = new Sprite(subElement);
break;
case "tempmeterbar":
tempMeterBar = new Sprite(subElement);
break;
case "temprangeindicator":
tempRangeIndicator = new Sprite(subElement);
break;
case "graphline":
graphLine = new Sprite(subElement);
break;
}
}
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.85f), GuiFrame.RectTransform, Anchor.Center), isHorizontal: true) fissionRateMeter = new Sprite(element.GetChildElement("fissionratemeter")?.GetChildElement("sprite"));
turbineOutputMeter = new Sprite(element.GetChildElement("turbineoutputmeter")?.GetChildElement("sprite"));
meterPointer = new Sprite(element.GetChildElement("meterpointer")?.GetChildElement("sprite"));
sectorSprite = new Sprite(element.GetChildElement("sectorsprite")?.GetChildElement("sprite"));
tempMeterFrame = new Sprite(element.GetChildElement("tempmeterframe")?.GetChildElement("sprite"));
tempMeterBar = new Sprite(element.GetChildElement("tempmeterbar")?.GetChildElement("sprite"));
tempRangeIndicator = new Sprite(element.GetChildElement("temprangeindicator")?.GetChildElement("sprite"));
graphLine = new Sprite(element.GetChildElement("graphline")?.GetChildElement("sprite"));
var paddedFrame = new GUILayoutGroup(new RectTransform(
GuiFrame.Rect.Size - GUIStyle.ItemFrameMargin.Multiply(new Vector2(1.4f, 1.2f)), GuiFrame.RectTransform, Anchor.Center)
{ AbsoluteOffset = GUIStyle.ItemFrameOffset },
isHorizontal: true)
{ {
RelativeSpacing = 0.012f, RelativeSpacing = 0.012f,
Stretch = true Stretch = true
}; };
GUIFrame columnLeft = new GUIFrame(new RectTransform(new Vector2(0.25f, 1.0f), paddedFrame.RectTransform), style: null); GUILayoutGroup columnLeft = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), paddedFrame.RectTransform))
GUIFrame columnMid = new GUIFrame(new RectTransform(new Vector2(0.45f, 1.0f), paddedFrame.RectTransform), style: null); {
GUIFrame columnRight = new GUIFrame(new RectTransform(new Vector2(0.3f, 1.0f), paddedFrame.RectTransform), style: null); RelativeSpacing = 0.012f,
leftHUDColumn = columnLeft; Stretch = true
midHUDColumn = columnMid; };
rightHUDColumn = columnRight; GUILayoutGroup columnRight = new GUILayoutGroup(new RectTransform(new Vector2(0.4f, 1.0f), paddedFrame.RectTransform))
{
RelativeSpacing = 0.012f,
Stretch = true
};
//---------------------------------------------------------- //----------------------------------------------------------
//left column //left column
//---------------------------------------------------------- //----------------------------------------------------------
int buttonsPerRow = 2; GUIFrame inventoryWindow = new GUIFrame(new RectTransform(new Vector2(0.1f, 0.5f), GuiFrame.RectTransform, Anchor.TopLeft, Pivot.TopRight)
int spacing = 5;
int buttonWidth = columnLeft.Rect.Width / buttonsPerRow - (spacing * (buttonsPerRow - 1));
int buttonHeight = (int)(columnLeft.Rect.Height * 0.5f) / 4;
for (int i = 0; i < warningTexts.Length; i++)
{ {
var warningBtn = new GUIButton(new RectTransform(new Point(buttonWidth, buttonHeight), columnLeft.RectTransform) MinSize = new Point(85, 220),
{ AbsoluteOffset = new Point((i % buttonsPerRow) * (buttonWidth + spacing), (int)Math.Floor(i / (float)buttonsPerRow) * (buttonHeight + spacing)) }, RelativeOffset = new Vector2(-0.02f, 0)
TextManager.Get(warningTexts[i]), style: "IndicatorButton") }, style: "ItemUI");
{
CanBeFocused = false
};
var btnText = warningBtn.GetChild<GUITextBlock>(); GUILayoutGroup inventoryContent = new GUILayoutGroup(new RectTransform(inventoryWindow.Rect.Size - GUIStyle.ItemFrameMargin.Multiply(0.75f), inventoryWindow.RectTransform, Anchor.Center)
btnText.Font = GUI.Font; { AbsoluteOffset = GUIStyle.ItemFrameOffset },
btnText.Wrap = false; childAnchor: Anchor.TopCenter)
btnText.SetTextPos(); {
warningButtons.Add(warningTexts[i], warningBtn); Stretch = true
} };
GUITextBlock.AutoScaleAndNormalize(warningButtons.Values.Select(b => b.TextBlock));
inventoryContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.45f), columnLeft.RectTransform, Anchor.BottomLeft), style: null); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), inventoryContent.RectTransform), "",
textAlignment: Alignment.Center, font: GUI.SubHeadingFont, wrap: true);
inventoryContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.9f), inventoryContent.RectTransform), style: null);
//---------------------------------------------------------- //----------------------------------------------------------
//mid column //mid column
//---------------------------------------------------------- //----------------------------------------------------------
criticalHeatWarning = new GUITickBox(new RectTransform(new Point(columnMid.Rect.Width / 3, (int)(30 * GUI.Scale)), columnMid.RectTransform), var topLeftArea = new GUILayoutGroup(new RectTransform(new Vector2(1, 0.2f), columnLeft.RectTransform),
TextManager.Get("ReactorWarningCriticalTemp"), font: GUI.SmallFont, style: "IndicatorLightRed") isHorizontal: true, childAnchor: Anchor.CenterLeft)
{ {
CanBeFocused = false Stretch = true,
}; RelativeSpacing = 0.02f
lowTemperatureWarning = new GUITickBox(new RectTransform(new Point(columnMid.Rect.Width / 3, (int)(30 * GUI.Scale)), columnMid.RectTransform) { RelativeOffset = new Vector2(0.27f, 0.0f) },
TextManager.Get("ReactorWarningCriticalLowTemp"), font: GUI.SmallFont, style: "IndicatorLightRed")
{
CanBeFocused = false
};
criticalOutputWarning = new GUITickBox(new RectTransform(new Point(columnMid.Rect.Width / 3, (int)(30 * GUI.Scale)), columnMid.RectTransform) { RelativeOffset = new Vector2(0.66f, 0.0f) },
TextManager.Get("ReactorWarningCriticalOutput"), font: GUI.SmallFont, style: "IndicatorLightRed")
{
CanBeFocused = false
}; };
GUITextBlock.AutoScaleAndNormalize(criticalHeatWarning.TextBlock, lowTemperatureWarning.TextBlock, criticalOutputWarning.TextBlock); Point maxIndicatorSize = new Point(int.MaxValue, (int)(50 * GUI.Scale));
criticalHeatWarning = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), topLeftArea.RectTransform) { MaxSize = maxIndicatorSize },
float gaugeOffset = criticalHeatWarning.Rect.Height / (float)columnMid.Rect.Height + 0.05f * GUI.Scale; TextManager.Get("ReactorWarningCriticalTemp"), font: GUI.SubHeadingFont, style: "IndicatorLightRed")
{
CanBeFocused = false
};
lowTemperatureWarning = new GUITickBox(new RectTransform(new Vector2(0.4f, 1.0f), topLeftArea.RectTransform) { MaxSize = maxIndicatorSize },
TextManager.Get("ReactorWarningCriticalLowTemp"), font: GUI.SubHeadingFont, style: "IndicatorLightRed")
{
CanBeFocused = false
};
criticalOutputWarning = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), topLeftArea.RectTransform) { MaxSize = maxIndicatorSize },
TextManager.Get("ReactorWarningCriticalOutput"), font: GUI.SubHeadingFont, style: "IndicatorLightRed")
{
CanBeFocused = false
};
criticalHeatWarning.TextBlock.OverrideTextColor(GUI.Style.TextColor);
lowTemperatureWarning.TextBlock.OverrideTextColor(GUI.Style.TextColor);
criticalOutputWarning.TextBlock.OverrideTextColor(GUI.Style.TextColor);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.05f), columnMid.RectTransform) { RelativeOffset = new Vector2(0.0f, gaugeOffset) }, topLeftArea.Recalculate();
TextManager.Get("ReactorFissionRate"));
new GUICustomComponent(new RectTransform(new Vector2(0.5f, 0.5f), columnMid.RectTransform) { RelativeOffset = new Vector2(0.0f, gaugeOffset + 0.05f) }, new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), columnLeft.RectTransform), style: "HorizontalLine");
float relativeYMargin = 0.02f;
Vector2 relativeTextSize = new Vector2(0.8f, 0.1f);
Vector2 sliderSize = new Vector2(1.0f, 0.125f);
Vector2 meterSize = new Vector2(1, 1 - relativeTextSize.Y - relativeYMargin - sliderSize.Y - 0.1f);
var meterArea = new GUIFrame(new RectTransform(new Vector2(1, 0.6f - relativeYMargin * 2), columnLeft.RectTransform), style: null);
var leftArea = new GUIFrame(new RectTransform(new Vector2(0.49f, 1), meterArea.RectTransform), style: null);
var rightArea = new GUIFrame(new RectTransform(new Vector2(0.49f, 1), meterArea.RectTransform, Anchor.TopCenter, Pivot.TopLeft), style: null);
var fissionRateTextBox = new GUITextBlock(new RectTransform(relativeTextSize, leftArea.RectTransform, Anchor.TopCenter),
TextManager.Get("ReactorFissionRate"), textColor: GUI.Style.TextColor, textAlignment: Alignment.Center, font: GUI.SubHeadingFont)
{
AutoScale = true
};
var fissionMeter = new GUICustomComponent(new RectTransform(meterSize, leftArea.RectTransform, Anchor.TopCenter)
{
RelativeOffset = new Vector2(0.0f, relativeTextSize.Y + relativeYMargin)
},
DrawFissionRateMeter, null) DrawFissionRateMeter, null)
{ {
ToolTip = TextManager.Get("ReactorTipFissionRate") ToolTip = TextManager.Get("ReactorTipFissionRate")
}; };
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.05f), columnMid.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, gaugeOffset) }, var turbineOutputTextBox = new GUITextBlock(new RectTransform(relativeTextSize, rightArea.RectTransform, Anchor.TopCenter),
TextManager.Get("ReactorTurbineOutput")); TextManager.Get("ReactorTurbineOutput"), textColor: GUI.Style.TextColor, textAlignment: Alignment.Center, font: GUI.SubHeadingFont)
new GUICustomComponent(new RectTransform(new Vector2(0.5f, 0.5f), columnMid.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, gaugeOffset + 0.05f) }, {
AutoScale = true
};
GUITextBlock.AutoScaleAndNormalize(turbineOutputTextBox, fissionRateTextBox);
var turbineMeter = new GUICustomComponent(new RectTransform(meterSize, rightArea.RectTransform, Anchor.TopCenter)
{
RelativeOffset = new Vector2(0.0f, relativeTextSize.Y + relativeYMargin)
},
DrawTurbineOutputMeter, null) DrawTurbineOutputMeter, null)
{ {
ToolTip = TextManager.Get("ReactorTipTurbineOutput") ToolTip = TextManager.Get("ReactorTipTurbineOutput")
}; };
GUILayoutGroup sliderControls = new GUILayoutGroup(new RectTransform(new Point(columnMid.Rect.Width, (int)(114 * GUI.Scale)), columnMid.RectTransform, Anchor.BottomCenter)) FissionRateScrollBar = new GUIScrollBar(new RectTransform(sliderSize, leftArea.RectTransform, Anchor.TopCenter)
{ {
Stretch = true, RelativeOffset = new Vector2(0, fissionMeter.RectTransform.RelativeOffset.Y + meterSize.Y)
AbsoluteSpacing = (int)(5 * GUI.Scale) },
}; style: "DeviceSlider", barSize: 0.1f)
sliderControlsContainer = sliderControls;
new GUITextBlock(new RectTransform(new Point(0, (int)(20 * GUI.Scale)), sliderControls.RectTransform, Anchor.TopLeft),
TextManager.Get("ReactorFissionRate"));
fissionRateScrollBar = new GUIScrollBar(new RectTransform(new Point(sliderControls.Rect.Width, (int)(30 * GUI.Scale)), sliderControls.RectTransform, Anchor.TopCenter),
style: "GUISlider", barSize: 0.1f)
{ {
Enabled = false,
OnMoved = (GUIScrollBar bar, float scrollAmount) => OnMoved = (GUIScrollBar bar, float scrollAmount) =>
{ {
LastUser = Character.Controlled; LastUser = Character.Controlled;
@@ -207,11 +206,13 @@ namespace Barotrauma.Items.Components
} }
}; };
new GUITextBlock(new RectTransform(new Point(0, (int)(20 * GUI.Scale)), sliderControls.RectTransform, Anchor.BottomLeft), TurbineOutputScrollBar = new GUIScrollBar(new RectTransform(sliderSize, rightArea.RectTransform, Anchor.TopCenter)
TextManager.Get("ReactorTurbineOutput"));
turbineOutputScrollBar = new GUIScrollBar(new RectTransform(new Point(sliderControls.Rect.Width, (int)(30 * GUI.Scale)), sliderControls.RectTransform, Anchor.BottomCenter),
style: "GUISlider", barSize: 0.1f, isHorizontal: true)
{ {
RelativeOffset = new Vector2(0, turbineMeter.RectTransform.RelativeOffset.Y + meterSize.Y)
},
style: "DeviceSlider", barSize: 0.1f, isHorizontal: true)
{
Enabled = false,
OnMoved = (GUIScrollBar bar, float scrollAmount) => OnMoved = (GUIScrollBar bar, float scrollAmount) =>
{ {
LastUser = Character.Controlled; LastUser = Character.Controlled;
@@ -222,134 +223,219 @@ namespace Barotrauma.Items.Components
} }
}; };
var buttonArea = new GUILayoutGroup(new RectTransform(new Vector2(1, 0.2f), columnLeft.RectTransform))
{
Stretch = true,
RelativeSpacing = 0.02f
};
var upperButtons = new GUILayoutGroup(new RectTransform(new Vector2(1, 0.5f), buttonArea.RectTransform), isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.01f
};
var lowerButtons = new GUILayoutGroup(new RectTransform(new Vector2(1, 0.5f), buttonArea.RectTransform), isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.01f
};
int buttonCount = warningTexts.Length;
for (int i = 0; i < buttonCount; i++)
{
string text = warningTexts[i];
var b = new GUIButton(new RectTransform(Vector2.One, (i < 4) ? upperButtons.RectTransform : lowerButtons.RectTransform),
TextManager.Get(text), style: "IndicatorButton")
{
Font = GUI.SubHeadingFont,
CanBeFocused = false
};
b.TextBlock.Wrap = false;
warningButtons.Add(text, b);
}
upperButtons.Recalculate();
lowerButtons.Recalculate();
GUITextBlock.AutoScaleAndNormalize(warningButtons.Values.Select(b => b.TextBlock));
//---------------------------------------------------------- //----------------------------------------------------------
//right column //right column
//---------------------------------------------------------- //----------------------------------------------------------
new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.1f), columnRight.RectTransform), TextManager.Get("ReactorAutoTemp")) // Auto temp
var topRightArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.25f), columnRight.RectTransform),
isHorizontal: true, childAnchor: Anchor.CenterLeft)
{ {
ToolTip = TextManager.Get("ReactorTipAutoTemp"), Stretch = true,
AutoScale = true RelativeSpacing = 0.02f
}; };
autoTempSlider = new GUIScrollBar(new RectTransform(new Vector2(0.6f, 0.15f), columnRight.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.1f) }, topRightArea.RectTransform.MaxSize = new Point(int.MaxValue, topLeftArea.Rect.Height);
barSize: 0.55f, style: "OnOffSlider", isHorizontal: true)
new GUIFrame(new RectTransform(new Vector2(0.01f, 1.0f), topRightArea.RectTransform), style: "VerticalLine");
AutoTempSwitch = new GUIButton(new RectTransform(new Vector2(0.15f, 0.9f), topRightArea.RectTransform),
style: "SwitchVertical")
{ {
ToolTip = TextManager.Get("ReactorTipAutoTemp"), Enabled = false,
IsBooleanSwitch = true, Selected = AutoTemp,
BarScroll = 1.0f, OnClicked = (button, data) =>
OnMoved = (scrollBar, scrollAmount) =>
{ {
AutoTemp = !AutoTemp;
LastUser = Character.Controlled; LastUser = Character.Controlled;
unsentChanges = true; unsentChanges = true;
return true; return true;
} }
}; };
var sliderSprite = autoTempSlider.Frame.Style.Sprites[GUIComponent.ComponentState.None].First(); AutoTempSwitch.RectTransform.MaxSize = new Point((int)(AutoTempSwitch.Rect.Height * 0.4f), int.MaxValue);
autoTempSlider.RectTransform.MaxSize = new Point((int)(sliderSprite.Sprite.SourceRect.Size.X * GUI.Scale), (int)(sliderSprite.Sprite.SourceRect.Size.Y * GUI.Scale));
onOffSwitch = new GUIScrollBar(new RectTransform(new Vector2(0.4f, 0.3f), columnRight.RectTransform, Anchor.TopRight), autoTempLight = new GUITickBox(new RectTransform(new Vector2(0.4f, 1.0f), topRightArea.RectTransform),
barSize: 0.2f, style: "OnOffLever", isHorizontal: false) TextManager.Get("ReactorAutoTemp"), font: GUI.SubHeadingFont, style: "IndicatorLightYellow")
{
IsBooleanSwitch = true,
MinValue = 0.25f,
MaxValue = 0.75f,
OnMoved = (scrollBar, scrollAmount) =>
{ {
ToolTip = TextManager.Get("ReactorTipAutoTemp"),
CanBeFocused = true,
Selected = AutoTemp
};
autoTempLight.RectTransform.MaxSize = new Point(int.MaxValue, criticalHeatWarning.Rect.Height);
autoTempLight.TextBlock.OverrideTextColor(GUI.Style.TextColor);
new GUIFrame(new RectTransform(new Vector2(0.01f, 1.0f), topRightArea.RectTransform), style: "VerticalLine");
// Power button
var powerArea = new GUIFrame(new RectTransform(new Vector2(0.4f, 1.0f), topRightArea.RectTransform), style: null);
var paddedPowerArea = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), powerArea.RectTransform, Anchor.Center, scaleBasis: ScaleBasis.BothHeight), style: "PowerButtonFrame");
powerLight = new GUITickBox(new RectTransform(new Vector2(0.87f, 0.2f), paddedPowerArea.RectTransform, Anchor.TopCenter, Pivot.Center),
TextManager.Get("PowerLabel"), font: GUI.SubHeadingFont, style: "IndicatorLightPower")
{
CanBeFocused = false,
Selected = _powerOn
};
powerLight.TextBlock.AutoScale = true;
powerLight.TextBlock.OverrideTextColor(GUI.Style.TextColor);
PowerButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.75f), paddedPowerArea.RectTransform, Anchor.BottomCenter)
{
RelativeOffset = new Vector2(0, 0.1f)
}, style: "PowerButton")
{
OnClicked = (button, data) =>
{
PowerOn = !PowerOn;
LastUser = Character.Controlled; LastUser = Character.Controlled;
unsentChanges = true; unsentChanges = true;
return true; return true;
} }
}; };
var switchSprite = onOffSwitch.Frame.Style.Sprites[GUIComponent.ComponentState.None].First();
onOffSwitch.RectTransform.MaxSize = new Point((int)(switchSprite.Sprite.SourceRect.Size.X * GUI.Scale), (int)(switchSprite.Sprite.SourceRect.Size.Y * GUI.Scale));
var lever = onOffSwitch.GetChild<GUIButton>(); topRightArea.Recalculate();
lever.RectTransform.NonScaledSize = new Point(lever.Rect.Width + (int)(30 * GUI.Scale), lever.Rect.Height); autoTempLight.TextBlock.Wrap = true;
GUITextBlock.AutoScaleAndNormalize(
criticalHeatWarning.TextBlock, lowTemperatureWarning.TextBlock, criticalOutputWarning.TextBlock, autoTempLight.TextBlock);
var graphArea = new GUICustomComponent(new RectTransform(new Vector2(1.0f, 0.5f), columnRight.RectTransform, Anchor.BottomCenter) { AbsoluteOffset = new Point(0, 30) }, // right bottom (graph area) -----------------------
DrawGraph, null);
Point textSize = new Point((int)(100 * GUI.Scale), (int)(30 * GUI.Scale)); new GUIFrame(new RectTransform(new Vector2(0.95f, 0.01f), columnRight.RectTransform), style: "HorizontalLine");
var loadText = new GUITextBlock(new RectTransform(textSize, graphArea.RectTransform, Anchor.TopLeft, Pivot.BottomLeft), var bottomRightArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.6f), columnRight.RectTransform), isHorizontal: true)
"Load", textColor: Color.LightBlue, textAlignment: Alignment.CenterLeft) {
Stretch = true,
RelativeSpacing = 0.02f
};
new GUIFrame(new RectTransform(new Vector2(0.01f, 1.0f), bottomRightArea.RectTransform), style: "VerticalLine");
new GUICustomComponent(new RectTransform(new Vector2(0.1f, 1), bottomRightArea.RectTransform, Anchor.Center), DrawTempMeter, null);
var graphArea = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 1.0f), bottomRightArea.RectTransform))
{
Stretch = true,
RelativeSpacing = 0.02f
};
relativeTextSize = new Vector2(1.0f, 0.0f);
var loadText = new GUITextBlock(new RectTransform(relativeTextSize, graphArea.RectTransform),
"Load", textColor: loadColor, font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
{ {
ToolTip = TextManager.Get("ReactorTipLoad") ToolTip = TextManager.Get("ReactorTipLoad")
}; };
string loadStr = TextManager.Get("ReactorLoad"); string loadStr = TextManager.Get("ReactorLoad");
loadText.TextGetter += () => { return loadStr.Replace("[kw]", ((int)load).ToString()); }; string kW = TextManager.Get("kilowatt");
loadText.TextGetter += () => $"{loadStr.Replace("[kw]", ((int)load).ToString())} {kW}";
var graph = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.9f), graphArea.RectTransform), style: "InnerFrameRed");
new GUICustomComponent(new RectTransform(new Vector2(0.9f, 0.98f), graph.RectTransform, Anchor.Center), DrawGraph, null);
var outputText = new GUITextBlock(new RectTransform(textSize, graphArea.RectTransform, Anchor.BottomLeft, Pivot.TopLeft), var outputText = new GUITextBlock(new RectTransform(relativeTextSize, graphArea.RectTransform),
"Output", textColor: Color.LightGreen, textAlignment: Alignment.CenterLeft) "Output", textColor: outputColor, font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
{ {
ToolTip = TextManager.Get("ReactorTipPower") ToolTip = TextManager.Get("ReactorTipPower")
}; };
string outputStr = TextManager.Get("ReactorOutput"); string outputStr = TextManager.Get("ReactorOutput");
outputText.TextGetter += () => { return outputStr.Replace("[kw]", ((int)-currPowerConsumption).ToString()); }; outputText.TextGetter += () => $"{outputStr.Replace("[kw]", ((int)-currPowerConsumption).ToString())} {kW}";
} }
public override void OnItemLoaded() public override void OnItemLoaded()
{ {
base.OnItemLoaded(); base.OnItemLoaded();
turbineOutputScrollBar.BarScroll = targetTurbineOutput / 100.0f; TurbineOutputScrollBar.BarScroll = targetTurbineOutput / 100.0f;
fissionRateScrollBar.BarScroll = targetFissionRate / 100.0f; FissionRateScrollBar.BarScroll = targetFissionRate / 100.0f;
var itemContainer = item.GetComponent<ItemContainer>(); var itemContainer = item.GetComponent<ItemContainer>();
if (itemContainer != null) if (itemContainer != null)
{ {
itemContainer.AllowUIOverlap = true; itemContainer.AllowUIOverlap = true;
itemContainer.Inventory.RectTransform = inventoryContainer.RectTransform; itemContainer.Inventory.RectTransform = inventoryContainer.RectTransform;
var inventoryLabel = inventoryContainer.Parent?.GetChild<GUITextBlock>();
if (inventoryLabel != null)
{
inventoryLabel.RectTransform.MinSize = new Point(100, 0);
inventoryLabel.Text = itemContainer.GetUILabel();
inventoryLabel.CalculateHeightFromText();
(inventoryLabel.Parent as GUILayoutGroup).Recalculate();
}
} }
} }
private void DrawGraph(SpriteBatch spriteBatch, GUICustomComponent container) private void DrawTempMeter(SpriteBatch spriteBatch, GUICustomComponent container)
{ {
if (item.Removed) { return; } Vector2 meterPos = new Vector2(container.Rect.X, container.Rect.Y);
Vector2 meterScale = new Vector2(container.Rect.Width / (float)tempMeterFrame.SourceRect.Width, container.Rect.Height / (float)tempMeterFrame.SourceRect.Height);
tempMeterFrame.Draw(spriteBatch, meterPos, Color.White, tempMeterFrame.Origin, 0.0f, scale: meterScale);
Rectangle graphArea = new Rectangle(container.Rect.X + 30, container.Rect.Y, container.Rect.Width - 30, container.Rect.Height);
float maxLoad = loadGraph.Max();
float xOffset = graphTimer / updateGraphInterval;
DrawGraph(outputGraph, spriteBatch,
graphArea, Math.Max(10000.0f, maxLoad), xOffset, Color.LightGreen);
DrawGraph(loadGraph, spriteBatch,
graphArea, Math.Max(10000.0f, maxLoad), xOffset, Color.LightBlue);
tempMeterFrame.Draw(spriteBatch, new Vector2(graphArea.X - 30, graphArea.Y), Color.White, Vector2.Zero, 0.0f, new Vector2(1.0f, graphArea.Height / tempMeterFrame.size.Y));
float tempFill = temperature / 100.0f; float tempFill = temperature / 100.0f;
float meterBarScale = container.Rect.Width / (float)tempMeterBar.SourceRect.Width;
int barPadding = 5; Vector2 meterBarPos = new Vector2(container.Center.X, container.Rect.Bottom - tempMeterBar.size.Y * meterBarScale - (int)(5 * GUI.yScale));
Vector2 meterBarPos = new Vector2(graphArea.X - 30 + tempMeterFrame.size.X / 2, graphArea.Bottom - tempMeterBar.size.Y); while (meterBarPos.Y > container.Rect.Bottom + (int)(5 * GUI.yScale) - container.Rect.Height * tempFill)
while (meterBarPos.Y > graphArea.Bottom - graphArea.Height * tempFill)
{ {
float tempRatio = 1.0f - ((meterBarPos.Y - graphArea.Y) / graphArea.Height); float tempRatio = 1.0f - ((meterBarPos.Y - container.Rect.Y) / container.Rect.Height);
Color color = tempRatio < 0.5f ? Color color = ToolBox.GradientLerp(tempRatio, coldColor, optimalRangeColor, warmColor, hotColor);
Color.Lerp(Color.Green, Color.Orange, tempRatio * 2.0f) : tempMeterBar.Draw(spriteBatch, meterBarPos, color: color, scale: meterBarScale);
Color.Lerp(Color.Orange, Color.Red, (tempRatio - 0.5f) * 2.0f); int spacing = 2;
meterBarPos.Y -= tempMeterBar.size.Y * meterBarScale + spacing;
tempMeterBar.Draw(spriteBatch, meterBarPos, color);
meterBarPos.Y -= (tempMeterBar.size.Y + barPadding);
} }
if (temperature > optimalTemperature.Y) if (temperature > optimalTemperature.Y)
{ {
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
new Vector2(graphArea.X - 30, graphArea.Y), meterPos,
new Vector2(tempMeterFrame.SourceRect.Width, (graphArea.Bottom - graphArea.Height * optimalTemperature.Y / 100.0f) - graphArea.Y), new Vector2(container.Rect.Width, (container.Rect.Bottom - container.Rect.Height * optimalTemperature.Y / 100.0f) - container.Rect.Y),
Color.Red * (float)Math.Sin(Timing.TotalTime * 5.0f) * 0.7f, isFilled: true); warningColor * (float)Math.Sin(Timing.TotalTime * 5.0f) * 0.7f, isFilled: true);
} }
if (temperature < optimalTemperature.X) if (temperature < optimalTemperature.X)
{ {
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
new Vector2(graphArea.X - 30, graphArea.Bottom - graphArea.Height * optimalTemperature.X / 100.0f), new Vector2(meterPos.X, container.Rect.Bottom - container.Rect.Height * optimalTemperature.X / 100.0f),
new Vector2(tempMeterFrame.SourceRect.Width, graphArea.Bottom - (graphArea.Bottom - graphArea.Height * optimalTemperature.X / 100.0f)), new Vector2(container.Rect.Width, container.Rect.Bottom - (container.Rect.Bottom - container.Rect.Height * optimalTemperature.X / 100.0f)),
Color.Red * (float)Math.Sin(Timing.TotalTime * 5.0f) * 0.7f, isFilled: true); warningColor * (float)Math.Sin(Timing.TotalTime * 5.0f) * 0.7f, isFilled: true);
} }
tempRangeIndicator.Draw(spriteBatch, new Vector2(meterBarPos.X, graphArea.Bottom - graphArea.Height * optimalTemperature.X / 100.0f)); float tempRangeIndicatorScale = container.Rect.Width / (float)tempRangeIndicator.SourceRect.Width;
tempRangeIndicator.Draw(spriteBatch, new Vector2(meterBarPos.X, graphArea.Bottom - graphArea.Height * optimalTemperature.Y / 100.0f)); tempRangeIndicator.Draw(spriteBatch, new Vector2(container.Center.X, container.Rect.Bottom - container.Rect.Height * optimalTemperature.X / 100.0f), Color.White, tempRangeIndicator.Origin, 0, scale: tempRangeIndicatorScale);
tempRangeIndicator.Draw(spriteBatch, new Vector2(container.Center.X, container.Rect.Bottom - container.Rect.Height * optimalTemperature.Y / 100.0f), Color.White, tempRangeIndicator.Origin, 0, scale: tempRangeIndicatorScale);
}
private void DrawGraph(SpriteBatch spriteBatch, GUICustomComponent container)
{
if (item.Removed) { return; }
float maxLoad = loadGraph.Max();
float xOffset = graphTimer / updateGraphInterval;
Rectangle graphRect = new Rectangle(container.Rect.X, container.Rect.Y, container.Rect.Width, container.Rect.Height - (int)(5 * GUI.yScale));
DrawGraph(outputGraph, spriteBatch, graphRect, Math.Max(10000.0f, maxLoad), xOffset, outputColor);
DrawGraph(loadGraph, spriteBatch, graphRect, Math.Max(10000.0f, maxLoad), xOffset, loadColor);
} }
@@ -367,8 +453,8 @@ namespace Barotrauma.Items.Components
if (autoTemp) if (autoTemp)
{ {
fissionRateScrollBar.BarScroll = FissionRate / 100.0f; FissionRateScrollBar.BarScroll = FissionRate / 100.0f;
turbineOutputScrollBar.BarScroll = TurbineOutput / 100.0f; TurbineOutputScrollBar.BarScroll = TurbineOutput / 100.0f;
} }
} }
@@ -411,10 +497,7 @@ namespace Barotrauma.Items.Components
{ {
IsActive = true; IsActive = true;
bool lightOn = Timing.TotalTime % 0.5f < 0.25f && onOffSwitch.BarScroll < 0.5f; bool lightOn = Timing.TotalTime % 0.5f < 0.25f && PowerOn;
fissionRateScrollBar.Enabled = !autoTemp;
turbineOutputScrollBar.Enabled = !autoTemp;
criticalHeatWarning.Selected = temperature > allowedTemperature.Y && lightOn; criticalHeatWarning.Selected = temperature > allowedTemperature.Y && lightOn;
lowTemperatureWarning.Selected = temperature < allowedTemperature.X && lightOn; lowTemperatureWarning.Selected = temperature < allowedTemperature.X && lightOn;
@@ -427,21 +510,19 @@ namespace Barotrauma.Items.Components
warningButtons["ReactorWarningFuelOut"].Selected = prevAvailableFuel < fissionRate * 0.01f && lightOn; warningButtons["ReactorWarningFuelOut"].Selected = prevAvailableFuel < fissionRate * 0.01f && lightOn;
warningButtons["ReactorWarningLowFuel"].Selected = prevAvailableFuel < fissionRate && lightOn; warningButtons["ReactorWarningLowFuel"].Selected = prevAvailableFuel < fissionRate && lightOn;
warningButtons["ReactorWarningMeltdown"].Selected = meltDownTimer > MeltdownDelay * 0.5f || item.Condition == 0.0f && lightOn; warningButtons["ReactorWarningMeltdown"].Selected = meltDownTimer > MeltdownDelay * 0.5f || item.Condition == 0.0f && lightOn;
warningButtons["ReactorWarningSCRAM"].Selected = temperature > 0.1f && onOffSwitch.BarScroll > 0.5f; warningButtons["ReactorWarningSCRAM"].Selected = temperature > 0.1f && !PowerOn;
AutoTemp = autoTempSlider.BarScroll < 0.5f; if ((FissionRateScrollBar.Rect.Contains(PlayerInput.MousePosition) || FissionRateScrollBar.Children.Contains(GUIScrollBar.DraggingBar) ||
shutDown = onOffSwitch.BarScroll > 0.5f; TurbineOutputScrollBar.Rect.Contains(PlayerInput.MousePosition) || TurbineOutputScrollBar.Children.Contains(GUIScrollBar.DraggingBar)) &&
if ((sliderControlsContainer.Rect.Contains(PlayerInput.MousePosition) || sliderControlsContainer.Children.Contains(GUIScrollBar.DraggingBar)) &&
!PlayerInput.KeyDown(InputType.Deselect) && !PlayerInput.KeyHit(InputType.Deselect)) !PlayerInput.KeyDown(InputType.Deselect) && !PlayerInput.KeyHit(InputType.Deselect))
{ {
Character.DisableControls = true; Character.DisableControls = true;
} }
if (shutDown) if (!PowerOn)
{ {
fissionRateScrollBar.BarScroll = FissionRate / 100.0f; FissionRateScrollBar.BarScroll = FissionRate / 100.0f;
turbineOutputScrollBar.BarScroll = TurbineOutput / 100.0f; TurbineOutputScrollBar.BarScroll = TurbineOutput / 100.0f;
} }
else if (!autoTemp && Character.DisableControls && GUI.KeyboardDispatcher.Subscriber == null) else if (!autoTemp && Character.DisableControls && GUI.KeyboardDispatcher.Subscriber == null)
{ {
@@ -465,29 +546,20 @@ namespace Barotrauma.Items.Components
{ {
LastUser = Character.Controlled; LastUser = Character.Controlled;
unsentChanges = true; unsentChanges = true;
if (input.X != 0.0f && GUIScrollBar.DraggingBar != fissionRateScrollBar) if (input.X != 0.0f && GUIScrollBar.DraggingBar != FissionRateScrollBar)
{ {
targetFissionRate = MathHelper.Clamp(targetFissionRate + input.X, 0.0f, 100.0f); targetFissionRate = MathHelper.Clamp(targetFissionRate + input.X, 0.0f, 100.0f);
fissionRateScrollBar.BarScroll += input.X / 100.0f; FissionRateScrollBar.BarScroll += input.X / 100.0f;
} }
if (input.Y != 0.0f && GUIScrollBar.DraggingBar != turbineOutputScrollBar) if (input.Y != 0.0f && GUIScrollBar.DraggingBar != TurbineOutputScrollBar)
{ {
targetTurbineOutput = MathHelper.Clamp(targetTurbineOutput + input.Y, 0.0f, 100.0f); targetTurbineOutput = MathHelper.Clamp(targetTurbineOutput + input.Y, 0.0f, 100.0f);
turbineOutputScrollBar.BarScroll += input.Y / 100.0f; TurbineOutputScrollBar.BarScroll += input.Y / 100.0f;
} }
} }
} }
} }
private bool ToggleAutoTemp(GUITickBox tickBox)
{
unsentChanges = true;
autoTemp = tickBox.Selected;
LastUser = Character.Controlled;
return true;
}
private void DrawMeter(SpriteBatch spriteBatch, Rectangle rect, Sprite meterSprite, float value, Vector2 range, Vector2 optimalRange, Vector2 allowedRange) private void DrawMeter(SpriteBatch spriteBatch, Rectangle rect, Sprite meterSprite, float value, Vector2 range, Vector2 optimalRange, Vector2 allowedRange)
{ {
float scale = Math.Min(rect.Width / meterSprite.size.X, rect.Height / meterSprite.size.Y); float scale = Math.Min(rect.Width / meterSprite.size.X, rect.Height / meterSprite.size.Y);
@@ -513,7 +585,7 @@ namespace Barotrauma.Items.Components
if (optimalRangeNormalized.X == optimalRangeNormalized.Y) if (optimalRangeNormalized.X == optimalRangeNormalized.Y)
{ {
sectorSprite.Draw(spriteBatch, pos, Color.Red, MathHelper.PiOver2, scale); sectorSprite.Draw(spriteBatch, pos, GUI.Style.Red, MathHelper.PiOver2, scale);
} }
else else
{ {
@@ -522,13 +594,12 @@ namespace Barotrauma.Items.Components
spriteBatch.GraphicsDevice.ScissorRectangle = new Rectangle(0, 0, GameMain.GraphicsWidth, (int)(pos.Y + (meterSprite.size.Y - meterSprite.Origin.Y) * scale) - 3); spriteBatch.GraphicsDevice.ScissorRectangle = new Rectangle(0, 0, GameMain.GraphicsWidth, (int)(pos.Y + (meterSprite.size.Y - meterSprite.Origin.Y) * scale) - 3);
spriteBatch.Begin(SpriteSortMode.Deferred, rasterizerState: GameMain.ScissorTestEnable); spriteBatch.Begin(SpriteSortMode.Deferred, rasterizerState: GameMain.ScissorTestEnable);
sectorSprite.Draw(spriteBatch, pos, Color.LightGreen, MathHelper.PiOver2 + (allowedSectorRad.X + allowedSectorRad.Y) / 2.0f, scale); float scaleMultiplier = 0.95f;
sectorSprite.Draw(spriteBatch, pos, optimalRangeColor, MathHelper.PiOver2 + (allowedSectorRad.X + allowedSectorRad.Y) / 2.0f, scale * scaleMultiplier);
sectorSprite.Draw(spriteBatch, pos, Color.Orange, optimalSectorRad.X, scale); sectorSprite.Draw(spriteBatch, pos, offRangeColor, optimalSectorRad.X, scale * scaleMultiplier);
sectorSprite.Draw(spriteBatch, pos, Color.Red, allowedSectorRad.X, scale); sectorSprite.Draw(spriteBatch, pos, warningColor, allowedSectorRad.X, scale * scaleMultiplier);
sectorSprite.Draw(spriteBatch, pos, offRangeColor, MathHelper.Pi + optimalSectorRad.Y, scale * scaleMultiplier);
sectorSprite.Draw(spriteBatch, pos, Color.Orange, MathHelper.Pi + optimalSectorRad.Y, scale); sectorSprite.Draw(spriteBatch, pos, warningColor, MathHelper.Pi + allowedSectorRad.Y, scale * scaleMultiplier);
sectorSprite.Draw(spriteBatch, pos, Color.Red, MathHelper.Pi + allowedSectorRad.Y, scale);
spriteBatch.End(); spriteBatch.End();
spriteBatch.GraphicsDevice.ScissorRectangle = prevScissorRect; spriteBatch.GraphicsDevice.ScissorRectangle = prevScissorRect;
@@ -539,7 +610,8 @@ namespace Barotrauma.Items.Components
float normalizedValue = (value - range.X) / (range.Y - range.X); float normalizedValue = (value - range.X) / (range.Y - range.X);
float valueRad = MathHelper.Lerp(sectorRad.X, sectorRad.Y, normalizedValue); float valueRad = MathHelper.Lerp(sectorRad.X, sectorRad.Y, normalizedValue);
meterPointer.Draw(spriteBatch, pos, valueRad, scale); Vector2 offset = new Vector2(0, 40) * scale;
meterPointer.Draw(spriteBatch, pos - offset, valueRad, scale);
} }
static void UpdateGraph<T>(IList<T> graph, T newValue) static void UpdateGraph<T>(IList<T> graph, T newValue)
@@ -561,8 +633,6 @@ namespace Barotrauma.Items.Components
float lineWidth = (float)rect.Width / (float)(graph.Count - 2); float lineWidth = (float)rect.Width / (float)(graph.Count - 2);
float yScale = (float)rect.Height / maxVal; float yScale = (float)rect.Height / maxVal;
GUI.DrawRectangle(spriteBatch, rect, Color.White);
Vector2 prevPoint = new Vector2(rect.Right, rect.Bottom - (graph[1] + (graph[0] - graph[1]) * xOffset) * yScale); Vector2 prevPoint = new Vector2(rect.Right, rect.Bottom - (graph[1] + (graph[0] - graph[1]) * xOffset) * yScale);
float currX = rect.Right - ((xOffset - 1.0f) * lineWidth); float currX = rect.Right - ((xOffset - 1.0f) * lineWidth);
@@ -619,7 +689,7 @@ namespace Barotrauma.Items.Components
public void ClientWrite(IWriteMessage msg, object[] extraData = null) public void ClientWrite(IWriteMessage msg, object[] extraData = null)
{ {
msg.Write(autoTemp); msg.Write(autoTemp);
msg.Write(shutDown); msg.Write(PowerOn);
msg.WriteRangedSingle(targetFissionRate, 0.0f, 100.0f, 8); msg.WriteRangedSingle(targetFissionRate, 0.0f, 100.0f, 8);
msg.WriteRangedSingle(targetTurbineOutput, 0.0f, 100.0f, 8); msg.WriteRangedSingle(targetTurbineOutput, 0.0f, 100.0f, 8);
@@ -635,17 +705,41 @@ namespace Barotrauma.Items.Components
} }
AutoTemp = msg.ReadBoolean(); AutoTemp = msg.ReadBoolean();
shutDown = msg.ReadBoolean(); PowerOn = msg.ReadBoolean();
Temperature = msg.ReadRangedSingle(0.0f, 100.0f, 8); Temperature = msg.ReadRangedSingle(0.0f, 100.0f, 8);
targetFissionRate = msg.ReadRangedSingle(0.0f, 100.0f, 8); targetFissionRate = msg.ReadRangedSingle(0.0f, 100.0f, 8);
targetTurbineOutput = msg.ReadRangedSingle(0.0f, 100.0f, 8); targetTurbineOutput = msg.ReadRangedSingle(0.0f, 100.0f, 8);
degreeOfSuccess = msg.ReadRangedSingle(0.0f, 1.0f, 8); degreeOfSuccess = msg.ReadRangedSingle(0.0f, 1.0f, 8);
fissionRateScrollBar.BarScroll = targetFissionRate / 100.0f; FissionRateScrollBar.BarScroll = targetFissionRate / 100.0f;
turbineOutputScrollBar.BarScroll = targetTurbineOutput / 100.0f; TurbineOutputScrollBar.BarScroll = targetTurbineOutput / 100.0f;
onOffSwitch.BarScroll = shutDown ? Math.Max(onOffSwitch.BarScroll, 0.55f) : Math.Min(onOffSwitch.BarScroll, 0.45f);
IsActive = true; IsActive = true;
} }
private void UpdateUIElementStates()
{
if (powerLight != null)
{
powerLight.Selected = _powerOn;
}
if (AutoTempSwitch != null)
{
AutoTempSwitch.Selected = autoTemp;
AutoTempSwitch.Enabled = _powerOn;
}
if (autoTempLight != null)
{
autoTempLight.Selected = autoTemp && _powerOn;
}
if (FissionRateScrollBar != null)
{
FissionRateScrollBar.Enabled = _powerOn && !autoTemp;
}
if (TurbineOutputScrollBar != null)
{
TurbineOutputScrollBar.Enabled = _powerOn && !autoTemp;
}
}
} }
} }
@@ -6,30 +6,32 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Xml.Linq; using System.Xml.Linq;
using Barotrauma.Extensions;
namespace Barotrauma.Items.Components namespace Barotrauma.Items.Components
{ {
partial class Sonar : Powered, IServerSerializable, IClientSerializable partial class Sonar : Powered, IServerSerializable, IClientSerializable
{ {
public enum BlipType
{
Default,
Disruption
}
private bool dynamicDockingIndicator = true; private bool dynamicDockingIndicator = true;
private bool unsentChanges; private bool unsentChanges;
private float networkUpdateTimer; private float networkUpdateTimer;
public GUITickBox ActiveTickBox public GUIButton SonarModeSwitch { get; private set; }
{
get { return activeTickBox; }
}
private GUITickBox activeTickBox, passiveTickBox; private GUITickBox activeTickBox, passiveTickBox;
private GUITextBlock signalWarningText; private GUITextBlock signalWarningText;
private GUIScrollBar zoomSlider; private GUIScrollBar zoomSlider;
private GUITickBox directionalTickBox; private GUIButton directionalModeSwitch;
private GUIScrollBar directionalSlider;
private Vector2? pingDragDirection = null; private Vector2? pingDragDirection = null;
private GUILayoutGroup activeControlsContainer;
private GUIFrame controlContainer; private GUIFrame controlContainer;
private GUICustomComponent sonarView; private GUICustomComponent sonarView;
@@ -54,21 +56,32 @@ namespace Barotrauma.Items.Components
private Vector2 center; private Vector2 center;
private float displayScale; private float displayScale;
private const float DisruptionUpdateInterval = 0.2f;
private float disruptionUpdateTimer;
private float zoomSqrt; private float zoomSqrt;
private float showDirectionalIndicatorTimer; private float showDirectionalIndicatorTimer;
//Vector2 = vector from the ping source to the position of the disruption //Vector2 = vector from the ping source to the position of the disruption
//float = strength of the disruption, between 0-1 //float = strength of the disruption, between 0-1
List<Pair<Vector2, float>> disruptedDirections = new List<Pair<Vector2, float>>(); List<Pair<Vector2, float>> disruptedDirections = new List<Pair<Vector2, float>>();
private static readonly Color[] blipColorGradient = private readonly Color positiveColor = Color.Green;
private readonly Color warningColor = Color.Orange;
private readonly Color negativeColor = Color.Red;
private readonly Color markerColor = Color.Red;
private static readonly Dictionary<BlipType, Color[]> blipColorGradient = new Dictionary<BlipType, Color[]>()
{ {
Color.TransparentBlack, {
new Color(0, 50, 160), BlipType.Default,
new Color(0, 133, 166), new Color[] { Color.TransparentBlack, new Color(0, 50, 160), new Color(0, 133, 166), new Color(2, 159, 30), new Color(255, 255, 255) }
new Color(2, 159, 30), },
new Color(255, 255, 255) {
BlipType.Disruption,
new Color[] { Color.TransparentBlack, new Color(254, 68, 19), new Color(255, 220, 62), new Color(255, 255, 255) }
}
}; };
private float prevDockingDist; private float prevDockingDist;
@@ -79,102 +92,8 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
System.Diagnostics.Debug.Assert(Enum.GetValues(typeof(BlipType)).Cast<BlipType>().All(t => blipColorGradient.ContainsKey(t)));
sonarBlips = new List<SonarBlip>(); sonarBlips = new List<SonarBlip>();
sonarView = new GUICustomComponent(new RectTransform(Point.Zero, GuiFrame.RectTransform, Anchor.CenterLeft),
(spriteBatch, guiCustomComponent) => { DrawSonar(spriteBatch, guiCustomComponent.Rect); }, null);
controlContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.35f), GuiFrame.RectTransform, Anchor.TopLeft)
{ MinSize = new Point(150, 0) }, "SonarFrame");
controlContainer.RectTransform.SetAsFirstChild();
var paddedControlContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), controlContainer.RectTransform, Anchor.Center))
{
RelativeSpacing = 0.03f,
Stretch = true
};
passiveTickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.2f), paddedControlContainer.RectTransform), TextManager.Get("SonarPassive"), style: "GUIRadioButton")
{
ToolTip = TextManager.Get("SonarTipPassive"),
Selected = true
};
activeTickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.2f), paddedControlContainer.RectTransform), TextManager.Get("SonarActive"), style: "GUIRadioButton")
{
ToolTip = TextManager.Get("SonarTipActive"),
OnSelected = (GUITickBox box) =>
{
CurrentMode = box.Selected ? Mode.Active : Mode.Passive;
if (GameMain.Client != null)
{
unsentChanges = true;
correctionTimer = CorrectionDelay;
}
return true;
}
};
var zoomContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedControlContainer.RectTransform), isHorizontal: true);
new GUITextBlock(new RectTransform(new Vector2(0.35f, 1.0f), zoomContainer.RectTransform), TextManager.Get("SonarZoom"), font: GUI.SmallFont)
{
Padding = Vector4.Zero
};
zoomSlider = new GUIScrollBar(new RectTransform(new Vector2(0.65f, 1.0f), zoomContainer.RectTransform), barSize: 0.1f, isHorizontal: true)
{
OnMoved = (scrollbar, scroll) =>
{
zoom = MathHelper.Lerp(MinZoom, MaxZoom, scroll);
if (GameMain.Client != null)
{
unsentChanges = true;
correctionTimer = CorrectionDelay;
}
return true;
}
};
var activeControls = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.6f), paddedControlContainer.RectTransform) { RelativeOffset = new Vector2(0.1f, 0.0f) }, "InnerFrame");
activeControlsContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), activeControls.RectTransform, Anchor.Center))
{
RelativeSpacing = 0.03f,
Stretch = true
};
directionalTickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.3f), activeControlsContainer.RectTransform), TextManager.Get("SonarDirectionalPing"))
{
OnSelected = (tickBox) =>
{
useDirectionalPing = tickBox.Selected;
if (GameMain.Client != null)
{
unsentChanges = true;
correctionTimer = CorrectionDelay;
}
return true;
}
};
directionalSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.3f), activeControlsContainer.RectTransform), barSize: 0.1f, isHorizontal: true)
{
OnMoved = (scrollbar, scroll) =>
{
showDirectionalIndicatorTimer = 1.0f;
float pingAngle = MathHelper.Lerp(0.0f, MathHelper.TwoPi, scroll);
SetPingDirection(new Vector2((float)Math.Cos(pingAngle), (float)Math.Sin(pingAngle)));
return true;
},
Range = new Vector2(0,MathHelper.TwoPi)
};
signalWarningText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedControlContainer.RectTransform), "", Color.Orange, textAlignment: Alignment.Center);
GUIRadioButtonGroup sonarMode = new GUIRadioButtonGroup();
sonarMode.AddRadioButton((int)Mode.Active, activeTickBox);
sonarMode.AddRadioButton((int)Mode.Passive, passiveTickBox);
sonarMode.Selected = (int)Mode.Passive;
GuiFrame.CanBeFocused = false;
foreach (XElement subElement in element.Elements()) foreach (XElement subElement in element.Elements())
{ {
@@ -212,20 +131,125 @@ namespace Barotrauma.Items.Components
break; break;
} }
} }
CreateGUI();
SetUILayout(); GameMain.Instance.OnResolutionChanged += ResetLayout;
// TODO: do we need to react on this?
GameMain.Instance.OnResolutionChanged += SetUILayout; GameMain.Config.OnHUDScaleChanged += ResetLayout;
GameMain.Config.OnHUDScaleChanged += SetUILayout;
} }
private void SetUILayout() private void ResetLayout()
{ {
int viewSize = (int)Math.Min(GuiFrame.Rect.Width - 150, GuiFrame.Rect.Height * 0.9f); GuiFrame.RectTransform.Children.ForEachMod(c => c.Parent = null);
sonarView.RectTransform.NonScaledSize = new Point(viewSize); CreateGUI();
controlContainer.RectTransform.AbsoluteOffset = new Point((int)(viewSize * 0.9f), 0);
} }
private void CreateGUI()
{
controlContainer = new GUIFrame(new RectTransform(new Vector2(controlContainerRelativeWidth, 0.32f), GuiFrame.RectTransform, Anchor.TopRight)
{
RelativeOffset = new Vector2(controlContainerRelativeOffset, 0)
}, "ItemUI");
var paddedControlContainer = new GUIFrame(new RectTransform(controlContainer.Rect.Size - GUIStyle.ItemFrameMargin, controlContainer.RectTransform, Anchor.Center)
{
AbsoluteOffset = GUIStyle.ItemFrameOffset
}, style: null);
var sonarModeArea = new GUIFrame(new RectTransform(new Vector2(1, 0.5f), paddedControlContainer.RectTransform, Anchor.TopCenter), style: null);
SonarModeSwitch = new GUIButton(new RectTransform(new Vector2(0.2f, 1), sonarModeArea.RectTransform), string.Empty, style: "SwitchVertical")
{
Selected = false,
Enabled = true,
OnClicked = (button, data) =>
{
button.Selected = !button.Selected;
CurrentMode = button.Selected ? Mode.Active : Mode.Passive;
if (GameMain.Client != null)
{
unsentChanges = true;
correctionTimer = CorrectionDelay;
}
return true;
}
};
var sonarModeRightSide = new GUIFrame(new RectTransform(new Vector2(0.7f, 0.8f), sonarModeArea.RectTransform, Anchor.CenterLeft)
{
RelativeOffset = new Vector2(SonarModeSwitch.RectTransform.RelativeSize.X, 0)
}, style: null);
passiveTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), sonarModeRightSide.RectTransform, Anchor.TopLeft),
TextManager.Get("SonarPassive"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall")
{
ToolTip = TextManager.Get("SonarTipPassive"),
Selected = true,
Enabled = false
};
activeTickBox = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), sonarModeRightSide.RectTransform, Anchor.BottomLeft),
TextManager.Get("SonarActive"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall")
{
ToolTip = TextManager.Get("SonarTipActive"),
Selected = false,
Enabled = false
};
passiveTickBox.TextBlock.OverrideTextColor(GUI.Style.TextColor);
activeTickBox.TextBlock.OverrideTextColor(GUI.Style.TextColor);
var zoomContainer = new GUIFrame(new RectTransform(new Vector2(1, 0.2f), paddedControlContainer.RectTransform, Anchor.TopCenter)
{
RelativeOffset = new Vector2(0, sonarModeArea.RectTransform.RelativeSize.Y + 0.025f)
}, style: null);
new GUITextBlock(new RectTransform(new Vector2(0.3f, 0.6f), zoomContainer.RectTransform, Anchor.CenterLeft),
TextManager.Get("SonarZoom"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterRight);
zoomSlider = new GUIScrollBar(new RectTransform(new Vector2(0.6f, 0.8f), zoomContainer.RectTransform, Anchor.CenterLeft)
{
RelativeOffset = new Vector2(0.35f, 0)
}, barSize: 0.15f, isHorizontal: true, style: "DeviceSlider")
{
OnMoved = (scrollbar, scroll) =>
{
zoom = MathHelper.Lerp(MinZoom, MaxZoom, scroll);
if (GameMain.Client != null)
{
unsentChanges = true;
correctionTimer = CorrectionDelay;
}
return true;
}
};
var directionalModeFrame = new GUIFrame(new RectTransform(new Vector2(1, 0.2f), paddedControlContainer.RectTransform, Anchor.BottomCenter), style: null);
new GUIFrame(new RectTransform(new Vector2(0.9f, 0.01f), directionalModeFrame.RectTransform, Anchor.TopCenter, Pivot.BottomCenter)
{
RelativeOffset = new Vector2(0, -0.15f)
}, style: "HorizontalLine");
directionalModeSwitch = new GUIButton(new RectTransform(new Vector2(0.3f, 0.8f), directionalModeFrame.RectTransform, Anchor.CenterLeft), string.Empty, style: "SwitchHorizontal")
{
OnClicked = (button, data) =>
{
useDirectionalPing = !useDirectionalPing;
button.Selected = useDirectionalPing;
if (GameMain.Client != null)
{
unsentChanges = true;
correctionTimer = CorrectionDelay;
}
return true;
}
};
var directionalModeSwitchText = new GUITextBlock(new RectTransform(new Vector2(0.7f, 1), directionalModeFrame.RectTransform, Anchor.CenterRight),
TextManager.Get("SonarDirectionalPing"), GUI.Style.TextColor, GUI.SubHeadingFont, Alignment.CenterLeft);
signalWarningText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedControlContainer.RectTransform), "", warningColor, textAlignment: Alignment.Center);
GuiFrame.CanBeFocused = false;
sonarView = new GUICustomComponent(new RectTransform(SonarAreaSize, GuiFrame.RectTransform, Anchor.CenterLeft),
(spriteBatch, guiCustomComponent) => { DrawSonar(spriteBatch, guiCustomComponent.Rect); }, null);
sonarView.RectTransform.SetAsFirstChild();
}
public static readonly float controlContainerRelativeWidth = 0.35f;
public static readonly float controlContainerRelativeOffset = 0.1f;
public static Vector2 SonarAreaSize => Vector2.One - new Vector2(controlContainerRelativeWidth + controlContainerRelativeOffset);
private void SetPingDirection(Vector2 direction) private void SetPingDirection(Vector2 direction)
{ {
pingDirection = direction; pingDirection = direction;
@@ -278,15 +302,7 @@ namespace Barotrauma.Items.Components
sonarBlips[i].FadeTimer -= deltaTime * MathHelper.Lerp(0.5f, 2.0f, distort); sonarBlips[i].FadeTimer -= deltaTime * MathHelper.Lerp(0.5f, 2.0f, distort);
sonarBlips[i].Position += sonarBlips[i].Velocity * deltaTime; sonarBlips[i].Position += sonarBlips[i].Velocity * deltaTime;
if (sonarBlips[i].FadeTimer <= 0.0f) sonarBlips.RemoveAt(i); if (sonarBlips[i].FadeTimer <= 0.0f) { sonarBlips.RemoveAt(i); }
}
foreach (GUIComponent component in activeControlsContainer.Parent.GetAllChildren())
{
if (component is GUITextBlock textBlock)
{
textBlock.TextColor = currentMode == Mode.Active ? textBlock.Style.textColor : textBlock.Style.textColor * 0.5f;
}
} }
//sonar view can only get focus when the cursor is inside the circle //sonar view can only get focus when the cursor is inside the circle
@@ -415,44 +431,46 @@ namespace Barotrauma.Items.Components
null; null;
} }
if (useDirectionalPing && PlayerInput.PrimaryMouseButtonHeld()) if (useDirectionalPing)
{ {
if ((MouseInDirectionalPingRing(sonarView.Rect, false) && PlayerInput.PrimaryMouseButtonDown()) || pingDragDirection != null) Vector2 newDragDir = Vector2.Normalize(PlayerInput.MousePosition - sonarView.Rect.Center.ToVector2());
if (MouseInDirectionalPingRing(sonarView.Rect, true) && PlayerInput.PrimaryMouseButtonDown())
{ {
Vector2 newDragDir = Vector2.Normalize(PlayerInput.MousePosition - sonarView.Rect.Center.ToVector2());
if (pingDragDirection == null && !MouseInDirectionalPingRing(sonarView.Rect, true))
{
directionalSlider.BarScrollValue = MathUtils.WrapAngleTwoPi(MathUtils.VectorToAngle(newDragDir));
directionalSlider.OnMoved(directionalSlider, directionalSlider.BarScroll);
}
else if (pingDragDirection != null)
{
float newAngle = MathUtils.VectorToAngle(newDragDir);
float oldAngle = MathUtils.VectorToAngle(pingDragDirection.Value);
float pingAngle = MathUtils.VectorToAngle(pingDirection);
pingAngle = MathUtils.WrapAngleTwoPi(pingAngle + MathUtils.GetShortestAngle(oldAngle, newAngle));
directionalSlider.BarScrollValue = pingAngle;
directionalSlider.OnMoved(directionalSlider, directionalSlider.BarScroll);
}
pingDragDirection = newDragDir; pingDragDirection = newDragDir;
} }
if (pingDragDirection != null && PlayerInput.PrimaryMouseButtonHeld())
{
float newAngle = MathUtils.WrapAngleTwoPi(MathUtils.VectorToAngle(newDragDir));
SetPingDirection(new Vector2((float)Math.Cos(newAngle), (float)Math.Sin(newAngle)));
}
else
{
pingDragDirection = null;
}
} }
else else
{ {
pingDragDirection = null; pingDragDirection = null;
} }
disruptionUpdateTimer -= deltaTime;
for (var pingIndex = 0; pingIndex < activePingsCount; ++pingIndex) for (var pingIndex = 0; pingIndex < activePingsCount; ++pingIndex)
{ {
var activePing = activePings[pingIndex]; var activePing = activePings[pingIndex];
float pingRadius = DisplayRadius * activePing.State / zoom; float pingRadius = DisplayRadius * activePing.State / zoom;
UpdateDisruptions(transducerCenter, pingRadius / displayScale, activePing.PrevPingRadius / displayScale); if (disruptionUpdateTimer <= 0.0f) { UpdateDisruptions(transducerCenter, pingRadius / displayScale); }
Ping(transducerCenter, transducerCenter, Ping(transducerCenter, transducerCenter,
pingRadius, activePing.PrevPingRadius, displayScale, range / zoom, passive: false, pingStrength: 2.0f); pingRadius, activePing.PrevPingRadius, displayScale, range / zoom, passive: false, pingStrength: 2.0f);
activePing.PrevPingRadius = pingRadius; activePing.PrevPingRadius = pingRadius;
} }
if (disruptionUpdateTimer <= 0.0f)
{
disruptionUpdateTimer = DisruptionUpdateInterval;
}
if (currentMode == Mode.Active && currentPingIndex != -1) if (currentMode == Mode.Active && currentPingIndex != -1)
{ {
return; return;
@@ -464,7 +482,7 @@ namespace Barotrauma.Items.Components
disruptedDirections.Clear(); disruptedDirections.Clear();
foreach (AITarget t in AITarget.List) foreach (AITarget t in AITarget.List)
{ {
if (t.SoundRange <= 0.0f || !t.Enabled) { continue; } if (t.SoundRange <= 0.0f || !t.Enabled || float.IsNaN(t.SoundRange) || float.IsInfinity(t.SoundRange)) { continue; }
float distSqr = Vector2.DistanceSquared(t.WorldPosition, transducerCenter); float distSqr = Vector2.DistanceSquared(t.WorldPosition, transducerCenter);
if (distSqr > t.SoundRange * t.SoundRange * 2) { continue; } if (distSqr > t.SoundRange * t.SoundRange * 2) { continue; }
@@ -610,7 +628,7 @@ namespace Barotrauma.Items.Components
if (signalStrength <= 0.5f) if (signalStrength <= 0.5f)
{ {
signalWarningText.Text = TextManager.Get(signalStrength <= 0.0f ? "SonarNoSignal" : "SonarSignalWeak"); signalWarningText.Text = TextManager.Get(signalStrength <= 0.0f ? "SonarNoSignal" : "SonarSignalWeak");
signalWarningText.Color = signalStrength <= 0.0f ? Color.Red : Color.Orange; signalWarningText.Color = signalStrength <= 0.0f ? negativeColor : warningColor;
signalWarningText.Visible = true; signalWarningText.Visible = true;
} }
else else
@@ -796,7 +814,7 @@ namespace Barotrauma.Items.Components
size.Y = 0.0f; size.Y = 0.0f;
} }
GUI.DrawLine(spriteBatch, center + offset - size - Vector2.Normalize(size) * zoom, center + offset + size + Vector2.Normalize(size) * zoom, Color.Black * signalStrength * 0.5f, width: (int)(zoom * 5.0f)); GUI.DrawLine(spriteBatch, center + offset - size - Vector2.Normalize(size) * zoom, center + offset + size + Vector2.Normalize(size) * zoom, Color.Black * signalStrength * 0.5f, width: (int)(zoom * 5.0f));
GUI.DrawLine(spriteBatch, center + offset - size, center + offset + size, Color.LightGreen * signalStrength, width: (int)(zoom * 2.5f)); GUI.DrawLine(spriteBatch, center + offset - size, center + offset + size, positiveColor * signalStrength, width: (int)(zoom * 2.5f));
} }
} }
@@ -845,7 +863,7 @@ namespace Barotrauma.Items.Components
Vector2 midNormal = new Vector2(-normalizedDockingDir.Y, normalizedDockingDir.X); Vector2 midNormal = new Vector2(-normalizedDockingDir.Y, normalizedDockingDir.X);
DrawLine(spriteBatch, targetPortPos, targetPortPos + normalizedDockingDir * midLength, readyToDock ? Color.LightGreen : staticLineColor, width: 2); DrawLine(spriteBatch, targetPortPos, targetPortPos + normalizedDockingDir * midLength, readyToDock ? positiveColor : staticLineColor, width: 2);
DrawLine(spriteBatch, targetPortPos, DrawLine(spriteBatch, targetPortPos,
targetPortPos + MathUtils.RotatePoint(normalizedDockingDir, sector) * sectorLength, staticLineColor, width: 2); targetPortPos + MathUtils.RotatePoint(normalizedDockingDir, sector) * sectorLength, staticLineColor, width: 2);
DrawLine(spriteBatch, targetPortPos, DrawLine(spriteBatch, targetPortPos,
@@ -859,7 +877,7 @@ namespace Barotrauma.Items.Components
if (readyToDock) if (readyToDock)
{ {
Color indicatorColor = Color.LightGreen * 0.8f; Color indicatorColor = positiveColor * 0.8f;
float indicatorSize = (float)Math.Sin((float)Timing.TotalTime * 5.0f) * DisplayRadius * 0.75f; float indicatorSize = (float)Math.Sin((float)Timing.TotalTime * 5.0f) * DisplayRadius * 0.75f;
Vector2 midPoint = (sourcePortPos + targetPortPos) / 2.0f; Vector2 midPoint = (sourcePortPos + targetPortPos) / 2.0f;
@@ -882,7 +900,8 @@ namespace Barotrauma.Items.Components
Vector2.Dot(normalizedDockingDir, MathUtils.RotatePoint(normalizedDockingDir, indicatorSector)) < Vector2.Dot(normalizedDockingDir, MathUtils.RotatePoint(normalizedDockingDir, indicatorSector)) <
Vector2.Dot(normalizedDockingDir, Vector2.Normalize(dockingDir)); Vector2.Dot(normalizedDockingDir, Vector2.Normalize(dockingDir));
Color indicatorColor = withinSector ? Color.LightGreen * 0.8f : Color.Red * 0.8f; Color indicatorColor = withinSector ? positiveColor : negativeColor;
indicatorColor *= 0.8f;
DrawLine(spriteBatch, targetPortPos, DrawLine(spriteBatch, targetPortPos,
targetPortPos + MathUtils.RotatePoint(normalizedDockingDir,indicatorSector) * indicatorSectorLength, indicatorColor, width: 3); targetPortPos + MathUtils.RotatePoint(normalizedDockingDir,indicatorSector) * indicatorSectorLength, indicatorColor, width: 3);
@@ -892,7 +911,7 @@ namespace Barotrauma.Items.Components
} }
private void UpdateDisruptions(Vector2 pingSource, float worldPingRadius, float worldPrevPingRadius) private void UpdateDisruptions(Vector2 pingSource, float worldPingRadius)
{ {
float worldPingRadiusSqr = worldPingRadius * worldPingRadius; float worldPingRadiusSqr = worldPingRadius * worldPingRadius;
@@ -912,10 +931,8 @@ namespace Barotrauma.Items.Components
float disruptionDist = Vector2.Distance(pingSource, disruptionPos); float disruptionDist = Vector2.Distance(pingSource, disruptionPos);
disruptedDirections.Add(new Pair<Vector2, float>((disruptionPos - pingSource) / disruptionDist, disruptionStrength)); disruptedDirections.Add(new Pair<Vector2, float>((disruptionPos - pingSource) / disruptionDist, disruptionStrength));
if (disruptionDist > worldPrevPingRadius && disruptionDist <= worldPingRadius) CreateBlipsForDisruption(disruptionPos, disruptionStrength);
{
CreateBlipsForDisruption(disruptionPos, disruptionStrength);
}
} }
foreach (AITarget aiTarget in AITarget.List) foreach (AITarget aiTarget in AITarget.List)
{ {
@@ -926,18 +943,23 @@ namespace Barotrauma.Items.Components
float disruptionDist = (float)Math.Sqrt(distSqr); float disruptionDist = (float)Math.Sqrt(distSqr);
disruptedDirections.Add(new Pair<Vector2, float>((aiTarget.WorldPosition - pingSource) / disruptionDist, aiTarget.SonarDisruption)); disruptedDirections.Add(new Pair<Vector2, float>((aiTarget.WorldPosition - pingSource) / disruptionDist, aiTarget.SonarDisruption));
if (disruptionDist > worldPrevPingRadius && disruptionDist <= worldPingRadius) CreateBlipsForDisruption(aiTarget.WorldPosition, aiTarget.SonarDisruption);
{
CreateBlipsForDisruption(aiTarget.WorldPosition, aiTarget.SonarDisruption);
}
} }
} }
void CreateBlipsForDisruption(Vector2 disruptionPos, float disruptionStrength) void CreateBlipsForDisruption(Vector2 disruptionPos, float disruptionStrength)
{ {
for (int i = 0; i < disruptionStrength * Level.GridCellSize * 0.02f; i++) disruptionStrength = Math.Min(disruptionStrength, 10.0f);
Vector2 dir = disruptionPos - pingSource;
for (int i = 0; i < disruptionStrength * 10.0f; i++)
{ {
var blip = new SonarBlip(disruptionPos + Rand.Vector(Rand.Range(0.0f, Level.GridCellSize * 4 * disruptionStrength)), MathHelper.Lerp(1.0f, 1.5f, disruptionStrength), Rand.Range(1.0f, 2.0f + disruptionStrength)); Vector2 pos = disruptionPos + Rand.Vector(Rand.Range(0.0f, Level.GridCellSize * 4 * disruptionStrength));
if (Vector2.Dot(pos - pingSource, -dir) > 1.0f - disruptionStrength) { continue; }
var blip = new SonarBlip(
pos,
MathHelper.Lerp(0.1f, 1.5f, Math.Min(disruptionStrength, 1.0f)),
Rand.Range(0.2f, 1.0f + disruptionStrength),
BlipType.Disruption);
sonarBlips.Add(blip); sonarBlips.Add(blip);
} }
} }
@@ -1143,6 +1165,8 @@ namespace Barotrauma.Items.Components
Vector2 lineDir = (point2 - point1) / length; Vector2 lineDir = (point2 - point1) / length;
for (float x = 0; x < length; x += lineStep * Rand.Range(0.8f, 1.2f)) for (float x = 0; x < length; x += lineStep * Rand.Range(0.8f, 1.2f))
{ {
if (Rand.Int(sonarBlips.Count) > 500) { continue; }
Vector2 point = point1 + lineDir * x; Vector2 point = point1 + lineDir * x;
//ignore if outside the display //ignore if outside the display
@@ -1253,7 +1277,7 @@ namespace Barotrauma.Items.Components
Vector2 dir = pos / (float)Math.Sqrt(posDistSqr); Vector2 dir = pos / (float)Math.Sqrt(posDistSqr);
Vector2 normal = new Vector2(dir.Y, -dir.X); Vector2 normal = new Vector2(dir.Y, -dir.X);
float scale = (strength + 3.0f) * blip.Scale * zoomSqrt; float scale = (strength + 3.0f) * blip.Scale * zoomSqrt;
Color color = ToolBox.GradientLerp(strength, blipColorGradient); Color color = ToolBox.GradientLerp(strength, blipColorGradient[blip.BlipType]);
sonarBlip.Draw(spriteBatch, center + pos, color, sonarBlip.Origin, blip.Rotation ?? MathUtils.VectorToAngle(pos), sonarBlip.Draw(spriteBatch, center + pos, color, sonarBlip.Origin, blip.Rotation ?? MathUtils.VectorToAngle(pos),
blip.Size * scale * 0.04f, SpriteEffects.None, 0); blip.Size * scale * 0.04f, SpriteEffects.None, 0);
@@ -1304,7 +1328,7 @@ namespace Barotrauma.Items.Components
if (string.IsNullOrEmpty(iconIdentifier) || !targetIcons.ContainsKey(iconIdentifier)) if (string.IsNullOrEmpty(iconIdentifier) || !targetIcons.ContainsKey(iconIdentifier))
{ {
GUI.DrawRectangle(spriteBatch, new Rectangle((int)markerPos.X - 3, (int)markerPos.Y - 3, 6, 6), Color.Red, thickness: 2); GUI.DrawRectangle(spriteBatch, new Rectangle((int)markerPos.X - 3, (int)markerPos.Y - 3, 6, 6), markerColor, thickness: 2);
} }
else else
{ {
@@ -1355,7 +1379,8 @@ namespace Barotrauma.Items.Components
msg.Write(useDirectionalPing); msg.Write(useDirectionalPing);
if (useDirectionalPing) if (useDirectionalPing)
{ {
msg.WriteRangedSingle(directionalSlider.BarScroll, 0.0f, 1.0f, 8); float pingAngle = MathUtils.WrapAngleTwoPi(MathUtils.VectorToAngle(pingDirection));
msg.WriteRangedSingle(MathUtils.InverseLerp(0.0f, MathHelper.TwoPi, pingAngle), 0.0f, 1.0f, 8);
} }
} }
} }
@@ -1380,7 +1405,7 @@ namespace Barotrauma.Items.Components
if (correctionTimer > 0.0f) if (correctionTimer > 0.0f)
{ {
int msgLength = (int)(msg.BitPosition - msgStartPos); int msgLength = msg.BitPosition - msgStartPos;
msg.BitPosition = msgStartPos; msg.BitPosition = msgStartPos;
StartDelayedCorrection(type, msg.ExtractBits(msgLength), sendingTime); StartDelayedCorrection(type, msg.ExtractBits(msgLength), sendingTime);
return; return;
@@ -1389,22 +1414,25 @@ namespace Barotrauma.Items.Components
CurrentMode = isActive ? Mode.Active : Mode.Passive; CurrentMode = isActive ? Mode.Active : Mode.Passive;
if (isActive) if (isActive)
{ {
activeTickBox.Selected = true;
zoomSlider.BarScroll = zoomT; zoomSlider.BarScroll = zoomT;
zoom = MathHelper.Lerp(MinZoom, MaxZoom, zoomT); zoom = MathHelper.Lerp(MinZoom, MaxZoom, zoomT);
if (directionalPing) if (directionalPing)
{ {
directionalSlider.BarScroll = directionT; float pingAngle = MathHelper.Lerp(0.0f, MathHelper.TwoPi, directionT);
float pingAngle = MathHelper.Lerp(0.0f, MathHelper.TwoPi, directionalSlider.BarScroll);
pingDirection = new Vector2((float)Math.Cos(pingAngle), (float)Math.Sin(pingAngle)); pingDirection = new Vector2((float)Math.Cos(pingAngle), (float)Math.Sin(pingAngle));
} }
useDirectionalPing = directionalTickBox.Selected = directionalPing; useDirectionalPing = directionalModeSwitch.Selected = directionalPing;
}
else
{
passiveTickBox.Selected = true;
} }
} }
private void UpdateGUIElements()
{
bool isActive = CurrentMode == Mode.Active;
SonarModeSwitch.Selected = isActive;
passiveTickBox.Selected = !isActive;
activeTickBox.Selected = isActive;
directionalModeSwitch.Selected = useDirectionalPing;
}
} }
class SonarBlip class SonarBlip
@@ -1415,13 +1443,15 @@ namespace Barotrauma.Items.Components
public Vector2 Velocity; public Vector2 Velocity;
public float? Rotation; public float? Rotation;
public Vector2 Size; public Vector2 Size;
public Sonar.BlipType BlipType;
public SonarBlip(Vector2 pos, float fadeTimer, float scale) public SonarBlip(Vector2 pos, float fadeTimer, float scale, Sonar.BlipType blipType = Sonar.BlipType.Default)
{ {
Position = pos; Position = pos;
FadeTimer = Math.Max(fadeTimer, 0.0f); FadeTimer = Math.Max(fadeTimer, 0.0f);
Scale = scale; Scale = scale;
Size = new Vector2(0.5f, 1.0f); Size = new Vector2(0.5f, 1.0f);
BlipType = blipType;
} }
} }
} }
@@ -7,17 +7,14 @@ using System;
using System.Linq; using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Xml.Linq; using System.Xml.Linq;
using Barotrauma.Extensions;
namespace Barotrauma.Items.Components namespace Barotrauma.Items.Components
{ {
partial class Steering : Powered, IServerSerializable, IClientSerializable partial class Steering : Powered, IServerSerializable, IClientSerializable
{ {
enum Mode private GUIButton steeringModeSwitch;
{ private GUITickBox autopilotIndicator, manualPilotIndicator;
AutoPilot,
Manual
};
private GUITickBox autopilotTickBox, manualTickBox;
enum Destination enum Destination
{ {
@@ -34,8 +31,6 @@ namespace Barotrauma.Items.Components
private GUIButton dockingButton; private GUIButton dockingButton;
private string dockText, undockText; private string dockText, undockText;
private GUIFrame autoPilotControlsDisabler;
private GUIComponent steerArea; private GUIComponent steerArea;
private GUITextBlock pressureWarningText; private GUITextBlock pressureWarningText;
@@ -92,67 +87,84 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
controlContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.35f), GuiFrame.RectTransform, Anchor.CenterLeft) foreach (XElement subElement in element.Elements())
{ MinSize = new Point(150, 0) }, "SonarFrame");
var paddedControlContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), controlContainer.RectTransform, Anchor.Center))
{ {
RelativeSpacing = 0.03f, switch (subElement.Name.ToString().ToLowerInvariant())
Stretch = true {
}; case "steeringindicator":
steeringIndicator = new Sprite(subElement);
break;
case "maintainposindicator":
maintainPosIndicator = new Sprite(subElement);
break;
case "maintainposoriginindicator":
maintainPosOriginIndicator = new Sprite(subElement);
break;
}
}
CreateGUI();
GameMain.Instance.OnResolutionChanged += ResetGUI;
// TODO: do we need to react on this?
GameMain.Config.OnHUDScaleChanged += ResetGUI;
}
statusContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GuiFrame.RectTransform, Anchor.BottomLeft) private void CreateGUI()
{ MinSize = new Point(150, 0) }, "SonarFrame"); {
var paddedStatusContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), statusContainer.RectTransform, Anchor.Center)) controlContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.36f), GuiFrame.RectTransform, Anchor.CenterRight)
{ {
RelativeSpacing = 0.03f, RelativeOffset = new Vector2(Sonar.controlContainerRelativeOffset / 2, 0.01f) // Based on the relative size differende of the steering and the status windows
Stretch = true }, "ItemUI");
}; var paddedControlContainer = new GUIFrame(new RectTransform(controlContainer.Rect.Size - GUIStyle.ItemFrameMargin, controlContainer.RectTransform, Anchor.Center)
{
AbsoluteOffset = GUIStyle.ItemFrameOffset
}, style: null);
manualTickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.3f), paddedControlContainer.RectTransform), var steeringModeArea = new GUIFrame(new RectTransform(new Vector2(1, 0.4f), paddedControlContainer.RectTransform, Anchor.TopLeft), style: null);
TextManager.Get("SteeringManual"), style: "GUIRadioButton") steeringModeSwitch = new GUIButton(new RectTransform(new Vector2(0.2f, 1), steeringModeArea.RectTransform), string.Empty, style: "SwitchVertical")
{
Selected = false,
Enabled = true,
OnClicked = (button, data) =>
{
button.Selected = !button.Selected;
AutoPilot = button.Selected;
if (GameMain.Client != null)
{
unsentChanges = true;
user = Character.Controlled;
}
return true;
}
};
var steeringModeRightSide = new GUIFrame(new RectTransform(new Vector2(1.0f - steeringModeSwitch.RectTransform.RelativeSize.X, 0.8f), steeringModeArea.RectTransform, Anchor.CenterLeft)
{
RelativeOffset = new Vector2(steeringModeSwitch.RectTransform.RelativeSize.X, 0)
}, style: null);
manualPilotIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), steeringModeRightSide.RectTransform, Anchor.TopLeft),
TextManager.Get("SteeringManual"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall")
{ {
Selected = true, Selected = true,
OnSelected = (GUITickBox box) => Enabled = false
{
AutoPilot = !box.Selected;
unsentChanges = true;
user = Character.Controlled;
return true;
}
}; };
autopilotTickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.3f), paddedControlContainer.RectTransform), autopilotIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.45f), steeringModeRightSide.RectTransform, Anchor.BottomLeft),
TextManager.Get("SteeringAutoPilot"), style: "GUIRadioButton") TextManager.Get("SteeringAutoPilot"), font: GUI.SubHeadingFont, style: "IndicatorLightRedSmall")
{ {
OnSelected = (GUITickBox box) => Selected = false,
{ Enabled = false
AutoPilot = box.Selected;
if (AutoPilot && MaintainPos)
{
posToMaintain = controlledSub != null ?
controlledSub.WorldPosition :
item.Submarine == null ? item.WorldPosition : item.Submarine.WorldPosition;
}
unsentChanges = true;
user = Character.Controlled;
return true;
}
}; };
manualPilotIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
autopilotIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
GUITextBlock.AutoScaleAndNormalize(manualPilotIndicator.TextBlock, autopilotIndicator.TextBlock);
GUIRadioButtonGroup modes = new GUIRadioButtonGroup(); var autoPilotControls = new GUIFrame(new RectTransform(new Vector2(0.8f, 0.6f), paddedControlContainer.RectTransform, Anchor.BottomRight), "OutlineFrame");
modes.AddRadioButton((int)Mode.AutoPilot, autopilotTickBox); var paddedAutoPilotControls = new GUILayoutGroup(new RectTransform(new Vector2(0.9f), autoPilotControls.RectTransform, Anchor.Center))
modes.AddRadioButton((int)Mode.Manual, manualTickBox);
modes.Selected = (int)Mode.Manual;
var autoPilotControls = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.6f), paddedControlContainer.RectTransform), "InnerFrame");
var paddedAutoPilotControls = new GUILayoutGroup(new RectTransform(new Vector2(0.8f), autoPilotControls.RectTransform, Anchor.Center))
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.03f RelativeSpacing = 0.03f,
ChildAnchor = Anchor.TopCenter
}; };
maintainPosTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), paddedAutoPilotControls.RectTransform), maintainPosTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.2f), paddedAutoPilotControls.RectTransform),
TextManager.Get("SteeringMaintainPos"), font: GUI.SmallFont, style: "GUIRadioButton") TextManager.Get("SteeringMaintainPos"), font: GUI.SmallFont, style: "GUIRadioButton")
{ {
Enabled = false, Enabled = false,
@@ -188,7 +200,7 @@ namespace Barotrauma.Items.Components
} }
}; };
levelStartTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), paddedAutoPilotControls.RectTransform), levelStartTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.2f), paddedAutoPilotControls.RectTransform),
GameMain.GameSession?.StartLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.StartLocation.Name, 20), GameMain.GameSession?.StartLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.StartLocation.Name, 20),
font: GUI.SmallFont, style: "GUIRadioButton") font: GUI.SmallFont, style: "GUIRadioButton")
{ {
@@ -215,7 +227,7 @@ namespace Barotrauma.Items.Components
} }
}; };
levelEndTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), paddedAutoPilotControls.RectTransform), levelEndTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.2f), paddedAutoPilotControls.RectTransform),
GameMain.GameSession?.EndLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.EndLocation.Name, 20), GameMain.GameSession?.EndLocation == null ? "" : ToolBox.LimitString(GameMain.GameSession.EndLocation.Name, 20),
font: GUI.SmallFont, style: "GUIRadioButton") font: GUI.SmallFont, style: "GUIRadioButton")
{ {
@@ -242,53 +254,103 @@ namespace Barotrauma.Items.Components
} }
}; };
autoPilotControlsDisabler = new GUIFrame(new RectTransform(Vector2.One, autoPilotControls.RectTransform), "InnerFrame"); GUITextBlock.AutoScaleAndNormalize(maintainPosTickBox.TextBlock, levelStartTickBox.TextBlock, levelEndTickBox.TextBlock);
maintainPosTickBox.RectTransform.IsFixedSize = levelStartTickBox.RectTransform.IsFixedSize = levelEndTickBox.RectTransform.IsFixedSize = false;
maintainPosTickBox.RectTransform.MaxSize = levelStartTickBox.RectTransform.MaxSize = levelEndTickBox.RectTransform.MaxSize =
new Point(int.MaxValue, paddedAutoPilotControls.Rect.Height / 3);
maintainPosTickBox.RectTransform.MinSize = levelStartTickBox.RectTransform.MinSize = levelEndTickBox.RectTransform.MinSize =
Point.Zero;
GUIRadioButtonGroup destinations = new GUIRadioButtonGroup(); GUIRadioButtonGroup destinations = new GUIRadioButtonGroup();
destinations.AddRadioButton((int)Destination.MaintainPos, maintainPosTickBox); destinations.AddRadioButton((int)Destination.MaintainPos, maintainPosTickBox);
destinations.AddRadioButton((int)Destination.LevelStart, levelStartTickBox); destinations.AddRadioButton((int)Destination.LevelStart, levelStartTickBox);
destinations.AddRadioButton((int)Destination.LevelEnd, levelEndTickBox); destinations.AddRadioButton((int)Destination.LevelEnd, levelEndTickBox);
destinations.Selected = (int)(maintainPos ? Destination.MaintainPos : destinations.Selected = (int)(maintainPos ? Destination.MaintainPos :
levelStartSelected ? Destination.LevelStart : Destination.LevelEnd); levelStartSelected ? Destination.LevelStart : Destination.LevelEnd);
string steeringVelX = TextManager.Get("SteeringVelocityX");
string steeringVelY = TextManager.Get("SteeringVelocityY");
string steeringDepth = TextManager.Get("SteeringDepth");
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), "")
{
TextGetter = () =>
{
Vector2 vel = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
var realWorldVel = ConvertUnits.ToDisplayUnits(vel.Y * Physics.DisplayToRealWorldRatio) * 3.6f;
return steeringVelY.Replace("[kph]", ((int)-realWorldVel).ToString());
}
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), "")
{
TextGetter = () =>
{
Vector2 vel = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
var realWorldVel = ConvertUnits.ToDisplayUnits(vel.X * Physics.DisplayToRealWorldRatio) * 3.6f;
return steeringVelX.Replace("[kph]", ((int)realWorldVel).ToString());
}
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), "")
{
TextGetter = () =>
{
Vector2 pos = controlledSub == null ? Vector2.Zero : controlledSub.Position;
float realWorldDepth = Level.Loaded == null ? 0.0f : Math.Abs(pos.Y - Level.Loaded.Size.Y) * Physics.DisplayToRealWorldRatio;
return steeringDepth.Replace("[m]", ((int)realWorldDepth).ToString());
}
};
pressureWarningText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), TextManager.Get("SteeringDepthWarning"), Color.Red) // Status ->
statusContainer = new GUIFrame(new RectTransform(new Vector2(0.33f, 0.3f), GuiFrame.RectTransform, Anchor.BottomRight)
{
RelativeOffset = new Vector2(Sonar.controlContainerRelativeOffset, 0)
}, "ItemUI");
var paddedStatusContainer = new GUIFrame(new RectTransform(statusContainer.Rect.Size - GUIStyle.ItemFrameMargin, statusContainer.RectTransform, Anchor.Center)
{
AbsoluteOffset = GUIStyle.ItemFrameOffset
}, style: null);
var elements = GUI.CreateElements(3, new Vector2(1f, 0.323f), paddedStatusContainer.RectTransform, rt => new GUIFrame(rt, style: null), Anchor.TopCenter, relativeSpacing: 0.01f);
List<GUIComponent> leftElements = new List<GUIComponent>(), centerElements = new List<GUIComponent>(), rightElements = new List<GUIComponent>();
for (int i = 0; i < elements.Count; i++)
{
var e = elements[i];
var group = new GUILayoutGroup(new RectTransform(Vector2.One, e.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft)
{
RelativeSpacing = 0.01f,
Stretch = true
};
var left = new GUIFrame(new RectTransform(new Vector2(0.5f, 1), group.RectTransform), style: null);
var center = new GUIFrame(new RectTransform(new Vector2(0.175f, 1), group.RectTransform), style: null);
var right = new GUIFrame(new RectTransform(new Vector2(0.325f, 0.8f), group.RectTransform), style: null);
leftElements.Add(left);
centerElements.Add(center);
rightElements.Add(right);
string leftText = string.Empty, centerText = string.Empty;
GUITextBlock.TextGetterHandler rightTextGetter = null;
switch (i)
{
case 0:
leftText = TextManager.Get("DescentVelocity");
centerText = $"({TextManager.Get("KilometersPerHour")})";
rightTextGetter = () =>
{
Vector2 vel = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
var realWorldVel = ConvertUnits.ToDisplayUnits(vel.Y * Physics.DisplayToRealWorldRatio) * 3.6f;
return ((int)(-realWorldVel)).ToString();
};
break;
case 1:
leftText = TextManager.Get("Velocity");
centerText = $"({TextManager.Get("KilometersPerHour")})";
rightTextGetter = () =>
{
Vector2 vel = controlledSub == null ? Vector2.Zero : controlledSub.Velocity;
var realWorldVel = ConvertUnits.ToDisplayUnits(vel.X * Physics.DisplayToRealWorldRatio) * 3.6f;
return ((int)realWorldVel).ToString();
};
break;
case 2:
leftText = TextManager.Get("Depth");
centerText = $"({TextManager.Get("Meter")})";
rightTextGetter = () =>
{
Vector2 pos = controlledSub == null ? Vector2.Zero : controlledSub.Position;
float realWorldDepth = Level.Loaded == null ? 0.0f : Math.Abs(pos.Y - Level.Loaded.Size.Y) * Physics.DisplayToRealWorldRatio;
return ((int)realWorldDepth).ToString();
};
break;
}
new GUITextBlock(new RectTransform(Vector2.One, left.RectTransform), leftText, font: GUI.SubHeadingFont, wrap: true, textAlignment: Alignment.CenterRight);
new GUITextBlock(new RectTransform(Vector2.One, center.RectTransform), centerText, font: GUI.Font, textAlignment: Alignment.Center) { Padding = Vector4.Zero };
var digitalFrame = new GUIFrame(new RectTransform(Vector2.One, right.RectTransform), style: "DigitalFrameDark");
new GUITextBlock(new RectTransform(Vector2.One * 0.85f, digitalFrame.RectTransform, Anchor.Center), "12345", GUI.Style.TextColorDark, GUI.DigitalFont, Alignment.CenterRight)
{
TextGetter = rightTextGetter
};
}
GUITextBlock.AutoScaleAndNormalize(leftElements.SelectMany(e => e.GetAllChildren<GUITextBlock>()));
// TODO: center texts are too small on low resolutions
GUITextBlock.AutoScaleAndNormalize(centerElements.SelectMany(e => e.GetAllChildren<GUITextBlock>()));
GUITextBlock.AutoScaleAndNormalize(rightElements.SelectMany(e => e.GetAllChildren<GUITextBlock>()));
pressureWarningText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), paddedStatusContainer.RectTransform), TextManager.Get("SteeringDepthWarning"), GUI.Style.Red)
{ {
Visible = false Visible = false
}; };
tipContainer = new GUITextBlock(new RectTransform(new Vector2(0.25f, 0.12f), GuiFrame.RectTransform, Anchor.BottomLeft) tipContainer = new GUITextBlock(new RectTransform(new Vector2(0.3f, 0.1f), GuiFrame.RectTransform, Anchor.BottomCenter, Pivot.TopCenter)
{ MinSize = new Point(150, 0), RelativeOffset = new Vector2(0.0f, -0.05f) }, "", wrap: true, style: "GUIToolTip") {
RelativeOffset = new Vector2(-0.2f, 0.0f)
}, "", font: GUI.Font, wrap: true, style: "GUIToolTip", textAlignment: Alignment.Center)
{ {
AutoScale = true AutoScale = true
}; };
@@ -300,17 +362,17 @@ namespace Barotrauma.Items.Components
autoPilotLevelEndTip = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]", autoPilotLevelEndTip = TextManager.GetWithVariable("SteeringAutoPilotLocationTip", "[locationname]",
GameMain.GameSession?.EndLocation == null ? "End" : GameMain.GameSession.EndLocation.Name); GameMain.GameSession?.EndLocation == null ? "End" : GameMain.GameSession.EndLocation.Name);
steerArea = new GUICustomComponent(new RectTransform(Point.Zero, GuiFrame.RectTransform, Anchor.CenterLeft),
(spriteBatch, guiCustomComponent) => { DrawHUD(spriteBatch, guiCustomComponent.Rect); }, null);
//docking interface ---------------------------------------------------- //docking interface ----------------------------------------------------
dockingContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GuiFrame.RectTransform, Anchor.BottomLeft) float dockingButtonSize = 1.1f;
{ MinSize = new Point(150, 0) }, style: null); float elementScale = 0.6f;
var paddedDockingContainer = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), dockingContainer.RectTransform, Anchor.Center), style: null); dockingContainer = new GUIFrame(new RectTransform(new Point(160).Multiply(GUI.Scale * dockingButtonSize), GuiFrame.RectTransform, Anchor.BottomRight)
{
RelativeOffset = new Vector2(Sonar.controlContainerRelativeOffset + 0.05f, -0.05f)
}, style: null);
dockText = TextManager.Get("label.navterminaldock", fallBackTag: "captain.dock"); dockText = TextManager.Get("label.navterminaldock", fallBackTag: "captain.dock");
undockText = TextManager.Get("label.navterminalundock", fallBackTag: "captain.undock"); undockText = TextManager.Get("label.navterminalundock", fallBackTag: "captain.undock");
dockingButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.5f), paddedDockingContainer.RectTransform, Anchor.Center), dockText, style: "GUIButtonLarge") dockingButton = new GUIButton(new RectTransform(new Vector2(elementScale), dockingContainer.RectTransform, Anchor.Center), dockText, style: "PowerButton")
{ {
OnClicked = (btn, userdata) => OnClicked = (btn, userdata) =>
{ {
@@ -326,65 +388,45 @@ namespace Barotrauma.Items.Components
return true; return true;
} }
}; };
dockingButton.Font = GUI.SmallFont; dockingButton.Font = GUI.SubHeadingFont;
var leftButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.5f), paddedDockingContainer.RectTransform, Anchor.CenterLeft), "") var style = GUI.Style.GetComponentStyle("DockingButtonUp");
Sprite buttonSprite = style.Sprites.FirstOrDefault().Value.FirstOrDefault()?.Sprite;
Point buttonSize = buttonSprite != null ? buttonSprite.size.ToPoint() : new Point(149, 52);
Point horizontalButtonSize = buttonSize.Multiply(elementScale * GUI.Scale * dockingButtonSize);
Point verticalButtonSize = horizontalButtonSize.Flip();
var leftButton = new GUIButton(new RectTransform(verticalButtonSize, dockingContainer.RectTransform, Anchor.CenterLeft), "", style: "DockingButtonLeft")
{ {
OnClicked = NudgeButtonClicked, OnClicked = NudgeButtonClicked,
UserData = -Vector2.UnitX UserData = -Vector2.UnitX
}; };
new GUIImage(new RectTransform(new Vector2(0.7f), leftButton.RectTransform, Anchor.Center), "GUIButtonHorizontalArrow").SpriteEffects = SpriteEffects.FlipHorizontally; var rightButton = new GUIButton(new RectTransform(verticalButtonSize, dockingContainer.RectTransform, Anchor.CenterRight), "", style: "DockingButtonRight")
var rightButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.5f), paddedDockingContainer.RectTransform, Anchor.CenterRight), "")
{ {
OnClicked = NudgeButtonClicked, OnClicked = NudgeButtonClicked,
UserData = Vector2.UnitX UserData = Vector2.UnitX
}; };
new GUIImage(new RectTransform(new Vector2(0.7f), rightButton.RectTransform, Anchor.Center), "GUIButtonHorizontalArrow"); var upButton = new GUIButton(new RectTransform(horizontalButtonSize, dockingContainer.RectTransform, Anchor.TopCenter), "", style: "DockingButtonUp")
var upButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.2f), paddedDockingContainer.RectTransform, Anchor.TopCenter), "")
{ {
OnClicked = NudgeButtonClicked, OnClicked = NudgeButtonClicked,
UserData = Vector2.UnitY UserData = Vector2.UnitY
}; };
new GUIImage(new RectTransform(new Vector2(0.7f), upButton.RectTransform, Anchor.Center), "GUIButtonVerticalArrow"); var downButton = new GUIButton(new RectTransform(horizontalButtonSize, dockingContainer.RectTransform, Anchor.BottomCenter), "", style: "DockingButtonDown")
var downButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.2f), paddedDockingContainer.RectTransform, Anchor.BottomCenter), "")
{ {
OnClicked = NudgeButtonClicked, OnClicked = NudgeButtonClicked,
UserData = -Vector2.UnitY UserData = -Vector2.UnitY
}; };
new GUIImage(new RectTransform(new Vector2(0.7f), downButton.RectTransform, Anchor.Center), "GUIButtonVerticalArrow").SpriteEffects = SpriteEffects.FlipVertically;
foreach (XElement subElement in element.Elements()) steerArea = new GUICustomComponent(new RectTransform(Sonar.SonarAreaSize, GuiFrame.RectTransform, Anchor.CenterLeft),
{ (spriteBatch, guiCustomComponent) => { DrawHUD(spriteBatch, guiCustomComponent.Rect); }, null);
switch (subElement.Name.ToString().ToLowerInvariant()) steerArea.RectTransform.SetAsFirstChild();
{ steerRadius = steerArea.Rect.Width / 2;
case "steeringindicator":
steeringIndicator = new Sprite(subElement);
break;
case "maintainposindicator":
maintainPosIndicator = new Sprite(subElement);
break;
case "maintainposoriginindicator":
maintainPosOriginIndicator = new Sprite(subElement);
break;
}
}
SetUILayout();
GameMain.Instance.OnResolutionChanged += SetUILayout;
GameMain.Config.OnHUDScaleChanged += SetUILayout;
} }
private void SetUILayout()
private void ResetGUI()
{ {
int viewSize = (int)Math.Min(GuiFrame.Rect.Width - 150, GuiFrame.Rect.Height * 0.9f); GuiFrame.RectTransform.Children.ForEachMod(c => c.Parent = null);
CreateGUI();
controlContainer.RectTransform.AbsoluteOffset = new Point((int)(viewSize * 0.99f), (int)(viewSize * 0.05f));
statusContainer.RectTransform.AbsoluteOffset = new Point((int)(viewSize * 0.9f), 0);
steerArea.RectTransform.NonScaledSize = new Point(viewSize);
dockingContainer.RectTransform.AbsoluteOffset = new Point((int)(viewSize * 0.9f), 0);
steerRadius = steerArea.Rect.Width / 2;
} }
/// <summary> /// <summary>
@@ -434,7 +476,7 @@ namespace Barotrauma.Items.Components
if (velRect.Contains(PlayerInput.MousePosition)) if (velRect.Contains(PlayerInput.MousePosition))
{ {
GUI.DrawRectangle(spriteBatch, new Rectangle((int)steeringInputPos.X - 4, (int)steeringInputPos.Y - 4, 8, 8), Color.Red, thickness: 2); GUI.DrawRectangle(spriteBatch, new Rectangle((int)steeringInputPos.X - 4, (int)steeringInputPos.Y - 4, 8, 8), GUI.Style.Red, thickness: 2);
} }
} }
else if (posToMaintain.HasValue && !LevelStartSelected && !LevelEndSelected) else if (posToMaintain.HasValue && !LevelStartSelected && !LevelEndSelected)
@@ -447,7 +489,7 @@ namespace Barotrauma.Items.Components
displayPosToMaintain = displayPosToMaintain.ClampLength(velRect.Width / 2); displayPosToMaintain = displayPosToMaintain.ClampLength(velRect.Width / 2);
displayPosToMaintain = steerArea.Rect.Center.ToVector2() + displayPosToMaintain; displayPosToMaintain = steerArea.Rect.Center.ToVector2() + displayPosToMaintain;
Color crosshairColor = Color.Orange * (0.5f + ((float)Math.Sin(Timing.TotalTime * 5.0f) + 1.0f) / 4.0f); Color crosshairColor = GUI.Style.Orange * (0.5f + ((float)Math.Sin(Timing.TotalTime * 5.0f) + 1.0f) / 4.0f);
if (maintainPosIndicator != null) if (maintainPosIndicator != null)
{ {
maintainPosIndicator.Draw(spriteBatch, displayPosToMaintain, crosshairColor, scale: 0.5f * sonar.Zoom); maintainPosIndicator.Draw(spriteBatch, displayPosToMaintain, crosshairColor, scale: 0.5f * sonar.Zoom);
@@ -461,11 +503,11 @@ namespace Barotrauma.Items.Components
if (maintainPosOriginIndicator != null) if (maintainPosOriginIndicator != null)
{ {
maintainPosOriginIndicator.Draw(spriteBatch, displaySubPos, Color.Orange, scale: 0.5f * sonar.Zoom); maintainPosOriginIndicator.Draw(spriteBatch, displaySubPos, GUI.Style.Orange, scale: 0.5f * sonar.Zoom);
} }
else else
{ {
GUI.DrawRectangle(spriteBatch, new Rectangle((int)displaySubPos.X - 5, (int)displaySubPos.Y - 5, 10, 10), Color.Orange); GUI.DrawRectangle(spriteBatch, new Rectangle((int)displaySubPos.X - 5, (int)displaySubPos.Y - 5, 10, 10), GUI.Style.Orange);
} }
} }
} }
@@ -507,11 +549,11 @@ namespace Barotrauma.Items.Components
pos.Y = -pos.Y; pos.Y = -pos.Y;
pos += center; pos += center;
GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X - 3 / 2, (int)pos.Y - 3, 6, 6), (SteeringPath.CurrentNode == wp) ? Color.LightGreen : Color.Green, false); GUI.DrawRectangle(spriteBatch, new Rectangle((int)pos.X - 3 / 2, (int)pos.Y - 3, 6, 6), (SteeringPath.CurrentNode == wp) ? Color.LightGreen : GUI.Style.Green, false);
if (prevPos != Vector2.Zero) if (prevPos != Vector2.Zero)
{ {
GUI.DrawLine(spriteBatch, pos, prevPos, Color.Green); GUI.DrawLine(spriteBatch, pos, prevPos, GUI.Style.Green);
} }
prevPos = pos; prevPos = pos;
@@ -529,14 +571,14 @@ namespace Barotrauma.Items.Components
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
pos1, pos1,
pos2, pos2,
Color.Red * 0.6f, width: 3); GUI.Style.Red * 0.6f, width: 3);
if (obstacle.Intersection.HasValue) if (obstacle.Intersection.HasValue)
{ {
Vector2 intersectionPos = (obstacle.Intersection.Value - transducerCenter) *displayScale; Vector2 intersectionPos = (obstacle.Intersection.Value - transducerCenter) *displayScale;
intersectionPos.Y = -intersectionPos.Y; intersectionPos.Y = -intersectionPos.Y;
intersectionPos += center; intersectionPos += center;
GUI.DrawRectangle(spriteBatch, intersectionPos - Vector2.One * 2, Vector2.One * 4, Color.Red); GUI.DrawRectangle(spriteBatch, intersectionPos - Vector2.One * 2, Vector2.One * 4, GUI.Style.Red);
} }
Vector2 obstacleCenter = (pos1 + pos2) / 2; Vector2 obstacleCenter = (pos1 + pos2) / 2;
@@ -545,7 +587,7 @@ namespace Barotrauma.Items.Components
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
obstacleCenter, obstacleCenter,
obstacleCenter + new Vector2(obstacle.AvoidStrength.X, -obstacle.AvoidStrength.Y) * 100, obstacleCenter + new Vector2(obstacle.AvoidStrength.X, -obstacle.AvoidStrength.Y) * 100,
Color.Lerp(Color.Green, Color.Orange, obstacle.Dot), width: 2); Color.Lerp(GUI.Style.Green, GUI.Style.Orange, obstacle.Dot), width: 2);
} }
} }
} }
@@ -580,7 +622,7 @@ namespace Barotrauma.Items.Components
dockingButton.Text = dockText; dockingButton.Text = dockText;
if (dockingButton.FlashTimer <= 0.0f) if (dockingButton.FlashTimer <= 0.0f)
{ {
dockingButton.Flash(Color.LightGreen, 0.5f); dockingButton.Flash(GUI.Style.Blue, 0.5f, useCircularFlash: true);
dockingButton.Pulsate(Vector2.One, Vector2.One * 1.2f, dockingButton.FlashTimer); dockingButton.Pulsate(Vector2.One, Vector2.One * 1.2f, dockingButton.FlashTimer);
} }
} }
@@ -592,7 +634,7 @@ namespace Barotrauma.Items.Components
statusContainer.Visible = false; statusContainer.Visible = false;
if (dockingButton.FlashTimer <= 0.0f) if (dockingButton.FlashTimer <= 0.0f)
{ {
dockingButton.Flash(Color.OrangeRed); dockingButton.Flash(GUI.Style.Orange, useCircularFlash: true);
dockingButton.Pulsate(Vector2.One, Vector2.One * 1.2f, dockingButton.FlashTimer); dockingButton.Pulsate(Vector2.One, Vector2.One * 1.2f, dockingButton.FlashTimer);
} }
} }
@@ -601,8 +643,6 @@ namespace Barotrauma.Items.Components
dockingButton.Text = dockText; dockingButton.Text = dockText;
} }
autoPilotControlsDisabler.Visible = !AutoPilot;
if (Voltage < MinVoltage) if (Voltage < MinVoltage)
{ {
tipContainer.Visible = true; tipContainer.Visible = true;
@@ -781,11 +821,11 @@ namespace Barotrauma.Items.Components
public void ClientWrite(IWriteMessage msg, object[] extraData = null) public void ClientWrite(IWriteMessage msg, object[] extraData = null)
{ {
msg.Write(autoPilot); msg.Write(AutoPilot);
msg.Write(dockingNetworkMessagePending); msg.Write(dockingNetworkMessagePending);
dockingNetworkMessagePending = false; dockingNetworkMessagePending = false;
if (!autoPilot) if (!AutoPilot)
{ {
//no need to write steering info if autopilot is controlling //no need to write steering info if autopilot is controlling
msg.Write(steeringInput.X); msg.Write(steeringInput.X);
@@ -879,5 +919,15 @@ namespace Barotrauma.Items.Components
} }
} }
} }
private void UpdateGUIElements()
{
steeringModeSwitch.Selected = AutoPilot;
autopilotIndicator.Selected = AutoPilot;
manualPilotIndicator.Selected = !AutoPilot;
maintainPosTickBox.Enabled = AutoPilot;
levelEndTickBox.Enabled = AutoPilot;
levelStartTickBox.Enabled = AutoPilot;
}
} }
} }
@@ -18,13 +18,20 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific() partial void InitProjSpecific()
{ {
if (GuiFrame == null) return; if (GuiFrame == null) { return; }
var paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.75f, 0.75f), GuiFrame.RectTransform, Anchor.Center)
{
//RelativeOffset = new Vector2(0, 0.05f)
}, style: null);
var upperArea = new GUIFrame(new RectTransform(new Vector2(1, 0.4f), paddedFrame.RectTransform, Anchor.TopCenter), style: null);
var lowerArea = new GUIFrame(new RectTransform(new Vector2(1, 0.6f), paddedFrame.RectTransform, Anchor.BottomCenter), style: null);
GUILayoutGroup paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.7f), GuiFrame.RectTransform, Anchor.Center))
{ RelativeSpacing = 0.1f, Stretch = true };
string rechargeStr = TextManager.Get("PowerContainerRechargeRate"); string rechargeStr = TextManager.Get("PowerContainerRechargeRate");
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform), "RechargeRate", textAlignment: Alignment.Center) new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), upperArea.RectTransform, Anchor.TopCenter),
"RechargeRate", textColor: GUI.Style.TextColor, font: GUI.SubHeadingFont, textAlignment: Alignment.Center)
{ {
TextGetter = () => TextGetter = () =>
{ {
@@ -32,21 +39,14 @@ namespace Barotrauma.Items.Components
} }
}; };
var sliderArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform, Anchor.BottomCenter), isHorizontal: true) rechargeSpeedSlider = new GUIScrollBar(new RectTransform(new Vector2(0.9f, 0.4f), upperArea.RectTransform, Anchor.BottomCenter),
{ barSize: 0.15f, style: "DeviceSlider")
Stretch = true,
RelativeSpacing = 0.05f
};
new GUITextBlock(new RectTransform(new Vector2(0.15f, 1.0f), sliderArea.RectTransform),
"0 %", textAlignment: Alignment.Center);
rechargeSpeedSlider = new GUIScrollBar(new RectTransform(new Vector2(0.8f, 1.0f), sliderArea.RectTransform), barSize: 0.25f, style: "GUISlider")
{ {
Step = 0.1f, Step = 0.1f,
OnMoved = (GUIScrollBar scrollBar, float barScroll) => OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{ {
float newRechargeSpeed = maxRechargeSpeed * barScroll; float newRechargeSpeed = maxRechargeSpeed * barScroll;
if (Math.Abs(newRechargeSpeed - rechargeSpeed) < 0.1f) return false; if (Math.Abs(newRechargeSpeed - rechargeSpeed) < 0.1f) { return false; }
RechargeSpeed = newRechargeSpeed; RechargeSpeed = newRechargeSpeed;
if (GameMain.Client != null) if (GameMain.Client != null)
@@ -57,21 +57,30 @@ namespace Barotrauma.Items.Components
return true; return true;
} }
}; };
new GUITextBlock(new RectTransform(new Vector2(0.15f, 1.0f), sliderArea.RectTransform), rechargeSpeedSlider.Bar.RectTransform.MaxSize = new Point(rechargeSpeedSlider.Bar.Rect.Height);
"100 %", textAlignment: Alignment.Center);
// lower area --------------------------
string chargeStr = TextManager.Get("PowerContainerCharge"); var textArea = new GUIFrame(new RectTransform(new Vector2(1, 0.4f), lowerArea.RectTransform), style: null);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform), "Charge", textAlignment: Alignment.Center) var chargeLabel = new GUITextBlock(new RectTransform(new Vector2(0.4f, 0.0f), textArea.RectTransform, Anchor.CenterLeft),
TextManager.Get("charge"), textColor: GUI.Style.TextColor, font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
{ {
TextGetter = () => ToolTip = TextManager.Get("PowerTransferTipPower")
{
return chargeStr.Replace("[charge]", (int)charge + "/" + (int)capacity).Replace("[percentage]", ((int)((charge / capacity) * 100.0f)).ToString());
}
}; };
string kWmin = TextManager.Get("kilowattminute");
chargeIndicator = new GUIProgressBar(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), barSize: 0.0f) var chargeText = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1), textArea.RectTransform, Anchor.CenterRight),
"", textColor: GUI.Style.TextColor, font: GUI.Font, textAlignment: Alignment.CenterRight)
{ {
ProgressGetter = () => TextGetter = () => $"{(int)charge}/{(int)capacity} {kWmin} ({((int)MathUtils.Percentage(charge, capacity)).ToString()} %)"
};
if (chargeText.TextSize.X > chargeText.Rect.Width) { chargeText.Font = GUI.SmallFont; }
chargeIndicator = new GUIProgressBar(new RectTransform(new Vector2(1.1f, 0.5f), lowerArea.RectTransform, Anchor.BottomCenter)
{
RelativeOffset = new Vector2(0, 0.1f)
}, barSize: 0.0f, style: "DeviceProgressBar")
{
ProgressGetter = () =>
{ {
return capacity <= 0.0f ? 1.0f : charge / capacity; return capacity <= 0.0f ? 1.0f : charge / capacity;
} }
@@ -95,7 +104,7 @@ namespace Barotrauma.Items.Components
public void Draw(SpriteBatch spriteBatch, bool editing = false, float itemDepth = -1) public void Draw(SpriteBatch spriteBatch, bool editing = false, float itemDepth = -1)
{ {
if (indicatorSize.X <= 1.0f || indicatorSize.Y <= 1.0f) return; if (indicatorSize.X <= 1.0f || indicatorSize.Y <= 1.0f) { return; }
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
new Vector2( new Vector2(
@@ -1,5 +1,4 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System; using System;
using System.Xml.Linq; using System.Xml.Linq;
@@ -13,66 +12,95 @@ namespace Barotrauma.Items.Components
partial void InitProjectSpecific(XElement element) partial void InitProjectSpecific(XElement element)
{ {
if (GuiFrame == null) return; if (GuiFrame == null) { return; }
Point indicatorSize = new Point((int)(30 * GUI.Scale)); var paddedFrame = new GUIFrame(new RectTransform(GuiFrame.Rect.Size - GUIStyle.ItemFrameMargin, GuiFrame.RectTransform, Anchor.Center) { AbsoluteOffset = GUIStyle.ItemFrameOffset },
style: null)
var paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.7f), GuiFrame.RectTransform, Anchor.Center), style: null);
powerIndicator = new GUITickBox(new RectTransform(indicatorSize, paddedFrame.RectTransform),
TextManager.Get("PowerTransferPowered"), style: "IndicatorLightGreen")
{ {
Enabled = false CanBeFocused = false
}; };
powerIndicator.TextColor = powerIndicator.DefaultTextColor.Value;
highVoltageIndicator = new GUITickBox(new RectTransform(indicatorSize, paddedFrame.RectTransform) { AbsoluteOffset = new Point(0, (int)(40 * GUI.yScale)) }, var lightsArea = new GUILayoutGroup(new RectTransform(new Vector2(0.4f, 1), paddedFrame.RectTransform, Anchor.CenterLeft))
TextManager.Get("PowerTransferHighVoltage"), style: "IndicatorLightRed") {
Stretch = true,
RelativeSpacing = 0.05f
};
powerIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.3f), lightsArea.RectTransform),
TextManager.Get("PowerTransferPowered"), font: GUI.SubHeadingFont, style: "IndicatorLightGreen")
{
CanBeFocused = false
};
highVoltageIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.3f), lightsArea.RectTransform),
TextManager.Get("PowerTransferHighVoltage"), font: GUI.SubHeadingFont, style: "IndicatorLightRed")
{ {
ToolTip = TextManager.Get("PowerTransferTipOvervoltage"), ToolTip = TextManager.Get("PowerTransferTipOvervoltage"),
Enabled = false Enabled = false
}; };
highVoltageIndicator.TextColor = highVoltageIndicator.DefaultTextColor.Value; lowVoltageIndicator = new GUITickBox(new RectTransform(new Vector2(1, 0.3f), lightsArea.RectTransform),
TextManager.Get("PowerTransferLowVoltage"), font: GUI.SubHeadingFont, style: "IndicatorLightRed")
lowVoltageIndicator = new GUITickBox(new RectTransform(indicatorSize, paddedFrame.RectTransform) { AbsoluteOffset = new Point(0, (int)(80 * GUI.yScale)) },
TextManager.Get("PowerTransferLowVoltage"), style: "IndicatorLightRed")
{ {
ToolTip = TextManager.Get("PowerTransferTipLowvoltage"), ToolTip = TextManager.Get("PowerTransferTipLowvoltage"),
Enabled = false Enabled = false
}; };
lowVoltageIndicator.TextColor = lowVoltageIndicator.DefaultTextColor.Value; powerIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
highVoltageIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
lowVoltageIndicator.TextBlock.OverrideTextColor(GUI.Style.TextColor);
GUITextBlock.AutoScaleAndNormalize(powerIndicator.TextBlock, highVoltageIndicator.TextBlock, lowVoltageIndicator.TextBlock);
var textContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), paddedFrame.RectTransform, Anchor.TopRight)); var textContainer = new GUIFrame(new RectTransform(new Vector2(0.58f, 1.0f), paddedFrame.RectTransform, Anchor.CenterRight), style: null);
var upperTextArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), textContainer.RectTransform, Anchor.TopLeft), isHorizontal: true, childAnchor: Anchor.CenterLeft)
{
Stretch = true
};
var lowerTextArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), textContainer.RectTransform, Anchor.BottomLeft), isHorizontal: true, childAnchor: Anchor.CenterLeft)
{
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), textContainer.RectTransform), var powerLabel = new GUITextBlock(new RectTransform(new Vector2(0.4f, 1), upperTextArea.RectTransform),
TextManager.Get("PowerTransferPowerLabel"), font: GUI.LargeFont) TextManager.Get("PowerTransferPowerLabel"), textColor: GUI.Style.TextColorBright, font: GUI.LargeFont, textAlignment: Alignment.CenterRight)
{ {
ToolTip = TextManager.Get("PowerTransferTipPower") ToolTip = TextManager.Get("PowerTransferTipPower")
}; };
string powerStr = TextManager.Get("PowerTransferPower"); var loadLabel = new GUITextBlock(new RectTransform(new Vector2(0.4f, 1), lowerTextArea.RectTransform),
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), textContainer.RectTransform), "", textColor: Color.LightGreen) TextManager.Get("PowerTransferLoadLabel"), textColor: GUI.Style.TextColorBright, font: GUI.LargeFont, textAlignment: Alignment.CenterRight)
{
ToolTip = TextManager.Get("PowerTransferTipPower"),
TextGetter = () => { return powerStr.Replace("[power]", ((int)Math.Round(-currPowerConsumption)).ToString()); }
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), textContainer.RectTransform),
TextManager.Get("PowerTransferLoadLabel"), font: GUI.LargeFont)
{ {
ToolTip = TextManager.Get("PowerTransferTipLoad") ToolTip = TextManager.Get("PowerTransferTipLoad")
}; };
string loadStr = TextManager.Get("PowerTransferLoad");
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), textContainer.RectTransform), "", textColor: Color.LightBlue) var digitalBackground = new GUIFrame(new RectTransform(new Vector2(0.55f, 0.8f), upperTextArea.RectTransform), style: "DigitalFrameDark");
var powerText = new GUITextBlock(new RectTransform(new Vector2(0.9f, 0.95f), digitalBackground.RectTransform, Anchor.Center),
"", font: GUI.DigitalFont, textColor: GUI.Style.TextColorDark)
{ {
ToolTip = TextManager.Get("PowerTransferTipLoad"), TextAlignment = Alignment.CenterRight,
TextGetter = () => ToolTip = TextManager.Get("PowerTransferTipPower"),
{ TextGetter = () => ((int)Math.Round(-currPowerConsumption)).ToString()
return loadStr.Replace("[load]",
this is RelayComponent relay ?
((int)Math.Round(relay.DisplayLoad)).ToString() :
((int)Math.Round(powerLoad)).ToString());
}
}; };
var kw1 = new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.5f), upperTextArea.RectTransform),
TextManager.Get("kilowatt"), textColor: GUI.Style.TextColor, font: GUI.Font)
{
Padding = Vector4.Zero,
TextAlignment = Alignment.BottomCenter
};
digitalBackground = new GUIFrame(new RectTransform(new Vector2(0.55f, 0.8f), lowerTextArea.RectTransform), style: "DigitalFrameDark");
var loadText = new GUITextBlock(new RectTransform(new Vector2(0.9f, 0.95f), digitalBackground.RectTransform, Anchor.Center),
"", font: GUI.DigitalFont, textColor: GUI.Style.TextColorDark)
{
TextAlignment = Alignment.CenterRight,
ToolTip = TextManager.Get("PowerTransferTipLoad"),
TextGetter = () => ((int)Math.Round(this is RelayComponent relay ? relay.DisplayLoad : powerLoad)).ToString()
};
var kw2 = new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.5f), lowerTextArea.RectTransform),
TextManager.Get("kilowatt"), textColor: GUI.Style.TextColor, font: GUI.Font)
{
Padding = Vector4.Zero,
TextAlignment = Alignment.BottomCenter
};
GUITextBlock.AutoScaleAndNormalize(powerLabel, loadLabel);
GUITextBlock.AutoScaleAndNormalize(powerText, loadText);
GUITextBlock.AutoScaleAndNormalize(kw1, kw2);
} }
public override void UpdateHUD(Character character, float deltaTime, Camera cam) public override void UpdateHUD(Character character, float deltaTime, Camera cam)
@@ -84,7 +84,7 @@ namespace Barotrauma.Items.Components
targetStructure.ID * 1000 + sectionIndex, //unique "identifier" for each wall section targetStructure.ID * 1000 + sectionIndex, //unique "identifier" for each wall section
progressBarPos, progressBarPos,
1.0f - targetStructure.SectionDamage(sectionIndex) / targetStructure.Health, 1.0f - targetStructure.SectionDamage(sectionIndex) / targetStructure.Health,
Color.Red, Color.Green); GUI.Style.Red, GUI.Style.Green);
if (progressBar != null) progressBar.Size = new Vector2(60.0f, 20.0f); if (progressBar != null) progressBar.Size = new Vector2(60.0f, 20.0f);
@@ -121,7 +121,7 @@ namespace Barotrauma.Items.Components
targetItem, targetItem,
progressBarPos, progressBarPos,
progressBarState, progressBarState,
Color.Red, Color.Green); GUI.Style.Red, GUI.Style.Green);
if (progressBar != null) { progressBar.Size = new Vector2(60.0f, 20.0f); } if (progressBar != null) { progressBar.Size = new Vector2(60.0f, 20.0f); }
} }
prevProgressBarState = progressBarState; prevProgressBarState = progressBarState;
@@ -48,10 +48,11 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.85f), GuiFrame.RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter) var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 0.75f), GuiFrame.RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter)
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.05f RelativeSpacing = 0.05f,
CanBeFocused = true
}; };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform),
@@ -60,11 +61,11 @@ namespace Barotrauma.Items.Components
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
Description, font: GUI.SmallFont, wrap: true); Description, font: GUI.SmallFont, wrap: true);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
TextManager.Get("RequiredRepairSkills")); TextManager.Get("RequiredRepairSkills"), font: GUI.SubHeadingFont);
for (int i = 0; i < requiredSkills.Count; i++) for (int i = 0; i < requiredSkills.Count; i++)
{ {
var skillText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform), var skillText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
" - " + TextManager.AddPunctuation(':', TextManager.Get("SkillName." + requiredSkills[i].Identifier), ((int) requiredSkills[i].Level).ToString()), " - " + TextManager.AddPunctuation(':', TextManager.Get("SkillName." + requiredSkills[i].Identifier), ((int) requiredSkills[i].Level).ToString()),
font: GUI.SmallFont) font: GUI.SmallFont)
{ {
@@ -72,12 +73,17 @@ namespace Barotrauma.Items.Components
}; };
} }
progressBar = new GUIProgressBar(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform), var progressBarHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), isHorizontal: true)
color: Color.Green, barSize: 0.0f); {
Stretch = true,
RelativeSpacing = 0.02f
};
progressBar = new GUIProgressBar(new RectTransform(new Vector2(0.7f, 1.0f), progressBarHolder.RectTransform),
color: GUI.Style.Green, barSize: 0.0f, style: "DeviceProgressBar");
repairButtonText = TextManager.Get("RepairButton"); repairButtonText = TextManager.Get("RepairButton");
repairingText = TextManager.Get("Repairing"); repairingText = TextManager.Get("Repairing");
RepairButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.15f), paddedFrame.RectTransform, Anchor.TopCenter), repairButtonText) RepairButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), progressBarHolder.RectTransform, Anchor.TopCenter), repairButtonText)
{ {
OnClicked = (btn, obj) => OnClicked = (btn, obj) =>
{ {
@@ -86,10 +92,15 @@ namespace Barotrauma.Items.Components
return true; return true;
} }
}; };
progressBarHolder.RectTransform.MinSize = RepairButton.RectTransform.MinSize;
RepairButton.RectTransform.MinSize = new Point((int)(RepairButton.TextBlock.TextSize.X * 1.2f), RepairButton.RectTransform.MinSize.Y);
sabotageButtonText = TextManager.Get("SabotageButton"); sabotageButtonText = TextManager.Get("SabotageButton");
sabotagingText = TextManager.Get("Sabotaging"); sabotagingText = TextManager.Get("Sabotaging");
SabotageButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.15f), paddedFrame.RectTransform, Anchor.BottomCenter), sabotageButtonText) SabotageButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.15f), paddedFrame.RectTransform, Anchor.BottomCenter), sabotageButtonText, style: "GUIButtonSmall")
{ {
IgnoreLayoutGroups = true,
Visible = false,
OnClicked = (btn, obj) => OnClicked = (btn, obj) =>
{ {
requestStartFixAction = FixActions.Sabotage; requestStartFixAction = FixActions.Sabotage;
@@ -157,7 +168,7 @@ namespace Barotrauma.Items.Components
IsActive = true; IsActive = true;
progressBar.BarSize = item.Condition / item.MaxCondition; progressBar.BarSize = item.Condition / item.MaxCondition;
progressBar.Color = ToolBox.GradientLerp(progressBar.BarSize, Color.Red, Color.Orange, Color.Green); progressBar.Color = ToolBox.GradientLerp(progressBar.BarSize, GUI.Style.Red, GUI.Style.Orange, GUI.Style.Green);
RepairButton.Enabled = (currentFixerAction == FixActions.None || (CurrentFixer == character && currentFixerAction != FixActions.Repair)) && !item.IsFullCondition; RepairButton.Enabled = (currentFixerAction == FixActions.None || (CurrentFixer == character && currentFixerAction != FixActions.Repair)) && !item.IsFullCondition;
RepairButton.Text = (currentFixerAction == FixActions.None || CurrentFixer != character || currentFixerAction != FixActions.Repair) ? RepairButton.Text = (currentFixerAction == FixActions.None || CurrentFixer != character || currentFixerAction != FixActions.Repair) ?
@@ -165,6 +176,7 @@ namespace Barotrauma.Items.Components
repairingText + new string('.', ((int)(Timing.TotalTime * 2.0f) % 3) + 1); repairingText + new string('.', ((int)(Timing.TotalTime * 2.0f) % 3) + 1);
SabotageButton.Visible = character.IsTraitor; SabotageButton.Visible = character.IsTraitor;
SabotageButton.IgnoreLayoutGroups = !SabotageButton.Visible;
SabotageButton.Enabled = (currentFixerAction == FixActions.None || (CurrentFixer == character && currentFixerAction != FixActions.Sabotage)) && character.IsTraitor && item.ConditionPercentage > MinSabotageCondition; SabotageButton.Enabled = (currentFixerAction == FixActions.None || (CurrentFixer == character && currentFixerAction != FixActions.Sabotage)) && character.IsTraitor && item.ConditionPercentage > MinSabotageCondition;
SabotageButton.Text = (currentFixerAction == FixActions.None || CurrentFixer != character || currentFixerAction != FixActions.Sabotage || !character.IsTraitor) ? SabotageButton.Text = (currentFixerAction == FixActions.None || CurrentFixer != character || currentFixerAction != FixActions.Sabotage || !character.IsTraitor) ?
sabotageButtonText : sabotageButtonText :
@@ -178,7 +190,7 @@ namespace Barotrauma.Items.Components
GUITextBlock textBlock = (GUITextBlock)c; GUITextBlock textBlock = (GUITextBlock)c;
if (character.GetSkillLevel(skill.Identifier) < skill.Level) if (character.GetSkillLevel(skill.Identifier) < skill.Level)
{ {
textBlock.TextColor = Color.Red; textBlock.TextColor = GUI.Style.Red;
} }
else else
{ {
@@ -202,11 +214,11 @@ namespace Barotrauma.Items.Components
{ {
GUI.DrawString(spriteBatch, GUI.DrawString(spriteBatch,
new Vector2(item.WorldPosition.X, -item.WorldPosition.Y), "Deteriorating at " + (int)(DeteriorationSpeed * 60.0f) + " units/min" + (paused ? " [PAUSED]" : ""), new Vector2(item.WorldPosition.X, -item.WorldPosition.Y), "Deteriorating at " + (int)(DeteriorationSpeed * 60.0f) + " units/min" + (paused ? " [PAUSED]" : ""),
paused ? Color.Cyan : Color.Red, Color.Black * 0.5f); paused ? Color.Cyan : GUI.Style.Red, Color.Black * 0.5f);
} }
GUI.DrawString(spriteBatch, GUI.DrawString(spriteBatch,
new Vector2(item.WorldPosition.X, -item.WorldPosition.Y + 20), "Condition: " + (int)item.Condition + "/" + (int)item.MaxCondition, new Vector2(item.WorldPosition.X, -item.WorldPosition.Y + 20), "Condition: " + (int)item.Condition + "/" + (int)item.MaxCondition,
Color.Orange); GUI.Style.Orange);
} }
} }
@@ -16,21 +16,11 @@ namespace Barotrauma.Items.Components
private static Sprite connectionSpriteHighlight; private static Sprite connectionSpriteHighlight;
private static List<Sprite> screwSprites; private static List<Sprite> screwSprites;
private static Wire draggingConnected;
private Color flashColor; private Color flashColor;
private float flashDuration = 1.5f; private float flashDuration = 1.5f;
public float FlashTimer
{ public float FlashTimer { get; private set; }
get { return flashTimer; } public static Wire DraggingConnected { get; private set; }
}
public static Wire DraggingConnected
{
get => draggingConnected;
}
private float flashTimer;
public static void DrawConnections(SpriteBatch spriteBatch, ConnectionPanel panel, Character character) public static void DrawConnections(SpriteBatch spriteBatch, ConnectionPanel panel, Character character)
{ {
@@ -38,6 +28,16 @@ namespace Barotrauma.Items.Components
int x = panelRect.X, y = panelRect.Y; int x = panelRect.X, y = panelRect.Y;
int width = panelRect.Width, height = panelRect.Height; int width = panelRect.Width, height = panelRect.Height;
Vector2 scale = new Vector2(GUI.Scale);
if (panel.GuiFrame.RectTransform.MaxSize.X < int.MaxValue)
{
scale.X = panel.GuiFrame.RectTransform.MaxSize.X / panel.GuiFrame.Rect.Width;
}
if (panel.GuiFrame.RectTransform.MaxSize.Y < int.MaxValue)
{
scale.Y = panel.GuiFrame.RectTransform.MaxSize.Y / panel.GuiFrame.Rect.Height;
}
bool mouseInRect = panelRect.Contains(PlayerInput.MousePosition); bool mouseInRect = panelRect.Contains(PlayerInput.MousePosition);
int totalWireCount = 0; int totalWireCount = 0;
@@ -57,73 +57,90 @@ namespace Barotrauma.Items.Components
{ {
Item selectedItem = character.SelectedItems[i]; Item selectedItem = character.SelectedItems[i];
if (selectedItem == null) continue; if (selectedItem == null) { continue; }
Wire wireComponent = selectedItem.GetComponent<Wire>(); Wire wireComponent = selectedItem.GetComponent<Wire>();
if (wireComponent != null) equippedWire = wireComponent; if (wireComponent != null)
}
}
Vector2 rightPos = new Vector2(x + width - 110 * GUI.xScale, y + 80 * GUI.yScale);
Vector2 leftPos = new Vector2(x + 110 * GUI.xScale, y + 80 * GUI.yScale);
Vector2 rightWirePos = new Vector2(x + width - 5 * GUI.xScale, y + 30 * GUI.yScale);
Vector2 leftWirePos = new Vector2(x + 5 * GUI.xScale, y + 30 * GUI.yScale);
int wireInterval = (height - (int)(20 * GUI.yScale)) / Math.Max(totalWireCount, 1);
int connectorIntervalLeft = (height - (int)(100 * GUI.yScale)) / Math.Max(panel.Connections.Count(c => c.IsOutput), 1);
int connectorIntervalRight = (height - (int)(100 * GUI.yScale)) / Math.Max(panel.Connections.Count(c => !c.IsOutput), 1);
foreach (Connection c in panel.Connections)
{
//if dragging a wire, let the Inventory know so that the wire can be
//dropped or dragged from the panel to the players inventory
if (draggingConnected != null)
{
//the wire can only be dragged out if it's not connected to anything at the other end
if (Screen.Selected == GameMain.SubEditorScreen ||
(draggingConnected.Connections[0] == null && draggingConnected.Connections[1] == null) ||
(draggingConnected.Connections.Contains(c) && draggingConnected.Connections.Contains(null)))
{ {
int linkIndex = c.FindWireIndex(draggingConnected.Item); equippedWire = wireComponent;
if (linkIndex > -1 || panel.DisconnectedWires.Contains(draggingConnected))
{
Inventory.draggingItem = draggingConnected.Item;
}
} }
} }
}
//outputs are drawn at the right side of the panel, inputs at the left //two passes: first the connector, then the wires to get the wires to render in front
if (c.IsOutput) for (int i = 0; i < 2; i++)
{
Vector2 rightPos = new Vector2(x + width - 80 * scale.X, y + 60 * scale.Y);
Vector2 leftPos = new Vector2(x + 80 * scale.X, y + 60 * scale.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);
int wireInterval = (height - (int)(20 * scale.Y)) / Math.Max(totalWireCount, 1);
int connectorIntervalLeft = (height - (int)(100 * scale.Y)) / Math.Max(panel.Connections.Count(c => c.IsOutput), 1);
int connectorIntervalRight = (height - (int)(100 * scale.Y)) / Math.Max(panel.Connections.Count(c => !c.IsOutput), 1);
foreach (Connection c in panel.Connections)
{ {
c.Draw(spriteBatch, panel, rightPos, //if dragging a wire, let the Inventory know so that the wire can be
new Vector2(rightPos.X - GUI.SmallFont.MeasureString(c.DisplayName).X - 20 * GUI.xScale, rightPos.Y + 3 * GUI.yScale), //dropped or dragged from the panel to the players inventory
rightWirePos, if (DraggingConnected != null && i == 1)
mouseInRect, equippedWire, {
wireInterval); //the wire can only be dragged out if it's not connected to anything at the other end
if (Screen.Selected == GameMain.SubEditorScreen ||
(DraggingConnected.Connections[0] == null && DraggingConnected.Connections[1] == null) ||
(DraggingConnected.Connections.Contains(c) && DraggingConnected.Connections.Contains(null)))
{
int linkIndex = c.FindWireIndex(DraggingConnected.Item);
if (linkIndex > -1 || panel.DisconnectedWires.Contains(DraggingConnected))
{
Inventory.draggingItem = DraggingConnected.Item;
}
}
}
rightPos.Y += connectorIntervalLeft; //outputs are drawn at the right side of the panel, inputs at the left
rightWirePos.Y += c.Wires.Count(w => w != null) * wireInterval; if (c.IsOutput)
} {
else if (i == 0)
{ {
c.Draw(spriteBatch, panel, leftPos, c.DrawConnection(spriteBatch, panel, rightPos,
new Vector2(leftPos.X + 20 * GUI.xScale, leftPos.Y - 12 * GUI.yScale), new Vector2(rightPos.X - GUI.SmallFont.MeasureString(c.DisplayName.ToUpper()).X - 25 * panel.Scale, rightPos.Y + 5 * panel.Scale),
leftWirePos, scale);
mouseInRect, equippedWire, }
wireInterval); else
{
c.DrawWires(spriteBatch, panel, rightPos, rightWirePos, mouseInRect, equippedWire, wireInterval);
}
leftPos.Y += connectorIntervalRight; rightPos.Y += connectorIntervalLeft;
leftWirePos.Y += c.Wires.Count(w => w != null) * wireInterval; rightWirePos.Y += c.Wires.Count(w => w != null) * wireInterval;
//leftWireX -= wireInterval; }
else
{
if (i == 0)
{
c.DrawConnection(spriteBatch, panel, leftPos,
new Vector2(leftPos.X + 25 * panel.Scale, leftPos.Y - 5 * panel.Scale - GUI.SmallFont.MeasureString(c.DisplayName.ToUpper()).Y),
scale);
}
else
{
c.DrawWires(spriteBatch, panel, leftPos, leftWirePos, mouseInRect, equippedWire, wireInterval);
}
leftPos.Y += connectorIntervalRight;
leftWirePos.Y += c.Wires.Count(w => w != null) * wireInterval;
}
} }
} }
if (draggingConnected != null)
if (DraggingConnected != null)
{ {
if (mouseInRect) if (mouseInRect)
{ {
DrawWire(spriteBatch, draggingConnected, PlayerInput.MousePosition, new Vector2(x + width / 2, y + height - 10), null, panel, ""); DrawWire(spriteBatch, DraggingConnected, PlayerInput.MousePosition, new Vector2(x + width / 2, y + height - 10), null, panel, "");
} }
panel.TriggerRewiringSound(); panel.TriggerRewiringSound();
@@ -131,11 +148,11 @@ namespace Barotrauma.Items.Components
{ {
if (GameMain.NetworkMember != null || panel.CheckCharacterSuccess(character)) if (GameMain.NetworkMember != null || panel.CheckCharacterSuccess(character))
{ {
if (draggingConnected.Connections[0]?.ConnectionPanel == panel || if (DraggingConnected.Connections[0]?.ConnectionPanel == panel ||
draggingConnected.Connections[1]?.ConnectionPanel == panel) DraggingConnected.Connections[1]?.ConnectionPanel == panel)
{ {
draggingConnected.RemoveConnection(panel.Item); DraggingConnected.RemoveConnection(panel.Item);
panel.DisconnectedWires.Add(draggingConnected); panel.DisconnectedWires.Add(DraggingConnected);
} }
} }
@@ -144,13 +161,13 @@ namespace Barotrauma.Items.Components
panel.Item.CreateClientEvent(panel); panel.Item.CreateClientEvent(panel);
} }
draggingConnected = null; DraggingConnected = null;
} }
} }
//if the Character using the panel has a wire item equipped //if the Character using the panel has a wire item equipped
//and the wire hasn't been connected yet, draw it on the panel //and the wire hasn't been connected yet, draw it on the panel
if (equippedWire != null && (draggingConnected != equippedWire || !mouseInRect)) if (equippedWire != null && (DraggingConnected != equippedWire || !mouseInRect))
{ {
if (panel.Connections.Find(c => c.Wires.Contains(equippedWire)) == null) if (panel.Connections.Find(c => c.Wires.Contains(equippedWire)) == null)
{ {
@@ -158,7 +175,7 @@ namespace Barotrauma.Items.Components
new Vector2(x + width / 2, y + height), new Vector2(x + width / 2, y + height),
null, panel, ""); null, panel, "");
if (draggingConnected == equippedWire) { Inventory.draggingItem = equippedWire.Item; } if (DraggingConnected == equippedWire) { Inventory.draggingItem = equippedWire.Item; }
} }
} }
@@ -167,7 +184,7 @@ namespace Barotrauma.Items.Components
x = (int)(x + width / 2 - step * (panel.DisconnectedWires.Count() - 1) / 2); x = (int)(x + width / 2 - step * (panel.DisconnectedWires.Count() - 1) / 2);
foreach (Wire wire in panel.DisconnectedWires) foreach (Wire wire in panel.DisconnectedWires)
{ {
if (wire == draggingConnected && mouseInRect) { continue; } if (wire == DraggingConnected && mouseInRect) { continue; }
Connection recipient = wire.OtherConnection(null); Connection recipient = wire.OtherConnection(null);
string label = recipient == null ? "" : recipient.item.Name + $" ({recipient.DisplayName})"; string label = recipient == null ? "" : recipient.item.Name + $" ({recipient.DisplayName})";
@@ -183,15 +200,34 @@ namespace Barotrauma.Items.Components
if (mouseInRect || GUI.MouseOn?.UserData is ConnectionPanel) { Inventory.draggingItem = null; } if (mouseInRect || GUI.MouseOn?.UserData is ConnectionPanel) { Inventory.draggingItem = null; }
} }
private void Draw(SpriteBatch spriteBatch, ConnectionPanel panel, Vector2 position, Vector2 labelPos, Vector2 wirePosition, bool mouseIn, Wire equippedWire, float wireInterval) private void DrawConnection(SpriteBatch spriteBatch, ConnectionPanel panel, Vector2 position, Vector2 labelPos, Vector2 scale)
{ {
GUI.DrawString(spriteBatch, labelPos, DisplayName, IsPower ? Color.Red : Color.White, Color.Black, 0, GUI.SmallFont); string text = DisplayName.ToUpper();
Vector2 textSize = GUI.SmallFont.MeasureString(text);
connectionSprite.Draw(spriteBatch, position); //nasty
var labelSprite = GUI.Style.GetComponentStyle("ConnectionPanelLabel")?.Sprites.Values.First().First();
if (labelSprite != null)
{
Rectangle labelArea = new Rectangle(labelPos.ToPoint(), textSize.ToPoint());
labelArea.Inflate(10 * scale.X, 3 * scale.Y);
labelSprite.Draw(spriteBatch, labelArea, IsPower ? GUI.Style.Red : Color.SteelBlue);
}
GUI.DrawString(spriteBatch, labelPos + Vector2.UnitY, text, Color.Black * 0.8f, font: GUI.SmallFont);
GUI.DrawString(spriteBatch, labelPos, text, GUI.Style.TextColorBright, font: GUI.SmallFont);
float connectorSpriteScale = (35.0f / connectionSprite.SourceRect.Width) * panel.Scale;
connectionSprite.Draw(spriteBatch, position, scale: connectorSpriteScale);
}
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;
for (int i = 0; i < MaxLinked; i++) for (int i = 0; i < MaxLinked; i++)
{ {
if (wires[i] == null || wires[i].Hidden || (draggingConnected == wires[i] && (mouseIn || Screen.Selected == GameMain.SubEditorScreen))) { continue; } if (wires[i] == null || wires[i].Hidden || (DraggingConnected == wires[i] && (mouseIn || Screen.Selected == GameMain.SubEditorScreen))) { continue; }
Connection recipient = wires[i].OtherConnection(this); Connection recipient = wires[i].OtherConnection(this);
string label = recipient == null ? "" : recipient.item.Name + $" ({recipient.DisplayName})"; string label = recipient == null ? "" : recipient.item.Name + $" ({recipient.DisplayName})";
@@ -201,9 +237,9 @@ namespace Barotrauma.Items.Components
wirePosition.Y += wireInterval; wirePosition.Y += wireInterval;
} }
if (draggingConnected != null && Vector2.Distance(position, PlayerInput.MousePosition) < (20.0f * GUI.Scale)) if (DraggingConnected != null && Vector2.Distance(position, PlayerInput.MousePosition) < (20.0f * GUI.Scale))
{ {
connectionSpriteHighlight.Draw(spriteBatch, position); connectionSpriteHighlight.Draw(spriteBatch, position, scale: connectorSpriteScale);
if (!PlayerInput.PrimaryMouseButtonHeld()) if (!PlayerInput.PrimaryMouseButtonHeld())
{ {
@@ -211,14 +247,14 @@ namespace Barotrauma.Items.Components
{ {
//find an empty cell for the new connection //find an empty cell for the new connection
int index = FindEmptyIndex(); int index = FindEmptyIndex();
if (index > -1 && !Wires.Contains(draggingConnected)) if (index > -1 && !Wires.Contains(DraggingConnected))
{ {
bool alreadyConnected = draggingConnected.IsConnectedTo(panel.Item); bool alreadyConnected = DraggingConnected.IsConnectedTo(panel.Item);
draggingConnected.RemoveConnection(panel.Item); DraggingConnected.RemoveConnection(panel.Item);
if (draggingConnected.Connect(this, !alreadyConnected, true)) if (DraggingConnected.Connect(this, !alreadyConnected, true))
{ {
var otherConnection = draggingConnected.OtherConnection(this); var otherConnection = DraggingConnected.OtherConnection(this);
SetWire(index, draggingConnected); SetWire(index, DraggingConnected);
} }
} }
} }
@@ -227,11 +263,11 @@ namespace Barotrauma.Items.Components
{ {
panel.Item.CreateClientEvent(panel); panel.Item.CreateClientEvent(panel);
} }
draggingConnected = null; DraggingConnected = null;
} }
} }
if (flashTimer > 0.0f) if (FlashTimer > 0.0f)
{ {
//the number of flashes depends on the duration, 1 flash per 1 full second //the number of flashes depends on the duration, 1 flash per 1 full second
int flashCycleCount = (int)Math.Max(flashDuration, 1); int flashCycleCount = (int)Math.Max(flashDuration, 1);
@@ -239,27 +275,28 @@ namespace Barotrauma.Items.Components
//MathHelper.Pi * 0.8f -> the curve goes from 144 deg to 0, //MathHelper.Pi * 0.8f -> the curve goes from 144 deg to 0,
//i.e. quickly bumps up from almost full brightness to full and then fades out //i.e. quickly bumps up from almost full brightness to full and then fades out
connectionSpriteHighlight.Draw(spriteBatch, position, flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f)); connectionSpriteHighlight.Draw(spriteBatch, position,
flashColor * (float)Math.Sin(FlashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f), scale: connectorSpriteScale);
} }
if (Wires.Any(w => w != null && w != draggingConnected)) if (Wires.Any(w => w != null && w != DraggingConnected))
{ {
int screwIndex = (int)Math.Floor(position.Y / 30.0f) % screwSprites.Count; int screwIndex = (int)Math.Floor(position.Y / 30.0f) % screwSprites.Count;
screwSprites[screwIndex].Draw(spriteBatch, position); screwSprites[screwIndex].Draw(spriteBatch, position, scale: connectorSpriteScale);
} }
} }
public void Flash(Color? color = null, float flashDuration = 1.5f) public void Flash(Color? color = null, float flashDuration = 1.5f)
{ {
flashTimer = flashDuration; FlashTimer = flashDuration;
this.flashDuration = flashDuration; this.flashDuration = flashDuration;
flashColor = (color == null) ? Color.Red : (Color)color; flashColor = (color == null) ? GUI.Style.Red : (Color)color;
} }
public void UpdateFlashTimer(float deltaTime) public void UpdateFlashTimer(float deltaTime)
{ {
if (flashTimer <= 0) return; if (FlashTimer <= 0) return;
flashTimer -= deltaTime; FlashTimer -= deltaTime;
} }
private static void DrawWire(SpriteBatch spriteBatch, Wire wire, Vector2 end, Vector2 start, Wire equippedWire, ConnectionPanel panel, string label) private static void DrawWire(SpriteBatch spriteBatch, Wire wire, Vector2 end, Vector2 start, Wire equippedWire, ConnectionPanel panel, string label)
@@ -287,41 +324,45 @@ namespace Barotrauma.Items.Components
if (start.Y > panel.GuiFrame.Rect.Bottom - 1.0f) if (start.Y > panel.GuiFrame.Rect.Bottom - 1.0f)
{ {
//wire at the bottom of the panel -> draw the text below the panel, tilted 45 degrees //wire at the bottom of the panel -> draw the text below the panel, tilted 45 degrees
GUI.SmallFont.DrawString(spriteBatch, label, start + Vector2.UnitY * 20 * GUI.Scale, Color.White, 45.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0.0f); GUI.Font.DrawString(spriteBatch, label, start + Vector2.UnitY * 20 * GUI.Scale, Color.White, 45.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0.0f);
} }
else else
{ {
GUI.DrawString(spriteBatch, GUI.DrawString(spriteBatch,
new Vector2(start.X < end.X ? textX - GUI.SmallFont.MeasureString(label).X : textX, start.Y - 5.0f), new Vector2(start.X < end.X ? textX - GUI.SmallFont.MeasureString(label).X : textX, start.Y - 5.0f),
label, label,
(mouseOn ? Color.Gold : Color.White) * (wire.Locked ? 0.6f : 1.0f), Color.Black * 0.8f, wire.Locked ? GUI.Style.TextColorDim : (mouseOn ? Wire.higlightColor : GUI.Style.TextColor), Color.Black * 0.9f,
3, GUI.SmallFont); 3, GUI.SmallFont);
} }
} }
var wireEnd = end + Vector2.Normalize(start - end) * 30.0f; var wireEnd = end + Vector2.Normalize(start - end) * 30.0f * panel.Scale;
float dist = Vector2.Distance(start, wireEnd); float dist = Vector2.Distance(start, wireEnd);
float wireWidth = 12 * panel.Scale;
float highlight = 5 * panel.Scale;
if (mouseOn) if (mouseOn)
{ {
spriteBatch.Draw(wireVertical.Texture, new Rectangle(wireEnd.ToPoint(), new Point(18, (int)dist)), wireVertical.SourceRect, spriteBatch.Draw(wireVertical.Texture, new Rectangle(wireEnd.ToPoint(), new Point((int)(wireWidth + highlight), (int)dist)), wireVertical.SourceRect,
Color.Gold, Wire.higlightColor,
MathUtils.VectorToAngle(end - start) + MathHelper.PiOver2, MathUtils.VectorToAngle(end - start) + MathHelper.PiOver2,
new Vector2(6, 0), // point in line about which to rotate new Vector2(wireVertical.size.X / 2, 0), // point in line about which to rotate
SpriteEffects.None, SpriteEffects.None,
0.0f); 0.0f);
} }
spriteBatch.Draw(wireVertical.Texture, new Rectangle(wireEnd.ToPoint(), new Point(12, (int)dist)), wireVertical.SourceRect, spriteBatch.Draw(wireVertical.Texture, new Rectangle(wireEnd.ToPoint(), new Point((int)wireWidth, (int)dist)), wireVertical.SourceRect,
wire.Item.Color * alpha, wire.Item.Color * alpha,
MathUtils.VectorToAngle(end - start) + MathHelper.PiOver2, MathUtils.VectorToAngle(end - start) + MathHelper.PiOver2,
new Vector2(6, 0), // point in line about which to rotate new Vector2(wireVertical.size.X / 2, 0), // point in line about which to rotate
SpriteEffects.None, SpriteEffects.None,
0.0f); 0.0f);
connector.Draw(spriteBatch, end, Color.White, new Vector2(10.0f, 10.0f), MathUtils.VectorToAngle(end - start) + MathHelper.PiOver2); float connectorScale = wireWidth / (float)wireVertical.SourceRect.Width;
if (draggingConnected == null && canDrag) connector.Draw(spriteBatch, end, Color.White, connector.Origin, MathUtils.VectorToAngle(end - start) + MathHelper.PiOver2, scale: connectorScale);
if (DraggingConnected == null && canDrag)
{ {
if (mouseOn) if (mouseOn)
{ {
@@ -331,7 +372,7 @@ namespace Barotrauma.Items.Components
if (allowRewiring && !wire.Locked && (!panel.Locked || Screen.Selected == GameMain.SubEditorScreen)) if (allowRewiring && !wire.Locked && (!panel.Locked || Screen.Selected == GameMain.SubEditorScreen))
{ {
//start dragging the wire //start dragging the wire
if (PlayerInput.PrimaryMouseButtonHeld()) { draggingConnected = wire; } if (PlayerInput.PrimaryMouseButtonHeld()) { DraggingConnected = wire; }
} }
} }
} }
@@ -19,6 +19,11 @@ namespace Barotrauma.Items.Components
private SoundChannel rewireSoundChannel; private SoundChannel rewireSoundChannel;
private float rewireSoundTimer; private float rewireSoundTimer;
public float Scale
{
get { return GuiFrame.Rect.Width / 400.0f; }
}
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
if (GuiFrame == null) { return; } if (GuiFrame == null) { return; }
@@ -107,7 +112,6 @@ namespace Barotrauma.Items.Components
} }
} }
public void ClientRead(ServerNetObject type, IReadMessage msg, float sendingTime) public void ClientRead(ServerNetObject type, IReadMessage msg, float sendingTime)
{ {
if (GameMain.Client.MidRoundSyncing) if (GameMain.Client.MidRoundSyncing)
@@ -19,7 +19,7 @@ namespace Barotrauma.Items.Components
var visibleElements = customInterfaceElementList.Where(ciElement => !string.IsNullOrEmpty(ciElement.Label)); var visibleElements = customInterfaceElementList.Where(ciElement => !string.IsNullOrEmpty(ciElement.Label));
uiElementContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), GuiFrame.RectTransform, Anchor.Center), uiElementContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.75f, 0.65f), GuiFrame.RectTransform, Anchor.Center) { RelativeOffset = new Vector2(0.0f, 0.025f) },
childAnchor: customInterfaceElementList.Count > 1 ? Anchor.TopCenter : Anchor.Center) childAnchor: customInterfaceElementList.Count > 1 ? Anchor.TopCenter : Anchor.Center)
{ {
RelativeSpacing = 0.05f, RelativeSpacing = 0.05f,
@@ -49,12 +49,15 @@ namespace Barotrauma.Items.Components
} }
return true; return true;
}; };
//reset size restrictions set by the Style to make sure the elements can fit the interface
tickBox.RectTransform.MinSize = new Point(0, 0);
tickBox.RectTransform.MaxSize = new Point(int.MaxValue, int.MaxValue);
uiElements.Add(tickBox); uiElements.Add(tickBox);
} }
else else
{ {
var btn = new GUIButton(new RectTransform(new Vector2(1.0f, elementSize), uiElementContainer.RectTransform), var btn = new GUIButton(new RectTransform(new Vector2(1.0f, elementSize), uiElementContainer.RectTransform),
TextManager.Get(ciElement.Label, returnNull: true) ?? ciElement.Label, style: "GUIButtonLarge") TextManager.Get(ciElement.Label, returnNull: true) ?? ciElement.Label, style: "DeviceButton")
{ {
UserData = ciElement UserData = ciElement
}; };
@@ -71,6 +74,12 @@ namespace Barotrauma.Items.Components
} }
return true; return true;
}; };
//reset size restrictions set by the Style to make sure the elements can fit the interface
btn.RectTransform.MinSize = btn.Frame.RectTransform.MinSize = new Point(0, 0);
btn.RectTransform.MaxSize = btn.Frame.RectTransform.MaxSize = new Point(int.MaxValue, int.MaxValue);
btn.TextBlock.Wrap = true;
uiElements.Add(btn); uiElements.Add(btn);
} }
} }
@@ -15,9 +15,14 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific(XElement element) partial void InitProjSpecific(XElement element)
{ {
GUILayoutGroup layoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(.9f, .8f), GuiFrame.RectTransform, anchor: Anchor.Center)); var layoutGroup = new GUILayoutGroup(new RectTransform(GuiFrame.Rect.Size - GUIStyle.ItemFrameMargin, GuiFrame.RectTransform, Anchor.Center) { AbsoluteOffset = GUIStyle.ItemFrameOffset })
{
ChildAnchor = Anchor.TopCenter,
RelativeSpacing = 0.02f,
Stretch = true
};
historyBox = new GUIListBox(new RectTransform(new Vector2(1, .9f), layoutGroup.RectTransform)) historyBox = new GUIListBox(new RectTransform(new Vector2(1, .9f), layoutGroup.RectTransform), style: null)
{ {
AutoHideScrollBar = false AutoHideScrollBar = false
}; };
@@ -29,6 +34,8 @@ namespace Barotrauma.Items.Components
CanBeFocused = false CanBeFocused = false
}; };
new GUIFrame(new RectTransform(new Vector2(0.9f, 0.01f), layoutGroup.RectTransform), style: "HorizontalLine");
inputBox = new GUITextBox(new RectTransform(new Vector2(1, .1f), layoutGroup.RectTransform), textColor: Color.LimeGreen) inputBox = new GUITextBox(new RectTransform(new Vector2(1, .1f), layoutGroup.RectTransform), textColor: Color.LimeGreen)
{ {
MaxTextLength = MaxMessageLength, MaxTextLength = MaxMessageLength,
@@ -11,6 +11,10 @@ namespace Barotrauma.Items.Components
{ {
partial class Wire : ItemComponent, IDrawableComponent, IServerSerializable, IClientSerializable partial class Wire : ItemComponent, IDrawableComponent, IServerSerializable, IClientSerializable
{ {
public static Color higlightColor = Color.LightGreen;
public static Color editorHighlightColor = Color.Yellow;
public static Color editorSelectedColor = Color.Red;
partial class WireSection partial class WireSection
{ {
public void Draw(SpriteBatch spriteBatch, Wire wire, Color color, Vector2 offset, float depth, float width = 0.3f) public void Draw(SpriteBatch spriteBatch, Wire wire, Color color, Vector2 offset, float depth, float width = 0.3f)
@@ -105,14 +109,14 @@ namespace Barotrauma.Items.Components
{ {
foreach (WireSection section in sections) foreach (WireSection section in sections)
{ {
section.Draw(spriteBatch, this, Color.Gold, drawOffset, depth + 0.00001f, 0.7f); section.Draw(spriteBatch, this, Screen.Selected == GameMain.GameScreen ? higlightColor : editorHighlightColor, drawOffset, depth + 0.00001f, 0.7f);
} }
} }
else if (item.IsSelected) else if (item.IsSelected)
{ {
foreach (WireSection section in sections) foreach (WireSection section in sections)
{ {
section.Draw(spriteBatch, this, Color.Red, drawOffset, depth + 0.00001f, 0.7f); section.Draw(spriteBatch, this, editorSelectedColor, drawOffset, depth + 0.00001f, 0.7f);
} }
} }
@@ -183,7 +187,7 @@ namespace Barotrauma.Items.Components
if ((highlightedNodeIndex == i && item.IsHighlighted) || (selectedNodeIndex == i && item.IsSelected)) if ((highlightedNodeIndex == i && item.IsHighlighted) || (selectedNodeIndex == i && item.IsSelected))
{ {
GUI.DrawRectangle(spriteBatch, drawPos + new Vector2(-10, -10), new Vector2(20, 20), Color.Red, false, 0.0f); GUI.DrawRectangle(spriteBatch, drawPos + new Vector2(-10, -10), new Vector2(20, 20), editorHighlightColor, false, 0.0f);
} }
if (item.IsSelected) if (item.IsSelected)
@@ -206,7 +210,7 @@ namespace Barotrauma.Items.Components
WireSection.Draw( WireSection.Draw(
spriteBatch, this, spriteBatch, this,
start, endPos, start, endPos,
Color.Orange, depth + 0.00001f, 0.2f); GUI.Style.Orange, depth + 0.00001f, 0.2f);
WireSection.Draw( WireSection.Draw(
spriteBatch, this, spriteBatch, this,
@@ -3,6 +3,7 @@ using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace Barotrauma.Items.Components namespace Barotrauma.Items.Components
{ {
@@ -47,13 +48,22 @@ namespace Barotrauma.Items.Components
private set; private set;
} }
private List<Character> visibleCharacters = new List<Character>(); private readonly List<Character> visibleCharacters = new List<Character>();
private const float UpdateInterval = 0.5f; private const float UpdateInterval = 0.5f;
private float updateTimer; private float updateTimer;
private Character equipper; private Character equipper;
public IEnumerable<Character> VisibleCharacters
{
get
{
if (equipper == null || equipper.Removed) { return Enumerable.Empty<Character>(); }
return visibleCharacters;
}
}
public override void Update(float deltaTime, Camera cam) public override void Update(float deltaTime, Camera cam)
{ {
base.Update(deltaTime, cam); base.Update(deltaTime, cam);
@@ -104,10 +114,10 @@ namespace Barotrauma.Items.Components
public override void DrawHUD(SpriteBatch spriteBatch, Character character) public override void DrawHUD(SpriteBatch spriteBatch, Character character)
{ {
if (character == null) return; if (character == null) { return; }
GUI.DrawRectangle(spriteBatch, new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.UIGlow.Draw(spriteBatch, new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight),
Color.Green * 0.1f, true); Color.LightGreen * 0.5f);
Character closestCharacter = null; Character closestCharacter = null;
float closestDist = float.PositiveInfinity; float closestDist = float.PositiveInfinity;
@@ -141,40 +151,40 @@ namespace Barotrauma.Items.Components
if (target.Info != null) if (target.Info != null)
{ {
texts.Add(target.Name); texts.Add(target.Name);
textColors.Add(Color.White); textColors.Add(GUI.Style.TextColor);
} }
if (target.IsDead) if (target.IsDead)
{ {
texts.Add(TextManager.Get("Deceased")); texts.Add(TextManager.Get("Deceased"));
textColors.Add(Color.Red); textColors.Add(GUI.Style.Red);
texts.Add( texts.Add(
target.CauseOfDeath.Affliction?.CauseOfDeathDescription ?? target.CauseOfDeath.Affliction?.CauseOfDeathDescription ??
TextManager.AddPunctuation(':', TextManager.Get("CauseOfDeath"), TextManager.Get("CauseOfDeath." + target.CauseOfDeath.Type.ToString()))); TextManager.AddPunctuation(':', TextManager.Get("CauseOfDeath"), TextManager.Get("CauseOfDeath." + target.CauseOfDeath.Type.ToString())));
textColors.Add(Color.Red); textColors.Add(GUI.Style.Red);
} }
else else
{ {
if (target.IsUnconscious) if (target.IsUnconscious)
{ {
texts.Add(TextManager.Get("Unconscious")); texts.Add(TextManager.Get("Unconscious"));
textColors.Add(Color.Orange); textColors.Add(GUI.Style.Orange);
} }
if (target.Stun > 0.01f) if (target.Stun > 0.01f)
{ {
texts.Add(TextManager.Get("Stunned")); texts.Add(TextManager.Get("Stunned"));
textColors.Add(Color.Orange); textColors.Add(GUI.Style.Orange);
} }
int oxygenTextIndex = MathHelper.Clamp((int)Math.Floor((1.0f - (target.Oxygen / 100.0f)) * OxygenTexts.Length), 0, OxygenTexts.Length - 1); int oxygenTextIndex = MathHelper.Clamp((int)Math.Floor((1.0f - (target.Oxygen / 100.0f)) * OxygenTexts.Length), 0, OxygenTexts.Length - 1);
texts.Add(OxygenTexts[oxygenTextIndex]); texts.Add(OxygenTexts[oxygenTextIndex]);
textColors.Add(Color.Lerp(Color.Red, Color.Green, target.Oxygen / 100.0f)); textColors.Add(Color.Lerp(GUI.Style.Red, GUI.Style.Green, target.Oxygen / 100.0f));
if (target.Bleeding > 0.0f) if (target.Bleeding > 0.0f)
{ {
int bleedingTextIndex = MathHelper.Clamp((int)Math.Floor(target.Bleeding / 100.0f) * BleedingTexts.Length, 0, BleedingTexts.Length - 1); int bleedingTextIndex = MathHelper.Clamp((int)Math.Floor(target.Bleeding / 100.0f) * BleedingTexts.Length, 0, BleedingTexts.Length - 1);
texts.Add(BleedingTexts[bleedingTextIndex]); texts.Add(BleedingTexts[bleedingTextIndex]);
textColors.Add(Color.Lerp(Color.Orange, Color.Red, target.Bleeding / 100.0f)); textColors.Add(Color.Lerp(GUI.Style.Orange, GUI.Style.Red, target.Bleeding / 100.0f));
} }
var allAfflictions = target.CharacterHealth.GetAllAfflictions(); var allAfflictions = target.CharacterHealth.GetAllAfflictions();
@@ -195,11 +205,11 @@ namespace Barotrauma.Items.Components
foreach (AfflictionPrefab affliction in combinedAfflictionStrengths.Keys) foreach (AfflictionPrefab affliction in combinedAfflictionStrengths.Keys)
{ {
texts.Add(TextManager.AddPunctuation(':', affliction.Name, ((int)combinedAfflictionStrengths[affliction]).ToString() + " %")); texts.Add(TextManager.AddPunctuation(':', affliction.Name, ((int)combinedAfflictionStrengths[affliction]).ToString() + " %"));
textColors.Add(Color.Lerp(Color.Orange, Color.Red, combinedAfflictionStrengths[affliction] / affliction.MaxStrength)); textColors.Add(Color.Lerp(GUI.Style.Orange, GUI.Style.Red, combinedAfflictionStrengths[affliction] / affliction.MaxStrength));
} }
} }
GUI.DrawString(spriteBatch, hudPos, texts[0], textColors[0] * alpha, Color.Black * 0.7f * alpha, 2); GUI.DrawString(spriteBatch, hudPos, texts[0], textColors[0] * alpha, Color.Black * 0.7f * alpha, 2, GUI.SubHeadingFont);
hudPos.X += 5.0f; hudPos.X += 5.0f;
hudPos.Y += 24.0f; hudPos.Y += 24.0f;
@@ -116,7 +116,7 @@ namespace Barotrauma.Items.Components
MinSize = new Point(100,20), MinSize = new Point(100,20),
RelativeOffset = new Vector2(0.0f, 0.01f) RelativeOffset = new Vector2(0.0f, 0.01f)
}, },
barSize: 0.0f); barSize: 0.0f, style: "DeviceProgressBar");
} }
public override void Move(Vector2 amount) public override void Move(Vector2 amount)
@@ -131,7 +131,7 @@ namespace Barotrauma.Items.Components
Vector2 particlePos = new Vector2(item.WorldRect.X + transformedBarrelPos.X, item.WorldRect.Y - transformedBarrelPos.Y); Vector2 particlePos = new Vector2(item.WorldRect.X + transformedBarrelPos.X, item.WorldRect.Y - transformedBarrelPos.Y);
foreach (ParticleEmitter emitter in particleEmitters) foreach (ParticleEmitter emitter in particleEmitters)
{ {
emitter.Emit(1.0f, particlePos, hullGuess: null, angle: rotation, particleRotation: rotation); emitter.Emit(1.0f, particlePos, hullGuess: null, angle: -rotation, particleRotation: rotation);
} }
} }
@@ -260,12 +260,12 @@ namespace Barotrauma.Items.Components
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
drawPos, drawPos,
drawPos + new Vector2((float)Math.Cos(minRotation), (float)Math.Sin(minRotation)) * widgetRadius, drawPos + new Vector2((float)Math.Cos(minRotation), (float)Math.Sin(minRotation)) * widgetRadius,
Color.Green); GUI.Style.Green);
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
drawPos, drawPos,
drawPos + new Vector2((float)Math.Cos(maxRotation), (float)Math.Sin(maxRotation)) * widgetRadius, drawPos + new Vector2((float)Math.Cos(maxRotation), (float)Math.Sin(maxRotation)) * widgetRadius,
Color.Green); GUI.Style.Green);
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
drawPos, drawPos,
@@ -278,7 +278,7 @@ namespace Barotrauma.Items.Components
{ {
widget.MouseDown += () => widget.MouseDown += () =>
{ {
widget.color = Color.Green; widget.color = GUI.Style.Green;
prevAngle = minRotation; prevAngle = minRotation;
}; };
widget.Deselected += () => widget.Deselected += () =>
@@ -319,7 +319,7 @@ namespace Barotrauma.Items.Components
{ {
widget.MouseDown += () => widget.MouseDown += () =>
{ {
widget.color = Color.Green; widget.color = GUI.Style.Green;
prevAngle = minRotation; prevAngle = minRotation;
}; };
widget.Deselected += () => widget.Deselected += () =>
@@ -431,7 +431,7 @@ namespace Barotrauma.Items.Components
bool readyToFire = reload <= 0.0f && charged && availableAmmo.Any(p => p != null); bool readyToFire = reload <= 0.0f && charged && availableAmmo.Any(p => p != null);
if (ShowChargeIndicator && PowerConsumption > 0.0f) if (ShowChargeIndicator && PowerConsumption > 0.0f)
{ {
powerIndicator.Color = charged ? Color.Green : Color.Red; powerIndicator.Color = charged ? GUI.Style.Green : GUI.Style.Red;
if (flashLowPower) if (flashLowPower)
{ {
powerIndicator.BarSize = 1; powerIndicator.BarSize = 1;
@@ -452,7 +452,7 @@ namespace Barotrauma.Items.Components
if (ShowProjectileIndicator) if (ShowProjectileIndicator)
{ {
Point slotSize = new Point((int)(60 * GUI.Scale), (int)(30 * GUI.Scale)); Point slotSize = (Inventory.SlotSpriteSmall.size * Inventory.UIScale).ToPoint();
int spacing = 5; int spacing = 5;
int slotsPerRow = Math.Min(availableAmmo.Count, 6); int slotsPerRow = Math.Min(availableAmmo.Count, 6);
int totalWidth = slotSize.X * slotsPerRow + spacing * (slotsPerRow - 1); int totalWidth = slotSize.X * slotsPerRow + spacing * (slotsPerRow - 1);
@@ -469,7 +469,7 @@ namespace Barotrauma.Items.Components
Rectangle rect = new Rectangle(invSlotPos.X, invSlotPos.Y, totalWidth, slotSize.Y); Rectangle rect = new Rectangle(invSlotPos.X, invSlotPos.Y, totalWidth, slotSize.Y);
float inflate = MathHelper.Lerp(3, 8, (float)Math.Abs(1 * Math.Sin(flashTimer * 5))); float inflate = MathHelper.Lerp(3, 8, (float)Math.Abs(1 * Math.Sin(flashTimer * 5)));
rect.Inflate(inflate, inflate); rect.Inflate(inflate, inflate);
Color color = Color.Red * MathHelper.Max(0.5f, (float)Math.Sin(flashTimer * 12)); Color color = GUI.Style.Red * MathHelper.Max(0.5f, (float)Math.Sin(flashTimer * 12));
GUI.DrawRectangle(spriteBatch, rect, color, thickness: 3); GUI.DrawRectangle(spriteBatch, rect, color, thickness: 3);
} }
} }
@@ -131,7 +131,8 @@ namespace Barotrauma
protected float prevHUDScale = GUI.Scale; protected float prevHUDScale = GUI.Scale;
protected Point prevScreenResolution; protected Point prevScreenResolution;
protected static Sprite slotSpriteSmall, slotSpriteHorizontal, slotSpriteVertical, slotSpriteRound; protected static Sprite slotSpriteHorizontal, slotSpriteVertical, slotSpriteRound, slotHotkeySprite;
public static Sprite SlotSpriteSmall;
public static Sprite EquipIndicator, EquipIndicatorHighlight; public static Sprite EquipIndicator, EquipIndicatorHighlight;
public static Sprite DropIndicator, DropIndicatorHighlight; public static Sprite DropIndicator, DropIndicatorHighlight;
public static Inventory DraggingInventory; public static Inventory DraggingInventory;
@@ -293,8 +294,7 @@ namespace Barotrauma
Vector2 spacing = new Vector2(10 * UIScale, (10 + EquipIndicator.size.Y) * UIScale); Vector2 spacing = new Vector2(10 * UIScale, (10 + EquipIndicator.size.Y) * UIScale);
Vector2 rectSize = new Vector2(60.0f * UIScale); Vector2 rectSize = new Vector2(60.0f * UIScale);
//y is larger to give more space for the header padding = new Vector4(spacing.X, spacing.Y, spacing.X, spacing.X);
padding = new Vector4(spacing.X, 40 * UIScale, spacing.X, spacing.X);
Vector2 slotAreaSize = new Vector2( Vector2 slotAreaSize = new Vector2(
columns * rectSize.X + (columns - 1) * spacing.X, columns * rectSize.X + (columns - 1) * spacing.X,
@@ -546,9 +546,6 @@ namespace Barotrauma
else else
{ {
Rectangle subRect = slot.Rect; Rectangle subRect = slot.Rect;
subRect.Width = slots[slotIndex].SlotSprite == null ? (int)(60 * UIScale) : (int)(slots[slotIndex].SlotSprite.size.X * UIScale);
subRect.Height = (int)(60 * UIScale);
Vector2 spacing = new Vector2(10 * UIScale, (10 + EquipIndicator.size.Y) * UIScale); Vector2 spacing = new Vector2(10 * UIScale, (10 + EquipIndicator.size.Y) * UIScale);
int columns = (int)Math.Max(Math.Floor(Math.Sqrt(itemCapacity)), 1); int columns = (int)Math.Max(Math.Floor(Math.Sqrt(itemCapacity)), 1);
@@ -615,7 +612,7 @@ namespace Barotrauma
if (canMove) if (canMove)
{ {
subInventory.movableFrameRect.X = subRect.X - (int)spacing.X; subInventory.movableFrameRect.X = subRect.X - (int)spacing.X;
subInventory.movableFrameRect.Y = subRect.Y + (int)(spacing.Y / 2f); subInventory.movableFrameRect.Y = subRect.Y + (int)(spacing.Y);
} }
slots[slotIndex].State = GUIComponent.ComponentState.Hover; slots[slotIndex].State = GUIComponent.ComponentState.Hover;
} }
@@ -933,7 +930,7 @@ namespace Barotrauma
selectedInventory.slots[slotIndex].ShowBorderHighlight(Color.White, 0.1f, 0.4f); selectedInventory.slots[slotIndex].ShowBorderHighlight(Color.White, 0.1f, 0.4f);
} }
} }
selectedInventory.slots[slotIndex].ShowBorderHighlight(Color.Red, 0.1f, 0.9f); selectedInventory.slots[slotIndex].ShowBorderHighlight(GUI.Style.Red, 0.1f, 0.9f);
} }
GUI.PlayUISound(GUISoundType.PickItem); GUI.PlayUISound(GUISoundType.PickItem);
} }
@@ -944,7 +941,7 @@ namespace Barotrauma
} }
else else
{ {
if (selectedInventory.slots != null){ selectedInventory.slots[slotIndex].ShowBorderHighlight(Color.Red, 0.1f, 0.9f); } if (selectedInventory.slots != null){ selectedInventory.slots[slotIndex].ShowBorderHighlight(GUI.Style.Red, 0.1f, 0.9f); }
GUI.PlayUISound(GUISoundType.PickItemFail); GUI.PlayUISound(GUISoundType.PickItemFail);
} }
selectedInventory.HideTimer = 2.0f; selectedInventory.HideTimer = 2.0f;
@@ -1056,7 +1053,7 @@ namespace Barotrauma
new Rectangle(itemPos.ToPoint() - new Point(iconSize / 2) - shadowBorders, new Point(iconSize + textWidth + textSpacing, iconSize) + shadowBorders.Multiply(2)), Color.Black * 0.8f); new Rectangle(itemPos.ToPoint() - new Point(iconSize / 2) - shadowBorders, new Point(iconSize + textWidth + textSpacing, iconSize) + shadowBorders.Multiply(2)), Color.Black * 0.8f);
GUI.DrawString(spriteBatch, new Vector2(itemPos.X + iconSize / 2 + textSpacing, itemPos.Y - iconSize / 2), draggingItem.Name, Color.White); GUI.DrawString(spriteBatch, new Vector2(itemPos.X + iconSize / 2 + textSpacing, itemPos.Y - iconSize / 2), draggingItem.Name, Color.White);
GUI.DrawString(spriteBatch, new Vector2(itemPos.X + iconSize / 2 + textSpacing, itemPos.Y), toolTip, GUI.DrawString(spriteBatch, new Vector2(itemPos.X + iconSize / 2 + textSpacing, itemPos.Y), toolTip,
color: Character.Controlled.FocusedItem == null && !mouseOnHealthInterface ? Color.Red : Color.LightGreen, color: Character.Controlled.FocusedItem == null && !mouseOnHealthInterface ? GUI.Style.Red : Color.LightGreen,
font: GUI.SmallFont); font: GUI.SmallFont);
} }
sprite.Draw(spriteBatch, itemPos + Vector2.One * 2, Color.Black, scale: scale); sprite.Draw(spriteBatch, itemPos + Vector2.One * 2, Color.Black, scale: scale);
@@ -1075,7 +1072,7 @@ namespace Barotrauma
} }
} }
public static void DrawSlot(SpriteBatch spriteBatch, Inventory inventory, InventorySlot slot, Item item, int slotIndex, bool drawItem = true) public static void DrawSlot(SpriteBatch spriteBatch, Inventory inventory, InventorySlot slot, Item item, int slotIndex, bool drawItem = true, InvSlotType type = InvSlotType.Any)
{ {
Rectangle rect = slot.Rect; Rectangle rect = slot.Rect;
rect.Location += slot.DrawOffset.ToPoint(); rect.Location += slot.DrawOffset.ToPoint();
@@ -1086,6 +1083,7 @@ namespace Barotrauma
rect.Inflate(rect.Width * inflateAmount, rect.Height * inflateAmount); rect.Inflate(rect.Width * inflateAmount, rect.Height * inflateAmount);
} }
Color slotColor = Color.White;
var itemContainer = item?.GetComponent<ItemContainer>(); var itemContainer = item?.GetComponent<ItemContainer>();
if (itemContainer != null && (itemContainer.InventoryTopSprite != null || itemContainer.InventoryBottomSprite != null)) if (itemContainer != null && (itemContainer.InventoryTopSprite != null || itemContainer.InventoryBottomSprite != null))
{ {
@@ -1099,8 +1097,18 @@ namespace Barotrauma
} }
else else
{ {
Sprite slotSprite = slot.SlotSprite ?? slotSpriteSmall; Sprite slotSprite = slot.SlotSprite ?? SlotSpriteSmall;
Color slotColor = slot.IsHighlighted ? Color.White : Color.White * 0.8f;
if (inventory != null && (CharacterInventory.PersonalSlots.HasFlag(type) || (inventory.isSubInventory && (inventory.Owner as Item) != null
&& (inventory.Owner as Item).AllowedSlots.Any(a => CharacterInventory.PersonalSlots.HasFlag(a)))))
{
slotColor = slot.IsHighlighted ? GUIColorSettings.EquipmentSlotColor : GUIColorSettings.EquipmentSlotColor * 0.8f;
}
else
{
slotColor = slot.IsHighlighted ? GUIColorSettings.InventorySlotColor : GUIColorSettings.InventorySlotColor * 0.8f;
}
if (inventory != null && inventory.Locked) { slotColor = Color.Gray * 0.5f; } if (inventory != null && inventory.Locked) { slotColor = Color.Gray * 0.5f; }
spriteBatch.Draw(slotSprite.Texture, rect, slotSprite.SourceRect, slotColor); spriteBatch.Draw(slotSprite.Texture, rect, slotSprite.SourceRect, slotColor);
@@ -1125,7 +1133,7 @@ namespace Barotrauma
} }
if (slot.MouseOn() && canBePut) if (slot.MouseOn() && canBePut)
{ {
GUI.UIGlow.Draw(spriteBatch, rect, Color.LightGreen); GUI.UIGlow.Draw(spriteBatch, rect, GUI.Style.Green);
} }
if (item != null && drawItem) if (item != null && drawItem)
@@ -1135,7 +1143,7 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, new Rectangle(rect.X, rect.Bottom - 8, rect.Width, 8), Color.Black * 0.8f, true); GUI.DrawRectangle(spriteBatch, new Rectangle(rect.X, rect.Bottom - 8, rect.Width, 8), Color.Black * 0.8f, true);
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
new Rectangle(rect.X, rect.Bottom - 8, (int)(rect.Width * (item.Condition / item.MaxCondition)), 8), new Rectangle(rect.X, rect.Bottom - 8, (int)(rect.Width * (item.Condition / item.MaxCondition)), 8),
Color.Lerp(Color.Red, Color.Green, item.Condition / item.MaxCondition) * 0.8f, true); Color.Lerp(GUI.Style.Red, GUI.Style.Green, item.Condition / item.MaxCondition) * 0.8f, true);
} }
if (itemContainer != null && itemContainer.ShowContainedStateIndicator) if (itemContainer != null && itemContainer.ShowContainedStateIndicator)
@@ -1163,7 +1171,7 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, containedIndicatorArea, Color.DarkGray * 0.9f, true); GUI.DrawRectangle(spriteBatch, containedIndicatorArea, Color.DarkGray * 0.9f, true);
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
new Rectangle(containedIndicatorArea.X, containedIndicatorArea.Y, (int)(containedIndicatorArea.Width * containedState), containedIndicatorArea.Height), new Rectangle(containedIndicatorArea.X, containedIndicatorArea.Y, (int)(containedIndicatorArea.Width * containedState), containedIndicatorArea.Height),
Color.Lerp(Color.Red, Color.Green, containedState) * 0.8f, true); Color.Lerp(GUI.Style.Red, GUI.Style.Green, containedState) * 0.8f, true);
} }
else else
{ {
@@ -1172,7 +1180,7 @@ namespace Barotrauma
containedIndicatorArea.Width / (float)indicatorSprite.SourceRect.Width, containedIndicatorArea.Width / (float)indicatorSprite.SourceRect.Width,
containedIndicatorArea.Height / (float)indicatorSprite.SourceRect.Height); containedIndicatorArea.Height / (float)indicatorSprite.SourceRect.Height);
if (containedState >= 0.0f && containedState < 0.25f) if (containedState >= 0.0f && containedState < 0.25f && inventory == Character.Controlled?.Inventory && Character.Controlled.HasEquippedItem(item))
{ {
indicatorScale += ((float)Math.Sin(Timing.TotalTime * 5.0f) + 1.0f) * 0.25f; indicatorScale += ((float)Math.Sin(Timing.TotalTime * 5.0f) + 1.0f) * 0.25f;
} }
@@ -1183,7 +1191,7 @@ namespace Barotrauma
rotate: 0.0f, rotate: 0.0f,
scale: indicatorScale); scale: indicatorScale);
Color indicatorColor = ToolBox.GradientLerp(containedState, Color.Red, Color.Orange, Color.Green); Color indicatorColor = ToolBox.GradientLerp(containedState, GUI.Style.Red, GUI.Style.Orange, GUI.Style.Green);
if (inventory != null && inventory.Locked) { indicatorColor *= 0.5f; } if (inventory != null && inventory.Locked) { indicatorColor *= 0.5f; }
spriteBatch.Draw(indicatorSprite.Texture, containedIndicatorArea.Center.ToVector2(), spriteBatch.Draw(indicatorSprite.Texture, containedIndicatorArea.Center.ToVector2(),
@@ -1212,7 +1220,7 @@ namespace Barotrauma
if (item != null && drawItem) if (item != null && drawItem)
{ {
Sprite sprite = item.Prefab.InventoryIcon ?? item.Sprite; Sprite sprite = item.Prefab.InventoryIcon ?? item.Sprite;
float scale = Math.Min(Math.Min((rect.Width - 10) / sprite.size.X, (rect.Height - 10) / sprite.size.Y), 3.0f); float scale = Math.Min(Math.Min((rect.Width - 10) / sprite.size.X, (rect.Height - 10) / sprite.size.Y), 2.0f);
Vector2 itemPos = rect.Center.ToVector2(); Vector2 itemPos = rect.Center.ToVector2();
if (itemPos.Y > GameMain.GraphicsHeight) if (itemPos.Y > GameMain.GraphicsHeight)
{ {
@@ -1245,15 +1253,14 @@ namespace Barotrauma
Character.Controlled?.Inventory == inventory && Character.Controlled?.Inventory == inventory &&
slot.QuickUseKey != Keys.None) slot.QuickUseKey != Keys.None)
{ {
GUI.DrawString(spriteBatch, rect.Location.ToVector2(), spriteBatch.Draw(slotHotkeySprite.Texture, rect.ScaleSize(1.25f), slotHotkeySprite.SourceRect, slotColor);
slot.QuickUseKey.ToString().Substring(1, 1), GUI.DrawString(spriteBatch, rect.Location.ToVector2() + new Vector2(1, -2), slot.QuickUseKey.ToString().Substring(1, 1), Color.Black, font: GUI.SmallFont);
item == null || !drawItem ? Color.Gray : Color.White,
Color.Black * 0.8f);
} }
} }
public void ClientRead(ServerNetObject type, IReadMessage msg, float sendingTime) public void ClientRead(ServerNetObject type, IReadMessage msg, float sendingTime)
{ {
UInt16 lastEventID = msg.ReadUInt16();
byte itemCount = msg.ReadByte(); byte itemCount = msg.ReadByte();
receivedItemIDs = new ushort[itemCount]; receivedItemIDs = new ushort[itemCount];
for (int i = 0; i < itemCount; i++) for (int i = 0; i < itemCount; i++)
@@ -1268,7 +1275,7 @@ namespace Barotrauma
if (syncItemsDelay > 0.0f || GameMain.Client.MidRoundSyncing) if (syncItemsDelay > 0.0f || GameMain.Client.MidRoundSyncing)
{ {
if (syncItemsCoroutine != null) CoroutineManager.StopCoroutines(syncItemsCoroutine); if (syncItemsCoroutine != null) CoroutineManager.StopCoroutines(syncItemsCoroutine);
syncItemsCoroutine = CoroutineManager.StartCoroutine(SyncItemsAfterDelay()); syncItemsCoroutine = CoroutineManager.StartCoroutine(SyncItemsAfterDelay(lastEventID));
} }
else else
{ {
@@ -1281,9 +1288,13 @@ namespace Barotrauma
} }
} }
private IEnumerable<object> SyncItemsAfterDelay() private IEnumerable<object> SyncItemsAfterDelay(UInt16 lastEventID)
{ {
while (syncItemsDelay > 0.0f || (GameMain.Client != null && GameMain.Client.MidRoundSyncing)) while (syncItemsDelay > 0.0f ||
//don't apply inventory updates until
// 1. MidRound syncing is done AND
// 2. We've received all the events created before the update was written (otherwise we may not yet know about some items the server has spawned in the inventory)
(GameMain.Client != null && (GameMain.Client.MidRoundSyncing || NetIdUtils.IdMoreRecent(lastEventID, GameMain.Client.EntityEventManager.LastReceivedID))))
{ {
syncItemsDelay = Math.Max((float)(syncItemsDelay - Timing.Step), 0.0f); syncItemsDelay = Math.Max((float)(syncItemsDelay - Timing.Step), 0.0f);
yield return CoroutineStatus.Running; yield return CoroutineStatus.Running;
@@ -52,7 +52,7 @@ namespace Barotrauma
if (itemInUseWarning == null) if (itemInUseWarning == null)
{ {
itemInUseWarning = new GUITextBlock(new RectTransform(new Point(10), GUI.Canvas), "", itemInUseWarning = new GUITextBlock(new RectTransform(new Point(10), GUI.Canvas), "",
textColor: Color.Orange, color: Color.Black, textColor: GUI.Style.Orange, color: Color.Black,
textAlignment: Alignment.Center, style: "OuterGlow"); textAlignment: Alignment.Center, style: "OuterGlow");
} }
return itemInUseWarning; return itemInUseWarning;
@@ -195,7 +195,7 @@ namespace Barotrauma
if (!Visible || (!editing && HiddenInGame)) return; if (!Visible || (!editing && HiddenInGame)) return;
if (editing && !ShowItems) return; if (editing && !ShowItems) return;
Color color = IsHighlighted && !GUI.DisableItemHighlights && Screen.Selected != GameMain.GameScreen ? Color.Orange : GetSpriteColor(); Color color = IsHighlighted && !GUI.DisableItemHighlights && Screen.Selected != GameMain.GameScreen ? GUI.Style.Orange : GetSpriteColor();
//if (IsSelected && editing) color = Color.Lerp(color, Color.Gold, 0.5f); //if (IsSelected && editing) color = Color.Lerp(color, Color.Gold, 0.5f);
BrokenItemSprite fadeInBrokenSprite = null; BrokenItemSprite fadeInBrokenSprite = null;
@@ -364,7 +364,7 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
rectWorldPos, rectWorldPos,
new Vector2(transformedTrigger.Width, transformedTrigger.Height), new Vector2(transformedTrigger.Width, transformedTrigger.Height),
Color.Green, GUI.Style.Green,
false, false,
0, 0,
(int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f)); (int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f));
@@ -376,7 +376,7 @@ namespace Barotrauma
foreach (MapEntity e in linkedTo) foreach (MapEntity e in linkedTo)
{ {
bool isLinkAllowed = prefab.IsLinkAllowed(e.prefab); bool isLinkAllowed = prefab.IsLinkAllowed(e.prefab);
Color lineColor = Color.Red * 0.5f; Color lineColor = GUI.Style.Red * 0.5f;
if (isLinkAllowed) if (isLinkAllowed)
{ {
lineColor = e is Item i && (DisplaySideBySideWhenLinked || i.DisplaySideBySideWhenLinked) ? Color.Purple * 0.5f : Color.LightGreen * 0.5f; lineColor = e is Item i && (DisplaySideBySideWhenLinked || i.DisplaySideBySideWhenLinked) ? Color.Purple * 0.5f : Color.LightGreen * 0.5f;
@@ -525,32 +525,19 @@ namespace Barotrauma
{ {
var linkText = new GUITextBlock(new RectTransform(new Point(editingHUD.Rect.Width, heightScaled)), TextManager.Get("HoldToLink"), font: GUI.SmallFont); var linkText = new GUITextBlock(new RectTransform(new Point(editingHUD.Rect.Width, heightScaled)), TextManager.Get("HoldToLink"), font: GUI.SmallFont);
var itemsText = new GUITextBlock(new RectTransform(new Point(editingHUD.Rect.Width, heightScaled)), TextManager.Get("AllowedLinks"), font: GUI.SmallFont); var itemsText = new GUITextBlock(new RectTransform(new Point(editingHUD.Rect.Width, heightScaled)), TextManager.Get("AllowedLinks"), font: GUI.SmallFont);
if (AllowedLinks.None()) string allowedItems = AllowedLinks.None() ? TextManager.Get("None") :string.Join(", ", AllowedLinks);
{ itemsText.Text = TextManager.AddPunctuation(':', itemsText.Text, allowedItems);
itemsText.Text += TextManager.Get("None");
}
else
{
for (int i = 0; i < AllowedLinks.Count; i++)
{
itemsText.Text += AllowedLinks[i];
if (i < AllowedLinks.Count - 1)
{
itemsText.Text += ", ";
}
}
}
itemEditor.AddCustomContent(linkText, 1); itemEditor.AddCustomContent(linkText, 1);
itemEditor.AddCustomContent(itemsText, 2); itemEditor.AddCustomContent(itemsText, 2);
linkText.TextColor = Color.Yellow; linkText.TextColor = GUI.Style.Orange;
itemsText.TextColor = Color.Yellow; itemsText.TextColor = GUI.Style.Orange;
} }
var buttonContainer = new GUILayoutGroup(new RectTransform(new Point(listBox.Content.Rect.Width, heightScaled)), isHorizontal: true) var buttonContainer = new GUILayoutGroup(new RectTransform(new Point(listBox.Content.Rect.Width, heightScaled)), isHorizontal: true)
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.02f RelativeSpacing = 0.02f
}; };
new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityX")) new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityX"), style: "GUIButtonSmall")
{ {
ToolTip = TextManager.Get("MirrorEntityXToolTip"), ToolTip = TextManager.Get("MirrorEntityXToolTip"),
OnClicked = (button, data) => OnClicked = (button, data) =>
@@ -559,7 +546,7 @@ namespace Barotrauma
return true; return true;
} }
}; };
new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityY")) new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityY"), style: "GUIButtonSmall")
{ {
ToolTip = TextManager.Get("MirrorEntityYToolTip"), ToolTip = TextManager.Get("MirrorEntityYToolTip"),
OnClicked = (button, data) => OnClicked = (button, data) =>
@@ -570,7 +557,7 @@ namespace Barotrauma
}; };
if (Sprite != null) if (Sprite != null)
{ {
var reloadTextureButton = new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ReloadSprite")); var reloadTextureButton = new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ReloadSprite"), style: "GUIButtonSmall");
reloadTextureButton.OnClicked += (button, data) => reloadTextureButton.OnClicked += (button, data) =>
{ {
Sprite.ReloadXML(); Sprite.ReloadXML();
@@ -578,7 +565,7 @@ namespace Barotrauma
return true; return true;
}; };
} }
new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ResetToPrefab")) new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ResetToPrefab"), style: "GUIButtonSmall")
{ {
OnClicked = (button, data) => OnClicked = (button, data) =>
{ {
@@ -587,6 +574,7 @@ namespace Barotrauma
return true; return true;
} }
}; };
buttonContainer.RectTransform.MinSize = new Point(0, buttonContainer.RectTransform.Children.Max(c => c.MinSize.Y));
itemEditor.AddCustomContent(buttonContainer, itemEditor.ContentCount); itemEditor.AddCustomContent(buttonContainer, itemEditor.ContentCount);
GUITextBlock.AutoScaleAndNormalize(buttonContainer.Children.Select(b => ((GUIButton)b).TextBlock)); GUITextBlock.AutoScaleAndNormalize(buttonContainer.Children.Select(b => ((GUIButton)b).TextBlock));
} }
@@ -595,15 +583,17 @@ namespace Barotrauma
{ {
if (inGame) if (inGame)
{ {
if (!ic.AllowInGameEditing) continue; if (!ic.AllowInGameEditing) { continue; }
if (SerializableProperty.GetProperties<InGameEditable>(ic).Count == 0) continue; if (SerializableProperty.GetProperties<InGameEditable>(ic).Count == 0) { continue; }
} }
else else
{ {
if (ic.requiredItems.Count == 0 && ic.DisabledRequiredItems.Count == 0 && SerializableProperty.GetProperties<Editable>(ic).Count == 0) continue; if (ic.requiredItems.Count == 0 && ic.DisabledRequiredItems.Count == 0 && SerializableProperty.GetProperties<Editable>(ic).Count == 0) { continue; }
} }
var componentEditor = new SerializableEntityEditor(listBox.Content.RectTransform, ic, inGame, showName: !inGame); new GUIFrame(new RectTransform(new Vector2(1.0f, 0.02f), listBox.Content.RectTransform), style: "HorizontalLine");
var componentEditor = new SerializableEntityEditor(listBox.Content.RectTransform, ic, inGame, showName: !inGame, titleFont: GUI.SubHeadingFont);
componentEditor.Children.First().Color = Color.Black * 0.7f; componentEditor.Children.First().Color = Color.Black * 0.7f;
if (inGame) if (inGame)
@@ -625,7 +615,7 @@ namespace Barotrauma
foreach (RelatedItem relatedItem in requiredItems) foreach (RelatedItem relatedItem in requiredItems)
{ {
var textBlock = new GUITextBlock(new RectTransform(new Point(editingHUD.Rect.Width, heightScaled)), var textBlock = new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, heightScaled)),
relatedItem.Type.ToString() + " required", font: GUI.SmallFont) relatedItem.Type.ToString() + " required", font: GUI.SmallFont)
{ {
Padding = new Vector4(10.0f, 0.0f, 10.0f, 0.0f) Padding = new Vector4(10.0f, 0.0f, 10.0f, 0.0f)
@@ -637,6 +627,7 @@ namespace Barotrauma
Font = GUI.SmallFont, Font = GUI.SmallFont,
Text = relatedItem.JoinedIdentifiers Text = relatedItem.JoinedIdentifiers
}; };
textBlock.RectTransform.Resize(new Point(textBlock.Rect.Width, namesBox.RectTransform.MinSize.Y));
namesBox.OnDeselected += (textBox, key) => namesBox.OnDeselected += (textBox, key) =>
{ {
@@ -713,17 +704,17 @@ namespace Barotrauma
if (GameMain.GameSession?.CrewManager != null && Screen.Selected == GameMain.GameScreen) if (GameMain.GameSession?.CrewManager != null && Screen.Selected == GameMain.GameScreen)
{ {
int disallowedPadding = (int)(50 * GUI.Scale); int disallowedPadding = (int)(50 * GUI.Scale);
disallowedAreas.Add(GameMain.GameSession.CrewManager.GetCharacterListArea()); disallowedAreas.Add(GameMain.GameSession.CrewManager.GetActiveCrewArea());
disallowedAreas.Add(new Rectangle( disallowedAreas.Add(new Rectangle(
HUDLayoutSettings.ChatBoxArea.X - disallowedPadding, HUDLayoutSettings.ChatBoxArea.Y, HUDLayoutSettings.ChatBoxArea.X - disallowedPadding, HUDLayoutSettings.ChatBoxArea.Y,
HUDLayoutSettings.ChatBoxArea.Width + disallowedPadding, HUDLayoutSettings.ChatBoxArea.Height)); HUDLayoutSettings.ChatBoxArea.Width + disallowedPadding, HUDLayoutSettings.ChatBoxArea.Height));
} }
GUI.PreventElementOverlap(elementsToMove, disallowedAreas, //GUI.PreventElementOverlap(elementsToMove, disallowedAreas,
new Rectangle( // new Rectangle(
20, 20, // 0, 20,
GameMain.GraphicsWidth - 40, // GameMain.GraphicsWidth,
HUDLayoutSettings.InventoryTopY > 0 ? HUDLayoutSettings.InventoryTopY - 40 : GameMain.GraphicsHeight - 80)); // HUDLayoutSettings.InventoryTopY > 0 ? HUDLayoutSettings.InventoryTopY - 40 : GameMain.GraphicsHeight - 80));
foreach (ItemComponent ic in activeHUDs) foreach (ItemComponent ic in activeHUDs)
{ {
@@ -1125,10 +1116,10 @@ namespace Barotrauma
catch (Exception e) catch (Exception e)
{ {
DebugConsole.ThrowError("Exception in PhysicsBody.Enabled = false (" + body.PhysEnabled + ")", e); DebugConsole.ThrowError("Exception in PhysicsBody.Enabled = false (" + body.PhysEnabled + ")", e);
if (body.UserData != null) DebugConsole.NewMessage("PhysicsBody UserData: " + body.UserData.GetType().ToString(), Color.Red); if (body.UserData != null) DebugConsole.NewMessage("PhysicsBody UserData: " + body.UserData.GetType().ToString(), GUI.Style.Red);
if (GameMain.World.ContactManager == null) DebugConsole.NewMessage("ContactManager is null!", Color.Red); if (GameMain.World.ContactManager == null) DebugConsole.NewMessage("ContactManager is null!", GUI.Style.Red);
else if (GameMain.World.ContactManager.BroadPhase == null) DebugConsole.NewMessage("Broadphase is null!", Color.Red); else if (GameMain.World.ContactManager.BroadPhase == null) DebugConsole.NewMessage("Broadphase is null!", GUI.Style.Red);
if (body.FarseerBody.FixtureList == null) DebugConsole.NewMessage("FixtureList is null!", Color.Red); if (body.FarseerBody.FixtureList == null) DebugConsole.NewMessage("FixtureList is null!", GUI.Style.Red);
} }
} }
@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework; using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System.Linq; using System.Linq;
@@ -6,8 +7,6 @@ namespace Barotrauma
{ {
partial class ItemInventory : Inventory partial class ItemInventory : Inventory
{ {
private string uiLabel;
protected override void ControlInput(Camera cam) protected override void ControlInput(Camera cam)
{ {
base.ControlInput(cam); base.ControlInput(cam);
@@ -75,30 +74,7 @@ namespace Barotrauma
0.0f, UIScale); 0.0f, UIScale);
} }
if (container.InventoryTopSprite == null) if (container.InventoryTopSprite != null && !subInventory)
{
if (uiLabel == null || uiLabel == string.Empty)
{
if (container.UILabel != null && container.UILabel.Length > 0)
{
uiLabel = TextManager.Get("UILabel." + container.UILabel);
}
else
{
Item item = Owner as Item;
uiLabel = item?.Name;
}
}
if (!string.IsNullOrEmpty(uiLabel) && !subInventory)
{
uiLabel = ToolBox.WrapText(uiLabel, BackgroundFrame.Width, GUI.Font, 1);
GUI.DrawString(spriteBatch,
new Vector2((int)(BackgroundFrame.Center.X - GUI.Font.MeasureString(uiLabel).X / 2), (int)BackgroundFrame.Y + 5),
uiLabel, Color.White * 0.9f);
}
}
else if (!subInventory)
{ {
container.InventoryTopSprite.Draw(spriteBatch, new Vector2(BackgroundFrame.Center.X, BackgroundFrame.Y), 0.0f, UIScale); container.InventoryTopSprite.Draw(spriteBatch, new Vector2(BackgroundFrame.Center.X, BackgroundFrame.Y), 0.0f, UIScale);
} }
@@ -27,8 +27,8 @@ namespace Barotrauma
if (GameMain.DebugDraw) if (GameMain.DebugDraw)
{ {
Vector2 center = new Vector2(WorldRect.X + rect.Width / 2.0f, -(WorldRect.Y - rect.Height / 2.0f)); Vector2 center = new Vector2(WorldRect.X + rect.Width / 2.0f, -(WorldRect.Y - rect.Height / 2.0f));
GUI.DrawLine(sb, center, center + new Vector2(flowForce.X, -flowForce.Y) / 10.0f, Color.Red); GUI.DrawLine(sb, center, center + new Vector2(flowForce.X, -flowForce.Y) / 10.0f, GUI.Style.Red);
GUI.DrawLine(sb, center + Vector2.One * 5.0f, center + new Vector2(lerpedFlowForce.X, -lerpedFlowForce.Y) / 10.0f + Vector2.One * 5.0f, Color.Orange); GUI.DrawLine(sb, center + Vector2.One * 5.0f, center + new Vector2(lerpedFlowForce.X, -lerpedFlowForce.Y) / 10.0f + Vector2.One * 5.0f, GUI.Style.Orange);
if (outsideCollisionBlocker.Enabled && Submarine != null) if (outsideCollisionBlocker.Enabled && Submarine != null)
{ {
@@ -43,7 +43,7 @@ namespace Barotrauma
if (!editing || !ShowGaps) return; if (!editing || !ShowGaps) return;
Color clr = (open == 0.0f) ? Color.Red : Color.Cyan; Color clr = (open == 0.0f) ? GUI.Style.Red : Color.Cyan;
if (IsHighlighted) clr = Color.Gold; if (IsHighlighted) clr = Color.Gold;
float depth = (ID % 255) * 0.000001f; float depth = (ID % 255) * 0.000001f;
@@ -109,7 +109,7 @@ namespace Barotrauma
GUI.DrawRectangle(sb, GUI.DrawRectangle(sb,
new Vector2(WorldRect.X - 5, -WorldRect.Y - 5), new Vector2(WorldRect.X - 5, -WorldRect.Y - 5),
new Vector2(rect.Width + 10, rect.Height + 10), new Vector2(rect.Width + 10, rect.Height + 10),
Color.Red, GUI.Style.Red,
false, false,
depth, depth,
(int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f)); (int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f));
@@ -86,7 +86,7 @@ namespace Barotrauma
{ {
editingHUD = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GUI.Canvas, Anchor.CenterRight) { MinSize = new Point(400, 0) }) { UserData = this }; editingHUD = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GUI.Canvas, Anchor.CenterRight) { MinSize = new Point(400, 0) }) { UserData = this };
GUIListBox listBox = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.8f), editingHUD.RectTransform, Anchor.Center), style: null); GUIListBox listBox = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.8f), editingHUD.RectTransform, Anchor.Center), style: null);
new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true); new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true, titleFont: GUI.LargeFont);
PositionEditingHUD(); PositionEditingHUD();
@@ -260,7 +260,7 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
new Rectangle(drawRect.X, -drawRect.Y, rect.Width, rect.Height), new Rectangle(drawRect.X, -drawRect.Y, rect.Width, rect.Height),
Color.Red * ((100.0f - OxygenPercentage) / 400.0f), true, 0, (int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f)); GUI.Style.Red * ((100.0f - OxygenPercentage) / 400.0f), true, 0, (int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f));
if (GameMain.DebugDraw) if (GameMain.DebugDraw)
{ {
@@ -271,14 +271,14 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, (int)(100 * Math.Min(waterVolume / Volume, 1.0f))), Color.Cyan, true); GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, (int)(100 * Math.Min(waterVolume / Volume, 1.0f))), Color.Cyan, true);
if (WaterVolume > Volume) if (WaterVolume > Volume)
{ {
GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, (int)(100 * (waterVolume - Volume) / MaxCompress)), Color.Red, true); GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, (int)(100 * (waterVolume - Volume) / MaxCompress)), GUI.Style.Red, true);
} }
GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, 100), Color.Black); GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, 100), Color.Black);
foreach (FireSource fs in FireSources) foreach (FireSource fs in FireSources)
{ {
Rectangle fireSourceRect = new Rectangle((int)fs.WorldPosition.X, -(int)fs.WorldPosition.Y, (int)fs.Size.X, (int)fs.Size.Y); Rectangle fireSourceRect = new Rectangle((int)fs.WorldPosition.X, -(int)fs.WorldPosition.Y, (int)fs.Size.X, (int)fs.Size.Y);
GUI.DrawRectangle(spriteBatch, fireSourceRect, Color.Orange, false, 0, 5); GUI.DrawRectangle(spriteBatch, fireSourceRect, GUI.Style.Orange, false, 0, 5);
//GUI.DrawRectangle(spriteBatch, new Rectangle((int)fs.LastExtinguishPos.X, (int)-fs.LastExtinguishPos.Y, 5,5), Color.Yellow, true); //GUI.DrawRectangle(spriteBatch, new Rectangle((int)fs.LastExtinguishPos.X, (int)-fs.LastExtinguishPos.Y, 5,5), Color.Yellow, true);
} }
@@ -296,7 +296,7 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
new Vector2(drawRect.X + 5, -drawRect.Y + 5), new Vector2(drawRect.X + 5, -drawRect.Y + 5),
new Vector2(rect.Width - 10, rect.Height - 10), new Vector2(rect.Width - 10, rect.Height - 10),
IsHighlighted ? Color.LightBlue * 0.5f : Color.Red * 0.5f, true, 0, (int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f)); IsHighlighted ? Color.LightBlue * 0.5f : GUI.Style.Red * 0.5f, true, 0, (int)Math.Max((1.5f / GameScreen.Selected.Cam.Zoom), 1.0f));
} }
foreach (MapEntity e in linkedTo) foreach (MapEntity e in linkedTo)
@@ -322,7 +322,7 @@ namespace Barotrauma
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
new Vector2(currentHullRect.X, -currentHullRect.Y), new Vector2(currentHullRect.X, -currentHullRect.Y),
new Vector2(connectedHullRect.X, -connectedHullRect.Y), new Vector2(connectedHullRect.X, -connectedHullRect.Y),
Color.Green, width: 2); GUI.Style.Green, width: 2);
} }
} }
} }
@@ -142,7 +142,7 @@ namespace Barotrauma
if (GameMain.DebugDraw) if (GameMain.DebugDraw)
{ {
GUI.DrawRectangle(spriteBatch, new Vector2(obj.Position.X, -obj.Position.Y), new Vector2(10.0f, 10.0f), Color.Red, true); GUI.DrawRectangle(spriteBatch, new Vector2(obj.Position.X, -obj.Position.Y), new Vector2(10.0f, 10.0f), GUI.Style.Red, true);
foreach (LevelTrigger trigger in obj.Triggers) foreach (LevelTrigger trigger in obj.Triggers)
{ {
@@ -153,7 +153,7 @@ namespace Barotrauma
if (flowForce.LengthSquared() > 1) if (flowForce.LengthSquared() > 1)
{ {
flowForce.Y = -flowForce.Y; flowForce.Y = -flowForce.Y;
GUI.DrawLine(spriteBatch, new Vector2(trigger.WorldPosition.X, -trigger.WorldPosition.Y), new Vector2(trigger.WorldPosition.X, -trigger.WorldPosition.Y) + flowForce * 10, Color.Orange, 0, 5); GUI.DrawLine(spriteBatch, new Vector2(trigger.WorldPosition.X, -trigger.WorldPosition.Y), new Vector2(trigger.WorldPosition.X, -trigger.WorldPosition.Y) + flowForce * 10, GUI.Style.Orange, 0, 5);
} }
trigger.PhysicsBody.UpdateDrawPosition(); trigger.PhysicsBody.UpdateDrawPosition();
trigger.PhysicsBody.DebugDraw(spriteBatch, trigger.IsTriggered ? Color.Cyan : Color.DarkCyan); trigger.PhysicsBody.DebugDraw(spriteBatch, trigger.IsTriggered ? Color.Cyan : Color.DarkCyan);
@@ -259,7 +259,7 @@ namespace Barotrauma
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
new Vector2(nodeList[i - 1].X, -nodeList[i - 1].Y), new Vector2(nodeList[i - 1].X, -nodeList[i - 1].Y),
new Vector2(nodeList[i].X, -nodeList[i].Y), new Vector2(nodeList[i].X, -nodeList[i].Y),
Color.Lerp(Color.Yellow, Color.Red, i / (float)nodeList.Count), 0, 10); Color.Lerp(Color.Yellow, GUI.Style.Red, i / (float)nodeList.Count), 0, 10);
} }
} }
@@ -13,7 +13,7 @@ namespace Barotrauma.RuinGeneration
} }
foreach (Line line in walls) foreach (Line line in walls)
{ {
GUI.DrawLine(spriteBatch, new Vector2(line.A.X, -line.A.Y), new Vector2(line.B.X, -line.B.Y), Color.Red, 0.0f, 10); GUI.DrawLine(spriteBatch, new Vector2(line.A.X, -line.A.Y), new Vector2(line.B.X, -line.B.Y), GUI.Style.Red, 0.0f, 10);
} }
} }
} }
@@ -985,16 +985,16 @@ namespace Barotrauma.Lights
if (CastShadows && Screen.Selected == GameMain.SubEditorScreen) if (CastShadows && Screen.Selected == GameMain.SubEditorScreen)
{ {
GUI.DrawRectangle(spriteBatch, drawPos - Vector2.One * 20, Vector2.One * 40, Color.Orange, isFilled: false); GUI.DrawRectangle(spriteBatch, drawPos - Vector2.One * 20, Vector2.One * 40, GUI.Style.Orange, isFilled: false);
GUI.DrawLine(spriteBatch, drawPos - Vector2.One * 20, drawPos + Vector2.One * 20, Color.Orange); GUI.DrawLine(spriteBatch, drawPos - Vector2.One * 20, drawPos + Vector2.One * 20, GUI.Style.Orange);
GUI.DrawLine(spriteBatch, drawPos - new Vector2(1.0f, -1.0f) * 20, drawPos + new Vector2(1.0f, -1.0f) * 20, Color.Orange); GUI.DrawLine(spriteBatch, drawPos - new Vector2(1.0f, -1.0f) * 20, drawPos + new Vector2(1.0f, -1.0f) * 20, GUI.Style.Orange);
} }
//visualize light recalculations //visualize light recalculations
float timeSinceRecalculation = (float)Timing.TotalTime - lastRecalculationTime; float timeSinceRecalculation = (float)Timing.TotalTime - lastRecalculationTime;
if (timeSinceRecalculation < 0.1f) if (timeSinceRecalculation < 0.1f)
{ {
GUI.DrawRectangle(spriteBatch, drawPos - Vector2.One * 10, Vector2.One * 20, Color.Red * (1.0f - timeSinceRecalculation * 10.0f), isFilled: true); GUI.DrawRectangle(spriteBatch, drawPos - Vector2.One * 10, Vector2.One * 20, GUI.Style.Red * (1.0f - timeSinceRecalculation * 10.0f), isFilled: true);
GUI.DrawLine(spriteBatch, drawPos - Vector2.One * Range, drawPos + Vector2.One * Range, Color); GUI.DrawLine(spriteBatch, drawPos - Vector2.One * Range, drawPos + Vector2.One * Range, Color);
GUI.DrawLine(spriteBatch, drawPos - new Vector2(1.0f, -1.0f) * Range, drawPos + new Vector2(1.0f, -1.0f) * Range, Color); GUI.DrawLine(spriteBatch, drawPos - new Vector2(1.0f, -1.0f) * Range, drawPos + new Vector2(1.0f, -1.0f) * Range, Color);
} }
@@ -3,6 +3,7 @@ using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input;
using System.IO; using System.IO;
using System.Linq;
using System.Xml.Linq; using System.Xml.Linq;
namespace Barotrauma namespace Barotrauma
@@ -13,8 +14,8 @@ namespace Barotrauma
{ {
if (!editing || wallVertices == null) return; if (!editing || wallVertices == null) return;
Color color = (IsHighlighted) ? Color.Orange : Color.Green; Color color = (IsHighlighted) ? GUI.Style.Orange : GUI.Style.Green;
if (IsSelected) color = Color.Red; if (IsSelected) color = GUI.Style.Red;
Vector2 pos = Position; Vector2 pos = Position;
@@ -38,7 +39,7 @@ namespace Barotrauma
Rectangle drawRect = rect; Rectangle drawRect = rect;
drawRect.Y = -rect.Y; drawRect.Y = -rect.Y;
GUI.DrawRectangle(spriteBatch, drawRect, Color.Red, true); GUI.DrawRectangle(spriteBatch, drawRect, GUI.Style.Red, true);
if (!Item.ShowLinks) return; if (!Item.ShowLinks) return;
@@ -49,7 +50,7 @@ namespace Barotrauma
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
new Vector2(WorldPosition.X, -WorldPosition.Y), new Vector2(WorldPosition.X, -WorldPosition.Y),
new Vector2(e.WorldPosition.X, -e.WorldPosition.Y), new Vector2(e.WorldPosition.X, -e.WorldPosition.Y),
isLinkAllowed ? Color.LightGreen * 0.5f : Color.Red * 0.5f, width: 3); isLinkAllowed ? GUI.Style.Green * 0.5f : GUI.Style.Red * 0.5f, width: 3);
} }
} }
@@ -83,18 +84,14 @@ namespace Barotrauma
private GUIComponent CreateEditingHUD(bool inGame = false) private GUIComponent CreateEditingHUD(bool inGame = false)
{ {
int width = 450, height = 120; editingHUD = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GUI.Canvas, Anchor.CenterRight) { MinSize = new Point(400, 0) })
int x = GameMain.GraphicsWidth / 2 - width / 2, y = 30;
editingHUD = new GUIFrame(new RectTransform(new Point(width, height), GUI.Canvas) { ScreenSpaceOffset = new Point(x, y) })
{ {
UserData = this UserData = this
}; };
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), editingHUD.RectTransform, Anchor.Center)) var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), editingHUD.RectTransform, Anchor.Center))
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.05f AbsoluteSpacing = (int)(GUI.Scale * 5)
}; };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform),
@@ -103,19 +100,24 @@ namespace Barotrauma
if (!inGame) if (!inGame)
{ {
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform),
TextManager.Get("LinkLinkedSub"), textColor: Color.Yellow, font: GUI.SmallFont); TextManager.Get("LinkLinkedSub"), textColor: GUI.Style.Orange, font: GUI.SmallFont);
} }
var pathContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), isHorizontal: true); var pathContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), isHorizontal: true);
var pathBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), pathContainer.RectTransform), filePath, font: GUI.SmallFont); var pathBox = new GUITextBox(new RectTransform(new Vector2(0.75f, 1.0f), pathContainer.RectTransform), filePath, font: GUI.SmallFont);
var reloadButton = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), pathContainer.RectTransform), TextManager.Get("ReloadLinkedSub")) var reloadButton = new GUIButton(new RectTransform(new Vector2(0.25f / pathBox.RectTransform.RelativeSize.X, 1.0f), pathBox.RectTransform, Anchor.CenterRight, Pivot.CenterLeft),
TextManager.Get("ReloadLinkedSub"), style: "GUIButtonSmall")
{ {
OnClicked = Reload, OnClicked = Reload,
UserData = pathBox, UserData = pathBox,
ToolTip = TextManager.Get("ReloadLinkedSubTooltip") ToolTip = TextManager.Get("ReloadLinkedSubTooltip")
}; };
editingHUD.RectTransform.Resize(new Point(
editingHUD.Rect.Width,
(int)(paddedFrame.Children.Sum(c => c.Rect.Height + paddedFrame.AbsoluteSpacing) / paddedFrame.RectTransform.RelativeSize.Y)));
PositionEditingHUD(); PositionEditingHUD();
return editingHUD; return editingHUD;
@@ -128,7 +130,7 @@ namespace Barotrauma
if (!File.Exists(pathBox.Text)) if (!File.Exists(pathBox.Text))
{ {
new GUIMessageBox(TextManager.Get("Error"), TextManager.GetWithVariable("ReloadLinkedSubError", "[file]", pathBox.Text)); new GUIMessageBox(TextManager.Get("Error"), TextManager.GetWithVariable("ReloadLinkedSubError", "[file]", pathBox.Text));
pathBox.Flash(Color.Red); pathBox.Flash(GUI.Style.Red);
pathBox.Text = filePath; pathBox.Text = filePath;
return false; return false;
} }
@@ -136,7 +138,7 @@ namespace Barotrauma
XDocument doc = Submarine.OpenFile(pathBox.Text); XDocument doc = Submarine.OpenFile(pathBox.Text);
if (doc == null || doc.Root == null) return false; if (doc == null || doc.Root == null) return false;
pathBox.Flash(Color.Green); pathBox.Flash(GUI.Style.Green);
GenerateWallVertices(doc.Root); GenerateWallVertices(doc.Root);
saveElement = doc.Root; saveElement = doc.Root;
@@ -510,7 +510,7 @@ namespace Barotrauma
MapGenerationParams.Instance.LargeLevelConnectionLength, MapGenerationParams.Instance.LargeLevelConnectionLength,
connection.Length); connection.Length);
connectionColor = ToolBox.GradientLerp(sizeFactor, Color.LightGreen, Color.Orange, Color.Red); connectionColor = ToolBox.GradientLerp(sizeFactor, Color.LightGreen, GUI.Style.Orange, GUI.Style.Red);
} }
else else
{ {
@@ -667,10 +667,10 @@ namespace Barotrauma
pos.Y -= 5 * zoom; pos.Y -= 5 * zoom;
Vector2 size = GUI.LargeFont.MeasureString(location.Name); Vector2 size = GUI.LargeFont.MeasureString(location.Name);
GUI.Style.GetComponentStyle("OuterGlow").Sprites[GUIComponent.ComponentState.None][0].Draw( GUI.Style.GetComponentStyle("OuterGlow").Sprites[GUIComponent.ComponentState.None][0].Draw(
spriteBatch, new Rectangle((int)pos.X - 30, (int)pos.Y, (int)size.X + 60, (int)(size.Y + 25 * GUI.Scale)), Color.Black * hudOpenState * 0.7f); spriteBatch, new Rectangle((int)pos.X - 30, (int)(pos.Y - 10), (int)size.X + 60, (int)(size.Y + 50 * GUI.Scale)), Color.Black * hudOpenState * 0.7f);
GUI.DrawString(spriteBatch, pos, GUI.DrawString(spriteBatch, pos,
location.Name, Color.White * hudOpenState * 1.5f, font: GUI.LargeFont); location.Name, Color.White * hudOpenState * 1.5f, font: GUI.LargeFont);
GUI.DrawString(spriteBatch, pos + Vector2.UnitY * 25 * GUI.Scale, GUI.DrawString(spriteBatch, pos + Vector2.UnitY * size.Y * 0.8f,
location.Type.Name, Color.White * hudOpenState * 1.5f); location.Type.Name, Color.White * hudOpenState * 1.5f);
} }
@@ -8,6 +8,7 @@ using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace Barotrauma namespace Barotrauma
{ {
@@ -78,12 +79,12 @@ namespace Barotrauma
int heightScaled = (int)(20 * GUI.Scale); int heightScaled = (int)(20 * GUI.Scale);
editingHUD = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GUI.Canvas, Anchor.CenterRight) { MinSize = new Point(400, 0) }) { UserData = this }; editingHUD = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GUI.Canvas, Anchor.CenterRight) { MinSize = new Point(400, 0) }) { UserData = this };
GUIListBox listBox = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.8f), editingHUD.RectTransform, Anchor.Center), style: null); GUIListBox listBox = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.8f), editingHUD.RectTransform, Anchor.Center), style: null);
var editor = new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true); var editor = new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true, titleFont: GUI.LargeFont);
var buttonContainer = new GUILayoutGroup(new RectTransform(new Point(listBox.Content.Rect.Width, heightScaled)), isHorizontal: true) var buttonContainer = new GUILayoutGroup(new RectTransform(new Point(listBox.Content.Rect.Width, heightScaled)), isHorizontal: true)
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.02f RelativeSpacing = 0.01f
}; };
new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityX")) new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityX"))
{ {
@@ -103,7 +104,7 @@ namespace Barotrauma
return true; return true;
} }
}; };
var reloadTextureButton = new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ReloadSprite")) new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ReloadSprite"))
{ {
OnClicked = (button, data) => OnClicked = (button, data) =>
{ {
@@ -121,6 +122,8 @@ namespace Barotrauma
return true; return true;
} }
}; };
GUITextBlock.AutoScaleAndNormalize(buttonContainer.Children.Where(c => c is GUIButton).Select(b => ((GUIButton)b).TextBlock));
buttonContainer.RectTransform.Resize(new Point(buttonContainer.Rect.Width, buttonContainer.RectTransform.Children.Max(c => c.MinSize.Y)));
editor.AddCustomContent(buttonContainer, editor.ContentCount); editor.AddCustomContent(buttonContainer, editor.ContentCount);
PositionEditingHUD(); PositionEditingHUD();
@@ -191,7 +194,7 @@ namespace Barotrauma
if (HasBody && !ShowWalls) return; if (HasBody && !ShowWalls) return;
} }
Color color = IsHighlighted ? Color.Orange : spriteColor; Color color = IsHighlighted ? GUI.Style.Orange : spriteColor;
if (IsSelected && editing) if (IsSelected && editing)
{ {
//color = Color.Lerp(color, Color.Gold, 0.5f); //color = Color.Lerp(color, Color.Gold, 0.5f);
@@ -342,22 +342,24 @@ namespace Barotrauma
public void CreatePreviewWindow(GUIComponent parent) public void CreatePreviewWindow(GUIComponent parent)
{ {
var upperPart = new GUILayoutGroup(new RectTransform(new Vector2(1, 0.5f), parent.RectTransform, Anchor.Center, Pivot.BottomCenter)); var content = new GUIFrame(new RectTransform(Vector2.One, parent.RectTransform), style: null);
var descriptionBox = new GUIListBox(new RectTransform(new Vector2(1, 0.5f), parent.RectTransform, Anchor.Center, Pivot.TopCenter))
{
ScrollBarVisible = true,
Spacing = 5
};
if (PreviewImage == null) if (PreviewImage == null)
{ {
new GUITextBlock(new RectTransform(new Vector2(1.0f, 1), upperPart.RectTransform), TextManager.Get(SavedSubmarines.Contains(this) ? "SubPreviewImageNotFound" : "SubNotDownloaded")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform), TextManager.Get(SavedSubmarines.Contains(this) ? "SubPreviewImageNotFound" : "SubNotDownloaded"));
} }
else else
{ {
var submarinePreviewBackground = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), upperPart.RectTransform)) { Color = Color.Black }; var submarinePreviewBackground = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform), style: null) { Color = Color.Black };
new GUIImage(new RectTransform(new Vector2(1.0f, 1.0f), submarinePreviewBackground.RectTransform), PreviewImage, scaleToFit: true); new GUIImage(new RectTransform(new Vector2(0.98f), submarinePreviewBackground.RectTransform, Anchor.Center), PreviewImage, scaleToFit: true);
new GUIFrame(new RectTransform(Vector2.One, submarinePreviewBackground.RectTransform), "InnerGlow", color: Color.Black);
} }
var descriptionBox = new GUIListBox(new RectTransform(new Vector2(1, 0.5f), content.RectTransform, Anchor.BottomCenter))
{
UserData = "descriptionbox",
ScrollBarVisible = true,
Spacing = 5
};
//space //space
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.03f), descriptionBox.Content.RectTransform), style: null); new GUIFrame(new RectTransform(new Vector2(1.0f, 0.03f), descriptionBox.Content.RectTransform), style: null);
@@ -41,7 +41,7 @@ namespace Barotrauma
{ {
clr = Color.Black; clr = Color.Black;
} }
if (IsSelected) clr = Color.Red; if (IsSelected) clr = GUI.Style.Red;
if (IsHighlighted) clr = Color.DarkRed; if (IsHighlighted) clr = Color.DarkRed;
int iconX = iconIndices[(int)spawnType] * IconSize % iconTexture.Width; int iconX = iconIndices[(int)spawnType] * IconSize % iconTexture.Width;
@@ -74,7 +74,7 @@ namespace Barotrauma
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
drawPos, drawPos,
new Vector2(e.DrawPosition.X, -e.DrawPosition.Y), new Vector2(e.DrawPosition.X, -e.DrawPosition.Y),
isObstructed ? Color.Gray : Color.Green, width: 5); isObstructed ? Color.Gray : GUI.Style.Green, width: 5);
} }
GUI.SmallFont.DrawString(spriteBatch, GUI.SmallFont.DrawString(spriteBatch,
@@ -193,7 +193,7 @@ namespace Barotrauma
{ {
IdCardDesc = text; IdCardDesc = text;
textBox.Text = text; textBox.Text = text;
textBox.Color = Color.Green; textBox.Color = GUI.Style.Green;
textBox.Deselect(); textBox.Deselect();
@@ -203,14 +203,14 @@ namespace Barotrauma
{ {
IdCardTags = text.Split(','); IdCardTags = text.Split(',');
textBox.Text = string.Join(",", IdCardTags); textBox.Text = string.Join(",", IdCardTags);
textBox.Flash(Color.Green); textBox.Flash(GUI.Style.Green);
textBox.Deselect(); textBox.Deselect();
return true; return true;
} }
private bool TextBoxChanged(GUITextBox textBox, string text) private bool TextBoxChanged(GUITextBox textBox, string text)
{ {
textBox.Color = Color.Red; textBox.Color = GUI.Style.Red;
return true; return true;
} }
@@ -234,12 +234,12 @@ namespace Barotrauma
if (spawnType == SpawnType.Path) if (spawnType == SpawnType.Path)
{ {
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("Editing") + " " + TextManager.Get("Waypoint")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("Waypoint"), font: GUI.LargeFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("LinkWaypoint")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("LinkWaypoint"));
} }
else else
{ {
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("Editing") + " " + TextManager.Get("Spawnpoint")); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("Spawnpoint"), font: GUI.LargeFont);
var spawnTypeContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), isHorizontal: true) var spawnTypeContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), isHorizontal: true)
{ {
@@ -248,7 +248,7 @@ namespace Barotrauma
}; };
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), spawnTypeContainer.RectTransform), TextManager.Get("SpawnType")); new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), spawnTypeContainer.RectTransform), TextManager.Get("SpawnType"));
var button = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), spawnTypeContainer.RectTransform), "-") var button = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), spawnTypeContainer.RectTransform, scaleBasis: ScaleBasis.BothHeight), style: "GUIMinusButton")
{ {
UserData = -1, UserData = -1,
OnClicked = ChangeSpawnType OnClicked = ChangeSpawnType
@@ -257,13 +257,12 @@ namespace Barotrauma
{ {
UserData = "spawntypetext" UserData = "spawntypetext"
}; };
button = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), spawnTypeContainer.RectTransform), "+") button = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), spawnTypeContainer.RectTransform, scaleBasis: ScaleBasis.BothHeight), style: "GUIPlusButton")
{ {
UserData = 1, UserData = 1,
OnClicked = ChangeSpawnType OnClicked = ChangeSpawnType
}; };
var descText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), var descText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform),
TextManager.Get("IDCardDescription"), font: GUI.SmallFont); TextManager.Get("IDCardDescription"), font: GUI.SmallFont);
GUITextBox propertyBox = new GUITextBox(new RectTransform(new Vector2(0.5f, 1.0f), descText.RectTransform, Anchor.CenterRight), idCardDesc) GUITextBox propertyBox = new GUITextBox(new RectTransform(new Vector2(0.5f, 1.0f), descText.RectTransform, Anchor.CenterRight), idCardDesc)
@@ -274,7 +273,6 @@ namespace Barotrauma
}; };
propertyBox.OnTextChanged += TextBoxChanged; propertyBox.OnTextChanged += TextBoxChanged;
var tagsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), var tagsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform),
TextManager.Get("IDCardTags"), font: GUI.SmallFont); TextManager.Get("IDCardTags"), font: GUI.SmallFont);
propertyBox = new GUITextBox(new RectTransform(new Vector2(0.5f, 1.0f), tagsText.RectTransform, Anchor.CenterRight), string.Join(", ", idCardTags)) propertyBox = new GUITextBox(new RectTransform(new Vector2(0.5f, 1.0f), tagsText.RectTransform, Anchor.CenterRight), string.Join(", ", idCardTags))
@@ -1,6 +1,7 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace Barotrauma.Networking namespace Barotrauma.Networking
{ {
@@ -44,9 +45,9 @@ namespace Barotrauma.Networking
foreach (BannedPlayer bannedPlayer in bannedPlayers) foreach (BannedPlayer bannedPlayer in bannedPlayers)
{ {
if (localRemovedBans.Contains(bannedPlayer.UniqueIdentifier)) continue; if (localRemovedBans.Contains(bannedPlayer.UniqueIdentifier)) { continue; }
var playerFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.25f), ((GUIListBox)banFrame).Content.RectTransform) { MinSize = new Point(0, 70) }, style: null) var playerFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.2f), ((GUIListBox)banFrame).Content.RectTransform) { MinSize = new Point(0, 70) })
{ {
UserData = banFrame UserData = banFrame
}; };
@@ -54,42 +55,56 @@ namespace Barotrauma.Networking
var paddedPlayerFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.85f), playerFrame.RectTransform, Anchor.Center)) var paddedPlayerFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.85f), playerFrame.RectTransform, Anchor.Center))
{ {
Stretch = true, Stretch = true,
RelativeSpacing = 0.05f RelativeSpacing = 0.05f,
CanBeFocused = true
};
var topArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.0f), paddedPlayerFrame.RectTransform),
isHorizontal: true, childAnchor: Anchor.CenterLeft)
{
Stretch = true,
RelativeSpacing = 0.02f
}; };
string ip = bannedPlayer.IP; string ip = bannedPlayer.IP;
if (localRangeBans.Contains(bannedPlayer.UniqueIdentifier)) ip = ToRange(ip); if (localRangeBans.Contains(bannedPlayer.UniqueIdentifier)) ip = ToRange(ip);
GUITextBlock textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), paddedPlayerFrame.RectTransform), GUITextBlock textBlock = new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.0f), topArea.RectTransform),
bannedPlayer.Name + " (" + ip + ")"); bannedPlayer.Name + " (" + ip + ")");
textBlock.RectTransform.MinSize = new Point(textBlock.Rect.Width, 0);
var removeButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.4f), paddedPlayerFrame.RectTransform, Anchor.TopRight), TextManager.Get("BanListRemove"))
{
UserData = bannedPlayer,
IgnoreLayoutGroups = true,
OnClicked = RemoveBan
};
if (bannedPlayer.IP.IndexOf(".x") <= -1) if (bannedPlayer.IP.IndexOf(".x") <= -1)
{ {
var rangeBanButton = new GUIButton(new RectTransform(new Vector2(0.25f, 0.4f), paddedPlayerFrame.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.22f, 0.0f) }, TextManager.Get("BanRange")) var rangeBanButton = new GUIButton(new RectTransform(new Vector2(0.25f, 0.4f), topArea.RectTransform),
TextManager.Get("BanRange"), style: "GUIButtonSmall")
{ {
UserData = bannedPlayer, UserData = bannedPlayer,
IgnoreLayoutGroups = true,
OnClicked = RangeBan OnClicked = RangeBan
}; };
} }
var removeButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.4f), topArea.RectTransform),
TextManager.Get("BanListRemove"), style: "GUIButtonSmall")
{
UserData = bannedPlayer,
OnClicked = RemoveBan
};
topArea.RectTransform.MinSize = new Point(0, (int)topArea.RectTransform.Children.Max(c => c.Rect.Height * 1.25f));
new GUITextBlock(new RectTransform(new Vector2(0.6f, 0.0f), paddedPlayerFrame.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedPlayerFrame.RectTransform),
bannedPlayer.ExpirationTime == null ? bannedPlayer.ExpirationTime == null ?
TextManager.Get("BanPermanent") : TextManager.GetWithVariable("BanExpires", "[time]", bannedPlayer.ExpirationTime.Value.ToString()), TextManager.Get("BanPermanent") : TextManager.GetWithVariable("BanExpires", "[time]", bannedPlayer.ExpirationTime.Value.ToString()),
font: GUI.SmallFont); font: GUI.SmallFont);
var reasonText = new GUITextBlock(new RectTransform(new Vector2(0.6f, 0.0f), paddedPlayerFrame.RectTransform), var reasonText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedPlayerFrame.RectTransform),
TextManager.Get("BanReason") + " " + TextManager.Get("BanReason") + " " +
(string.IsNullOrEmpty(bannedPlayer.Reason) ? TextManager.Get("None") : ToolBox.LimitString(bannedPlayer.Reason, GUI.SmallFont, 170)), (string.IsNullOrEmpty(bannedPlayer.Reason) ? TextManager.Get("None") : bannedPlayer.Reason),
font: GUI.SmallFont, wrap: true) font: GUI.SmallFont, wrap: true)
{ {
ToolTip = bannedPlayer.Reason ToolTip = bannedPlayer.Reason
}; };
paddedPlayerFrame.Recalculate();
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), ((GUIListBox)banFrame).Content.RectTransform), style: "HorizontalLine");
} }
return banFrame; return banFrame;
@@ -26,7 +26,6 @@ namespace Barotrauma.Networking
PrivateStart(); PrivateStart();
processInfo.Arguments += " -pipes " + writePipe.GetClientHandleAsString() + " " + readPipe.GetClientHandleAsString(); processInfo.Arguments += " -pipes " + writePipe.GetClientHandleAsString() + " " + readPipe.GetClientHandleAsString();
DebugConsole.NewMessage(processInfo.Arguments, Microsoft.Xna.Framework.Color.Orange);
Process = Process.Start(processInfo); Process = Process.Start(processInfo);
localHandlesDisposed = false; localHandlesDisposed = false;
@@ -128,6 +128,11 @@ namespace Barotrauma.Networking
get { return entityEventManager.MidRoundSyncing; } get { return entityEventManager.MidRoundSyncing; }
} }
public ClientEntityEventManager EntityEventManager
{
get { return entityEventManager; }
}
private object serverEndpoint; private object serverEndpoint;
private int ownerKey; private int ownerKey;
private bool steamP2POwner; private bool steamP2POwner;
@@ -1028,33 +1033,39 @@ namespace Barotrauma.Networking
if (!IsServerOwner) if (!IsServerOwner)
{ {
GUIMessageBox.MessageBoxes.RemoveAll(mb => mb.UserData as string == "permissions"); GUIMessageBox.MessageBoxes.RemoveAll(mb => mb.UserData as string == "permissions");
GUIMessageBox msgBox = new GUIMessageBox("", "") { UserData = "permissions" };
msgBox.Content.ClearChildren();
msgBox.Content.RectTransform.RelativeSize = new Vector2(0.95f, 0.9f);
string msg = ""; var header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), msgBox.Content.RectTransform), TextManager.Get("PermissionsChanged"), textAlignment: Alignment.Center, font: GUI.LargeFont);
if (newPermissions == ClientPermissions.None) header.RectTransform.IsFixedSize = true;
var permissionArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), msgBox.Content.RectTransform), isHorizontal: true) { Stretch = true, RelativeSpacing = 0.05f };
var leftColumn = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), permissionArea.RectTransform)) { Stretch = true, RelativeSpacing = 0.05f };
var rightColumn = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), permissionArea.RectTransform)) { Stretch = true, RelativeSpacing = 0.05f };
var permissionsLabel = new GUITextBlock(new RectTransform(new Vector2(newPermissions == ClientPermissions.None ? 2.0f : 1.0f, 0.0f), leftColumn.RectTransform),
TextManager.Get(newPermissions == ClientPermissions.None ? "PermissionsRemoved" : "CurrentPermissions"),
wrap: true, font: (newPermissions == ClientPermissions.None ? GUI.Font : GUI.SubHeadingFont));
permissionsLabel.RectTransform.NonScaledSize = new Point(permissionsLabel.Rect.Width, permissionsLabel.Rect.Height);
permissionsLabel.RectTransform.IsFixedSize = true;
if (newPermissions != ClientPermissions.None)
{ {
msg = TextManager.Get("PermissionsRemoved"); string permissionList = "";
}
else
{
msg = TextManager.Get("CurrentPermissions") + '\n';
foreach (ClientPermissions permission in Enum.GetValues(typeof(ClientPermissions))) foreach (ClientPermissions permission in Enum.GetValues(typeof(ClientPermissions)))
{ {
if (!newPermissions.HasFlag(permission) || permission == ClientPermissions.None) continue; if (!newPermissions.HasFlag(permission) || permission == ClientPermissions.None) { continue; }
msg += " - " + TextManager.Get("ClientPermission." + permission) + "\n"; permissionList += " - " + TextManager.Get("ClientPermission." + permission) + "\n";
} }
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), leftColumn.RectTransform),
permissionList);
} }
GUIMessageBox msgBox = new GUIMessageBox(TextManager.Get("PermissionsChanged"), msg)
{
UserData = "permissions"
};
if (newPermissions.HasFlag(ClientPermissions.ConsoleCommands)) if (newPermissions.HasFlag(ClientPermissions.ConsoleCommands))
{ {
int listBoxWidth = (int)(msgBox.InnerFrame.Rect.Width) / 2 - 30; var commandsLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), rightColumn.RectTransform),
new GUITextBlock(new RectTransform(new Vector2(0.4f, 0.1f), msgBox.InnerFrame.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.05f, 0.15f) }, TextManager.Get("PermittedConsoleCommands"), wrap: true, font: GUI.SubHeadingFont);
TextManager.Get("PermittedConsoleCommands"), wrap: true, font: GUI.SmallFont); var commandList = new GUIListBox(new RectTransform(new Vector2(1.0f, 1.0f), rightColumn.RectTransform));
var commandList = new GUIListBox(new RectTransform(new Vector2(0.4f, 0.55f), msgBox.InnerFrame.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.05f, 0.25f) });
foreach (string permittedCommand in permittedConsoleCommands) foreach (string permittedCommand in permittedConsoleCommands)
{ {
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), commandList.Content.RectTransform, minSize: new Point(0, 15)), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), commandList.Content.RectTransform, minSize: new Point(0, 15)),
@@ -1063,7 +1074,23 @@ namespace Barotrauma.Networking
CanBeFocused = false CanBeFocused = false
}; };
} }
permissionsLabel.RectTransform.NonScaledSize = commandsLabel.RectTransform.NonScaledSize =
new Point(permissionsLabel.Rect.Width, Math.Max(permissionsLabel.Rect.Height, commandsLabel.Rect.Height));
commandsLabel.RectTransform.IsFixedSize = true;
} }
new GUIButton(new RectTransform(new Vector2(0.5f, 0.05f), msgBox.Content.RectTransform), TextManager.Get("ok"))
{
OnClicked = msgBox.Close
};
permissionArea.RectTransform.MinSize = new Point(0, Math.Max( leftColumn.RectTransform.Children.Sum(c => c.Rect.Height), rightColumn.RectTransform.Children.Sum(c => c.Rect.Height)));
permissionArea.RectTransform.IsFixedSize = true;
int contentHeight = (int)(msgBox.Content.RectTransform.Children.Sum(c => c.Rect.Height + msgBox.Content.AbsoluteSpacing) * 1.05f);
msgBox.Content.ChildAnchor = Anchor.TopCenter;
msgBox.Content.Stretch = true;
msgBox.Content.RectTransform.MinSize = new Point(0, contentHeight);
msgBox.InnerFrame.RectTransform.MinSize = new Point(0, (int)(contentHeight / permissionArea.RectTransform.RelativeSize.Y / msgBox.Content.RectTransform.RelativeSize.Y));
} }
GameMain.NetLobbyScreen.UpdatePermissions(); GameMain.NetLobbyScreen.UpdatePermissions();
@@ -2488,7 +2515,7 @@ namespace Barotrauma.Networking
//oscillate between 0-1 //oscillate between 0-1
float phase = (float)(Math.Sin(timeLeft * MathHelper.Pi) + 1.0f) * 0.5f; float phase = (float)(Math.Sin(timeLeft * MathHelper.Pi) + 1.0f) * 0.5f;
textScale = 1.0f + phase * 0.5f; textScale = 1.0f + phase * 0.5f;
textColor = Color.Lerp(Color.Red, Color.White, 1.0f - phase); textColor = Color.Lerp(GUI.Style.Red, Color.White, 1.0f - phase);
} }
} }
@@ -2536,14 +2563,17 @@ namespace Barotrauma.Networking
var client = GameMain.NetworkMember.ConnectedClients.Find(c => c.Character == character); var client = GameMain.NetworkMember.ConnectedClients.Find(c => c.Character == character);
if (client == null) { return false; } if (client == null) { return false; }
var mute = new GUITickBox(new RectTransform(new Vector2(0.95f, 0.1f), characterFrame.RectTransform, Anchor.BottomCenter) { RelativeOffset = new Vector2(0.0f, 0.1f) }, var content = new GUIFrame(new RectTransform(new Vector2(0.9f, 1.0f - characterFrame.RectTransform.RelativeSize.Y), characterFrame.RectTransform, Anchor.BottomCenter, Pivot.TopCenter),
style: null);
var mute = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform, Anchor.TopCenter),
TextManager.Get("Mute")) TextManager.Get("Mute"))
{ {
Selected = client.MutedLocally, Selected = client.MutedLocally,
OnSelected = (tickBox) => { client.MutedLocally = tickBox.Selected; return true; } OnSelected = (tickBox) => { client.MutedLocally = tickBox.Selected; return true; }
}; };
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.1f), characterFrame.RectTransform, Anchor.BottomCenter), isHorizontal: true) var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform, Anchor.BottomCenter), isHorizontal: true)
{ {
RelativeSpacing = 0.05f, RelativeSpacing = 0.05f,
ChildAnchor = Anchor.CenterLeft, ChildAnchor = Anchor.CenterLeft,
@@ -2553,7 +2583,7 @@ namespace Barotrauma.Networking
if (HasPermission(ClientPermissions.Ban)) if (HasPermission(ClientPermissions.Ban))
{ {
var banButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform), var banButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("Ban")) TextManager.Get("Ban"), style: "GUIButtonSmall")
{ {
UserData = client, UserData = client,
OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.BanPlayer(client); return false; } OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.BanPlayer(client); return false; }
@@ -2562,7 +2592,7 @@ namespace Barotrauma.Networking
if (HasPermission(ClientPermissions.Kick)) if (HasPermission(ClientPermissions.Kick))
{ {
var kickButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform), var kickButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("Kick")) TextManager.Get("Kick"), style: "GUIButtonSmall")
{ {
UserData = client, UserData = client,
OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.KickPlayer(client); return false; } OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.KickPlayer(client); return false; }
@@ -2571,7 +2601,7 @@ namespace Barotrauma.Networking
else if (serverSettings.Voting.AllowVoteKick) else if (serverSettings.Voting.AllowVoteKick)
{ {
var kickVoteButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform), var kickVoteButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("VoteToKick")) TextManager.Get("VoteToKick"), style: "GUIButtonSmall")
{ {
UserData = client, UserData = client,
OnClicked = (btn, userdata) => { VoteForKick(client); btn.Enabled = false; return true; } OnClicked = (btn, userdata) => { VoteForKick(client); btn.Enabled = false; return true; }
@@ -2708,6 +2738,19 @@ namespace Barotrauma.Networking
errorLines.Add("Event ID: " + eventID + ", entity ID " + entityID); errorLines.Add("Event ID: " + eventID + ", entity ID " + entityID);
} }
if (GameMain.GameSession?.GameMode != null)
{
errorLines.Add("Game mode: " + GameMain.GameSession.GameMode.Name);
}
if (GameMain.GameSession?.Submarine != null)
{
errorLines.Add("Submarine: " + GameMain.GameSession.Submarine.Name);
}
if (Level.Loaded != null)
{
errorLines.Add("Level: " + Level.Loaded.Seed + ", " + Level.Loaded.EqualityCheckVal);
}
errorLines.Add("Entity IDs:"); errorLines.Add("Entity IDs:");
List<Entity> sortedEntities = Entity.GetEntityList(); List<Entity> sortedEntities = Entity.GetEntityList();
sortedEntities.Sort((e1, e2) => e1.ID.CompareTo(e2.ID)); sortedEntities.Sort((e1, e2) => e1.ID.CompareTo(e2.ID));
@@ -2716,9 +2759,20 @@ namespace Barotrauma.Networking
errorLines.Add(e.ID + ": " + e.ToString()); errorLines.Add(e.ID + ": " + e.ToString());
} }
errorLines.Add("");
errorLines.Add("Last debug messages:");
for (int i = DebugConsole.Messages.Count - 1; i > 0 && i > DebugConsole.Messages.Count - 15; i--)
{
errorLines.Add(" " + DebugConsole.Messages[i].Time + " - " + DebugConsole.Messages[i].Text);
}
string filePath = "event_error_log_client_" + Name + "_" + ToolBox.RemoveInvalidFileNameChars(DateTime.UtcNow.ToShortTimeString() + ".log"); string filePath = "event_error_log_client_" + Name + "_" + ToolBox.RemoveInvalidFileNameChars(DateTime.UtcNow.ToShortTimeString() + ".log");
filePath = Path.Combine(ServerLog.SavePath, filePath); filePath = Path.Combine(ServerLog.SavePath, filePath);
if (!Directory.Exists(ServerLog.SavePath))
{
Directory.CreateDirectory(ServerLog.SavePath);
}
File.WriteAllLines(filePath, errorLines); File.WriteAllLines(filePath, errorLines);
} }
@@ -1,6 +1,7 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace Barotrauma namespace Barotrauma
@@ -14,41 +15,43 @@ namespace Barotrauma
CreateLabeledTickBox(parent, "ResetKarmaBetweenRounds"); CreateLabeledTickBox(parent, "ResetKarmaBetweenRounds");
} }
CreateLabeledSlider(parent, 0.0f, 40.0f, 1.0f, "KickBanThreshold"); CreateLabeledSlider(parent, 0.0f, 40.0f, 1.0f, nameof(KickBanThreshold));
if (TextManager.ContainsTag("Karma.KicksBeforeBan")) if (TextManager.ContainsTag("Karma.KicksBeforeBan"))
{ {
CreateLabeledNumberInput(parent, 0, 10, "KicksBeforeBan"); CreateLabeledNumberInput(parent, 0, 10, nameof(KicksBeforeBan));
} }
CreateLabeledSlider(parent, 0.0f, 50.0f, 1.0f, "HerpesThreshold"); CreateLabeledSlider(parent, 0.0f, 50.0f, 1.0f, nameof(HerpesThreshold));
CreateLabeledSlider(parent, 0.0f, 0.5f, 0.01f, "KarmaDecay"); CreateLabeledSlider(parent, 0.0f, 0.5f, 0.01f, nameof(KarmaDecay));
CreateLabeledSlider(parent, 50.0f, 100.0f, 1.0f, "KarmaDecayThreshold"); CreateLabeledSlider(parent, 50.0f, 100.0f, 1.0f, nameof(KarmaDecayThreshold));
CreateLabeledSlider(parent, 0.0f, 0.5f, 0.01f, "KarmaIncrease"); CreateLabeledSlider(parent, 0.0f, 0.5f, 0.01f, nameof(KarmaIncrease));
CreateLabeledSlider(parent, 0.0f, 50.0f, 1.0f, "KarmaIncreaseThreshold"); CreateLabeledSlider(parent, 0.0f, 50.0f, 1.0f, nameof(KarmaIncreaseThreshold));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.12f), parent.RectTransform), TextManager.Get("Karma.PositiveActions"), textAlignment: Alignment.Center) new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.12f), parent.RectTransform), TextManager.Get("Karma.PositiveActions"),
textAlignment: Alignment.Center, font: GUI.SubHeadingFont)
{ {
CanBeFocused = false CanBeFocused = false
}; };
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, "StructureRepairKarmaIncrease"); CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(StructureRepairKarmaIncrease));
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, "HealFriendlyKarmaIncrease"); CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(HealFriendlyKarmaIncrease));
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, "DamageEnemyKarmaIncrease"); CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(DamageEnemyKarmaIncrease));
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, "ItemRepairKarmaIncrease"); CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(ItemRepairKarmaIncrease));
CreateLabeledSlider(parent, 0.0f, 10.0f, 0.05f, "ExtinguishFireKarmaIncrease"); CreateLabeledSlider(parent, 0.0f, 10.0f, 0.05f, nameof(ExtinguishFireKarmaIncrease));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.12f), parent.RectTransform), TextManager.Get("Karma.NegativeActions"), textAlignment: Alignment.Center) new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.12f), parent.RectTransform), TextManager.Get("Karma.NegativeActions"),
textAlignment: Alignment.Center, font: GUI.SubHeadingFont)
{ {
CanBeFocused = false CanBeFocused = false
}; };
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, "StructureDamageKarmaDecrease"); CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(StructureDamageKarmaDecrease));
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, "DamageFriendlyKarmaDecrease"); CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(DamageFriendlyKarmaDecrease));
CreateLabeledSlider(parent, 0.0f, 100.0f, 1.0f, "ReactorMeltdownKarmaDecrease"); CreateLabeledSlider(parent, 0.0f, 100.0f, 1.0f, nameof(ReactorMeltdownKarmaDecrease));
CreateLabeledSlider(parent, 0.0f, 10.0f, 0.05f, "ReactorOverheatKarmaDecrease"); CreateLabeledSlider(parent, 0.0f, 10.0f, 0.05f, nameof(ReactorOverheatKarmaDecrease));
CreateLabeledNumberInput(parent, 0, 20, "AllowedWireDisconnectionsPerMinute"); CreateLabeledNumberInput(parent, 0, 20, nameof(AllowedWireDisconnectionsPerMinute));
CreateLabeledSlider(parent, 0.0f, 20.0f, 0.5f, "WireDisconnectionKarmaDecrease"); CreateLabeledSlider(parent, 0.0f, 20.0f, 0.5f, nameof(WireDisconnectionKarmaDecrease));
CreateLabeledSlider(parent, 0.0f, 30.0f, 1.0f, "SpamFilterKarmaDecrease"); CreateLabeledSlider(parent, 0.0f, 30.0f, 1.0f, nameof(SpamFilterKarmaDecrease));
} }
private void CreateLabeledSlider(GUIComponent parent, float min, float max, float step, string propertyName) private void CreateLabeledSlider(GUIComponent parent, float min, float max, float step, string propertyName)
@@ -61,13 +64,13 @@ namespace Barotrauma
}; };
string labelText = TextManager.Get("Karma." + propertyName); string labelText = TextManager.Get("Karma." + propertyName);
var label = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.8f), container.RectTransform), var label = new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), container.RectTransform),
labelText, font: GUI.SmallFont) labelText, textAlignment: Alignment.CenterLeft, font: GUI.SmallFont)
{ {
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip") ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip")
}; };
var slider = new GUIScrollBar(new RectTransform(new Vector2(0.3f, 0.8f), container.RectTransform), barSize: 0.1f) var slider = new GUIScrollBar(new RectTransform(new Vector2(0.3f, 1.0f), container.RectTransform), barSize: 0.1f, style: "GUISlider")
{ {
Step = step <= 0.0f ? 0.0f : step / (max - min), Step = step <= 0.0f ? 0.0f : step / (max - min),
Range = new Vector2(min, max), Range = new Vector2(min, max),
@@ -80,6 +83,7 @@ namespace Barotrauma
return true; return true;
} }
}; };
container.RectTransform.MinSize = new Point(0, container.RectTransform.Children.Max(c => c.MinSize.Y));
GameMain.NetworkMember.ServerSettings.AssignGUIComponent(propertyName, slider); GameMain.NetworkMember.ServerSettings.AssignGUIComponent(propertyName, slider);
slider.OnMoved(slider, slider.BarScroll); slider.OnMoved(slider, slider.BarScroll);
} }
@@ -94,16 +98,18 @@ namespace Barotrauma
}; };
string labelText = TextManager.Get("Karma." + propertyName); string labelText = TextManager.Get("Karma." + propertyName);
new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.8f), container.RectTransform), labelText, font: GUI.SmallFont) new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), container.RectTransform), labelText, textAlignment: Alignment.CenterLeft, font: GUI.SmallFont)
{ {
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip") ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip")
}; };
var numInput = new GUINumberInput(new RectTransform(new Vector2(0.3f, 0.8f), container.RectTransform), GUINumberInput.NumberType.Int) var numInput = new GUINumberInput(new RectTransform(new Vector2(0.3f, 1.0f), container.RectTransform), GUINumberInput.NumberType.Int)
{ {
MinValueInt = min, MinValueInt = min,
MaxValueInt = max MaxValueInt = max
}; };
container.RectTransform.MinSize = new Point(0, container.RectTransform.Children.Max(c => c.MinSize.Y));
GameMain.NetworkMember.ServerSettings.AssignGUIComponent(propertyName, numInput); GameMain.NetworkMember.ServerSettings.AssignGUIComponent(propertyName, numInput);
} }
@@ -195,7 +195,7 @@ namespace Barotrauma.Networking
DebugConsole.NewMessage( DebugConsole.NewMessage(
"Received msg " + thisEventID + " (waiting for " + (lastReceivedID + 1) + ")", "Received msg " + thisEventID + " (waiting for " + (lastReceivedID + 1) + ")",
NetIdUtils.IdMoreRecent(thisEventID, (UInt16)(lastReceivedID + 1)) NetIdUtils.IdMoreRecent(thisEventID, (UInt16)(lastReceivedID + 1))
? Microsoft.Xna.Framework.Color.Red ? GUI.Style.Red
: Microsoft.Xna.Framework.Color.Yellow); : Microsoft.Xna.Framework.Color.Yellow);
} }
} }
@@ -203,7 +203,7 @@ namespace Barotrauma.Networking
{ {
DebugConsole.NewMessage( DebugConsole.NewMessage(
"Received msg " + thisEventID + ", entity " + entityID + " not found", "Received msg " + thisEventID + ", entity " + entityID + " not found",
Microsoft.Xna.Framework.Color.Red); GUI.Style.Red);
GameMain.Client.ReportError(ClientNetError.MISSING_ENTITY, eventID: thisEventID, entityID: entityID); GameMain.Client.ReportError(ClientNetError.MISSING_ENTITY, eventID: thisEventID, entityID: entityID);
return false; return false;
} }
@@ -65,9 +65,9 @@ namespace Barotrauma.Networking
graphs[(int)NetStatType.ReceivedBytes].Draw(spriteBatch, rect, null, 0.0f, Color.Cyan); graphs[(int)NetStatType.ReceivedBytes].Draw(spriteBatch, rect, null, 0.0f, Color.Cyan);
graphs[(int)NetStatType.SentBytes].Draw(spriteBatch, rect, null, 0.0f, Color.Orange); graphs[(int)NetStatType.SentBytes].Draw(spriteBatch, rect, null, 0.0f, GUI.Style.Orange);
graphs[(int)NetStatType.ResentMessages].Draw(spriteBatch, rect, null, 0.0f, Color.Red); graphs[(int)NetStatType.ResentMessages].Draw(spriteBatch, rect, null, 0.0f, GUI.Style.Red);
GUI.SmallFont.DrawString(spriteBatch, GUI.SmallFont.DrawString(spriteBatch,
"Peak received: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.ReceivedBytes].LargestValue()) + "/s " + "Peak received: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.ReceivedBytes].LargestValue()) + "/s " +
@@ -77,17 +77,17 @@ namespace Barotrauma.Networking
GUI.SmallFont.DrawString(spriteBatch, "Peak sent: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.SentBytes].LargestValue()) + "/s " + GUI.SmallFont.DrawString(spriteBatch, "Peak sent: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.SentBytes].LargestValue()) + "/s " +
"Avg sent: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.SentBytes].Average()) + "/s", "Avg sent: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.SentBytes].Average()) + "/s",
new Vector2(rect.Right + 10, rect.Y + 30), Color.Orange); new Vector2(rect.Right + 10, rect.Y + 30), GUI.Style.Orange);
GUI.SmallFont.DrawString(spriteBatch, "Peak resent: " + graphs[(int)NetStatType.ResentMessages].LargestValue() + " messages/s", GUI.SmallFont.DrawString(spriteBatch, "Peak resent: " + graphs[(int)NetStatType.ResentMessages].LargestValue() + " messages/s",
new Vector2(rect.Right + 10, rect.Y + 50), Color.Red); new Vector2(rect.Right + 10, rect.Y + 50), GUI.Style.Red);
#if DEBUG #if DEBUG
/*int y = 10; /*int y = 10;
foreach (KeyValuePair<string, long> msgBytesSent in server.messageCount.OrderBy(key => -key.Value)) foreach (KeyValuePair<string, long> msgBytesSent in server.messageCount.OrderBy(key => -key.Value))
{ {
GUI.SmallFont.DrawString(spriteBatch, msgBytesSent.Key + ": " + MathUtils.GetBytesReadable(msgBytesSent.Value), GUI.SmallFont.DrawString(spriteBatch, msgBytesSent.Key + ": " + MathUtils.GetBytesReadable(msgBytesSent.Value),
new Vector2(rect.Right - 200, rect.Y + y), Color.Red); new Vector2(rect.Right - 200, rect.Y + y), GUI.Style.Red);
y += 15; y += 15;
} }
@@ -83,6 +83,14 @@ namespace Barotrauma.Networking
{ {
if (!isActive) { return; } if (!isActive) { return; }
if (ownerKey != 0 && (ChildServerRelay.Process?.HasExited ?? true))
{
Close();
var msgBox = new GUIMessageBox(TextManager.Get("ConnectionLost"), TextManager.Get("ServerProcessClosed"));
msgBox.Buttons[0].OnClicked += (btn, obj) => { GameMain.MainMenuScreen.Select(); return false; };
return;
}
netClient.ReadMessages(incomingLidgrenMessages); netClient.ReadMessages(incomingLidgrenMessages);
foreach (NetIncomingMessage inc in incomingLidgrenMessages) foreach (NetIncomingMessage inc in incomingLidgrenMessages)
@@ -188,6 +188,14 @@ namespace Barotrauma.Networking
{ {
if (!isActive) { return; } if (!isActive) { return; }
if (ChildServerRelay.HasShutDown || (ChildServerRelay.Process?.HasExited ?? true))
{
Close();
var msgBox = new GUIMessageBox(TextManager.Get("ConnectionLost"), TextManager.Get("ServerProcessClosed"));
msgBox.Buttons[0].OnClicked += (btn, obj) => { GameMain.MainMenuScreen.Select(); return false; };
return;
}
for (int i = remotePeers.Count - 1; i >= 0; i--) for (int i = remotePeers.Count - 1; i >= 0; i--)
{ {
if (remotePeers[i].DisconnectTime != null && remotePeers[i].DisconnectTime < Timing.TotalTime) if (remotePeers[i].DisconnectTime != null && remotePeers[i].DisconnectTime < Timing.TotalTime)
@@ -109,27 +109,21 @@ namespace Barotrauma.Networking
{ {
frame.ClearChildren(); frame.ClearChildren();
if (frame == null) return; if (frame == null) { return; }
var previewContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), frame.RectTransform, Anchor.Center)) var previewContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.98f), frame.RectTransform, Anchor.Center))
{ {
Stretch = true Stretch = true
}; };
var titleContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.035f), previewContainer.RectTransform), true) var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), previewContainer.RectTransform, Anchor.CenterLeft), ServerName, font: GUI.LargeFont)
{
Color = Color.White * 0.2f
};
var title = new GUITextBlock(new RectTransform(new Vector2(0.9f, 0.0f), titleContainer.RectTransform, Anchor.CenterLeft), ServerName, font: GUI.LargeFont)
{ {
ToolTip = ServerName ToolTip = ServerName
}; };
title.Text = ToolBox.LimitString(title.Text, title.Font, title.Rect.Width); title.Text = ToolBox.LimitString(title.Text, title.Font, (int)(title.Rect.Width * 0.85f));
title.Padding = new Vector4(10, 0, 0, 10); GUITickBox favoriteTickBox = new GUITickBox(new RectTransform(new Vector2(0.15f, 0.8f), title.RectTransform, Anchor.CenterRight),
"", null, "GUIServerListFavoriteTickBox")
GUITickBox favoriteTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.85f), titleContainer.RectTransform, Anchor.CenterRight, scaleBasis: ScaleBasis.BothHeight) { RelativeOffset = new Vector2(0.0f, 0.1f) }, "", null, "GUIServerListFavoriteTickBox")
{ {
Selected = Favorite, Selected = Favorite,
ToolTip = TextManager.Get(Favorite ? "removefromfavorites" : "addtofavorites"), ToolTip = TextManager.Get(Favorite ? "removefromfavorites" : "addtofavorites"),
@@ -153,44 +147,59 @@ namespace Barotrauma.Networking
PlayStyle playStyle = PlayStyle ?? Networking.PlayStyle.Serious; PlayStyle playStyle = PlayStyle ?? Networking.PlayStyle.Serious;
Sprite playStyleBannerSprite = GameMain.ServerListScreen.PlayStyleBanners[(int)playStyle]; Sprite playStyleBannerSprite = ServerListScreen.PlayStyleBanners[(int)playStyle];
float playStyleBannerAspectRatio = playStyleBannerSprite.SourceRect.Width / (playStyleBannerSprite.SourceRect.Height * 0.65f); float playStyleBannerAspectRatio = playStyleBannerSprite.SourceRect.Width / playStyleBannerSprite.SourceRect.Height;
var playStyleBanner = new GUIImage(new RectTransform(new Vector2(1.0f, 1.0f / playStyleBannerAspectRatio), previewContainer.RectTransform, Anchor.TopCenter, scaleBasis: ScaleBasis.BothWidth), var playStyleBanner = new GUIImage(new RectTransform(new Point(previewContainer.Rect.Width, (int)(previewContainer.Rect.Width / playStyleBannerAspectRatio)), previewContainer.RectTransform),
playStyleBannerSprite, null, true); playStyleBannerSprite, null, true);
var playStyleName = new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.0f), playStyleBanner.RectTransform) { RelativeOffset = new Vector2(0.01f, 0.06f) }, var playStyleName = new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.0f), playStyleBanner.RectTransform) { RelativeOffset = new Vector2(0.01f, 0.06f) },
TextManager.AddPunctuation(':', TextManager.Get("serverplaystyle"), TextManager.Get("servertag."+ playStyle)), textColor: Color.White, TextManager.AddPunctuation(':', TextManager.Get("serverplaystyle"), TextManager.Get("servertag."+ playStyle)), textColor: Color.White,
font: GUI.SmallFont, textAlignment: Alignment.Center, font: GUI.SmallFont, textAlignment: Alignment.Center,
color: GameMain.ServerListScreen.PlayStyleColors[(int)playStyle], style: "GUISlopedHeader"); color: ServerListScreen.PlayStyleColors[(int)playStyle], style: "GUISlopedHeader");
playStyleName.RectTransform.NonScaledSize = (playStyleName.Font.MeasureString(playStyleName.Text) + new Vector2(20, 5) * GUI.Scale).ToPoint(); playStyleName.RectTransform.NonScaledSize = (playStyleName.Font.MeasureString(playStyleName.Text) + new Vector2(20, 5) * GUI.Scale).ToPoint();
playStyleName.RectTransform.IsFixedSize = true; playStyleName.RectTransform.IsFixedSize = true;
var content = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.6f), previewContainer.RectTransform))
var columnContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.45f), previewContainer.RectTransform), isHorizontal: true)
{ {
Stretch = true Stretch = true
}; };
// playstyle tags -----------------------------------------------------------------------------
// Left column ------------------------------------------------------------------------------- var playStyleContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), content.RectTransform), isHorizontal: true)
var leftColumnHolder = new GUILayoutGroup(new RectTransform(new Vector2(0.75f, 1.0f), columnContainer.RectTransform), childAnchor: Anchor.Center)
{ {
Stretch = true Stretch = true,
RelativeSpacing = 0.01f,
CanBeFocused = true
}; };
var leftColumn = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 1.0f), leftColumnHolder.RectTransform)) var playStyleTags = GetPlayStyleTags();
foreach (string tag in playStyleTags)
{ {
Stretch = true if (!ServerListScreen.PlayStyleIcons.ContainsKey(tag)) { continue; }
};
new GUIImage(new RectTransform(Vector2.One, playStyleContainer.RectTransform),
ServerListScreen.PlayStyleIcons[tag], scaleToFit: true)
{
ToolTip = TextManager.Get("servertagdescription." + tag),
Color = ServerListScreen.PlayStyleIconColors[tag]
};
}
playStyleContainer.Recalculate();
// -----------------------------------------------------------------------------
float elementHeight = 0.075f; float elementHeight = 0.075f;
// Spacing // Spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.025f), leftColumn.RectTransform), style: null); new GUIFrame(new RectTransform(new Vector2(1.0f, 0.025f), content.RectTransform), style: null);
var serverMsg = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.3f), leftColumn.RectTransform)) { ScrollBarVisible = true }; var serverMsg = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform)) { ScrollBarVisible = true };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverMsg.Content.RectTransform), ServerMessage, font: GUI.SmallFont, wrap: true) { CanBeFocused = false }; var msgText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverMsg.Content.RectTransform), ServerMessage, font: GUI.SmallFont, wrap: true) { CanBeFocused = true };
serverMsg.Content.RectTransform.SizeChanged += () => { msgText.CalculateHeightFromText(); };
msgText.RectTransform.SizeChanged += () => { serverMsg.UpdateScrollBarSize(); };
var gameMode = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), leftColumn.RectTransform), TextManager.Get("GameMode")); var gameMode = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), content.RectTransform), TextManager.Get("GameMode"));
new GUITextBlock(new RectTransform(Vector2.One, gameMode.RectTransform), new GUITextBlock(new RectTransform(Vector2.One, gameMode.RectTransform),
TextManager.Get(string.IsNullOrEmpty(GameMode) ? "Unknown" : "GameMode." + GameMode, returnNull: true) ?? GameMode, TextManager.Get(string.IsNullOrEmpty(GameMode) ? "Unknown" : "GameMode." + GameMode, returnNull: true) ?? GameMode,
textAlignment: Alignment.Right); textAlignment: Alignment.Right);
@@ -198,13 +207,21 @@ namespace Barotrauma.Networking
/*var traitors = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), bodyContainer.RectTransform), TextManager.Get("Traitors")); /*var traitors = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), bodyContainer.RectTransform), TextManager.Get("Traitors"));
new GUITextBlock(new RectTransform(Vector2.One, traitors.RectTransform), TextManager.Get(!TraitorsEnabled.HasValue ? "Unknown" : TraitorsEnabled.Value.ToString()), textAlignment: Alignment.Right);*/ new GUITextBlock(new RectTransform(Vector2.One, traitors.RectTransform), TextManager.Get(!TraitorsEnabled.HasValue ? "Unknown" : TraitorsEnabled.Value.ToString()), textAlignment: Alignment.Right);*/
var subSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), leftColumn.RectTransform), TextManager.Get("ServerListSubSelection")); var subSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), content.RectTransform), TextManager.Get("ServerListSubSelection"));
new GUITextBlock(new RectTransform(Vector2.One, subSelection.RectTransform), TextManager.Get(!SubSelectionMode.HasValue ? "Unknown" : SubSelectionMode.Value.ToString()), textAlignment: Alignment.Right); new GUITextBlock(new RectTransform(Vector2.One, subSelection.RectTransform), TextManager.Get(!SubSelectionMode.HasValue ? "Unknown" : SubSelectionMode.Value.ToString()), textAlignment: Alignment.Right);
var modeSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), leftColumn.RectTransform), TextManager.Get("ServerListModeSelection")); var modeSelection = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), content.RectTransform), TextManager.Get("ServerListModeSelection"));
new GUITextBlock(new RectTransform(Vector2.One, modeSelection.RectTransform), TextManager.Get(!ModeSelectionMode.HasValue ? "Unknown" : ModeSelectionMode.Value.ToString()), textAlignment: Alignment.Right); new GUITextBlock(new RectTransform(Vector2.One, modeSelection.RectTransform), TextManager.Get(!ModeSelectionMode.HasValue ? "Unknown" : ModeSelectionMode.Value.ToString()), textAlignment: Alignment.Right);
var allowSpectating = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), leftColumn.RectTransform), TextManager.Get("ServerListAllowSpectating")) if (gameMode.TextSize.X + gameMode.GetChild<GUITextBlock>().TextSize.X > gameMode.Rect.Width ||
subSelection.TextSize.X + subSelection.GetChild<GUITextBlock>().TextSize.X > subSelection.Rect.Width ||
modeSelection.TextSize.X + modeSelection.GetChild<GUITextBlock>().TextSize.X > modeSelection.Rect.Width)
{
gameMode.Font = subSelection.Font = modeSelection.Font = GUI.SmallFont;
gameMode.GetChild<GUITextBlock>().Font = subSelection.GetChild<GUITextBlock>().Font = modeSelection.GetChild<GUITextBlock>().Font = GUI.SmallFont;
}
var allowSpectating = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), content.RectTransform), TextManager.Get("ServerListAllowSpectating"))
{ {
CanBeFocused = false CanBeFocused = false
}; };
@@ -213,7 +230,7 @@ namespace Barotrauma.Networking
else else
allowSpectating.Selected = AllowSpectating.Value; allowSpectating.Selected = AllowSpectating.Value;
var allowRespawn = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), leftColumn.RectTransform), TextManager.Get("ServerSettingsAllowRespawning")) var allowRespawn = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), content.RectTransform), TextManager.Get("ServerSettingsAllowRespawning"))
{ {
CanBeFocused = false CanBeFocused = false
}; };
@@ -231,7 +248,7 @@ namespace Barotrauma.Networking
else else
voipEnabledTickBox.Selected = VoipEnabled.Value;*/ voipEnabledTickBox.Selected = VoipEnabled.Value;*/
var usingWhiteList = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), leftColumn.RectTransform), TextManager.Get("ServerListUsingWhitelist")) var usingWhiteList = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), content.RectTransform), TextManager.Get("ServerListUsingWhitelist"))
{ {
CanBeFocused = false CanBeFocused = false
}; };
@@ -241,15 +258,15 @@ namespace Barotrauma.Networking
usingWhiteList.Selected = UsingWhiteList.Value; usingWhiteList.Selected = UsingWhiteList.Value;
leftColumn.RectTransform.SizeChanged += () => content.RectTransform.SizeChanged += () =>
{ {
GUITextBlock.AutoScaleAndNormalize(allowSpectating.TextBlock, allowRespawn.TextBlock, usingWhiteList.TextBlock); GUITextBlock.AutoScaleAndNormalize(allowSpectating.TextBlock, allowRespawn.TextBlock, usingWhiteList.TextBlock);
}; };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), leftColumn.RectTransform), new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform),
TextManager.Get("ServerListContentPackages")); TextManager.Get("ServerListContentPackages"), textAlignment: Alignment.Center, font: GUI.SubHeadingFont);
var contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), leftColumn.RectTransform)) { ScrollBarVisible = true }; var contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), content.RectTransform)) { ScrollBarVisible = true };
if (ContentPackageNames.Count == 0) if (ContentPackageNames.Count == 0)
{ {
new GUITextBlock(new RectTransform(Vector2.One, contentPackageList.Content.RectTransform), TextManager.Get("Unknown"), textAlignment: Alignment.Center) new GUITextBlock(new RectTransform(Vector2.One, contentPackageList.Content.RectTransform), TextManager.Get("Unknown"), textAlignment: Alignment.Center)
@@ -278,7 +295,7 @@ namespace Barotrauma.Networking
//matching content package found, but it hasn't been enabled //matching content package found, but it hasn't been enabled
if (ContentPackage.List.Any(cp => cp.MD5hash.Hash == ContentPackageHashes[i])) if (ContentPackage.List.Any(cp => cp.MD5hash.Hash == ContentPackageHashes[i]))
{ {
packageText.TextColor = Color.Orange; packageText.TextColor = GUI.Style.Orange;
packageText.ToolTip = TextManager.GetWithVariable("ServerListContentPackageNotEnabled", "[contentpackage]", ContentPackageNames[i]); packageText.ToolTip = TextManager.GetWithVariable("ServerListContentPackageNotEnabled", "[contentpackage]", ContentPackageNames[i]);
} }
//workshop download link found //workshop download link found
@@ -290,7 +307,7 @@ namespace Barotrauma.Networking
} }
else //no package or workshop download link found, tough luck else //no package or workshop download link found, tough luck
{ {
packageText.TextColor = Color.Red; packageText.TextColor = GUI.Style.Red;
packageText.ToolTip = TextManager.GetWithVariables("ServerListIncompatibleContentPackage", packageText.ToolTip = TextManager.GetWithVariables("ServerListIncompatibleContentPackage",
new string[2] { "[contentpackage]", "[hash]" }, new string[2] { ContentPackageNames[i], ContentPackageHashes[i] }); new string[2] { "[contentpackage]", "[hash]" }, new string[2] { ContentPackageNames[i], ContentPackageHashes[i] });
} }
@@ -298,7 +315,7 @@ namespace Barotrauma.Networking
} }
if (availableWorkshopUrls.Count > 0) if (availableWorkshopUrls.Count > 0)
{ {
var workshopBtn = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), leftColumn.RectTransform), TextManager.Get("ServerListSubscribeMissingPackages")) var workshopBtn = new GUIButton(new RectTransform(new Vector2(1.0f, 0.1f), content.RectTransform), TextManager.Get("ServerListSubscribeMissingPackages"))
{ {
ToolTip = TextManager.Get(SteamManager.IsInitialized ? "ServerListSubscribeMissingPackagesTooltip" : "ServerListSubscribeMissingPackagesTooltipNoSteam"), ToolTip = TextManager.Get(SteamManager.IsInitialized ? "ServerListSubscribeMissingPackagesTooltip" : "ServerListSubscribeMissingPackagesTooltipNoSteam"),
Enabled = SteamManager.IsInitialized, Enabled = SteamManager.IsInitialized,
@@ -313,50 +330,11 @@ namespace Barotrauma.Networking
} }
} }
// Spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform), style: null);
// Right column ------------------------------------------------------------------------------
var rightColumnBackground = new GUIFrame(new RectTransform(new Vector2(0.2f, 1.0f), columnContainer.RectTransform), style: null)
{
Color = Color.Black * 0.25f
};
var rightColumn = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 1.0f), rightColumnBackground.RectTransform, Anchor.Center));
// playstyle tags -----------------------------------------------------------------------------
var playStyleTags = GetPlayStyleTags();
foreach (string tag in playStyleTags)
{
if (!GameMain.ServerListScreen.PlayStyleIcons.ContainsKey(tag)) { continue; }
new GUIImage(new RectTransform(Vector2.One, rightColumn.RectTransform, scaleBasis: ScaleBasis.BothWidth),
GameMain.ServerListScreen.PlayStyleIcons[tag], scaleToFit: true)
{
ToolTip = TextManager.Get("servertagdescription." + tag),
Color = GameMain.ServerListScreen.PlayStyleIconColors[tag]
};
}
/*var playerCount = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListPlayers"));
new GUITextBlock(new RectTransform(Vector2.One, playerCount.RectTransform), PlayerCount + "/" + MaxPlayers, textAlignment: Alignment.Right);
new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), "Round running")
{
Selected = GameStarted,
CanBeFocused = false
};*/
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
foreach (GUIComponent c in leftColumn.Children) foreach (GUIComponent c in content.Children)
{ {
if (c is GUITextBlock textBlock) textBlock.Padding = Vector4.Zero; if (c is GUITextBlock textBlock) { textBlock.Padding = Vector4.Zero; }
} }
} }

Some files were not shown because too many files have changed in this diff Show More