v0.13.0.11

This commit is contained in:
Joonas Rikkonen
2021-04-22 17:33:08 +03:00
parent 0697d7fc64
commit 8bb31f2893
391 changed files with 17271 additions and 5949 deletions
@@ -22,47 +22,47 @@ namespace Barotrauma
var underwaterExplosion = GameMain.ParticleManager.CreateParticle("underwaterexplosion", worldPosition, Vector2.Zero, 0.0f, hull);
if (underwaterExplosion != null)
{
underwaterExplosion.Size *= MathHelper.Clamp(attack.Range / 150.0f, 0.5f, 10.0f);
underwaterExplosion.Size *= MathHelper.Clamp(Attack.Range / 150.0f, 0.5f, 10.0f);
underwaterExplosion.StartDelay = 0.0f;
}
}
for (int i = 0; i < attack.Range * 0.1f; i++)
for (int i = 0; i < Attack.Range * 0.1f; i++)
{
if (!underwater)
{
float particleSpeed = Rand.Range(0.0f, 1.0f);
particleSpeed = particleSpeed * particleSpeed * attack.Range;
particleSpeed = particleSpeed * particleSpeed * Attack.Range;
if (flames)
{
float particleScale = MathHelper.Clamp(attack.Range * 0.0025f, 0.5f, 2.0f);
float particleScale = MathHelper.Clamp(Attack.Range * 0.0025f, 0.5f, 2.0f);
var flameParticle = GameMain.ParticleManager.CreateParticle("explosionfire",
ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, attack.Range))), hull),
ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, Attack.Range))), hull),
Rand.Vector(Rand.Range(0.0f, particleSpeed)), 0.0f, hull);
if (flameParticle != null) flameParticle.Size *= particleScale;
}
if (smoke)
{
GameMain.ParticleManager.CreateParticle(Rand.Range(0.0f, 1.0f) < 0.5f ? "explosionsmoke" : "smoke",
ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, attack.Range))), hull),
ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, Attack.Range))), hull),
Rand.Vector(Rand.Range(0.0f, particleSpeed)), 0.0f, hull);
}
}
else if (underwaterBubble)
{
Vector2 bubblePos = Rand.Vector(Rand.Range(0.0f, attack.Range * 0.5f));
Vector2 bubblePos = Rand.Vector(Rand.Range(0.0f, Attack.Range * 0.5f));
GameMain.ParticleManager.CreateParticle("risingbubbles", worldPosition + bubblePos,
Vector2.Zero, 0.0f, hull);
if (i < attack.Range * 0.02f)
if (i < Attack.Range * 0.02f)
{
var underwaterExplosion = GameMain.ParticleManager.CreateParticle("underwaterexplosion", worldPosition + bubblePos,
Vector2.Zero, 0.0f, hull);
if (underwaterExplosion != null)
{
underwaterExplosion.Size *= MathHelper.Clamp(attack.Range / 300.0f, 0.5f, 2.0f) * Rand.Range(0.8f, 1.2f);
underwaterExplosion.Size *= MathHelper.Clamp(Attack.Range / 300.0f, 0.5f, 2.0f) * Rand.Range(0.8f, 1.2f);
}
}
@@ -77,7 +77,7 @@ namespace Barotrauma
if (flash)
{
float displayRange = flashRange.HasValue ? flashRange.Value : attack.Range;
float displayRange = flashRange.HasValue ? flashRange.Value : Attack.Range;
if (displayRange < 0.1f) { return; }
var light = new LightSource(worldPosition, displayRange, Color.LightYellow, null);
CoroutineManager.StartCoroutine(DimLight(light));
@@ -90,7 +90,10 @@ namespace Barotrauma
private GUIComponent CreateEditingHUD(bool inGame = false)
{
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)
{
CanTakeKeyBoardFocus = false
};
new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true, titleFont: GUI.LargeFont);
PositionEditingHUD();
@@ -302,7 +302,7 @@ namespace Barotrauma
{
GUI.DrawLine(spriteBatch, new Vector2(edge.Point1.X + cell.Translation.X, -(edge.Point1.Y + cell.Translation.Y)),
new Vector2(edge.Point2.X + cell.Translation.X, -(edge.Point2.Y + cell.Translation.Y)), edge.NextToCave ? Color.Red : (cell.Body == null ? Color.Cyan * 0.5f : (edge.IsSolid ? Color.White : Color.Gray)),
width: edge.NextToCave ? 8 :1);
width: edge.NextToCave ? 8 : 1);
}
foreach (Vector2 point in cell.BodyVertices)
@@ -322,6 +322,11 @@ namespace Barotrauma
}
}*/
foreach (var abyssIsland in level.AbyssIslands)
{
GUI.DrawRectangle(spriteBatch, new Vector2(abyssIsland.Area.X, -abyssIsland.Area.Y - abyssIsland.Area.Height), abyssIsland.Area.Size.ToVector2(), Color.Cyan, thickness: 5);
}
foreach (var ruin in level.Ruins)
{
ruin.DebugDraw(spriteBatch);
@@ -48,6 +48,7 @@ namespace Barotrauma.Lights
private readonly List<LightSource> lights;
public bool LosEnabled = true;
public float LosAlpha = 1f;
public LosMode LosMode = LosMode.Transparent;
public bool LightingEnabled = true;
@@ -497,7 +498,6 @@ namespace Barotrauma.Lights
graphics.SetRenderTarget(LosTexture);
spriteBatch.Begin(SpriteSortMode.Deferred, transformMatrix: cam.Transform * Matrix.CreateScale(new Vector3(GameMain.Config.LightMapScale, GameMain.Config.LightMapScale, 1.0f)));
if (ObstructVision)
{
graphics.Clear(Color.Black);
@@ -507,16 +507,17 @@ namespace Barotrauma.Lights
float rotation = MathUtils.VectorToAngle(losOffset);
Vector2 scale = new Vector2(
MathHelper.Clamp(losOffset.Length() / 256.0f, 2.0f, 5.0f), 2.0f);
MathHelper.Clamp(losOffset.Length() / 256.0f, 4.0f, 5.0f), 3.0f);
spriteBatch.Begin(SpriteSortMode.Deferred, transformMatrix: cam.Transform * Matrix.CreateScale(new Vector3(GameMain.Config.LightMapScale, GameMain.Config.LightMapScale, 1.0f)));
spriteBatch.Draw(visionCircle, new Vector2(ViewTarget.WorldPosition.X, -ViewTarget.WorldPosition.Y), null, Color.White, rotation,
new Vector2(visionCircle.Width * 0.2f, visionCircle.Height / 2), scale, SpriteEffects.None, 0.0f);
spriteBatch.End();
}
else
{
graphics.Clear(Color.White);
}
spriteBatch.End();
//--------------------------------------
@@ -2,8 +2,8 @@
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.Xna.Framework.Input;
namespace Barotrauma
{
@@ -63,7 +63,19 @@ namespace Barotrauma
private Sprite[,] mapTiles;
private bool[,] tileDiscovered;
private Pair<Rectangle, string> connectionTooltip;
private float connectionHighlightState;
private (Rectangle targetArea, string tip)? tooltip;
private string sanitizedTooltip;
private List<RichTextData> tooltipRichTextData;
private string prevTooltip;
private (SubmarineInfo pendingSub, float realWorldCrushDepth) pendingSubInfo;
/*private (Rectangle targetArea, string tip)? connectionTooltip;
private string sanitizedConnectionTooltip;
private List<RichTextData> connectionTooltipRichTextData;
private string prevConnectionTooltip;*/
#if DEBUG
private GUIComponent editor;
@@ -93,13 +105,6 @@ namespace Barotrauma
};
}
#endif
public Location CurrentDisplayLocation
{
get
{
return GameMain.GameSession.Campaign.CurrentDisplayLocation;
}
}
partial void InitProjectSpecific()
{
@@ -120,7 +125,6 @@ namespace Barotrauma
DrawOffset = -CurrentLocation.MapPosition;
}
Vector2 tileSize = generationParams.MapTiles.Values.First().First().size * generationParams.MapTileScale;
int tilesX = (int)Math.Ceiling(Width / tileSize.X);
int tilesY = (int)Math.Ceiling(Height / tileSize.Y);
@@ -227,8 +231,8 @@ namespace Barotrauma
if (change.Messages.Any())
{
string msg = change.Messages[Rand.Range(0, change.Messages.Count)]
.Replace("[previousname]", prevName)
.Replace("[name]", location.Name);
.Replace("[previousname]", $"‖color:gui.orange‖{prevName}‖end‖")
.Replace("[name]", $"‖color:gui.orange‖{location.Name}‖end‖");
location.LastTypeChangeMessage = msg;
if (GameMain.Client != null)
{
@@ -254,28 +258,52 @@ namespace Barotrauma
{
Rectangle rect = mapContainer.Rect;
if (CurrentDisplayLocation != null)
var currentDisplayLocation = GameMain.GameSession?.Campaign?.GetCurrentDisplayLocation();
if (currentDisplayLocation != null)
{
if (!CurrentDisplayLocation.Discovered)
if (!currentDisplayLocation.Discovered)
{
RemoveFogOfWar(CurrentDisplayLocation);
CurrentDisplayLocation.Discovered = true;
if (CurrentDisplayLocation.MapPosition.X > furthestDiscoveredLocation.MapPosition.X)
RemoveFogOfWar(currentDisplayLocation);
currentDisplayLocation.Discovered = true;
if (currentDisplayLocation.MapPosition.X > furthestDiscoveredLocation.MapPosition.X)
{
furthestDiscoveredLocation = CurrentDisplayLocation;
furthestDiscoveredLocation = currentDisplayLocation;
}
}
}
currLocationIndicatorPos = Vector2.Lerp(currLocationIndicatorPos, CurrentDisplayLocation.MapPosition, deltaTime);
Vector2 currentPosition = currentDisplayLocation.MapPosition;
if (Level.Loaded?.Type == LevelData.LevelType.LocationConnection && Level.Loaded.StartLocation != null && Level.Loaded.EndLocation != null)
{
Vector2 startPos = currentDisplayLocation == Level.Loaded.StartLocation ? Level.Loaded.StartLocation.MapPosition : Level.Loaded.EndLocation.MapPosition;
int moveDir = currentDisplayLocation == Level.Loaded.StartLocation ? 1 : -1;
Vector2 diff = Level.Loaded.EndLocation.MapPosition - Level.Loaded.StartLocation.MapPosition;
currentPosition = startPos +
Vector2.Normalize(diff) * Math.Min(100, diff.Length() * 0.2f) * moveDir;
}
else
{
currentPosition += Vector2.UnitY * 35;
}
currLocationIndicatorPos = Vector2.Lerp(currLocationIndicatorPos, currentPosition, deltaTime);
#if DEBUG
if (GameMain.DebugDraw)
{
if (editor == null) CreateEditor();
editor.AddToGUIUpdateList(order: 1);
}
if (PlayerInput.KeyHit(Keys.Space))
{
Radiation?.OnStep();
}
#endif
Radiation?.MapUpdate(deltaTime);
if (mapAnimQueue.Count > 0)
{
hudVisibility = Math.Max(hudVisibility - deltaTime, 0.0f);
@@ -299,15 +327,16 @@ namespace Barotrauma
for (int i = 0; i < Locations.Count; i++)
{
Location location = Locations[i];
if (IsInFogOfWar(location) && !(CurrentDisplayLocation?.Connections.Any(c => c.Locations.Contains(location)) ?? false) && !GameMain.DebugDraw) { continue; }
if (IsInFogOfWar(location) && !(currentDisplayLocation?.Connections.Any(c => c.Locations.Contains(location)) ?? false) && !GameMain.DebugDraw) { continue; }
Vector2 pos = rectCenter + (location.MapPosition + viewOffset) * zoom;
if (!rect.Contains(pos)) { continue; }
float iconScale = generationParams.LocationIconSize / location.Type.Sprite.size.X;
if (location == CurrentDisplayLocation) { iconScale *= 1.2f; }
Sprite locationSprite = location.IsCriticallyRadiated() ? location.Type.RadiationSprite ?? location.Type.Sprite : location.Type.Sprite;
float iconScale = generationParams.LocationIconSize / locationSprite.size.X;
if (location == currentDisplayLocation) { iconScale *= 1.2f; }
Rectangle drawRect = location.Type.Sprite.SourceRect;
Rectangle drawRect = locationSprite.SourceRect;
drawRect.Width = (int)(drawRect.Width * iconScale * zoom * 1.4f);
drawRect.Height = (int)(drawRect.Height * iconScale * zoom * 1.4f);
drawRect.X = (int)pos.X - drawRect.Width / 2;
@@ -324,6 +353,15 @@ namespace Barotrauma
}
}
if (SelectedConnection != null)
{
connectionHighlightState = Math.Min(connectionHighlightState + deltaTime, 1.0f);
}
else
{
connectionHighlightState = 0.0f;
}
if (GUI.KeyboardDispatcher.Subscriber == null)
{
float moveSpeed = 1000.0f;
@@ -336,21 +374,27 @@ namespace Barotrauma
}
targetZoom = MathHelper.Clamp(targetZoom, generationParams.MinZoom, generationParams.MaxZoom);
zoom = MathHelper.Lerp(zoom, targetZoom, 0.1f);
zoom = MathHelper.Lerp(zoom, targetZoom * GUI.Scale, 0.1f);
if (GUI.MouseOn == mapContainer)
{
foreach (LocationConnection connection in Connections)
{
if (HighlightedLocation != CurrentDisplayLocation &&
connection.Locations.Contains(HighlightedLocation) && connection.Locations.Contains(CurrentDisplayLocation))
if (HighlightedLocation != currentDisplayLocation &&
connection.Locations.Contains(HighlightedLocation) &&
connection.Locations.Contains(currentDisplayLocation))
{
if (PlayerInput.PrimaryMouseButtonClicked() &&
SelectedLocation != HighlightedLocation && HighlightedLocation != null)
{
//clients aren't allowed to select the location without a permission
if ((GameMain.GameSession?.GameMode as CampaignMode)?.AllowedToManageCampaign() ?? false)
if (connection.Locked)
{
new GUIMessageBox(string.Empty, TextManager.Get("LockedPathTooltip"));
}
//clients aren't allowed to select the location without a permission
else if ((GameMain.GameSession?.GameMode as CampaignMode)?.AllowedToManageCampaign() ?? false)
{
connectionHighlightState = 0.0f;
SelectedConnection = connection;
SelectedLocation = HighlightedLocation;
@@ -371,13 +415,13 @@ namespace Barotrauma
{
if (PlayerInput.DoubleClicked() && HighlightedLocation != null)
{
var passedConnection = CurrentDisplayLocation.Connections.Find(c => c.OtherLocation(CurrentDisplayLocation) == HighlightedLocation);
var passedConnection = currentDisplayLocation.Connections.Find(c => c.OtherLocation(currentDisplayLocation) == HighlightedLocation);
if (passedConnection != null)
{
passedConnection.Passed = true;
}
Location prevLocation = CurrentDisplayLocation;
Location prevLocation = currentDisplayLocation;
CurrentLocation = HighlightedLocation;
Level.Loaded.DebugSetStartLocation(CurrentLocation);
Level.Loaded.DebugSetEndLocation(null);
@@ -389,6 +433,7 @@ namespace Barotrauma
{
CurrentLocation.CreateStore();
ProgressWorld();
Radiation?.OnStep(1);
}
else
{
@@ -412,12 +457,13 @@ namespace Barotrauma
public void Draw(SpriteBatch spriteBatch, GUICustomComponent mapContainer)
{
connectionTooltip = null;
tooltip = null;
var currentDisplayLocation = GameMain.GameSession?.Campaign?.GetCurrentDisplayLocation();
Rectangle rect = mapContainer.Rect;
Vector2 viewSize = new Vector2(rect.Width / zoom, rect.Height / zoom);
Vector2 edgeBuffer = rect.Size.ToVector2() / 2;
Vector2 edgeBuffer = new Vector2(rect.Width * 0.05f);
DrawOffset.X = MathHelper.Clamp(DrawOffset.X, -Width - edgeBuffer.X + viewSize.X / 2.0f, edgeBuffer.X - viewSize.X / 2.0f);
DrawOffset.Y = MathHelper.Clamp(DrawOffset.Y, -Height - edgeBuffer.Y + viewSize.Y / 2.0f, edgeBuffer.Y - viewSize.Y / 2.0f);
@@ -481,30 +527,16 @@ namespace Barotrauma
}
float rawNoiseScale = 1.0f + PerlinNoise.GetPerlin((int)(Timing.TotalTime * 1 - 1), (int)(Timing.TotalTime * 1 - 1));
cameraNoiseStrength = PerlinNoise.GetPerlin((int)(Timing.TotalTime * 1 - 1), (int)(Timing.TotalTime * 1 - 1));
DrawNoise(spriteBatch, rect, rawNoiseScale);
noiseOverlay.DrawTiled(spriteBatch, rect.Location.ToVector2(), rect.Size.ToVector2(),
startOffset: new Vector2(Rand.Range(0.0f, noiseOverlay.SourceRect.Width), Rand.Range(0.0f, noiseOverlay.SourceRect.Height)),
color : Color.White * cameraNoiseStrength * 0.1f,
textureScale: Vector2.One * rawNoiseScale);
Radiation?.Draw(spriteBatch, rect, zoom);
noiseOverlay.DrawTiled(spriteBatch, rect.Location.ToVector2(), rect.Size.ToVector2(),
startOffset: new Vector2(Rand.Range(0.0f, noiseOverlay.SourceRect.Width), Rand.Range(0.0f, noiseOverlay.SourceRect.Height)),
color: new Color(20,20,20,50),
textureScale: Vector2.One * rawNoiseScale * 2);
noiseOverlay.DrawTiled(spriteBatch, Vector2.Zero, new Vector2(GameMain.GraphicsWidth, GameMain.GraphicsHeight),
startOffset: new Vector2(Rand.Range(0.0f, noiseOverlay.SourceRect.Width), Rand.Range(0.0f, noiseOverlay.SourceRect.Height)),
color: Color.White * cameraNoiseStrength * 0.1f,
textureScale: Vector2.One * noiseScale);
Pair<Rectangle, string> tooltip = null;
if (generationParams.ShowLocations)
{
foreach (LocationConnection connection in Connections)
{
if (IsInFogOfWar(connection.Locations[0]) && IsInFogOfWar(connection.Locations[1])) { continue; }
DrawConnection(spriteBatch, connection, rect, viewOffset);
DrawConnection(spriteBatch, connection, rect, viewOffset, currentDisplayLocation);
}
for (int i = 0; i < Locations.Count; i++)
@@ -512,19 +544,48 @@ namespace Barotrauma
Location location = Locations[i];
if (IsInFogOfWar(location)) { continue; }
Vector2 pos = rectCenter + (location.MapPosition + viewOffset) * zoom;
Rectangle drawRect = location.Type.Sprite.SourceRect;
Sprite locationSprite = location.IsCriticallyRadiated() ? location.Type.RadiationSprite ?? location.Type.Sprite : location.Type.Sprite;
Rectangle drawRect = locationSprite.SourceRect;
drawRect.X = (int)pos.X - drawRect.Width / 2;
drawRect.Y = (int)pos.Y - drawRect.Width / 2;
if (!rect.Intersects(drawRect)) { continue; }
if (location == CurrentDisplayLocation )
Color color = location.Type.SpriteColor;
if (!location.Discovered) { color = Color.White; }
if (location.Connections.Find(c => c.Locations.Contains(currentDisplayLocation)) == null)
{
color *= 0.5f;
}
float iconScale = location == currentDisplayLocation ? 1.2f : 1.0f;
if (location == HighlightedLocation)
{
iconScale *= 1.2f;
}
locationSprite.Draw(spriteBatch, pos, color,
scale: generationParams.LocationIconSize / locationSprite.size.X * iconScale * zoom);
if (location == currentDisplayLocation)
{
if (SelectedLocation != null)
{
Vector2 dir = Vector2.Normalize(SelectedLocation.MapPosition - currLocationIndicatorPos);
GUI.Arrow.Draw(spriteBatch,
rectCenter + (currLocationIndicatorPos + viewOffset) * zoom + dir * generationParams.LocationIconSize * 0.6f * zoom,
generationParams.IndicatorColor,
GUI.Arrow.Origin,
rotate: MathUtils.VectorToAngle(dir) + MathHelper.PiOver2,
new Vector2(0.5f, 1.0f) * zoom);
}
generationParams.CurrentLocationIndicator.Draw(spriteBatch,
rectCenter + (currLocationIndicatorPos + viewOffset) * zoom,
generationParams.IndicatorColor,
generationParams.CurrentLocationIndicator.Origin, 0, Vector2.One * (generationParams.LocationIconSize / generationParams.CurrentLocationIndicator.size.X) * 1.7f * zoom);
generationParams.CurrentLocationIndicator.Origin, 0, Vector2.One * (generationParams.LocationIconSize / generationParams.CurrentLocationIndicator.size.X) * 0.8f * zoom);
}
if (location == SelectedLocation)
@@ -535,31 +596,15 @@ namespace Barotrauma
generationParams.SelectedLocationIndicator.Origin, 0, Vector2.One * (generationParams.LocationIconSize / generationParams.SelectedLocationIndicator.size.X) * 1.7f * zoom);
}
Color color = location.Type.SpriteColor;
if (!location.Discovered) { color = Color.White; }
if (location.Connections.Find(c => c.Locations.Contains(CurrentDisplayLocation)) == null)
{
color *= 0.5f;
}
float iconScale = location == CurrentDisplayLocation ? 1.2f : 1.0f;
if (location == HighlightedLocation)
{
iconScale *= 1.2f;
}
location.Type.Sprite.Draw(spriteBatch, pos, color,
scale: generationParams.LocationIconSize / location.Type.Sprite.size.X * iconScale * zoom);
if (location.TimeSinceLastTypeChange < 1 && !string.IsNullOrEmpty(location.LastTypeChangeMessage) && generationParams.TypeChangeIcon != null)
{
Vector2 typeChangeIconPos = pos + new Vector2(1.35f, -0.35f) * generationParams.LocationIconSize * 0.5f * zoom;
float typeChangeIconScale = 18.0f / generationParams.TypeChangeIcon.SourceRect.Width;
generationParams.TypeChangeIcon.Draw(spriteBatch, typeChangeIconPos, GUI.Style.Red, scale: typeChangeIconScale * zoom);
if (Vector2.Distance(PlayerInput.MousePosition, typeChangeIconPos) < generationParams.TypeChangeIcon.SourceRect.Width * zoom)
if (Vector2.Distance(PlayerInput.MousePosition, typeChangeIconPos) < generationParams.TypeChangeIcon.SourceRect.Width * zoom &&
(tooltip == null || IsPreferredTooltip(typeChangeIconPos)))
{
tooltip = new Pair<Rectangle, string>(
new Rectangle(typeChangeIconPos.ToPoint(), new Point(30)),
location.LastTypeChangeMessage);
tooltip = (new Rectangle(typeChangeIconPos.ToPoint(), new Point(30)), location.LastTypeChangeMessage);
}
}
if (location != CurrentLocation && CurrentLocation.AvailableMissions.Any(m => m.Locations.Contains(location)) && generationParams.MissionIcon != null)
@@ -567,16 +612,14 @@ namespace Barotrauma
Vector2 missionIconPos = pos + new Vector2(1.35f, 0.35f) * generationParams.LocationIconSize * 0.5f * zoom;
float missionIconScale = 18.0f / generationParams.MissionIcon.SourceRect.Width;
generationParams.MissionIcon.Draw(spriteBatch, missionIconPos, generationParams.IndicatorColor, scale: missionIconScale * zoom);
if (Vector2.Distance(PlayerInput.MousePosition, missionIconPos) < generationParams.MissionIcon.SourceRect.Width * zoom)
if (Vector2.Distance(PlayerInput.MousePosition, missionIconPos) < generationParams.MissionIcon.SourceRect.Width * zoom && IsPreferredTooltip(missionIconPos))
{
var availableMissions = CurrentLocation.AvailableMissions.Where(m => m.Locations.Contains(location));
tooltip = new Pair<Rectangle, string>(
new Rectangle(missionIconPos.ToPoint(), new Point(30)),
TextManager.Get("mission") + '\n'+ string.Join('\n', availableMissions.Select(m => "- " + m.Name)));
tooltip = (new Rectangle(missionIconPos.ToPoint(), new Point(30)), TextManager.Get("mission") + '\n'+ string.Join('\n', availableMissions.Select(m => "- " + m.Name)));
}
}
if (GameMain.DebugDraw && location == HighlightedLocation && (!location.Discovered || !location.Type.HasOutpost))
if (GameMain.DebugDraw && location == HighlightedLocation && (!location.Discovered || !location.HasOutpost()))
{
if (location.Reputation != null)
{
@@ -603,12 +646,27 @@ namespace Barotrauma
DrawDecorativeHUD(spriteBatch, rect);
if (HighlightedLocation != null)
bool drawRadiationTooltip = true;
if (tooltip != null)
{
if (tooltip.Value.tip != prevTooltip)
{
prevTooltip = tooltip.Value.tip;
tooltipRichTextData = RichTextData.GetRichTextData(tooltip.Value.tip, out sanitizedTooltip);
}
GUIComponent.DrawToolTip(spriteBatch, sanitizedTooltip, tooltip.Value.targetArea, tooltipRichTextData);
drawRadiationTooltip = false;
}
else if (HighlightedLocation != null)
{
drawRadiationTooltip = false;
Vector2 pos = rectCenter + (HighlightedLocation.MapPosition + viewOffset) * zoom;
pos.X += 50 * zoom;
pos.X = (int)pos.X;
pos.Y = (int)pos.Y;
Vector2 nameSize = GUI.LargeFont.MeasureString(HighlightedLocation.Name);
Vector2 typeSize = GUI.Font.MeasureString(HighlightedLocation.Type.Name);
Vector2 typeSize = string.IsNullOrEmpty(HighlightedLocation.Type.Name) ? Vector2.Zero : GUI.Font.MeasureString(HighlightedLocation.Type.Name);
Vector2 size = new Vector2(Math.Max(nameSize.X, typeSize.X), nameSize.Y + typeSize.Y);
bool showReputation = hudVisibility > 0.0f && HighlightedLocation.Discovered && HighlightedLocation.Type.HasOutpost && HighlightedLocation.Reputation != null;
string repLabelText = null, repValueText = null;
@@ -616,15 +674,14 @@ namespace Barotrauma
if (showReputation)
{
repLabelText = TextManager.Get("reputation");
repLabelSize = GUI.Font.MeasureString(repLabelText);
size.X = Math.Max(size.X, repLabelSize.X);
repBarSize = new Vector2(Math.Max(0.75f * size.X, 100), repLabelSize.Y);
size.X = Math.Max(size.X, (4.0f / 3.0f) * repBarSize.X);
size.Y += 2 * repLabelSize.Y + 4 + repBarSize.Y;
repValueText = ((int)HighlightedLocation.Reputation.Value).ToString();
repLabelSize = GUI.Font.MeasureString(repLabelText);
repBarSize = new Vector2(GUI.IntScale(200), repLabelSize.Y);
size.Y += 2 * repLabelSize.Y + GUI.IntScale(5) + repBarSize.Y;
repValueText = HighlightedLocation.Reputation.GetFormattedReputationText(addColorTags: false);
size.X = Math.Max(size.X, repBarSize.X + GUI.Font.MeasureString(repValueText).X + GUI.IntScale(10));
}
GUI.Style.GetComponentStyle("OuterGlow").Sprites[GUIComponent.ComponentState.None][0].Draw(
spriteBatch, new Rectangle((int)(pos.X - 60 * GUI.Scale), (int)(pos.Y - size.Y), (int)(size.X + 120 * GUI.Scale), (int)(size.Y * 2.2f)), Color.Black * hudVisibility);
spriteBatch, new Rectangle((int)(pos.X - 60 * GUI.Scale), (int)(pos.Y - size.Y), (int)(size.X + 120 * GUI.Scale), (int)(size.Y * 2.2f)), Color.Black * hudVisibility);
var topLeftPos = pos - new Vector2(0.0f, size.Y / 2);
GUI.DrawString(spriteBatch, topLeftPos, HighlightedLocation.Name, GUI.Style.TextColor * hudVisibility * 1.5f, font: GUI.LargeFont);
topLeftPos += new Vector2(0.0f, nameSize.Y);
@@ -633,26 +690,51 @@ namespace Barotrauma
{
topLeftPos += new Vector2(0.0f, typeSize.Y + repLabelSize.Y);
GUI.DrawString(spriteBatch, topLeftPos, repLabelText, GUI.Style.TextColor * hudVisibility * 1.5f);
topLeftPos += new Vector2(0.0f, repLabelSize.Y + 4);
topLeftPos += new Vector2(0.0f, repLabelSize.Y + GUI.IntScale(10));
Rectangle repBarRect = new Rectangle(new Point((int)topLeftPos.X, (int)topLeftPos.Y), new Point((int)repBarSize.X, (int)repBarSize.Y));
RoundSummary.DrawReputationBar(spriteBatch, repBarRect, HighlightedLocation.Reputation.NormalizedValue);
GUI.DrawString(spriteBatch, new Vector2(repBarRect.Right + 4, repBarRect.Top), repValueText, GUI.Style.TextColor);
GUI.DrawString(spriteBatch, new Vector2(repBarRect.Right + GUI.IntScale(5), repBarRect.Top), repValueText, Reputation.GetReputationColor(HighlightedLocation.Reputation.NormalizedValue));
}
}
if (tooltip != null)
if (drawRadiationTooltip)
{
GUIComponent.DrawToolTip(spriteBatch, tooltip.Second, tooltip.First);
}
if (connectionTooltip != null)
{
GUIComponent.DrawToolTip(spriteBatch, connectionTooltip.Second, connectionTooltip.First);
Radiation?.DrawFront(spriteBatch);
}
spriteBatch.End();
GameMain.Instance.GraphicsDevice.ScissorRectangle = prevScissorRect;
spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState, rasterizerState: GameMain.ScissorTestEnable);
}
private void DrawConnection(SpriteBatch spriteBatch, LocationConnection connection, Rectangle viewArea, Vector2 viewOffset, Color? overrideColor = null)
public static void DrawNoise(SpriteBatch spriteBatch, Rectangle rect, float strength)
{
noiseOverlay ??= new Sprite("Content/UI/noise.png", Vector2.Zero);
float noiseT = (float)(Timing.TotalTime * 0.01f);
float noiseScale = (float)PerlinNoise.CalculatePerlin(noiseT * 5.0f, noiseT * 2.0f, 0) * 5.0f;
float rawNoiseScale = 1.0f + GetPerlinNoise();
noiseOverlay.DrawTiled(spriteBatch, rect.Location.ToVector2(), rect.Size.ToVector2(),
startOffset: new Vector2(Rand.Range(0.0f, noiseOverlay.SourceRect.Width), Rand.Range(0.0f, noiseOverlay.SourceRect.Height)),
color : Color.White * strength * 0.1f,
textureScale: Vector2.One * rawNoiseScale);
noiseOverlay.DrawTiled(spriteBatch, rect.Location.ToVector2(), rect.Size.ToVector2(),
startOffset: new Vector2(Rand.Range(0.0f, noiseOverlay.SourceRect.Width), Rand.Range(0.0f, noiseOverlay.SourceRect.Height)),
color: new Color(20,20,20,50),
textureScale: Vector2.One * rawNoiseScale * 2);
noiseOverlay.DrawTiled(spriteBatch, Vector2.Zero, new Vector2(GameMain.GraphicsWidth, GameMain.GraphicsHeight),
startOffset: new Vector2(Rand.Range(0.0f, noiseOverlay.SourceRect.Width), Rand.Range(0.0f, noiseOverlay.SourceRect.Height)),
color: Color.White * strength * 0.1f,
textureScale: Vector2.One * noiseScale);
}
private static float GetPerlinNoise() => PerlinNoise.GetPerlin((int)(Timing.TotalTime * 1 - 1), (int)(Timing.TotalTime * 1 - 1));
private void DrawConnection(SpriteBatch spriteBatch, LocationConnection connection, Rectangle viewArea, Vector2 viewOffset, Location currentDisplayLocation, Color? overrideColor = null)
{
Color connectionColor;
if (GameMain.DebugDraw)
@@ -674,19 +756,22 @@ namespace Barotrauma
int width = (int)(generationParams.LocationConnectionWidth * zoom);
//current level
if (Level.Loaded?.LevelData == connection.LevelData)
{
connectionColor = generationParams.HighlightedConnectionColor;
width = (int)(width * 1.5f);
}
if (SelectedLocation != CurrentDisplayLocation &&
(connection.Locations.Contains(SelectedLocation) && connection.Locations.Contains(CurrentDisplayLocation)))
//selected connection
if (SelectedLocation != currentDisplayLocation &&
connection.Locations.Contains(SelectedLocation) && connection.Locations.Contains(currentDisplayLocation))
{
connectionColor = generationParams.HighlightedConnectionColor;
width *= 2;
}
else if (HighlightedLocation != CurrentDisplayLocation &&
(connection.Locations.Contains(HighlightedLocation) && connection.Locations.Contains(CurrentDisplayLocation)))
//highlighted connection
else if (HighlightedLocation != currentDisplayLocation &&
connection.Locations.Contains(HighlightedLocation) && connection.Locations.Contains(currentDisplayLocation))
{
connectionColor = generationParams.HighlightedConnectionColor;
width *= 2;
@@ -741,16 +826,52 @@ namespace Barotrauma
}
float dist = Vector2.Distance(start, end);
var connectionSprite = connection.Passed ? generationParams.PassedConnectionSprite : generationParams.ConnectionSprite;
Color segmentColor = connectionColor;
int segmentWidth = width;
if (connection == SelectedConnection)
{
float t = (i - startIndex) / (float)(endIndex - startIndex - 1);
if (currentDisplayLocation == connection.Locations[1]) { t = 1.0f - t; }
if (t > connectionHighlightState)
{
segmentWidth /= 2;
segmentColor = connection.Passed ? generationParams.ConnectionColor : generationParams.UnvisitedConnectionColor;
}
else
{
}
}
spriteBatch.Draw(connectionSprite.Texture,
new Rectangle((int)start.X, (int)start.Y, (int)(dist - 1 * zoom), width),
connectionSprite.SourceRect, connectionColor * a, MathUtils.VectorToAngle(end - start),
new Rectangle((int)start.X, (int)start.Y, (int)(dist - 1 * zoom), segmentWidth),
connectionSprite.SourceRect, segmentColor * a,
MathUtils.VectorToAngle(end - start),
new Vector2(0, connectionSprite.size.Y / 2), SpriteEffects.None, 0.01f);
}
int iconCount = 0, iconIndex = 0;
if (connectionStart.HasValue && connectionEnd.HasValue)
{
GUIComponentStyle crushDepthWarningIconStyle = null;
{
if (connection.LevelData.HasBeaconStation) { iconCount++; }
if (connection.LevelData.HasHuntingGrounds) { iconCount++; }
if (connection.Locked) { iconCount++; }
string tooltip = null;
var subCrushDepth = Submarine.MainSub?.RealWorldCrushDepth ?? Level.DefaultRealWorldCrushDepth;
float subCrushDepth = Level.DefaultRealWorldCrushDepth;
var currentOrPendingSub = SubmarineSelection.CurrentOrPendingSubmarine();
if (Submarine.MainSub != null && Submarine.MainSub.Info == currentOrPendingSub)
{
subCrushDepth = Submarine.MainSub.RealWorldCrushDepth;
}
else if (currentOrPendingSub != null)
{
if (pendingSubInfo.pendingSub != currentOrPendingSub)
{
// Store the real world crush depth for the pending sub so that we don't have to calculate it again every time
pendingSubInfo = (currentOrPendingSub, currentOrPendingSub.GetRealWorldCrushDepth());
}
subCrushDepth = pendingSubInfo.realWorldCrushDepth;
}
if (GameMain.GameSession?.Campaign?.UpgradeManager != null)
{
var hullUpgradePrefab = UpgradePrefab.Find("increasewallhealth");
@@ -769,38 +890,71 @@ namespace Barotrauma
}
}
string crushDepthWarningIconStyle = null;
if (connection.LevelData.InitialDepth * Physics.DisplayToRealWorldRatio > subCrushDepth)
{
crushDepthWarningIconStyle = GUI.Style.GetComponentStyle("CrushDepthWarningHighIcon");
iconCount++;
crushDepthWarningIconStyle = "CrushDepthWarningHighIcon";
tooltip = "crushdepthwarninghigh";
}
else if ((connection.LevelData.InitialDepth + connection.LevelData.Size.Y) * Physics.DisplayToRealWorldRatio > subCrushDepth)
{
crushDepthWarningIconStyle = GUI.Style.GetComponentStyle("CrushDepthWarningLowIcon");
iconCount++;
crushDepthWarningIconStyle = "CrushDepthWarningLowIcon";
tooltip = "crushdepthwarninglow";
}
if (connection.LevelData.HasBeaconStation)
{
var beaconStationIconStyle = connection.LevelData.IsBeaconActive ? "BeaconStationActive" : "BeaconStationInactive";
DrawIcon(beaconStationIconStyle, (int)(28 * zoom), TextManager.Get(connection.LevelData.IsBeaconActive ? "BeaconStationActiveTooltip" : "BeaconStationInactiveTooltip"));
}
if (connection.Locked)
{
var gateLocation = connection.Locations[0].IsGateBetweenBiomes ? connection.Locations[0] : connection.Locations[1];
var unlockEvent =
EventSet.PrefabList.Find(ep => ep.UnlockPathEvent && ep.BiomeIdentifier == gateLocation.LevelData.Biome.Identifier) ??
EventSet.PrefabList.Find(ep => ep.UnlockPathEvent && string.IsNullOrEmpty(ep.BiomeIdentifier));
if (unlockEvent != null)
{
Reputation unlockReputation = CurrentLocation.Reputation;
Faction unlockFaction = null;
if (!string.IsNullOrEmpty(unlockEvent.UnlockPathFaction))
{
unlockFaction = GameMain.GameSession.Campaign.Factions.Find(f => f.Prefab.Identifier.Equals(unlockEvent.UnlockPathFaction, StringComparison.OrdinalIgnoreCase));
unlockReputation = unlockFaction?.Reputation;
}
DrawIcon(
"LockedLocationConnection", (int)(28 * zoom),
TextManager.GetWithVariables(unlockEvent.UnlockPathTooltip ?? "LockedPathTooltip",
new string[] { "[requiredreputation]", "[currentreputation]" },
new string[] { Reputation.GetFormattedReputationText(MathUtils.InverseLerp(unlockReputation.MinReputation, unlockReputation.MaxReputation, unlockEvent.UnlockPathReputation), unlockEvent.UnlockPathReputation, addColorTags: true), unlockReputation.GetFormattedReputationText(addColorTags: true) }));
}
else
{
DrawIcon("LockedLocationConnection", (int)(28 * zoom), TextManager.Get("LockedPathTooltip"));
}
}
if (connection.LevelData.HasHuntingGrounds)
{
DrawIcon("HuntingGrounds", (int)(28 * zoom), TextManager.Get("HuntingGroundsTooltip"));
}
if (crushDepthWarningIconStyle != null)
{
Vector2 iconPos = (connectionStart.Value + connectionEnd.Value) / 2;
float iconSize = 32.0f * GUI.Scale;
bool mouseOn = HighlightedLocation == null && Vector2.DistanceSquared(iconPos, PlayerInput.MousePosition) < iconSize * iconSize;
Sprite crushDepthWarningIcon = crushDepthWarningIconStyle.GetDefaultSprite();
crushDepthWarningIcon.Draw(spriteBatch, iconPos,
mouseOn ? crushDepthWarningIconStyle.HoverColor : crushDepthWarningIconStyle.Color,
scale: iconSize / crushDepthWarningIcon.size.X);
if (mouseOn)
{
connectionTooltip = new Pair<Rectangle, string>(
new Rectangle(iconPos.ToPoint(), new Point((int)iconSize)),
TextManager.Get(tooltip)
.Replace("[initialdepth]", ((int)(connection.LevelData.InitialDepth * Physics.DisplayToRealWorldRatio)).ToString())
.Replace("[submarinecrushdepth]", ((int)subCrushDepth).ToString()));
}
DrawIcon(crushDepthWarningIconStyle, (int)(32 * zoom),
TextManager.Get(tooltip)
.Replace("[initialdepth]", $"‖color:gui.orange‖{(int)(connection.LevelData.InitialDepth * Physics.DisplayToRealWorldRatio)}‖end‖")
.Replace("[submarinecrushdepth]", $"‖color:gui.orange‖{(int)subCrushDepth}‖end‖"));
}
}
if (GameMain.DebugDraw && zoom > 1.0f && generationParams.ShowLevelTypeNames)
if (GameMain.DebugDraw && zoom > (1.0f * GUI.Scale) && generationParams.ShowLevelTypeNames)
{
Vector2 center = rectCenter + (connection.CenterPos + viewOffset) * zoom;
if (viewArea.Contains(center) && connection.Biome != null)
@@ -808,6 +962,30 @@ namespace Barotrauma
GUI.DrawString(spriteBatch, center, connection.Biome.Identifier + " (" + connection.Difficulty + ")", Color.White);
}
}
void DrawIcon(string iconStyle, int iconSize, string tooltipText)
{
Vector2 iconPos = (connectionStart.Value + connectionEnd.Value) / 2;
Vector2 iconDiff = Vector2.Normalize(connectionEnd.Value - connectionStart.Value) * iconSize;
iconPos += (iconDiff * -(iconCount - 1) / 2.0f) + iconDiff * iconIndex;
var style = GUI.Style.GetComponentStyle(iconStyle);
bool mouseOn = Vector2.DistanceSquared(iconPos, PlayerInput.MousePosition) < iconSize * iconSize && IsPreferredTooltip(iconPos);
Sprite iconSprite = style.GetDefaultSprite();
iconSprite.Draw(spriteBatch, iconPos, (mouseOn ? style.HoverColor : style.Color) * 0.7f,
scale: iconSize / iconSprite.size.X);
if (mouseOn)
{
tooltip = (new Rectangle((iconPos - Vector2.One * iconSize / 2).ToPoint(), new Point(iconSize)), tooltipText);
}
iconIndex++;
}
}
private bool IsPreferredTooltip(Vector2 tooltipPos)
{
return tooltip == null || Vector2.DistanceSquared(tooltipPos, PlayerInput.MousePosition) < Vector2.DistanceSquared(tooltip.Value.targetArea.Center.ToVector2(), PlayerInput.MousePosition);
}
private float hudVisibility;
@@ -828,8 +1006,8 @@ namespace Barotrauma
private void UpdateMapAnim(MapAnim anim, float deltaTime)
{
//pause animation while there are messageboxes on screen
if (GUIMessageBox.MessageBoxes.Count > 0) return;
//pause animation while there are messageboxes (other than hints) on screen
if (GUIMessageBox.MessageBoxes.Count(c => !(c is GUIMessageBox mb) || mb.MessageBoxType != GUIMessageBox.Type.Hint) > 0) { return; }
if (!string.IsNullOrEmpty(anim.StartMessage))
{
@@ -838,8 +1016,9 @@ namespace Barotrauma
return;
}
if (anim.StartZoom == null) { anim.StartZoom = MathUtils.InverseLerp(generationParams.MinZoom, generationParams.MaxZoom, zoom); }
if (anim.EndZoom == null) { anim.EndZoom = MathUtils.InverseLerp(generationParams.MinZoom, generationParams.MaxZoom, zoom); }
float unscaledZoom = zoom / GUI.Scale;
if (anim.StartZoom == null) { anim.StartZoom = MathUtils.InverseLerp(generationParams.MinZoom, generationParams.MaxZoom, unscaledZoom); }
if (anim.EndZoom == null) { anim.EndZoom = MathUtils.InverseLerp(generationParams.MinZoom, generationParams.MaxZoom, unscaledZoom); }
anim.StartPos = (anim.StartLocation == null) ? -DrawOffset : anim.StartLocation.MapPosition;
@@ -852,7 +1031,8 @@ namespace Barotrauma
zoom =
MathHelper.Lerp(generationParams.MinZoom, generationParams.MaxZoom,
MathHelper.SmoothStep(anim.StartZoom.Value, anim.EndZoom.Value, t));
MathHelper.SmoothStep(anim.StartZoom.Value, anim.EndZoom.Value, t))
* GUI.Scale;
if (anim.Timer >= anim.Duration)
{
@@ -0,0 +1,68 @@
#nullable enable
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Barotrauma
{
internal partial class Radiation
{
private static readonly string radiationTooltip = TextManager.Get("RadiationTooltip");
private static float spriteIndex;
private readonly SpriteSheet sheet = GUI.Style.RadiationAnimSpriteSheet;
private int maxFrames => sheet.FrameCount + 1;
private bool isHovingOver;
public void Draw(SpriteBatch spriteBatch, Rectangle container, float zoom)
{
if (!Enabled) { return; }
UISprite uiSprite = GUI.Style.RadiationSprite;
var (offsetX, offsetY) = Map.DrawOffset * zoom;
var (centerX, centerY) = container.Center.ToVector2();
var (halfSizeX, halfSizeY) = new Vector2(container.Width / 2f, container.Height / 2f) * zoom;
float viewBottom = centerY + Map.Height * zoom;
Vector2 topLeft = new Vector2(centerX + offsetX - halfSizeX, centerY + offsetY - halfSizeY);
Vector2 size = new Vector2((Amount - increasedAmount) * zoom + halfSizeX, viewBottom - topLeft.Y);
if (size.X < 0) { return; }
Vector2 spriteScale = new Vector2(zoom);
uiSprite.Sprite.DrawTiled(spriteBatch, topLeft, size, Params.RadiationAreaColor, Vector2.Zero, textureScale: spriteScale);
Vector2 topRight = topLeft + Vector2.UnitX * size.X;
int index = 0;
for (float i = 0; i <= size.Y; i += sheet.FrameSize.Y / 2f * zoom)
{
bool isEven = ++index % 2 == 0;
Vector2 origin = new Vector2(0.5f, 0) * sheet.FrameSize.X;
// every other sprite's animation is reversed to make it seem more chaotic
int sprite = (int) MathF.Floor(isEven ? spriteIndex : maxFrames - spriteIndex);
sheet.Draw(spriteBatch, sprite, topRight + new Vector2(0, i), Params.RadiationBorderTint, origin, 0f, spriteScale);
}
isHovingOver = container.Contains(PlayerInput.MousePosition) && PlayerInput.MousePosition.X < topLeft.X + size.X;
}
public void DrawFront(SpriteBatch spriteBatch)
{
if (isHovingOver)
{
GUIComponent.DrawToolTip(spriteBatch, radiationTooltip, PlayerInput.MousePosition + new Vector2(18 * GUI.Scale));
}
}
public void MapUpdate(float deltaTime)
{
float spriteStep = Params.BorderAnimationSpeed * deltaTime;
spriteIndex = (spriteIndex + spriteStep) % maxFrames;
if (increasedAmount > 0)
{
increasedAmount -= (lastIncrease / Params.AnimationSpeed) * deltaTime;
}
}
}
}
@@ -20,9 +20,6 @@ namespace Barotrauma
public static Vector2 StartMovingPos => startMovingPos;
// Quick undo/redo for size and movement only. TODO: Remove if we do a more general implementation.
private Memento<Rectangle> rectMemento;
public event Action<Rectangle> Resized;
private static bool resizing;
@@ -65,8 +62,6 @@ namespace Barotrauma
}
}
//protected bool isSelected;
private static bool disableSelect;
public static bool DisableSelect
{
@@ -805,7 +800,7 @@ namespace Barotrauma
}
if (selectionPos != null && selectionPos != Vector2.Zero)
{
GUI.DrawRectangle(spriteBatch, new Vector2(selectionPos.X, -selectionPos.Y), selectionSize, Color.DarkRed, false, 0, (int)Math.Max(1.5f / GameScreen.Selected.Cam.Zoom, 1.0f));
GUI.DrawRectangle(spriteBatch, new Vector2(selectionPos.X, -selectionPos.Y), selectionSize, Color.DarkRed, false, 0, 2f / GameScreen.Selected.Cam.Zoom);
}
}
@@ -24,20 +24,23 @@ namespace Barotrauma
{
get
{
if (!GameMain.SubEditorScreen.ShowThalamus && prefab.Category.HasFlag(MapEntityCategory.Thalamus))
if (GameMain.SubEditorScreen.IsSubcategoryHidden(prefab.Subcategory))
{
return false;
}
return HasBody ? ShowWalls : ShowStructures;
}
}
private string specialTag;
#if DEBUG
[Editable, Serialize("", true)]
#else
[Serialize("", true)]
#endif
public string SpecialTag
{
get { return specialTag; }
set { specialTag = value; }
get;
set;
}
partial void InitProjSpecific()
@@ -92,7 +95,10 @@ namespace Barotrauma
{
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 };
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)
{
CanTakeKeyBoardFocus = false
};
var editor = new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true, titleFont: GUI.LargeFont) { UserData = this };
if (Submarine.MainSub?.Info?.Type == SubmarineType.OutpostModule)
@@ -79,14 +79,22 @@ namespace Barotrauma
if (maxDamageStructure != null)
{
SoundPlayer.PlayDamageSound(
soundTag,
impact * 10.0f,
ConvertUnits.ToDisplayUnits(impactSimPos),
MathHelper.Lerp(2000.0f, 10000.0f, (impact - MinCollisionImpact) / 2.0f),
maxDamageStructure.Tags);
PlayDamageSound(impactSimPos, impact, soundTag, maxDamageStructure);
}
}
private void PlayDamageSound(Vector2 impactSimPos, float impact, string soundTag, Structure hitStructure = null)
{
if (impact < MinCollisionImpact) { return; }
SoundPlayer.PlayDamageSound(
soundTag,
impact * 10.0f,
ConvertUnits.ToDisplayUnits(impactSimPos),
MathHelper.Lerp(2000.0f, 10000.0f, (impact - MinCollisionImpact) / 2.0f),
hitStructure?.Tags);
}
}
}
@@ -1,5 +1,6 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
@@ -19,7 +20,7 @@ namespace Barotrauma
{
var texture = TextureLoader.FromStream(mem, path: FilePath, compress: false);
if (texture == null) { throw new Exception("PreviewImage texture returned null"); }
PreviewImage = new Sprite(texture, null, null);
PreviewImage = new Sprite(texture, sourceRectangle: null, newOffset: null, path: FilePath);
}
}
catch (Exception e)
@@ -32,21 +33,49 @@ namespace Barotrauma
}
}
public void CreatePreviewWindow(GUIComponent parent)
{
var content = new GUIFrame(new RectTransform(Vector2.One, parent.RectTransform), style: null);
if (PreviewImage == null)
var previewButton = new GUIButton(new RectTransform(new Vector2(1f, 0.5f), content.RectTransform), style: null)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform), TextManager.Get(SavedSubmarines.Contains(this) ? "SubPreviewImageNotFound" : "SubNotDownloaded"));
CanBeFocused = SubmarineElement != null,
OnClicked = (btn, obj) => { SubmarinePreview.Create(this); return false; },
};
var previewImage = PreviewImage ?? savedSubmarines.Find(s => s.Name.Equals(Name, StringComparison.OrdinalIgnoreCase))?.PreviewImage;
if (previewImage == null)
{
new GUITextBlock(new RectTransform(Vector2.One, previewButton.RectTransform), TextManager.Get(SavedSubmarines.Contains(this) ? "SubPreviewImageNotFound" : "SubNotDownloaded"));
}
else
{
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(0.98f), submarinePreviewBackground.RectTransform, Anchor.Center), PreviewImage, scaleToFit: true);
new GUIFrame(new RectTransform(Vector2.One, submarinePreviewBackground.RectTransform), "InnerGlow", color: Color.Black);
var submarinePreviewBackground = new GUIFrame(new RectTransform(Vector2.One, previewButton.RectTransform), style: null)
{
Color = Color.Black,
HoverColor = Color.Black,
SelectedColor = Color.Black,
PressedColor = Color.Black,
CanBeFocused = false,
};
new GUIImage(new RectTransform(new Vector2(0.98f), submarinePreviewBackground.RectTransform, Anchor.Center), previewImage, scaleToFit: true) { CanBeFocused = false };
new GUIFrame(new RectTransform(Vector2.One, submarinePreviewBackground.RectTransform), "InnerGlow", color: Color.Black) { CanBeFocused = false };
}
if (SubmarineElement != null)
{
new GUIFrame(new RectTransform(Vector2.One * 0.12f, previewButton.RectTransform, anchor: Anchor.BottomRight, pivot: Pivot.BottomRight, scaleBasis: ScaleBasis.BothHeight)
{
AbsoluteOffset = new Point((int)(0.03f * previewButton.Rect.Height))
},
"ExpandButton", Color.White)
{
Color = Color.White,
HoverColor = Color.White,
PressedColor = Color.White
};
}
var descriptionBox = new GUIListBox(new RectTransform(new Vector2(1, 0.5f), content.RectTransform, Anchor.BottomCenter))
{
UserData = "descriptionbox",
@@ -56,39 +85,31 @@ namespace Barotrauma
ScalableFont font = parent.Rect.Width < 350 ? GUI.SmallFont : GUI.Font;
CreateSpecsWindow(descriptionBox, font);
//space
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), descriptionBox.Content.RectTransform), style: null);
if (!string.IsNullOrEmpty(Description))
{
new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform),
TextManager.Get("SaveSubDialogDescription", fallBackTag: "WorkshopItemDescription"), font: GUI.Font, wrap: true)
{ CanBeFocused = false, ForceUpperCase = true };
}
new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), Description, font: font, wrap: true)
{
CanBeFocused = false
};
CreateSpecsWindow(descriptionBox, font, includeDescription: true);
}
public void CreateSpecsWindow(GUIListBox parent, ScalableFont font)
public void CreateSpecsWindow(GUIListBox parent, ScalableFont font, bool includeTitle = true, bool includeClass = true, bool includeDescription = false)
{
float leftPanelWidth = 0.6f;
float rightPanelWidth = 0.4f / leftPanelWidth;
float rightPanelWidth = 0.4f;
string className = !HasTag(SubmarineTag.Shuttle) ? TextManager.Get($"submarineclass.{SubmarineClass}") : TextManager.Get("shuttle");
int nameHeight = (int)GUI.LargeFont.MeasureString(DisplayName, true).Y;
int classHeight = (int)GUI.SubHeadingFont.MeasureString(className).Y;
int leftPanelWidthInt = (int)(parent.Rect.Width * leftPanelWidth);
var submarineNameText = new GUITextBlock(new RectTransform(new Point(leftPanelWidthInt, nameHeight + HUDLayoutSettings.Padding / 2), parent.Content.RectTransform), DisplayName, textAlignment: Alignment.CenterLeft, font: GUI.LargeFont) { CanBeFocused = false };
submarineNameText.RectTransform.MinSize = new Point(0, (int)submarineNameText.TextSize.Y);
var submarineClassText = new GUITextBlock(new RectTransform(new Point(leftPanelWidthInt, classHeight), parent.Content.RectTransform), className, textAlignment: Alignment.CenterLeft, font: GUI.SubHeadingFont) { CanBeFocused = false };
submarineClassText.RectTransform.MinSize = new Point(0, (int)submarineClassText.TextSize.Y);
GUITextBlock submarineNameText = null;
GUITextBlock submarineClassText = null;
if (includeTitle)
{
int nameHeight = (int)GUI.LargeFont.MeasureString(DisplayName, true).Y;
submarineNameText = new GUITextBlock(new RectTransform(new Point(leftPanelWidthInt, nameHeight + HUDLayoutSettings.Padding / 2), parent.Content.RectTransform), DisplayName, textAlignment: Alignment.CenterLeft, font: GUI.LargeFont) { CanBeFocused = false };
submarineNameText.RectTransform.MinSize = new Point(0, (int)submarineNameText.TextSize.Y);
}
if (includeClass)
{
submarineClassText = new GUITextBlock(new RectTransform(new Point(leftPanelWidthInt, classHeight), parent.Content.RectTransform), className, textAlignment: Alignment.CenterLeft, font: GUI.SubHeadingFont) { CanBeFocused = false };
submarineClassText.RectTransform.MinSize = new Point(0, (int)submarineClassText.TextSize.Y);
}
Vector2 realWorldDimensions = Dimensions * Physics.DisplayToRealWorldRatio;
if (realWorldDimensions != Vector2.Zero)
{
@@ -149,8 +170,30 @@ namespace Barotrauma
versionText.RectTransform.MinSize = new Point(0, versionText.Children.First().Rect.Height);
}
submarineNameText.AutoScaleHorizontal = true;
GUITextBlock.AutoScaleAndNormalize(parent.Content.Children.Where(c => c is GUITextBlock && c != submarineNameText).Cast<GUITextBlock>());
if (submarineNameText != null)
{
submarineNameText.AutoScaleHorizontal = true;
}
GUITextBlock descBlock = null;
if (includeDescription)
{
//space
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), parent.Content.RectTransform), style: null);
if (!string.IsNullOrEmpty(Description))
{
var wsItemDesc = new GUITextBlock(new RectTransform(new Vector2(1, 0), parent.Content.RectTransform),
TextManager.Get("SaveSubDialogDescription", fallBackTag: "WorkshopItemDescription"), font: GUI.Font, wrap: true)
{ CanBeFocused = false, ForceUpperCase = true };
descBlock = new GUITextBlock(new RectTransform(new Vector2(1, 0), parent.Content.RectTransform), Description, font: font, wrap: true)
{
CanBeFocused = false
};
}
}
GUITextBlock.AutoScaleAndNormalize(parent.Content.GetAllChildren<GUITextBlock>().Where(c => c != submarineNameText && c != descBlock));
}
}
}
@@ -0,0 +1,648 @@
using Barotrauma.Extensions;
using Barotrauma.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Barotrauma
{
class SubmarinePreview : IDisposable
{
private SpriteRecorder spriteRecorder;
private SubmarineInfo submarineInfo;
private Camera camera;
private Task loadTask;
private volatile bool isDisposed;
private GUIFrame previewFrame;
private class HullCollection
{
public readonly List<Rectangle> Rects;
public readonly string Name;
public HullCollection(string identifier)
{
Rects = new List<Rectangle>();
Name = TextManager.Get(identifier, returnNull: true) ?? identifier;
}
public void AddRect(XElement element)
{
Rectangle rect = element.GetAttributeRect("rect", Rectangle.Empty);
rect.Y = -rect.Y;
Rects.Add(rect);
}
}
private struct Door
{
public readonly Rectangle Rect;
public Door(Rectangle rect)
{
rect.Y = -rect.Y;
Rect = rect;
}
}
private Dictionary<string,HullCollection> hullCollections;
private List<Door> doors;
private static SubmarinePreview instance = null;
public static void Create(SubmarineInfo submarineInfo)
{
Close();
instance = new SubmarinePreview(submarineInfo);
}
public static void Close()
{
instance?.Dispose();
}
private SubmarinePreview(SubmarineInfo subInfo)
{
camera = new Camera();
submarineInfo = subInfo;
spriteRecorder = new SpriteRecorder();
isDisposed = false;
loadTask = null;
hullCollections = new Dictionary<string, HullCollection>();
doors = new List<Door>();
previewFrame = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas, Anchor.Center), style: null);
new GUIFrame(new RectTransform(GUI.Canvas.RelativeSize, previewFrame.RectTransform, Anchor.Center), style: "GUIBackgroundBlocker");
new GUIButton(new RectTransform(Vector2.One, previewFrame.RectTransform), "", style: null)
{
OnClicked = (btn, obj) => { Dispose(); return false; }
};
var innerFrame = new GUIFrame(new RectTransform(Vector2.One * 0.9f, previewFrame.RectTransform, Anchor.Center));
int innerPadding = GUI.IntScale(100f);
var innerPadded = new GUIFrame(new RectTransform(new Point(innerFrame.Rect.Width - innerPadding, innerFrame.Rect.Height - innerPadding), previewFrame.RectTransform, Anchor.Center), style: null)
{
OutlineColor = Color.Black,
OutlineThickness = 2
};
GUITextBlock titleText = null;
GUIListBox specsContainer = null;
new GUICustomComponent(new RectTransform(Vector2.One, innerPadded.RectTransform, Anchor.Center),
(spriteBatch, component) => {
camera.UpdateTransform(interpolate: true, updateListener: false);
Rectangle drawRect = new Rectangle(component.Rect.X + 1, component.Rect.Y + 1, component.Rect.Width - 2, component.Rect.Height - 2);
RenderSubmarine(spriteBatch, drawRect);
},
(deltaTime, component) => {
bool isMouseOnComponent = GUI.MouseOn == component;
camera.MoveCamera(deltaTime, allowZoom: isMouseOnComponent, followSub: false);
if (isMouseOnComponent &&
(PlayerInput.MidButtonHeld() || PlayerInput.LeftButtonHeld()))
{
Vector2 moveSpeed = PlayerInput.MouseSpeed * (float)deltaTime * 60.0f / camera.Zoom;
moveSpeed.X = -moveSpeed.X;
camera.Position += moveSpeed;
}
if (titleText != null && specsContainer != null)
{
specsContainer.Visible = GUI.IsMouseOn(titleText);
}
});
var topContainer = new GUIFrame(new RectTransform(new Vector2(1f, 0.07f), innerPadded.RectTransform, Anchor.TopLeft), style: null)
{
Color = Color.Black * 0.65f
};
var topLayout = new GUILayoutGroup(new RectTransform(new Vector2(0.97f, 5f / 7f), topContainer.RectTransform, Anchor.Center), isHorizontal: true, childAnchor: Anchor.CenterLeft);
titleText = new GUITextBlock(new RectTransform(new Vector2(0.95f, 1f), topLayout.RectTransform), subInfo.DisplayName, font: GUI.LargeFont);
new GUIButton(new RectTransform(new Vector2(0.05f, 1f), topLayout.RectTransform), TextManager.Get("Close"))
{
OnClicked = (btn, obj) => { Dispose(); return false; }
};
specsContainer = new GUIListBox(new RectTransform(new Vector2(0.4f, 1f), innerPadded.RectTransform, Anchor.TopLeft) { RelativeOffset = new Vector2(0.015f, 0.07f) })
{
Color = Color.Black * 0.65f,
ScrollBarEnabled = false,
ScrollBarVisible = false,
Spacing = 5
};
subInfo.CreateSpecsWindow(specsContainer, GUI.Font, includeTitle: false, includeDescription: true);
int width = specsContainer.Rect.Width;
void recalculateSpecsContainerHeight()
{
int totalSize = 0;
var children = specsContainer.Content.Children.Where(c => c.Visible);
foreach (GUIComponent child in children)
{
totalSize += child.Rect.Height;
}
totalSize += specsContainer.Content.CountChildren * specsContainer.Spacing;
if (specsContainer.PadBottom)
{
GUIComponent last = specsContainer.Content.Children.LastOrDefault();
if (last != null)
{
totalSize += specsContainer.Rect.Height - last.Rect.Height;
}
}
specsContainer.RectTransform.Resize(new Point(width, totalSize), true);
specsContainer.RecalculateChildren();
}
//hell
recalculateSpecsContainerHeight();
specsContainer.Content.GetAllChildren<GUITextBlock>().ForEach(c =>
{
var firstChild = c.Children.FirstOrDefault() as GUITextBlock;
if (firstChild != null)
{
firstChild.CalculateHeightFromText(); firstChild.SetTextPos();
c.RectTransform.MinSize = new Point(0, firstChild.Rect.Height);
}
c.CalculateHeightFromText(); c.SetTextPos();
});
recalculateSpecsContainerHeight();
GeneratePreviewMeshes();
}
public static void AddToGUIUpdateList()
{
instance?.previewFrame?.AddToGUIUpdateList();
}
public Task GeneratePreviewMeshes()
{
if (loadTask != null) { throw new InvalidOperationException("Tried to start SubmarinePreview loadTask more than once!"); }
loadTask = Task.Run(GeneratePreviewMeshesInternal);
return loadTask;
}
private async Task GeneratePreviewMeshesInternal()
{
await Task.Yield();
spriteRecorder.Begin(SpriteSortMode.BackToFront);
HashSet<int> toIgnore = new HashSet<int>();
foreach (var subElement in submarineInfo.SubmarineElement.Elements())
{
switch (subElement.Name.LocalName.ToLowerInvariant())
{
case "item":
foreach (var component in subElement.Elements())
{
switch (component.Name.LocalName.ToLowerInvariant())
{
case "itemcontainer":
ExtractItemContainerIds(component, toIgnore);
break;
case "connectionpanel":
ExtractConnectionPanelLinks(component, toIgnore);
break;
}
}
break;
}
if (isDisposed) { return; }
await Task.Yield();
}
foreach (var subElement in submarineInfo.SubmarineElement.Elements())
{
switch (subElement.Name.LocalName.ToLowerInvariant())
{
case "item":
if (!toIgnore.Contains(subElement.GetAttributeInt("ID", 0)))
{
BakeMapEntity(subElement);
}
break;
case "structure":
BakeMapEntity(subElement);
break;
case "hull":
string identifier = subElement.GetAttributeString("roomname", "").ToLowerInvariant();
if (!string.IsNullOrEmpty(identifier))
{
HullCollection hullCollection = null;
if (!hullCollections.TryGetValue(identifier, out hullCollection))
{
hullCollection = new HullCollection(identifier);
hullCollections.Add(identifier, hullCollection);
}
hullCollection.AddRect(subElement);
}
break;
}
if (isDisposed) { return; }
await Task.Yield();
}
spriteRecorder.End();
camera.Position = (spriteRecorder.Min + spriteRecorder.Max) * 0.5f;
float scaledSpan = (spriteRecorder.Max - spriteRecorder.Min).X / camera.Resolution.X;
camera.Zoom = 0.8f / scaledSpan;
camera.StopMovement();
}
private void ExtractItemContainerIds(XElement component, HashSet<int> ids)
{
string containedString = component.GetAttributeString("contained", "");
string[] itemIdStrings = containedString.Split(',');
for (int i = 0; i < itemIdStrings.Length; i++)
{
foreach (string idStr in itemIdStrings[i].Split(';'))
{
if (!int.TryParse(idStr, NumberStyles.Any, CultureInfo.InvariantCulture, out int id)) { continue; }
if (id != 0 && !ids.Contains(id)) { ids.Add(id); }
}
}
}
private void ExtractConnectionPanelLinks(XElement component, HashSet<int> ids)
{
var pins = component.Elements("input").Concat(component.Elements("output"));
foreach (var pin in pins)
{
var links = pin.Elements("link");
foreach (var link in links)
{
int id = link.GetAttributeInt("w", 0);
if (id != 0 && !ids.Contains(id)) { ids.Add(id); }
}
}
}
private void BakeMapEntity(XElement element)
{
string identifier = element.GetAttributeString("identifier", "");
if (string.IsNullOrEmpty(identifier)) { return; }
Rectangle rect = element.GetAttributeRect("rect", Rectangle.Empty);
if (rect.Equals(Rectangle.Empty)) { return; }
float depth = element.GetAttributeFloat("spritedepth", 1f);
bool flippedX = element.GetAttributeBool("flippedx", false);
bool flippedY = element.GetAttributeBool("flippedy", false);
float scale = element.GetAttributeFloat("scale", 1f);
Color color = element.GetAttributeColor("spritecolor", Color.White);
float rotation = element.GetAttributeFloat("rotation", 0f);
MapEntityPrefab prefab = MapEntityPrefab.List.FirstOrDefault(p => p.Identifier.Equals(identifier, StringComparison.OrdinalIgnoreCase));
if (prefab == null) { return; }
var texture = prefab.sprite.Texture;
var srcRect = prefab.sprite.SourceRect;
SpriteEffects spriteEffects = SpriteEffects.None;
if (flippedX)
{
spriteEffects |= SpriteEffects.FlipHorizontally;
}
if (flippedY)
{
spriteEffects |= SpriteEffects.FlipVertically;
}
var prevEffects = prefab.sprite.effects;
prefab.sprite.effects ^= spriteEffects;
bool overrideSprite = false;
ItemPrefab itemPrefab = prefab as ItemPrefab;
StructurePrefab structurePrefab = prefab as StructurePrefab;
if (itemPrefab != null)
{
BakeItemComponents(itemPrefab, rect, color, scale, rotation, depth, out overrideSprite);
}
if (!overrideSprite)
{
if (structurePrefab != null)
{
ParseUpgrades(structurePrefab.ConfigElement, ref scale);
if (!prefab.ResizeVertical)
{
rect.Height = (int)(rect.Height * scale / prefab.Scale);
}
if (!prefab.ResizeHorizontal)
{
rect.Width = (int)(rect.Width * scale / prefab.Scale);
}
var textureScale = element.GetAttributeVector2("texturescale", Vector2.One);
Vector2 backGroundOffset = Vector2.Zero;
Vector2 textureOffset = element.GetAttributeVector2("textureoffset", Vector2.Zero);
if (flippedX) { textureOffset.X = -textureOffset.X; }
if (flippedY) { textureOffset.Y = -textureOffset.Y; }
backGroundOffset = new Vector2(
MathUtils.PositiveModulo((int)-textureOffset.X, prefab.sprite.SourceRect.Width),
MathUtils.PositiveModulo((int)-textureOffset.Y, prefab.sprite.SourceRect.Height));
prefab.sprite.DrawTiled(
spriteRecorder,
rect.Location.ToVector2() * new Vector2(1f, -1f),
rect.Size.ToVector2(),
color: color,
startOffset: backGroundOffset,
textureScale: textureScale * scale,
depth: depth);
}
else if (itemPrefab != null)
{
bool usePrefabValues = element.GetAttributeBool("isoverride", false) != itemPrefab.IsOverride;
if (usePrefabValues)
{
scale = itemPrefab.ConfigElement.GetAttributeFloat(scale, "scale", "Scale");
}
ParseUpgrades(itemPrefab.ConfigElement, ref scale);
if (prefab.ResizeVertical || prefab.ResizeHorizontal)
{
if (!prefab.ResizeHorizontal)
{
rect.Width = (int)(prefab.sprite.size.X * scale);
}
if (!prefab.ResizeVertical)
{
rect.Height = (int)(prefab.sprite.size.Y * scale);
}
var spritePos = rect.Center.ToVector2();
//spritePos.Y = rect.Height - spritePos.Y;
prefab.sprite.DrawTiled(
spriteRecorder,
rect.Location.ToVector2() * new Vector2(1f, -1f),
rect.Size.ToVector2(),
color: color,
textureScale: Vector2.One * scale,
depth: depth);
foreach (var decorativeSprite in itemPrefab.DecorativeSprites)
{
float offsetState = 0f;
Vector2 offset = decorativeSprite.GetOffset(ref offsetState, Vector2.Zero) * scale;
if (flippedX && itemPrefab.CanSpriteFlipX) { offset.X = -offset.X; }
if (flippedY && itemPrefab.CanSpriteFlipY) { offset.Y = -offset.Y; }
decorativeSprite.Sprite.DrawTiled(spriteRecorder,
new Vector2(spritePos.X + offset.X - rect.Width / 2, -(spritePos.Y + offset.Y + rect.Height / 2)),
rect.Size.ToVector2(), color: color,
textureScale: Vector2.One * scale,
depth: Math.Min(depth + (decorativeSprite.Sprite.Depth - prefab.sprite.Depth), 0.999f));
}
}
else
{
rect.Width = (int)(rect.Width * scale / prefab.Scale);
rect.Height = (int)(rect.Height * scale / prefab.Scale);
var spritePos = rect.Center.ToVector2();
spritePos.Y -= rect.Height;
//spritePos.Y = rect.Height - spritePos.Y;
prefab.sprite.Draw(
spriteRecorder,
spritePos * new Vector2(1f, -1f),
color,
prefab.sprite.Origin,
rotation,
scale,
prefab.sprite.effects, depth);
foreach (var decorativeSprite in itemPrefab.DecorativeSprites)
{
float rotationState = 0f; float offsetState = 0f;
float rot = decorativeSprite.GetRotation(ref rotationState, 0f);
Vector2 offset = decorativeSprite.GetOffset(ref offsetState, Vector2.Zero) * scale;
if (flippedX && itemPrefab.CanSpriteFlipX) { offset.X = -offset.X; }
if (flippedY && itemPrefab.CanSpriteFlipY) { offset.Y = -offset.Y; }
decorativeSprite.Sprite.Draw(spriteRecorder, new Vector2(spritePos.X + offset.X, -(spritePos.Y + offset.Y)), color,
MathHelper.ToRadians(rotation) + rot, decorativeSprite.GetScale(0f) * scale, prefab.sprite.effects,
depth: Math.Min(depth + (decorativeSprite.Sprite.Depth - prefab.sprite.Depth), 0.999f));
}
}
}
}
prefab.sprite.effects = prevEffects;
}
private void BakeItemComponents(
ItemPrefab prefab,
Rectangle rect, Color color,
float scale, float rotation, float depth,
out bool overrideSprite)
{
overrideSprite = false;
foreach (var subElement in prefab.ConfigElement.Elements())
{
switch (subElement.Name.LocalName.ToLowerInvariant())
{
case "turret":
Sprite barrelSprite = null;
Sprite railSprite = null;
foreach (XElement turretSubElem in subElement.Elements())
{
switch (turretSubElem.Name.ToString().ToLowerInvariant())
{
case "barrelsprite":
barrelSprite = new Sprite(turretSubElem);
break;
case "railsprite":
railSprite = new Sprite(turretSubElem);
break;
}
}
var transformedBarrelPos = MathUtils.RotatePointAroundTarget(
subElement.GetAttributeVector2("barrelpos", Vector2.Zero) * scale,
new Vector2(rect.Width / 2, rect.Height / 2),
MathHelper.ToRadians(rotation));
Vector2 drawPos = new Vector2(rect.X + transformedBarrelPos.X, rect.Y - transformedBarrelPos.Y);
drawPos.Y = -drawPos.Y;
railSprite?.Draw(spriteRecorder,
drawPos,
color,
rotation + MathHelper.PiOver2, scale,
SpriteEffects.None, depth + (railSprite.Depth - prefab.sprite.Depth));
barrelSprite?.Draw(spriteRecorder,
drawPos - new Vector2((float)Math.Cos(MathHelper.ToRadians(rotation)), (float)Math.Sin(MathHelper.ToRadians(rotation))) * scale,
color,
rotation + MathHelper.PiOver2, scale,
SpriteEffects.None, depth + (barrelSprite.Depth - prefab.sprite.Depth));
break;
case "door":
doors.Add(new Door(rect));
var doorSpriteElem = subElement.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("sprite", StringComparison.OrdinalIgnoreCase));
if (doorSpriteElem != null)
{
string texturePath = doorSpriteElem.GetAttributeString("texture", "");
Vector2 pos = rect.Location.ToVector2() * new Vector2(1f, -1f);
if (subElement.GetAttributeBool("horizontal", false))
{
pos.Y += (float)rect.Height * 0.5f;
}
else
{
pos.X += (float)rect.Width * 0.5f;
}
Sprite doorSprite = new Sprite(doorSpriteElem, texturePath.Contains("/") ? "" : Path.GetDirectoryName(prefab.FilePath));
spriteRecorder.Draw(doorSprite.Texture, pos,
new Rectangle((int)doorSprite.SourceRect.X,
(int)doorSprite.SourceRect.Y,
(int)doorSprite.size.X, (int)doorSprite.size.Y),
color, 0.0f, doorSprite.Origin, new Vector2(scale), SpriteEffects.None, doorSprite.Depth);
}
break;
case "ladder":
var backgroundSprElem = subElement.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("backgroundsprite", StringComparison.OrdinalIgnoreCase));
if (backgroundSprElem != null)
{
Sprite backgroundSprite = new Sprite(backgroundSprElem);
backgroundSprite.DrawTiled(spriteRecorder,
new Vector2(rect.Left, -rect.Top) - backgroundSprite.Origin * scale,
new Vector2(backgroundSprite.size.X * scale, rect.Height), color: color,
textureScale: Vector2.One * scale,
depth: depth + 0.1f);
}
break;
}
}
}
public void ParseUpgrades(XElement prefabConfigElement, ref float scale)
{
foreach (var upgrade in prefabConfigElement.Elements("Upgrade"))
{
var upgradeVersion = new Version(upgrade.GetAttributeString("gameversion", "0.0.0.0"));
if (upgradeVersion >= submarineInfo.GameVersion)
{
string scaleModifier = upgrade.GetAttributeString("scale", "*1");
if (scaleModifier.StartsWith("*"))
{
if (float.TryParse(scaleModifier.Substring(1), NumberStyles.Any, CultureInfo.InvariantCulture, out float parsedScale))
{
scale *= parsedScale;
}
}
else
{
if (float.TryParse(scaleModifier, NumberStyles.Any, CultureInfo.InvariantCulture, out float parsedScale))
{
scale = parsedScale;
}
}
}
}
}
private void RenderSubmarine(SpriteBatch spriteBatch, Rectangle scissorRectangle)
{
if (spriteRecorder == null) { return; }
GUI.DrawRectangle(spriteBatch, scissorRectangle, new Color(0.051f, 0.149f, 0.271f, 1.0f), isFilled: true);
if (!spriteRecorder.ReadyToRender)
{
string waitText = !loadTask.IsCompleted ?
"Generating preview..." :
(loadTask.Exception?.ToString() ?? "Task completed without marking as ready to render");
Vector2 origin = (GUI.Font.MeasureString(waitText) * 0.5f);
origin.X = MathF.Round(origin.X);
origin.Y = MathF.Round(origin.Y);
GUI.Font.DrawString(
spriteBatch,
waitText,
scissorRectangle.Center.ToVector2(),
Color.White,
0f,
origin,
1f,
SpriteEffects.None,
0f);
return;
}
spriteBatch.End();
var prevScissorRect = GameMain.Instance.GraphicsDevice.ScissorRectangle;
GameMain.Instance.GraphicsDevice.ScissorRectangle = scissorRectangle;
spriteRecorder.Render(camera);
var mousePos = camera.ScreenToWorld(PlayerInput.MousePosition);
mousePos.Y = -mousePos.Y;
spriteBatch.Begin(SpriteSortMode.BackToFront, rasterizerState: GameMain.ScissorTestEnable, transformMatrix: camera.Transform);
GameMain.Instance.GraphicsDevice.ScissorRectangle = scissorRectangle;
foreach (var hullCollection in hullCollections.Values)
{
bool mouseOver = false;
foreach (var rect in hullCollection.Rects)
{
mouseOver = rect.Contains(mousePos);
if (mouseOver) { break; }
}
foreach (var rect in hullCollection.Rects)
{
GUI.DrawRectangle(spriteBatch, rect, mouseOver ? Color.Red : Color.Blue, depth: mouseOver ? 0.45f : 0.5f, thickness: (mouseOver ? 4f : 2f) / camera.Zoom);
}
if (mouseOver)
{
string str = hullCollection.Name;
Vector2 strSize = GUI.Font.MeasureString(str) / camera.Zoom;
Vector2 padding = new Vector2(30, 30) / camera.Zoom;
Vector2 shift = new Vector2(10, 0) / camera.Zoom;
GUI.DrawRectangle(spriteBatch, mousePos + shift, strSize + padding, Color.Black, isFilled: true, depth: 0.25f);
GUI.Font.DrawString(spriteBatch, str, mousePos + shift + (strSize + padding) * 0.5f, Color.White, 0f, strSize * camera.Zoom * 0.5f, 1f / camera.Zoom, SpriteEffects.None, 0f);
}
}
foreach (var door in doors)
{
GUI.DrawRectangle(spriteBatch, door.Rect, GUI.Style.Green * 0.5f, isFilled: true, depth: 0.4f);
}
spriteBatch.End();
GameMain.Instance.GraphicsDevice.ScissorRectangle = prevScissorRect;
spriteBatch.Begin(SpriteSortMode.Deferred);
}
public void Dispose()
{
previewFrame = null;
spriteRecorder?.Dispose();
isDisposed = true;
}
}
}
@@ -222,18 +222,20 @@ namespace Barotrauma
private bool ChangeSpawnType(GUIButton button, object obj)
{
GUITextBlock spawnTypeText = button.Parent.GetChildByUserData("spawntypetext") as GUITextBlock;
spawnType += (int)button.UserData;
var values = Enum.GetValues(typeof(SpawnType));
var values = (SpawnType[])Enum.GetValues(typeof(SpawnType));
int currIndex = values.IndexOf(spawnType);
currIndex += (int)button.UserData;
int firstIndex = 1;
int lastIndex = values.Length - 1;
if ((int)spawnType > lastIndex)
if (currIndex > lastIndex)
{
spawnType = (SpawnType)firstIndex;
currIndex = firstIndex;
}
if ((int)spawnType < firstIndex)
if (currIndex < firstIndex)
{
spawnType = (SpawnType)values.GetValue(lastIndex);
currIndex = lastIndex;
}
spawnType = values[currIndex];
spawnTypeText.Text = spawnType.ToString();
return true;
}