Rebuild Soundings around harbor gameplay and guided careers

This commit is contained in:
josh
2026-11-27 21:11:51 -05:00
parent 75afa1c194
commit 4b870fb0ce
30 changed files with 3523 additions and 819 deletions

View File

@@ -59,7 +59,7 @@ namespace Soundings
public int Day = 1, Cash, Debt, Reputation, Voyages;
public long LifetimeProfit;
public bool Flagship, Bridge;
public int SelectedShip;
public int SelectedShip, TutorialStep;
public bool[] Permits = new bool[Market.Ports.Count];
public List<Ship> Fleet = new List<Ship>();
public List<Voyage> History = new List<Voyage>();

View File

@@ -1,3 +1,4 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
@@ -8,263 +9,379 @@ namespace Soundings
private int inspectedPort = 1;
private int selectedVoyage;
private bool worldChart;
private float chartScrollPosition;
private static readonly Vector2[][] AtlanticCoastlines =
{
new[]
{
new Vector2(0, 0), new Vector2(.33f, 0), new Vector2(.30f, .09f), new Vector2(.28f, .19f),
new Vector2(.25f, .21f), new Vector2(.26f, .26f), new Vector2(.22f, .31f), new Vector2(.21f, .37f),
new Vector2(.19f, .40f), new Vector2(.18f, .47f), new Vector2(.15f, .51f), new Vector2(.14f, .57f),
new Vector2(.15f, .64f), new Vector2(.13f, .68f), new Vector2(.12f, .64f), new Vector2(.11f, .56f),
new Vector2(.08f, .54f), new Vector2(.06f, .51f), new Vector2(.03f, .55f), new Vector2(0, .51f)
},
new[]
{
new Vector2(.75f, 0), new Vector2(.96f, 0), new Vector2(1, .08f), new Vector2(1, .41f),
new Vector2(.97f, .38f), new Vector2(.93f, .34f), new Vector2(.91f, .30f), new Vector2(.88f, .29f),
new Vector2(.84f, .25f), new Vector2(.85f, .18f), new Vector2(.88f, .16f), new Vector2(.86f, .11f),
new Vector2(.81f, .09f)
},
new[]
{
new Vector2(1, .44f), new Vector2(.94f, .37f), new Vector2(.90f, .42f), new Vector2(.89f, .47f),
new Vector2(.86f, .54f), new Vector2(.85f, .65f), new Vector2(.87f, .71f), new Vector2(.91f, .74f),
new Vector2(.94f, .79f), new Vector2(1, .82f)
},
new[]
{
new Vector2(0, .79f), new Vector2(.026f, .83f), new Vector2(.05f, .90f), new Vector2(.062f, .91f),
new Vector2(.078f, .95f), new Vector2(.12f, .96f), new Vector2(.16f, 1), new Vector2(0, 1)
},
new[]
{
new Vector2(.11f, .78f), new Vector2(.15f, .75f), new Vector2(.23f, .76f), new Vector2(.27f, .78f),
new Vector2(.23f, .79f), new Vector2(.17f, .781f), new Vector2(.13f, .80f)
},
new[]
{
new Vector2(.33f, .84f), new Vector2(.36f, .82f), new Vector2(.39f, .83f), new Vector2(.39f, .86f),
new Vector2(.36f, .86f), new Vector2(.34f, .85f)
}
};
private void OpenVoyageChart()
{
int port = destination >= 0 ? destination : Ship?.Port ?? 0;
worldChart = port >= Market.StarterPortCount || (Ship?.Port ?? 0) >= Market.StarterPortCount;
inspectedPort = port;
chartScrollPosition = 0;
ChangePage(3);
}
private void DrawPorts(VisualElement pageRoot)
{
var columns = Add(pageRoot, "columns");
var chartCard = Card(columns, "Shipping lanes", "wide");
var scope = Add(chartCard, "deck-tabs");
scope.Add(Action("Atlantic", () => ChangeChart(false), worldChart ? "" : "active-option", "chart-atlantic"));
scope.Add(Action("World", () => ChangeChart(true), worldChart ? "active-option" : "", "chart-world"));
var chart = Add(chartCard, "chart");
var labels = Add(chartCard, "chart-legend");
AddText(labels, "● Permit held", "gain");
AddText(labels, "● Permit required", "gold");
chart.generateVisualContent += DrawChart;
var board = Add(pageRoot, "navigation-chart");
board.styleSheets.Add(Resources.Load<StyleSheet>("Chart"));
var heading = Add(board, "chart-heading");
AddText(heading, Ship == null ? "PORT DIRECTORY" : $"ABOARD {Ship.Name.ToUpperInvariant()}", "chart-kicker");
AddDisplay(heading, "Shipping chart", "chart-heading-title");
var plot = Add(board, "chart-plot");
plot.generateVisualContent += DrawChart;
DrawChartLabels(plot);
var switches = Add(board, "chart-scopes");
switches.Add(Action("Atlantic", () => ChangeChart(false), worldChart ? "chart-scope" : "chart-scope chart-scope-current", "chart-atlantic"));
switches.Add(Action("World", () => ChangeChart(true), worldChart ? "chart-scope chart-scope-current" : "chart-scope", "chart-world"));
for (int i = 0; i < ChartPortCount; i++)
{
int portId = i;
PortSpec port = Market.Ports[i];
var marker = Action("●", () => { inspectedPort = portId; Notify(null); Render(); },
company.Permits[i] ? "map-port gain" : "map-port gold", "map-" + i);
bool berth = Ship?.Port == i;
bool cleared = company.Permits[i];
bool selected = inspectedPort == i;
string styles = "chart-port-pin";
if (berth)
styles += " chart-port-berth";
else if (!cleared)
styles += " chart-port-locked";
if (selected)
styles += " chart-port-selected";
var marker = Action("", () => InspectChartPort(portId), styles, "port-" + i);
marker.tooltip = $"{port.Name} · {(berth ? "Current port" : cleared ? "Permit held" : "Permit required")}";
Vector2 point = ChartPoint(port);
marker.style.left = Length.Percent(point.x * 100);
marker.style.top = Length.Percent(point.y * 100);
marker.EnableInClassList("active-option", i == inspectedPort);
marker.tooltip = port.Name;
chart.Add(marker);
var light = Add(marker, "chart-pin-light");
light.pickingMode = PickingMode.Ignore;
var caption = AddText(marker, port.Name, point.x > .77f ? "chart-pin-label chart-pin-label-west" : "chart-pin-label");
caption.EnableInClassList("chart-pin-label-on-focus", worldChart && !selected && !berth);
plot.Add(marker);
}
PortSpec current = Market.Ports[inspectedPort];
var portInfo = Card(columns, current.Name, "narrow");
AddText(portInfo, $"{current.Country} / {current.Region}", "muted");
AddLine(portInfo, "Bunker price", $"{Money(Market.FuelPrice(inspectedPort, company.Day))} / t");
AddLine(portInfo, "Arrival dues", Money(current.Fee));
AddLine(portInfo, "Destination appeal", $"{current.Appeal:P0}");
AddLine(portInfo, "Minimum hull", Market.Hulls[current.MinimumHull].Name);
bool licensed = company.Permits[inspectedPort];
AddLine(portInfo, "Port access", licensed ? "Permit held" : "Permit required", licensed ? "gain" : "gold");
if (!licensed)
{
int portId = inspectedPort;
string blocker = company.PermitBlock(portId);
Button license = Action($"Acquire permit · {Money(current.Permit)}", () =>
{
string failure = company.Permit(portId);
if (failure == null && destination < 0)
ResetItinerary();
Apply(failure, $"{current.Name} is now licensed.");
}, "primary full-button", "permit");
license.SetEnabled(blocker == null);
portInfo.Add(license);
if (blocker != null)
AddText(portInfo, blocker, "body-copy");
}
if (Ship != null && Market.TryDistance(Ship.Port, inspectedPort, out int miles))
{
AddLine(portInfo, $"From {Market.Ports[Ship.Port].Name}", $"{miles:N0} nm");
Button plan = Action("Plan this sailing →", () =>
{
destination = inspectedPort;
SetRecommendedFuel();
ChangePage(0);
}, "full-button", "plan-port");
portInfo.Add(plan);
}
var legend = Add(board, "chart-legends");
ChartKey(legend, "Current berth", "chart-key-berth");
ChartKey(legend, "Open port", "chart-key-open");
ChartKey(legend, "Permit required", "chart-key-locked");
var index = Card(pageRoot, "Port directory", "second-row");
var grid = Add(index, "port-grid");
var folio = new ScrollView(ScrollViewMode.Vertical) { horizontalScrollerVisibility = ScrollerVisibility.Hidden };
folio.AddToClassList("chart-folio");
float scrollPosition = chartScrollPosition;
folio.verticalScroller.valueChanged += value => chartScrollPosition = value;
if (scrollPosition > 0)
folio.schedule.Execute(() => folio.scrollOffset = new Vector2(0, scrollPosition));
board.Add(folio);
var contents = Add(folio, "chart-folio-content");
AddText(contents, "LOOK UP PORT", "chart-paper-kicker");
AddChartDirectory(contents);
DrawPortFolio(contents);
}
private static void ChartKey(VisualElement legend, string name, string color)
{
var key = Add(legend, "chart-key");
Add(key, "chart-key-light " + color);
AddText(key, name, "chart-key-label");
}
private void AddChartDirectory(VisualElement parent)
{
var choices = new List<string>(ChartPortCount);
for (int i = 0; i < ChartPortCount; i++)
choices.Add(Market.Ports[i].Name);
var selector = new DropdownField(choices, inspectedPort) { name = "chart-directory" };
selector.AddToClassList("chart-directory");
selector.RegisterValueChangedCallback(evt =>
{
int portId = i;
PortSpec port = Market.Ports[i];
Button option = Action("", () => { inspectedPort = portId; Notify(null); Render(); },
inspectedPort == i ? "port-row active-option" : "port-row", "port-" + i);
AddText(option, port.Name, "option-title");
AddText(option, $"{port.Country} · {Money(Market.FuelPrice(i, company.Day))}/t",
company.Permits[i] ? "muted" : "gold");
grid.Add(option);
int port = choices.IndexOf(evt.newValue);
if (port >= 0)
InspectChartPort(port);
});
parent.Add(selector);
}
private void DrawPortFolio(VisualElement parent)
{
Ship ship = Ship;
int selected = inspectedPort;
PortSpec port = Market.Ports[selected];
bool berth = ship?.Port == selected;
Voyage quote = ship == null ? null : company.Forecast(ship, selected);
bool permitted = company.Permits[selected];
bool eligible = ship == null || ship.HullIndex >= port.MinimumHull;
AddDisplay(parent, port.Name, "chart-port-name");
AddText(parent, $"{port.Country} · {port.Region}", "chart-paper-caption");
if (quote != null && permitted && eligible)
{
DrawVoyageFolio(parent, ship, quote);
return;
}
AddText(parent, berth ? "CURRENT BERTH" : "PORT CONDITIONS", "chart-paper-kicker chart-paper-section");
ChartLine(parent, "Fuel at this port", $"{Money(Market.FuelPrice(selected, company.Day))} / t");
ChartLine(parent, "Arrival dues", Money(port.Fee));
ChartLine(parent, "Destination appeal", $"{port.Appeal:P0}");
ChartLine(parent, "Minimum hull", Market.Hulls[port.MinimumHull].Name);
if (quote != null)
ChartLine(parent, $"From {Market.Ports[ship.Port].Name}", $"{quote.Miles:N0} nm");
if (berth)
{
DrawChartBunkering(parent, ship);
return;
}
if (!permitted)
{
string blocker = company.PermitBlock(selected);
Button permit = Action($"Acquire permit · {Money(port.Permit)}", () =>
{
string failure = company.Permit(selected);
Apply(failure, $"{port.Name} is now licensed.");
}, "chart-ink-button chart-wide-button", "permit");
permit.SetEnabled(blocker == null);
parent.Add(permit);
AddText(parent, blocker ?? $"Open {port.Name} to your fleet.", "chart-paper-note");
}
else if (!eligible)
{
AddText(parent, $"This sailing requires a {Market.Hulls[port.MinimumHull].Name} hull.", "chart-paper-note");
}
else if (ship == null)
{
AddText(parent, "Assign a vessel to plan a sailing.", "chart-paper-note");
parent.Add(Action("Visit shipyard", () => ChangePage(2), "chart-ink-button chart-wide-button"));
}
else
{
AddText(parent, $"There is no direct route from {Market.Ports[ship.Port].Name}. Select a linked port to plan this sailing.", "chart-paper-note");
}
}
private int ChartPortCount => worldChart ? Market.Ports.Count : Market.StarterPortCount;
private void ChangeChart(bool global)
private void InspectChartPort(int port)
{
worldChart = global;
if (inspectedPort >= ChartPortCount)
inspectedPort = Market.Lisbon;
if (port != inspectedPort)
chartScrollPosition = 0;
inspectedPort = port;
if (Ship != null && Market.TryDistance(Ship.Port, port, out _) && destination != port)
{
destination = port;
SetRecommendedFuel();
}
Notify(null);
Render();
}
private Vector2 ChartPoint(PortSpec port) => worldChart
? new Vector2((port.Longitude + 180) / 360, (76 - port.Latitude) / 137)
: new Vector2(port.MapX, port.MapY);
private void ChangeChart(bool global)
{
worldChart = global;
if (inspectedPort >= ChartPortCount)
{
InspectChartPort(Market.Lisbon);
return;
}
Notify(null);
Render();
}
private Vector2 ChartPoint(PortSpec port)
{
Vector2 point = worldChart
? new Vector2((port.Longitude + 180) / 360, (76 - port.Latitude) / 137)
: new Vector2(port.MapX, port.MapY);
return PlotInset(point);
}
private static Vector2 PlotInset(Vector2 point) => new Vector2(.035f + point.x * .93f, .035f + point.y * .93f);
private void DrawChartLabels(VisualElement plot)
{
if (worldChart)
{
OceanName("NORTH PACIFIC", .15f, .62f);
OceanName("ATLANTIC", .37f, .56f);
OceanName("INDIAN OCEAN", .62f, .72f);
OceanName("SOUTH PACIFIC", .11f, .88f);
}
else
{
OceanName("NORTH ATLANTIC", .48f, .29f);
OceanName("CARIBBEAN SEA", .25f, .95f);
}
void OceanName(string name, float x, float y)
{
Label label = AddText(plot, name, "chart-water-name");
label.style.left = Length.Percent(x * 100);
label.style.top = Length.Percent(y * 100);
}
}
private void DrawChart(MeshGenerationContext context)
{
VisualElement chart = context.visualElement;
float width = chart.contentRect.width;
float height = chart.contentRect.height;
Vector2 Point(float x, float y) => new Vector2(width * x, height * y);
float width = context.visualElement.contentRect.width;
float height = context.visualElement.contentRect.height;
if (width < 32 || height < 32)
return;
Vector2 Point(Vector2 point) => new Vector2(width * point.x, height * point.y);
Painter2D painter = context.painter2D;
painter.strokeColor = new Color(.18f, .32f, .36f);
painter.strokeColor = new Color(.23f, .39f, .44f, .44f);
painter.lineWidth = 1;
painter.BeginPath();
for (int i = 1; i < 12; i++)
for (int i = 0; i <= 12; i++)
{
painter.MoveTo(Point(i / 12f, 0));
painter.LineTo(Point(i / 12f, 1));
painter.MoveTo(Point(PlotInset(new Vector2(i / 12f, 0))));
painter.LineTo(Point(PlotInset(new Vector2(i / 12f, 1))));
}
for (int i = 1; i < 7; i++)
for (int i = 0; i <= 8; i++)
{
painter.MoveTo(Point(0, i / 7f));
painter.LineTo(Point(1, i / 7f));
painter.MoveTo(Point(PlotInset(new Vector2(0, i / 8f))));
painter.LineTo(Point(PlotInset(new Vector2(1, i / 8f))));
}
painter.Stroke();
void Polygon(Vector2[] points)
painter.fillColor = new Color(.139f, .255f, .276f);
painter.strokeColor = new Color(.49f, .55f, .49f, .72f);
painter.lineWidth = 1.15f;
foreach (Vector2[] outline in worldChart ? WorldCoastlines.Shapes : AtlanticCoastlines)
{
painter.BeginPath();
painter.MoveTo(Point(points[0].x, points[0].y));
for (int i = 1; i < points.Length; i++)
painter.LineTo(Point(points[i].x, points[i].y));
painter.MoveTo(Point(PlotInset(outline[0])));
for (int i = 1; i < outline.Length; i++)
painter.LineTo(Point(PlotInset(outline[i])));
painter.ClosePath();
painter.Fill();
painter.Stroke();
}
painter.fillColor = new Color(.15f, .28f, .29f);
painter.strokeColor = new Color(.30f, .43f, .42f);
if (worldChart)
{
foreach (Vector2[] continent in WorldCoastlines.Shapes)
Polygon(continent);
}
else
{
Polygon(new[]
{
new Vector2(0,0), new Vector2(.30f,0), new Vector2(.27f,.12f), new Vector2(.26f,.26f),
new Vector2(.23f,.33f), new Vector2(.20f,.46f), new Vector2(.15f,.52f), new Vector2(.13f,.60f),
new Vector2(.15f,.68f), new Vector2(.12f,.74f), new Vector2(.10f,.64f), new Vector2(.08f,.57f),
new Vector2(.02f,.54f), new Vector2(0,.60f)
});
Polygon(new[]
{
new Vector2(1,0), new Vector2(.84f,0), new Vector2(.86f,.08f), new Vector2(.88f,.13f),
new Vector2(.86f,.24f), new Vector2(.90f,.30f), new Vector2(.94f,.28f), new Vector2(.95f,.33f),
new Vector2(.90f,.39f), new Vector2(.86f,.52f), new Vector2(.87f,.68f), new Vector2(.95f,.83f), new Vector2(1,.83f)
});
Polygon(new[]
{
new Vector2(0,.84f), new Vector2(.08f,.88f), new Vector2(.15f,.92f),
new Vector2(.21f,.84f), new Vector2(.34f,.97f), new Vector2(.41f,1), new Vector2(0,1)
});
}
int berth = Ship?.Port ?? -1;
bool CanShow(Lane lane) => lane.A < ChartPortCount && lane.B < ChartPortCount;
bool IsSelected(Lane lane) => berth >= 0 && lane.Other(berth) == inspectedPort;
foreach (Lane lane in Market.Lanes)
{
if (lane.A >= ChartPortCount || lane.B >= ChartPortCount)
if (!CanShow(lane) || IsSelected(lane))
continue;
bool active = company.Permits[lane.A] && company.Permits[lane.B];
DrawLane(lane, active ? new Color(.40f, .73f, .71f, .68f) : new Color(.60f, .52f, .39f, .62f), active ? 1.55f : 1.1f);
}
foreach (Lane lane in Market.Lanes)
{
if (!CanShow(lane) || !IsSelected(lane))
continue;
DrawLane(lane, new Color(.92f, .65f, .28f, .18f), 9);
DrawLane(lane, new Color(.98f, .75f, .38f, 1), 2.3f);
}
DrawCompass(painter, new Vector2(width - 69, height - 76), 34);
void DrawLane(Lane lane, Color color, float thickness)
{
Vector2 a = ChartPoint(Market.Ports[lane.A]);
Vector2 b = ChartPoint(Market.Ports[lane.B]);
bool active = company.Permits[lane.A] && company.Permits[lane.B];
painter.strokeColor = active ? new Color(.41f, .75f, .68f, .8f) : new Color(.69f, .62f, .44f, .59f);
painter.lineWidth = active ? 1.65f : 1;
if (worldChart && Mathf.Abs(a.x - b.x) > .5f)
painter.strokeColor = color;
painter.lineWidth = thickness;
if (worldChart && Mathf.Abs(a.x - b.x) > .465f)
{
if (a.x > b.x)
(a, b) = (b, a);
float y = Mathf.Lerp(a.y, b.y, a.x / (a.x + 1 - b.x));
RouteSegment(a, new Vector2(0, y));
RouteSegment(new Vector2(1, y), b);
float toEdge = a.x - .035f;
float y = Mathf.Lerp(a.y, b.y, toEdge / (toEdge + .965f - b.x));
Curve(a, new Vector2(.035f, y));
Curve(new Vector2(.965f, y), b);
}
else
RouteSegment(a, b);
}
Curve(a, b);
void RouteSegment(Vector2 a, Vector2 b)
void Curve(Vector2 from, Vector2 to)
{
painter.BeginPath();
painter.MoveTo(Point(from));
float rise = (worldChart ? .10f : .145f) * Vector2.Distance(from, to);
painter.QuadraticCurveTo(Point((from + to) / 2 - new Vector2(0, rise)), Point(to));
painter.Stroke();
}
}
}
private static void DrawCompass(Painter2D painter, Vector2 center, float radius)
{
painter.lineWidth = 1;
painter.strokeColor = new Color(.64f, .58f, .44f, .68f);
painter.BeginPath();
painter.MoveTo(center + Vector2.right * radius);
const int segments = 48;
for (int i = 1; i <= segments; i++)
{
float angle = i * Mathf.PI * 2 / segments;
painter.LineTo(center + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius);
}
painter.ClosePath();
painter.Stroke();
painter.fillColor = new Color(.80f, .68f, .43f, .72f);
for (int i = 0; i < 4; i++)
{
float angle = i * Mathf.PI * .5f;
Vector2 axis = new Vector2(Mathf.Sin(angle), -Mathf.Cos(angle));
Vector2 wing = new Vector2(-axis.y, axis.x);
painter.BeginPath();
painter.MoveTo(Point(a.x, a.y));
float rise = worldChart ? .018f : .055f;
painter.QuadraticCurveTo(Point((a.x + b.x) / 2, (a.y + b.y) / 2 - rise), Point(b.x, b.y));
painter.MoveTo(center);
painter.LineTo(center + axis * radius * (i == 0 ? 1.28f : .95f));
painter.LineTo(center + wing * radius * .16f);
painter.ClosePath();
painter.Fill();
painter.Stroke();
}
}
private void DrawFinance(VisualElement pageRoot)
{
var summary = Add(pageRoot, "card deck-stats");
ForecastMetric(summary, "CASH RESERVES", Money(company.Cash), "gold");
ForecastMetric(summary, "OUTSTANDING DEBT", Money(company.Debt));
ForecastMetric(summary, "LIFETIME VOYAGE PROFIT", Money(company.LifetimeProfit), company.LifetimeProfit >= 0 ? "gain" : "loss");
ForecastMetric(summary, "COMPLETED VOYAGES", company.Voyages.ToString());
var columns = Add(pageRoot, "columns second-row");
var ledger = Card(columns, "Voyage ledger", "wide");
if (company.History.Count == 0)
AddText(ledger, "Completed voyages will be posted here.", "body-copy");
else
{
selectedVoyage = Mathf.Clamp(selectedVoyage, 0, company.History.Count - 1);
var list = new ScrollView(ScrollViewMode.Vertical);
list.AddToClassList("ledger-scroll");
ledger.Add(list);
for (int i = 0; i < company.History.Count; i++)
{
int record = i;
Voyage trip = company.History[i];
Button entry = Action("", () => { selectedVoyage = record; Render(); },
selectedVoyage == i ? "yard-item active-option" : "yard-item", "voyage-" + i);
var detail = Add(entry, "yard-copy");
AddText(detail, $"{Market.Ports[trip.Origin].Name} → {Market.Ports[trip.Destination].Name}", "option-title");
AddText(detail, $"Day {trip.Day} · {trip.ShipName} · {trip.Guests} guests", "muted");
AddText(entry, Money(trip.NetIncome), trip.NetIncome >= 0 ? "gain" : "loss");
list.Add(entry);
}
}
var account = Card(columns, "Financing", "narrow");
AddLine(account, "Interest", company.Debt > 0 ? "13% APR" : "No outstanding loan");
AddLine(account, "Principal per sailing day", company.Debt > 0 ? Money(850) : "—");
if (company.Debt > 0)
{
Button pay = Action($"Pay down · {Money(Mathf.Min(company.Debt, 25000))}",
() => Apply(company.PayDownDebt(), "Principal payment posted."), "full-button", "pay-debt");
pay.SetEnabled(company.Cash >= Mathf.Min(company.Debt, 25000));
account.Add(pay);
}
if (company.Bridge)
{
Button draw = Action("Draw $125,000 bridge loan", () => Apply(company.DrawBridge(), "Bridge loan posted."),
"full-button", "draw-bridge");
draw.SetEnabled(company.CanDrawBridge);
account.Add(draw);
if (!company.CanDrawBridge)
AddText(account, "Bridge credit opens below $100,000 cash.", "body-copy");
}
if (company.Flagship)
AddText(account, "Flagship milestone completed.", "body-copy gain");
if (company.History.Count == 0)
return;
Voyage selected = company.History[selectedVoyage];
var statement = Card(pageRoot, $"Sailing statement · Day {selected.Day}", "second-row");
var breakdown = Add(statement, "columns breakdown");
var earnings = Add(breakdown, "half");
AddLine(earnings, "Ticket revenue", Money(selected.TicketSales));
AddLine(earnings, "Onboard revenue", Money(selected.OnboardSales));
AddLine(earnings, "Crew & catering", Money(-selected.Crew - selected.Catering));
AddLine(earnings, "Port dues", Money(-selected.PortFees));
var costs = Add(breakdown, "half");
AddLine(costs, "Fuel consumed from inventory", Money(-selected.FuelExpense));
AddLine(costs, "Interest", Money(-selected.LoanInterest));
AddLine(costs, "Loan principal paid", Money(-selected.Principal));
AddLine(costs, "Cash change on arrival", Money(selected.CashChange), selected.CashChange >= 0 ? "gain" : "loss");
}
}
}

View File

@@ -7,150 +7,555 @@ namespace Soundings
{
private static readonly (int HullIndex, bool Used)[] Offers =
{ (0, true), (0, false), (1, true), (1, false), (2, false) };
private void DrawDecks(VisualElement pageRoot)
private static readonly Color DraftGrid = new Color(.37f, .62f, .65f, .19f);
private static readonly Color DraftFine = new Color(.47f, .75f, .74f, .42f);
private static readonly Color DraftInk = new Color(.64f, .89f, .82f, .88f);
private static readonly Color DraftGold = new Color(.91f, .70f, .42f, .88f);
private void DrawDecks(VisualElement workspace)
{
var work = Add(workspace, "ship-work deck-work");
Ship ship = Ship;
if (ship == null)
{
var empty = Card(pageRoot, "Choose a vessel first");
empty.Add(Action("Open shipyard →", () => ChangePage(2), "primary"));
var empty = Add(work, "ship-work-empty");
AddDisplay(empty, "No vessel in dock", "ship-work-heading");
AddText(empty, "Acquire a hull at the shipyard before fitting a deck.", "ship-work-detail");
empty.Add(Action("Visit shipyard", () => ChangePage(2), "work-primary", "open-shipyard"));
return;
}
var stats = Add(pageRoot, "deck-stats card");
ForecastMetric(stats, "CABIN BERTHS", ship.Beds.ToString("N0"));
ForecastMetric(stats, "DAILY MEAL CAPACITY", ship.Meals.ToString("N0"));
ForecastMetric(stats, "SHOW SEATS", ship.Entertainment.ToString("N0"));
ForecastMetric(stats, "BUNKER CAPACITY", $"{ship.Tank} t");
deckIndex = Mathf.Clamp(deckIndex, 0, ship.Decks.Count - 1);
var titleBar = Add(work, "ship-work-head");
var heading = Add(titleBar, "ship-work-name");
AddText(heading, "DECK PLANS", "work-caption");
AddDisplay(heading, ship.Name, "ship-work-heading");
AddText(heading, $"{ship.Hull.Name} hull · Deck {deckIndex + 1} of {ship.Decks.Count}", "ship-work-detail");
var workbench = Add(pageRoot, "columns second-row");
var plan = Card(workbench, ship.Name, "wide deck-card");
var tabs = Add(plan, "deck-tabs");
var deckControls = Add(titleBar, "work-deck-controls");
var selector = Add(deckControls, "work-deck-selector");
for (int i = 0; i < ship.Decks.Count; i++)
{
int floor = i;
tabs.Add(Action($"Deck {i + 1}", () => { deckIndex = floor; Notify(null); Render(); },
deckIndex == i ? "active-option" : "", $"deck-{i}"));
Button level = Action($"Deck {i + 1}", () =>
{
deckIndex = floor;
Notify(null);
Render();
}, "work-deck-tab", $"deck-{i}");
level.EnableInClassList("work-selected", deckIndex == i);
selector.Add(level);
}
int price = company.DeckPrice(ship);
Button add = Action($"+ Deck · {Money(price)}", () => Apply(company.AddDeck(ship), "Added a new deck."), "add-deck", "add-deck");
add.SetEnabled(ship.Decks.Count < ship.Hull.MaxDecks && company.Cash >= price);
tabs.Add(add);
var diagram = Add(plan, "blueprint");
var axes = Add(diagram, "axes");
AddText(axes, "STERN", "eyebrow");
AddText(axes, $"DECK {deckIndex + 1:00} / {ship.Hull.Columns * ship.Hull.Rows} MODULE BERTHS", "eyebrow deck-axis");
AddText(axes, "BOW →", "eyebrow");
int deckPrice = company.DeckPrice(ship);
string addLabel = ship.Decks.Count == ship.Hull.MaxDecks ? "Deck limit reached" : $"+ Deck {Money(deckPrice)}";
Button add = Action(addLabel, () =>
{
string failure = company.AddDeck(ship);
if (failure == null)
deckIndex = ship.Decks.Count - 1;
Apply(failure, "New deck ready to fit out.");
}, "work-deck-add", "add-deck");
add.SetEnabled(ship.Decks.Count < ship.Hull.MaxDecks && company.Cash >= deckPrice);
deckControls.Add(add);
var board = Add(work, "work-draft");
board.generateVisualContent += context => DrawDeckOutline(context, ship.Hull.Columns);
var markings = Add(board, "work-draft-markings");
markings.pickingMode = PickingMode.Ignore;
AddText(markings, "STERN", "work-caption");
AddText(markings, "TOP VIEW", "work-caption");
AddText(markings, "BOW →", "work-caption");
var layout = Add(board, "work-berth-grid");
var placement = Add(board, "work-placement");
var placementLabel = AddText(placement, PlacementInstruction(tool), "work-placement-text");
for (int row = 0; row < ship.Hull.Rows; row++)
{
var strip = Add(diagram, "cell-row");
var strip = Add(layout, "work-berth-row");
for (int column = 0; column < ship.Hull.Columns; column++)
{
int cell = row * ship.Hull.Columns + column;
Facility room = ship.Decks[deckIndex].Cells[cell];
string label = $"{(char)('A' + row)}{column + 1}";
string berthName = $"{(char)('A' + row)}{column + 1}";
Facility existing = ship.Decks[deckIndex].Cells[cell];
FacilitySpec room = Market.Facilities[(int)existing];
Button berth = Action("", () =>
{
Facility previous = ship.Decks[deckIndex].Cells[cell];
string success = tool == Facility.Empty ? $"Cleared berth {label}." : $"Built {Market.Facilities[(int)tool].Name.ToLowerInvariant()} at {label}.";
Apply(company.Build(ship, deckIndex, cell, tool), previous == tool ? null : success);
}, "berth room-" + (int)room, "berth-" + cell);
bool occupied = room != Facility.Empty;
FacilitySpec spec = Market.Facilities[(int)room];
berth.tooltip = $"{label} · {(occupied ? spec.Name : "Empty berth")}";
AddText(berth, label, "cell-label");
AddText(berth, occupied ? spec.Mark : "+", "cell-mark");
string failure = company.Build(ship, deckIndex, cell, tool);
if (failure == null && previous != tool)
SetRecommendedFuel();
string confirmation = tool == Facility.Empty
? $"Cleared berth {berthName}."
: $"Built {Market.Facilities[(int)tool].Name.ToLowerInvariant()} at {berthName}.";
Apply(failure, previous == tool ? null : confirmation);
}, "work-berth work-room-" + (int)existing, "berth-" + cell);
string description = BerthDescription(berthName, existing, tool);
berth.tooltip = description;
berth.RegisterCallback<PointerEnterEvent>(_ => placementLabel.text = description);
berth.RegisterCallback<PointerLeaveEvent>(_ => placementLabel.text = PlacementInstruction(tool));
berth.RegisterCallback<FocusInEvent>(_ => placementLabel.text = description);
berth.RegisterCallback<FocusOutEvent>(_ => placementLabel.text = PlacementInstruction(tool));
AddText(berth, berthName, "work-berth-index");
if (existing == Facility.Empty)
AddText(berth, "+", "work-berth-open");
else
{
var center = Add(berth, "work-berth-center");
center.pickingMode = PickingMode.Ignore;
AddFacilityMark(center, existing);
AddText(center, room.Name, "work-berth-name");
}
strip.Add(berth);
}
}
AddText(plan, $"The current plan serves up to {ship.Capacity:N0} guests per voyage.", "body-copy deck-hint");
var exterior = Add(plan, "exterior-preview");
AddHarbor(exterior);
var catalog = Card(workbench, "Facilities", "narrow");
var fittings = Add(work, "work-fittings");
var gauges = Add(fittings, "work-capacity-strip");
AddText(gauges, $"{ship.Beds:N0} berths", "work-capacity");
AddText(gauges, $"{ship.Meals:N0} meal covers", "work-capacity");
AddText(gauges, $"{ship.Entertainment:N0} show seats", "work-capacity");
AddText(gauges, $"{ship.Tank:N0} t bunker capacity", "work-capacity");
AddText(gauges, $"{ship.Capacity:N0} guests per sailing", "work-capacity work-capacity-emphasis");
var tools = Add(fittings, "work-tool-tray");
for (int i = 1; i <= Market.Facilities.Count; i++)
{
int type = i % Market.Facilities.Count;
FacilitySpec spec = Market.Facilities[type];
Button option = Action("", () => { tool = (Facility)type; Notify(null); Render(); },
tool == (Facility)type ? "facility active-option" : "facility", "facility-" + type);
AddText(option, spec.Mark, "facility-mark room-" + type);
var details = Add(option, "facility-details");
AddText(details, spec.Name, "facility-title");
AddText(details, spec.Details, "muted");
AddText(option, type > 0 ? Money(spec.Price) : "", "facility-price gold");
catalog.Add(option);
Facility option = (Facility)(i % Market.Facilities.Count);
FacilitySpec spec = Market.Facilities[(int)option];
Button button = Action("", () =>
{
tool = option;
Notify(null);
Render();
}, "work-tool work-tool-" + (int)option, "facility-" + (int)option);
button.EnableInClassList("work-selected", option == tool);
button.tooltip = spec.Details;
AddFacilityMark(button, option);
var copy = Add(button, "work-tool-copy");
copy.pickingMode = PickingMode.Ignore;
AddText(copy, spec.Name, "work-tool-name");
AddText(copy, option == Facility.Empty ? spec.Details : Money(spec.Price), "work-tool-cost");
tools.Add(button);
}
}
private void DrawShipyard(VisualElement pageRoot)
private static string PlacementInstruction(Facility selected)
{
var columns = Add(pageRoot, "columns");
var inventory = Card(columns, "Available hulls", "wide");
FacilitySpec spec = Market.Facilities[(int)selected];
return selected == Facility.Empty
? "Select a fitted berth to remove its facility and recover 25%."
: $"Select an open berth to build {spec.Name.ToLowerInvariant()}. {spec.Details} · {Money(spec.Price)}";
}
private static string BerthDescription(string berth, Facility room, Facility selected)
{
FacilitySpec existing = Market.Facilities[(int)room];
if (room == Facility.Empty)
return selected == Facility.Empty
? $"{berth} is already clear."
: $"{berth} · Place {Market.Facilities[(int)selected].Name.ToLowerInvariant()}";
return selected == Facility.Empty
? $"{berth} · Remove {existing.Name.ToLowerInvariant()} and recover {Money(existing.Price / 4)}"
: $"{berth} · {existing.Name} · {existing.Details}";
}
private static void AddFacilityMark(VisualElement parent, Facility facility)
{
var mark = Add(parent, "work-facility-icon work-mark-" + (int)facility);
mark.pickingMode = PickingMode.Ignore;
mark.generateVisualContent += context =>
{
Painter2D pen = context.painter2D;
float scale = context.visualElement.contentRect.width / 24;
Vector2 Point(float x, float y) => new Vector2(x * scale, y * scale);
pen.strokeColor = new Color(.88f, .94f, .89f);
pen.lineWidth = 1.6f;
pen.BeginPath();
void Line(float x1, float y1, float x2, float y2)
{
pen.MoveTo(Point(x1, y1));
pen.LineTo(Point(x2, y2));
}
void Segment(params float[] xy)
{
pen.MoveTo(Point(xy[0], xy[1]));
for (int i = 2; i < xy.Length; i += 2)
pen.LineTo(Point(xy[i], xy[i + 1]));
}
switch (facility)
{
case Facility.Cabin:
Segment(3,18,3,6,5,6,5,12,20,12,20,18);
Line(4,16,20,16);
Segment(6,11,6,9,10,9,10,11);
Segment(11,11,11,8,18,8,20,10,20,12);
break;
case Facility.Dining:
Segment(9,9,11,7,15,7,17,10,17,14,15,17,11,17,9,15,9,9);
Segment(3,5,3,10,5,12,7,10,7,5);
Line(5,11,5,19);
Segment(21,5,19,8,19,12,21,12,21,19);
break;
case Facility.Entertainment:
Segment(3,19,3,5,21,5,21,19);
Segment(4,7,9,7,7,13,4,16);
Segment(20,7,15,7,17,13,20,16);
Line(9,19,15,19);
break;
case Facility.Tank:
Segment(6,20,6,9,8,7,16,7,18,9,18,20,6,20);
Segment(10,7,10,4,14,4,14,7);
Line(6,11,18,11);
Line(6,16,18,16);
break;
default:
Line(6,6,18,18);
Line(6,18,18,6);
break;
}
pen.Stroke();
};
}
private void DrawShipyard(VisualElement workspace)
{
var work = Add(workspace, "ship-work yard-work");
(int hullIndex, bool used) = Offers[yardSelection];
HullSpec hull = Market.Hulls[hullIndex];
var titleBar = Add(work, "ship-work-head");
var heading = Add(titleBar, "ship-work-name");
AddText(heading, "MIAMI SHIPYARD", "work-caption");
AddDisplay(heading, used ? $"Pre-owned {hull.Name}" : $"{hull.Name} commission", "ship-work-heading");
AddText(heading, used ? "Fitted for service · 72% condition at delivery" : hull.Description, "ship-work-detail");
var stamp = Add(titleBar, "work-yard-stamp");
AddText(stamp, "DELIVERY AT MIAMI", "work-caption");
AddText(stamp, $"{hull.MaxDecks} decks max · {hull.Columns * hull.Rows} berths per deck · {hull.Tank} t fuel", "work-yard-specs");
var slipway = Add(work, "work-slipway");
slipway.generateVisualContent += context => DrawYardElevation(context, hullIndex, used);
var markings = Add(slipway, "work-draft-markings");
markings.pickingMode = PickingMode.Ignore;
AddText(markings, "STARBOARD ELEVATION", "work-caption");
AddText(markings, used ? "FITTED HULL" : $"BARE HULL / {Market.FirstDecks} STARTER DECKS", "work-caption");
var inventory = Add(work, "work-ship-inventory");
for (int item = 0; item < Offers.Length; item++)
{
int selection = item;
var offer = Offers[item];
HullSpec hull = Market.Hulls[offer.HullIndex];
Button option = Action("", () => { yardSelection = selection; Notify(null); Render(); },
selection == yardSelection ? "yard-item active-option" : "yard-item", "yard-" + item);
var itemCopy = Add(option, "yard-copy");
AddText(itemCopy, offer.Used ? $"Pre-owned {hull.Name}" : $"New {hull.Name}", "option-title");
AddText(itemCopy, offer.Used ? "Fitted with cabins, dining and entertainment. Condition 72%." : hull.Description, "muted");
AddText(option, Money(offer.Used ? Market.UsedPrice(offer.HullIndex) : hull.Price), "yard-price gold");
HullSpec candidate = Market.Hulls[offer.HullIndex];
bool locked = company.Voyages < candidate.Voyages || company.Reputation < candidate.Reputation;
Button option = Action("", () =>
{
yardSelection = selection;
Notify(null);
Render();
}, "work-offer", "yard-" + item);
option.EnableInClassList("work-selected", selection == yardSelection);
AddText(option, locked ? "LOCKED" : offer.Used ? "PRE-OWNED" : "NEW HULL", "work-caption");
AddText(option, candidate.Name, "work-offer-name");
AddText(option, Money(offer.Used ? Market.UsedPrice(offer.HullIndex) : candidate.Price), "work-offer-price");
inventory.Add(option);
}
(int hullIndex, bool secondhand) = Offers[yardSelection];
HullSpec chosen = Market.Hulls[hullIndex];
var purchase = Card(columns, secondhand ? "Take delivery" : "Commission a hull", "narrow");
AddLine(purchase, "Hull class", chosen.Name);
AddLine(purchase, "Decks at delivery", Market.FirstDecks.ToString());
AddLine(purchase, "Maximum decks", chosen.MaxDecks.ToString());
AddLine(purchase, "Module berths / deck", (chosen.Columns * chosen.Rows).ToString());
AddLine(purchase, "Base fuel capacity", $"{chosen.Tank} t");
AddLine(purchase, "Delivery port", "Miami");
if (!secondhand)
var order = Add(work, "work-order");
DrawShipyardOrder(order, hullIndex, used);
if (Ship != null)
DrawShipyardService(order, Ship);
}
private void DrawShipyardOrder(VisualElement order, int hullIndex, bool used)
{
var purchase = Add(order, "work-purchase");
if (!used)
{
AddText(purchase, "VESSEL NAME", "eyebrow control-label");
var nameControl = Add(purchase, "work-name-control");
AddText(nameControl, "VESSEL NAME", "work-caption");
var field = new TextField { value = shipName, maxLength = 24, name = "vessel-name" };
field.AddToClassList("field");
field.AddToClassList("work-name-field");
field.RegisterValueChangedCallback(evt => shipName = evt.newValue);
purchase.Add(field);
nameControl.Add(field);
}
string block = company.ShipyardBlock(hullIndex, secondhand);
Button buy = Action(secondhand ? "Purchase vessel →" : "Commission hull →", () =>
string block = company.ShipyardBlock(hullIndex, used);
var contract = Add(purchase, "work-contract");
long price = used ? Market.UsedPrice(hullIndex) : Market.Hulls[hullIndex].Price;
Button buy = Action(used ? $"Purchase · {Money(price)}" : $"Commission · {Money(price)}", () =>
{
string failure = company.Acquire(hullIndex, secondhand, shipName);
string failure = company.Acquire(hullIndex, used, shipName);
if (failure == null)
{
deckIndex = 0;
ResetItinerary();
page = secondhand ? 0 : 1;
page = used ? 0 : 1;
}
Apply(failure, secondhand ? "The vessel is ready in Miami." : "The hull is ready. Fit cabins and dining before sailing.");
}, "primary full-button", "buy-ship");
Apply(failure, used ? "The vessel is ready in Miami." : "The hull is ready. Fit cabins and dining before sailing.");
}, "work-primary work-commission", "buy-ship");
buy.SetEnabled(block == null);
contract.Add(buy);
if (block != null)
AddText(purchase, block, "body-copy");
purchase.Add(buy);
AddText(contract, block, "work-contract-block");
}
if (Ship == null)
return;
Ship ship = Ship;
var service = Card(pageRoot, "Maintenance", "second-row");
var condition = Add(service, "maintenance-row");
AddText(condition, $"{ship.Name} · {ship.Condition}% condition", "body-copy");
private void DrawShipyardService(VisualElement order, Ship ship)
{
var service = Add(order, "work-service");
var shipInfo = Add(service, "work-service-info");
AddText(shipInfo, ship.Name, "work-offer-name");
AddText(shipInfo, $"{ship.Condition}% condition", "work-yard-specs");
int price = company.ServiceCost(ship);
Button overhaul = Action($"Overhaul · {Money(price)}", () =>
Button overhaul = Action(price > 0 ? $"Overhaul · {Money(price)}" : "No repairs needed", () =>
{
string failure = company.Service(ship);
if (failure == null)
SetRecommendedFuel();
Apply(failure, "The ship has been restored to 100% condition.");
}, "", "overhaul");
}, "work-overhaul", "overhaul");
overhaul.SetEnabled(price > 0 && company.Cash >= price);
condition.Add(overhaul);
service.Add(overhaul);
}
private static void DrawDeckOutline(MeshGenerationContext context, int columns)
{
Rect bounds = context.visualElement.contentRect;
if (bounds.width <= 0 || bounds.height <= 0)
return;
Painter2D pen = context.painter2D;
Vector2 P(float x, float y) => new Vector2(bounds.width * x, bounds.height * y);
DrawDraftGrid(pen, bounds, 26);
void Hull(float inset)
{
Vector2 aftPort = P(.047f + inset, .37f + inset);
Vector2 portShoulder = P(.17f + inset, .145f + inset);
Vector2 portBow = P(.75f - inset, .145f + inset);
Vector2 bow = P(.965f - inset, .50f);
Vector2 starboardBow = P(.75f - inset, .855f - inset);
Vector2 starboardShoulder = P(.17f + inset, .855f - inset);
Vector2 aftStarboard = P(.047f + inset, .63f - inset);
pen.MoveTo(aftPort);
TraceDraftCurve(pen, aftPort, P(.078f + inset, .16f + inset), portShoulder);
pen.LineTo(portBow);
TraceDraftCurve(pen, portBow, P(.91f - inset, .15f + inset), bow);
TraceDraftCurve(pen, bow, P(.91f - inset, .85f - inset), starboardBow);
pen.LineTo(starboardShoulder);
TraceDraftCurve(pen, starboardShoulder, P(.078f + inset, .84f - inset), aftStarboard);
pen.LineTo(aftPort);
}
pen.fillColor = new Color(.065f, .18f, .217f, .98f);
pen.strokeColor = DraftInk;
pen.lineWidth = 2;
pen.BeginPath();
Hull(0);
pen.Fill();
pen.Stroke();
pen.strokeColor = DraftFine;
pen.lineWidth = 1;
pen.BeginPath();
Hull(.014f);
pen.Stroke();
pen.BeginPath();
void Guide(float x, float top, float control, float bottom)
{
Vector2 start = P(x, top);
pen.MoveTo(start);
TraceDraftCurve(pen, start, P(control, .50f), P(x, bottom));
}
Guide(.104f, .23f, .145f, .77f);
Guide(.780f, .18f, .853f, .82f);
Guide(.824f, .21f, .894f, .79f);
Guide(.872f, .28f, .937f, .72f);
pen.Stroke();
pen.BeginPath();
for (int i = 0; i <= columns; i++)
{
float station = Mathf.Lerp(.135f, .785f, i / (float)columns);
pen.MoveTo(P(station, .198f));
pen.LineTo(P(station, .256f));
pen.MoveTo(P(station, .744f));
pen.LineTo(P(station, .80f));
}
for (int i = 0; i < 9; i++)
{
float y = .37f + .033f * i;
pen.MoveTo(P(.073f, y));
pen.LineTo(P(.094f, y));
}
pen.MoveTo(P(.055f, .50f));
pen.LineTo(P(.131f, .50f));
pen.MoveTo(P(.789f, .50f));
pen.LineTo(P(.948f, .50f));
pen.Stroke();
pen.strokeColor = DraftGold;
pen.BeginPath();
pen.MoveTo(P(.91f, .47f));
pen.LineTo(P(.934f, .50f));
pen.LineTo(P(.91f, .53f));
pen.Stroke();
}
private static void DrawYardElevation(MeshGenerationContext context, int hullIndex, bool used)
{
Rect bounds = context.visualElement.contentRect;
if (bounds.width <= 0 || bounds.height <= 0)
return;
Painter2D pen = context.painter2D;
DrawDraftGrid(pen, bounds, 33);
Vector2 P(float x, float y) => new Vector2(bounds.width * x, bounds.height * y);
float stern = .178f - hullIndex * .028f;
float bow = .833f + hullIndex * .029f;
float L(float position) => Mathf.Lerp(stern, bow, position);
void Path(params float[] xy)
{
pen.MoveTo(P(L(xy[0]), xy[1]));
for (int i = 2; i < xy.Length; i += 2)
pen.LineTo(P(L(xy[i]), xy[i + 1]));
}
pen.strokeColor = DraftFine;
pen.lineWidth = 1;
pen.BeginPath();
for (int i = 0; i < 33; i++)
{
float x = .055f + i * .028f;
pen.MoveTo(P(x, .80f));
pen.LineTo(P(x, i % 4 == 0 ? .85f : .825f));
}
pen.MoveTo(P(.055f, .80f));
pen.LineTo(P(.955f, .80f));
for (int i = 1; i < 13; i++)
{
float position = i / 13f;
pen.MoveTo(P(L(position), .665f));
pen.LineTo(P(L(position - .022f), .80f));
pen.LineTo(P(L(position + .026f), .80f));
pen.ClosePath();
}
pen.Stroke();
pen.strokeColor = DraftGold;
pen.lineWidth = 1.35f;
pen.BeginPath();
Path(0,.875f, 0,.918f);
Path(0,.897f, 1,.897f);
Path(1,.875f, 1,.918f);
Path(0,.897f, .012f,.881f);
Path(0,.897f, .012f,.913f);
Path(1,.897f, .988f,.881f);
Path(1,.897f, .988f,.913f);
pen.Stroke();
pen.fillColor = new Color(.13f, .23f, .24f);
pen.strokeColor = DraftInk;
pen.lineWidth = 1.8f;
pen.BeginPath();
Vector2 transom = P(stern, .56f);
Vector2 aftDeck = P(L(.21f), .565f);
Vector2 foreDeck = P(L(.79f), .565f);
Vector2 stem = P(bow, .49f);
Vector2 forwardKeel = P(L(.903f), .712f);
Vector2 aftKeel = P(L(.135f), .712f);
pen.MoveTo(transom);
TraceDraftCurve(pen, transom, P(L(.11f), .57f), aftDeck);
pen.LineTo(foreDeck);
TraceDraftCurve(pen, foreDeck, P(L(.94f), .565f), stem);
TraceDraftCurve(pen, stem, P(L(.974f), .64f), forwardKeel);
pen.LineTo(aftKeel);
TraceDraftCurve(pen, aftKeel, P(L(.047f), .702f), transom);
pen.Fill();
pen.Stroke();
pen.strokeColor = DraftGold;
pen.lineWidth = 1;
pen.BeginPath();
Path(.026f,.609f, .119f,.627f, .885f,.627f, .959f,.579f);
pen.Stroke();
int levels = Market.FirstDecks;
int allowedDecks = Market.Hulls[hullIndex].MaxDecks;
pen.strokeColor = new Color(DraftFine.r, DraftFine.g, DraftFine.b, .28f);
pen.BeginPath();
for (int level = levels; level < allowedDecks; level++)
{
float y = .561f - level * .068f;
float left = .079f + level * .031f;
float right = .872f - level * .04f;
for (float x = left; x < right; x += .022f)
Path(x, y, Mathf.Min(x + .012f, right), y);
}
pen.Stroke();
for (int level = 0; level < levels; level++)
{
float bottom = .561f - level * .068f;
float left = .079f + level * .031f;
float right = .872f - level * .04f;
pen.fillColor = new Color(.17f + .022f * level, .29f, .30f);
pen.strokeColor = DraftFine;
pen.lineWidth = 1.25f;
pen.BeginPath();
Path(left,bottom, left + .006f,bottom - .055f, right - .036f,bottom - .062f, right,bottom);
pen.ClosePath();
pen.Fill();
pen.Stroke();
pen.strokeColor = DraftInk;
pen.BeginPath();
if (used)
for (float x = left + .022f; x < right - .04f; x += .028f)
Path(x,bottom - .036f, x + .014f,bottom - .036f);
else
for (float x = left + .025f; x < right - .04f; x += .1f)
Path(x,bottom - .026f, x + .050f,bottom - .026f);
pen.Stroke();
}
float top = .57f - levels * .068f;
pen.fillColor = new Color(.38f, .30f, .19f);
pen.strokeColor = DraftGold;
pen.BeginPath();
Path(.403f,top, .420f,top - .111f, .466f,top - .111f, .452f,top);
pen.ClosePath();
pen.Fill();
pen.Stroke();
pen.strokeColor = DraftInk;
pen.BeginPath();
Path(.645f,top + .01f, .645f,top - .125f);
Path(.619f,top - .090f, .671f,top - .090f);
Path(.628f,top - .108f, .662f,top - .108f);
pen.Stroke();
}
private static void TraceDraftCurve(Painter2D pen, Vector2 start, Vector2 control, Vector2 end)
{
// Explicit line segments keep UI Toolkit from closing these curves through the drawing origin.
const int subdivisions = 18;
for (int index = 1; index <= subdivisions; index++)
{
float t = index / (float)subdivisions;
pen.LineTo(Vector2.Lerp(Vector2.Lerp(start, control, t), Vector2.Lerp(control, end, t), t));
}
}
private static void DrawDraftGrid(Painter2D pen, Rect bounds, float cell)
{
pen.strokeColor = DraftGrid;
pen.lineWidth = 1;
pen.BeginPath();
for (float x = bounds.width / 2 % cell; x < bounds.width; x += cell)
{
pen.MoveTo(new Vector2(x, 0));
pen.LineTo(new Vector2(x, bounds.height));
}
for (float y = bounds.height / 2 % cell; y < bounds.height; y += cell)
{
pen.MoveTo(new Vector2(0, y));
pen.LineTo(new Vector2(bounds.width, y));
}
pen.Stroke();
}
}
}

View File

@@ -0,0 +1,199 @@
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private enum GuideStep
{
Off, GetShip, Cabins, Dining, SetCourse, Bunker, Fare, CastOff, Review
}
private const int StarterCabinModules = 4;
private static int StarterBerths => StarterCabinModules * Market.Facilities[(int)Facility.Cabin].Capacity;
private GuideStep guideContext;
private Ship guideFareShip;
private int guideInitialFare;
private void StartGuide(bool financed)
{
guideFareShip = null;
company.TutorialStep = (int)(financed ? GuideStep.GetShip : GuideStep.SetCourse);
}
private void RestartGuide()
{
StartGuide(Ship == null);
paused = false;
Notify(null);
Save();
Render();
}
private void ReviewGuideVoyage()
{
if (company.TutorialStep > 0 && company.Voyages > 0)
company.TutorialStep = (int)GuideStep.Review;
}
private void RefreshGuide()
{
guideContext = GuideStep.Off;
if (title || company == null || company.TutorialStep == 0 || underway != null)
return;
Ship ship = Ship;
if (guideFareShip != ship)
{
guideFareShip = ship;
guideInitialFare = ship?.Fare ?? 0;
}
var reached = (GuideStep)company.TutorialStep;
guideContext = FindGuideContext(ship, reached);
if ((int)guideContext <= company.TutorialStep)
return;
company.TutorialStep = (int)guideContext;
Save();
}
private GuideStep FindGuideContext(Ship ship, GuideStep reached)
{
if (reached == GuideStep.Review)
return GuideStep.Review;
if (ship == null)
return GuideStep.GetShip;
if (ship.Beds < StarterBerths)
return GuideStep.Cabins;
if (ship.Meals < StarterBerths)
return GuideStep.Dining;
Voyage quote = page == 3 ? company.Forecast(ship, inspectedPort) : null;
if (quote == null || !company.Permits[quote.Destination] || ship.HullIndex < Market.Ports[quote.Destination].MinimumHull)
return GuideStep.SetCourse;
if (ship.Fuel < quote.RequiredFuel)
return GuideStep.Bunker;
if (reached == GuideStep.CastOff || ship.Fare != guideInitialFare || company.DepartureBlock(ship, quote) != null)
return GuideStep.CastOff;
return GuideStep.Fare;
}
private void DrawGuide(VisualElement shell)
{
if (guideContext == GuideStep.Off)
return;
(string heading, string note, string target) = GuideMessage();
var guide = Add(shell, "voyage-guide");
guide.pickingMode = PickingMode.Ignore;
GameIcon(guide, "compass");
var instructions = Add(guide, "voyage-guide-copy");
instructions.pickingMode = PickingMode.Ignore;
AddText(instructions, heading, "voyage-guide-heading");
AddText(instructions, note, "voyage-guide-note");
bool reviewing = guideContext == GuideStep.Review && page == 4 && !ledgerAccounts;
guide.Add(Action(reviewing ? "Finish" : "Skip", () =>
{
company.TutorialStep = (int)GuideStep.Off;
Save();
Render();
}, "voyage-guide-close", reviewing ? "guide-finish" : "guide-skip"));
if (!string.IsNullOrEmpty(target))
{
var control = shell.Q<VisualElement>(target);
if (control != null && control.enabledInHierarchy)
control.AddToClassList("guide-target");
}
}
private (string Heading, string Note, string Target) GuideMessage()
{
switch (guideContext)
{
case GuideStep.GetShip:
if (page != 2)
return ("Register your first ship", "Open Shipyard to buy or commission a hull.", "nav-2");
return ("Register your first ship", "Choose a hull you can afford and sign the commission or purchase.", "buy-ship");
case GuideStep.Cabins:
return GuideFacility(Facility.Cabin, $"Outfit passenger cabins · {Ship.Beds}/{StarterBerths} berths");
case GuideStep.Dining:
return GuideFacility(Facility.Dining, $"Fit dining for {StarterBerths} guests");
case GuideStep.Bunker:
Voyage crossing = company.Forecast(Ship, inspectedPort);
if (crossing.RequiredFuel > Ship.Tank)
return ("Extend your range", "Fit a bunker tank in Deck Plans or select a shorter sailing.", "nav-1");
return ("Take on fuel", "In the route sheet, buy enough fuel to cover the burn and reserve.", "buy-fuel");
case GuideStep.Fare:
return ("Set the fare", "Try + or − to see the forecast change, or cast off at the current fare.", "fare-plus");
case GuideStep.CastOff:
Voyage departure = company.Forecast(Ship, inspectedPort);
if (Ship.Condition < 25)
return ("Clear departure", "Visit Shipyard to overhaul the ship before departing.", "nav-2");
if (departure.Guests == 0)
return ("Attract passengers", "Lower the fare until guests are expected to book.", "fare-minus");
string blocker = company.DepartureBlock(Ship, departure);
if (blocker != null)
return ("Clear departure", blocker, null);
return ("Clear departure", "Choose Cast off. Watch the crossing or skip to arrival.", "dispatch");
case GuideStep.Review:
if (page != 4)
return ("Read the arrival statement", "Open the Logbook to see your voyage profit and cash change.", "nav-4");
if (ledgerAccounts)
return ("Read the arrival statement", "Switch to Voyage records to review your latest crossing.", "log-voyages");
return ("Check the passage", "Compare net profit and cash change. You can refit the ship in Deck Plans.", "voyage-0");
default:
return GuideCourse();
}
}
private (string Heading, string Note, string Target) GuideFacility(Facility facility, string heading)
{
if (page != 1)
return (heading, "Open Deck Plans to lay out your ship.", "nav-1");
string facilityName = Market.Facilities[(int)facility].Name;
if (tool != facility)
return (heading, $"Select {facilityName} in the facility tray.", $"facility-{(int)facility}");
int floor = Mathf.Clamp(deckIndex, 0, Ship.Decks.Count - 1);
Facility[] cells = Ship.Decks[floor].Cells;
for (int i = 0; i < cells.Length; i++)
if (cells[i] == Facility.Empty)
return (heading, "Select any empty berth to place it.", $"berth-{i}");
return (heading, "Choose another deck or clear a berth to make room.", null);
}
private (string Heading, string Note, string Target) GuideCourse()
{
const string heading = "Plot the first passage";
if (page == 0)
return (heading, "Choose Set course to see the route from your current berth.", "plan-voyage");
if (page != 3)
return (heading, "Open Chart to select a route and review the departure forecast.", "nav-3");
foreach (Lane lane in Market.Lanes)
{
int next = lane.Other(Ship.Port);
if (next < 0 || !company.Permits[next] || Ship.HullIndex < Market.Ports[next].MinimumHull)
continue;
string port = Market.Ports[next].Name;
if (!worldChart && next >= Market.StarterPortCount)
return (heading, $"Switch to World and select {port} to review that sailing.", "chart-world");
return (heading, $"Select {port}, an open port linked to your current berth.", $"port-{next}");
}
return (heading, "Choose a linked port and acquire a permit before departing.", "chart-directory");
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 65cefb292013b32029c72177aef8eda0

View File

@@ -0,0 +1,127 @@
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private static void Shade(VisualElement parent, bool vertical, params (float Stop, Color32 Tint)[] stops)
{
var element = Add(parent, "screen-shade");
element.pickingMode = PickingMode.Ignore;
element.generateVisualContent += context =>
{
Rect rect = context.visualElement.contentRect;
if (rect.width <= 0 || rect.height <= 0)
return;
int strips = stops.Length - 1;
MeshWriteData mesh = context.Allocate(strips * 4, strips * 6);
for (int i = 0; i < strips; i++)
{
var (from, startColor) = stops[i];
var (to, endColor) = stops[i + 1];
float left = vertical ? 0 : from * rect.width;
float right = vertical ? rect.width : to * rect.width;
float top = vertical ? from * rect.height : 0;
float bottom = vertical ? to * rect.height : rect.height;
mesh.SetNextVertex(ShadeVertex(left, top, startColor));
mesh.SetNextVertex(ShadeVertex(right, top, vertical ? startColor : endColor));
mesh.SetNextVertex(ShadeVertex(right, bottom, endColor));
mesh.SetNextVertex(ShadeVertex(left, bottom, vertical ? endColor : startColor));
int v = i * 4;
mesh.SetNextIndex((ushort)v);
mesh.SetNextIndex((ushort)(v + 1));
mesh.SetNextIndex((ushort)(v + 2));
mesh.SetNextIndex((ushort)v);
mesh.SetNextIndex((ushort)(v + 2));
mesh.SetNextIndex((ushort)(v + 3));
}
};
}
private static Vertex ShadeVertex(float x, float y, Color32 color)
{
return new Vertex { position = new Vector3(x, y, Vertex.nearZ), tint = color, uv = Vector2.zero };
}
private static void GameIcon(VisualElement parent, string shape)
{
var icon = Add(parent, "game-icon " + shape + "-icon");
icon.pickingMode = PickingMode.Ignore;
icon.generateVisualContent += context =>
{
Rect area = context.visualElement.contentRect;
if (area.width <= 0 || area.height <= 0)
return;
float scale = Mathf.Min(area.width, area.height) / 24;
Vector2 center = area.center;
Vector2 Point(float x, float y) => center + new Vector2(x - 12, y - 12) * scale;
Painter2D pen = context.painter2D;
pen.lineWidth = 1.32f * scale;
pen.lineCap = LineCap.Round;
pen.lineJoin = LineJoin.Round;
pen.strokeColor = shape == "chart" && parent.ClassListContains("helm-command")
? new Color32(29, 32, 31, 255) : new Color32(218, 192, 144, 255);
pen.BeginPath();
void Path(params float[] points)
{
pen.MoveTo(Point(points[0], points[1]));
for (int i = 2; i < points.Length; i += 2)
pen.LineTo(Point(points[i], points[i + 1]));
}
switch (shape)
{
case "compass":
Path(12, 1, 20, 7, 20, 17, 12, 23, 4, 17, 4, 7, 12, 1);
Path(8, 16, 11, 8, 16, 7, 13, 15, 8, 16);
Path(11, 8, 13, 15);
break;
case "anchor":
pen.Arc(Point(12, 5), 2.2f * scale, 0, 360);
Path(12, 7.5f, 12, 21, 7, 19, 4, 15);
Path(12, 21, 17, 19, 20, 15);
Path(3, 18, 4, 15, 7, 15);
Path(17, 15, 20, 15, 21, 18);
Path(8, 11, 16, 11);
break;
case "decks":
Path(3, 9, 12, 4, 21, 9, 12, 14, 3, 9);
Path(3, 13, 12, 18, 21, 13);
Path(3, 17, 12, 22, 21, 17);
break;
case "chart":
Path(3, 7, 8, 4, 16, 7, 21, 4, 21, 18, 16, 21, 8, 18, 3, 21, 3, 7);
Path(8, 4, 8, 18);
Path(16, 7, 16, 21);
Path(5, 15, 10, 11, 14, 12, 19, 8);
break;
case "yard":
Path(4, 21, 4, 6, 21, 6, 17, 3, 8, 3, 4, 6);
Path(7, 21, 7, 6);
Path(16, 6, 16, 12, 14, 13, 15, 15, 17, 15, 18, 13);
Path(2, 21, 21, 21);
break;
case "log":
Path(5, 5, 11, 5, 12, 7, 13, 5, 20, 5, 20, 19, 13, 19, 12, 21, 11, 19, 5, 19, 5, 5);
Path(12, 7, 12, 21);
Path(7, 10, 10, 10);
Path(14, 10, 18, 10);
Path(14, 13, 17, 13);
break;
default:
Path(5, 7, 19, 7);
Path(5, 12, 19, 12);
Path(5, 17, 19, 17);
break;
}
pen.Stroke();
};
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f665ceaaedd60f56fac4d4880f870534

View File

@@ -18,6 +18,12 @@ namespace Soundings
private int lastHull = -2, lastDecks;
private string currentBackplate;
private ulong lastLayout;
private const float DefaultYaw = 37f, DefaultPitch = 17.5f;
private float yaw = DefaultYaw, pitch = DefaultPitch, zoom = 1f;
private float targetYaw = DefaultYaw, targetPitch = DefaultPitch, targetZoom = 1f;
private float passage;
private bool sailing;
private Bounds hullBounds;
public RenderTexture Frame { get; private set; }
@@ -38,9 +44,7 @@ namespace Soundings
viewCamera.cullingMask = 1 << 8;
viewCamera.enabled = false;
var center = new Vector3(3.2f, 3.5f, 0);
viewCamera.transform.position = center + new Vector3(61, 24, -104) * 2.3f;
viewCamera.transform.LookAt(center);
ComposeCamera();
var waterObject = new GameObject("Harbor backdrop and water", typeof(MeshFilter), typeof(MeshRenderer));
waterObject.layer = 8;
@@ -55,6 +59,93 @@ namespace Soundings
public void SetVisible(bool visible) => viewCamera.enabled = visible;
public void Orbit(Vector2 drag)
{
targetYaw = Mathf.Clamp(targetYaw - drag.x * .18f, 3f, 72f);
targetPitch = Mathf.Clamp(targetPitch + drag.y * .13f, 12f, 30f);
}
public void Zoom(float delta)
{
targetZoom = Mathf.Clamp(targetZoom * Mathf.Exp(delta * .050f), .64f, 1.51f);
}
public void ResetView(bool immediate = false)
{
targetYaw = DefaultYaw;
targetPitch = DefaultPitch;
targetZoom = 1f;
if (!immediate)
return;
yaw = targetYaw;
pitch = targetPitch;
zoom = targetZoom;
ComposeCamera();
}
public bool IsShipAt(Vector2 viewportPoint)
{
return vessel != null && hullBounds.IntersectRay(viewCamera.ViewportPointToRay(viewportPoint));
}
public void BeginPassage()
{
sailing = true;
targetYaw = 22f;
targetPitch = 16f;
targetZoom = 1.02f;
SetPassage(0);
}
public void SetPassage(float progress)
{
passage = progress;
float travel = Mathf.Lerp(-3.6f, 9.25f, progress);
if (vessel != null)
vessel.localPosition = new Vector3(travel, Mathf.Sin(progress * 19f) * .073f, 0);
Vector4 hull = water.GetVector("_HullSpan");
hull.z = travel;
water.SetVector("_HullSpan", hull);
water.SetFloat("_Underway", Mathf.SmoothStep(.3f, 1, Mathf.Clamp01(progress * 5)));
}
public void EndPassage()
{
sailing = false;
passage = 0;
if (vessel != null)
vessel.localPosition = Vector3.zero;
Vector4 hull = water.GetVector("_HullSpan");
hull.z = 0;
water.SetVector("_HullSpan", hull);
water.SetFloat("_Underway", 0);
ResetView(true);
}
private void LateUpdate()
{
if (!viewCamera.enabled)
return;
float easing = 1 - Mathf.Exp(-Time.unscaledDeltaTime * 11f);
if (!sailing && Mathf.Abs(yaw - targetYaw) < .005f && Mathf.Abs(pitch - targetPitch) < .005f &&
Mathf.Abs(zoom - targetZoom) < .0001f)
return;
yaw = Mathf.Lerp(yaw, targetYaw, easing);
pitch = Mathf.Lerp(pitch, targetPitch, easing);
zoom = Mathf.Lerp(zoom, targetZoom, easing);
ComposeCamera();
}
private void ComposeCamera()
{
var center = new Vector3(2.1f, 4.25f, 0);
if (sailing)
center.x += Mathf.Lerp(-2, 6.5f, passage);
Quaternion orbit = Quaternion.Euler(pitch, -yaw, 0);
viewCamera.transform.SetPositionAndRotation(center + orbit * (Vector3.back * 244f), orbit);
FitViewport();
}
private void SetHarbor(string region)
{
string backdrop = region switch
@@ -94,14 +185,29 @@ namespace Soundings
if (Frame == null)
return;
float aspect = (float)Frame.width / Frame.height;
viewCamera.orthographicSize = Mathf.Max(15.4f, vesselLength * .59f / aspect);
water.SetVector("_BackdropCrop", new Vector4(Mathf.Min(1, aspect / backplateRatio),
Mathf.Min(1, backplateRatio / aspect), 0, 0));
viewCamera.orthographicSize = Mathf.Max(17.6f, vesselLength * .71f / aspect) * zoom;
if (backplateRatio <= 0)
return;
float cropX = Mathf.Min(1, aspect / backplateRatio) * .95f;
float cropY = Mathf.Min(1, backplateRatio / aspect) * .95f;
float shiftX = Mathf.Clamp((yaw - DefaultYaw) * .00225f, -.47f * (1 - cropX), .47f * (1 - cropX));
float shiftY = Mathf.Clamp((pitch - DefaultPitch) * .002f, -.47f * (1 - cropY), .47f * (1 - cropY));
water.SetVector("_BackdropCrop", new Vector4(cropX, cropY, shiftX, shiftY));
}
public void Show(Ship ship)
{
SetHarbor(Market.Ports[ship.Port].Region);
SetHarbor(Market.Ports[ship?.Port ?? 0].Region);
if (ship == null)
{
if (lastHull == -1)
return;
lastHull = -1;
ReleaseShip();
water.SetVector("_HullSpan", Vector4.zero);
return;
}
int hullIndex = ship.HullIndex;
int deckCount = ship.Decks.Count;
ulong layout = 0;
@@ -123,6 +229,7 @@ namespace Soundings
vesselLength = 71 + hullIndex * 12;
float beam = 6.65f + hullIndex * .87f;
water.SetVector("_HullSpan", new Vector4(vesselLength, beam, 0, 0));
hullBounds = new Bounds(new Vector3(0, 5.5f, 0), new Vector3(vesselLength, 12.3f + deckCount * 1.7f, beam * 2.1f));
FitViewport();
var exterior = new VesselExterior(ship, vesselLength, beam);

View File

@@ -0,0 +1,262 @@
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private bool ledgerAccounts;
private float ledgerRecordOffset;
private void DrawFinance(VisualElement pageRoot)
{
var workspace = Add(pageRoot, "log-workspace");
var reader = new ScrollView(ScrollViewMode.Vertical)
{
verticalScrollerVisibility = ScrollerVisibility.Auto
};
reader.AddToClassList("log-reader");
workspace.Add(reader);
var folio = Add(reader, "log-folio");
var head = Add(folio, "log-heading");
AddDisplay(head, "Captain’s log", "log-title");
var tabs = Add(head, "log-tabs");
AddLogTab(tabs, "Voyage records", false, "log-voyages");
AddLogTab(tabs, "Company accounts", true, "log-accounts");
var binding = Add(folio, "log-binding");
var sheets = Add(binding, "log-sheets");
var left = Add(sheets, "log-leaf log-left-leaf");
var spine = Add(sheets, "log-spine");
spine.pickingMode = PickingMode.Ignore;
var right = Add(sheets, "log-leaf log-right-leaf");
if (ledgerAccounts)
DrawAccounts(left, right);
else
DrawVoyageRecords(left, right);
}
private void AddLogTab(VisualElement parent, string label, bool accounts, string id)
{
bool selected = ledgerAccounts == accounts;
Button button = Action(label, () =>
{
if (ledgerAccounts == accounts)
return;
ledgerAccounts = accounts;
Render();
}, selected ? "log-tab log-tab-active" : "log-tab", id);
parent.Add(button);
}
private void DrawVoyageRecords(VisualElement register, VisualElement entry)
{
AddText(register, "VOYAGE REGISTER", "log-small-title");
AddDisplay(register, "Passages", "log-sheet-title");
AddText(register, $"{company.Voyages:N0} completed", "log-secondary");
AddText(register, company.Flagship
? "Flagship charter complete · Bermuda to Lisbon"
: "Flagship charter · Bermuda to Lisbon",
"log-note " + (company.Flagship ? "log-positive" : "log-charter"));
if (!company.Flagship)
AddText(register, "Ocean Class hull · 320 berths · 160 show seats", "log-charter-terms");
if (company.History.Count == 0)
{
DrawEmptyLog(register, entry);
return;
}
var tableHead = Add(register, "log-index-heading");
AddText(tableHead, "DAY", "log-index-day");
AddText(tableHead, "PASSAGE", "log-index-passage");
AddText(tableHead, "NET PROFIT", "log-index-amount");
selectedVoyage = Mathf.Clamp(selectedVoyage, 0, company.History.Count - 1);
var recordList = new ScrollView(ScrollViewMode.Vertical) { verticalScrollerVisibility = ScrollerVisibility.Auto };
recordList.AddToClassList("log-index");
register.Add(recordList);
for (int i = 0; i < company.History.Count; i++)
{
int record = i;
Voyage trip = company.History[i];
string route = $"{Market.Ports[trip.Origin].Name} to {Market.Ports[trip.Destination].Name}";
Button item = Action("", () =>
{
ledgerRecordOffset = recordList.verticalScroller.value;
selectedVoyage = record;
Render();
}, i == selectedVoyage ? "log-entry log-entry-active" : "log-entry", "voyage-" + i);
item.tooltip = route + " aboard " + trip.ShipName;
AddText(item, trip.Day.ToString(), "log-index-day");
var line = Add(item, "log-index-passage");
AddText(line, route, "log-entry-route");
AddText(line, trip.ShipName, "log-entry-ship");
AddText(item, Money(trip.NetIncome), "log-index-amount " + LogAmountColor(trip.NetIncome));
recordList.Add(item);
}
recordList.verticalScroller.valueChanged += offset => ledgerRecordOffset = offset;
if (ledgerRecordOffset > 0)
{
float restore = ledgerRecordOffset;
recordList.schedule.Execute(() => recordList.scrollOffset = new Vector2(0, restore));
}
if (company.Voyages > company.History.Count)
AddText(register, $"Showing the latest {company.History.Count} voyages", "log-note");
DrawVoyageEntry(entry, company.History[selectedVoyage]);
}
private void DrawEmptyLog(VisualElement register, VisualElement entry)
{
var ruling = Add(register, "log-unused-lines");
ruling.pickingMode = PickingMode.Ignore;
ruling.generateVisualContent += DrawLedgerRuling;
var empty = Add(entry, "log-empty");
var compass = Add(empty, "log-compass");
compass.pickingMode = PickingMode.Ignore;
compass.generateVisualContent += DrawLedgerCompass;
AddDisplay(empty, "Awaiting first arrival", "log-sheet-title log-centered");
AddText(empty, "Complete a sailing to record its passengers, costs and earnings.", "log-note log-centered");
if (Ship != null)
empty.Add(Action("Set course", OpenVoyageChart, "log-paper-action", "log-set-course"));
else
empty.Add(Action("Visit shipyard", () => ChangePage(2), "log-paper-action", "log-visit-yard"));
}
private void DrawVoyageEntry(VisualElement leaf, Voyage trip)
{
AddText(leaf, $"ARRIVED ON DAY {trip.Day}", "log-small-title");
string origin = Market.Ports[trip.Origin].Name;
string destinationName = Market.Ports[trip.Destination].Name;
AddDisplay(leaf, $"{origin} to {destinationName}", "log-sheet-title log-route-title");
AddText(leaf, $"{trip.ShipName} · {trip.Miles:N0} nm over {trip.Days} days", "log-secondary");
AddText(leaf, $"{trip.Guests:N0} passengers · {trip.FuelBurn:N0} t of fuel consumed", "log-secondary");
var statement = Add(leaf, "log-statement");
LogLine(statement, "Ticket revenue", Money(trip.TicketSales));
LogLine(statement, "Onboard revenue", Money(trip.OnboardSales));
LogLine(statement, "Crew and catering", Money(-trip.Crew - trip.Catering));
LogLine(statement, "Port dues", Money(-trip.PortFees));
LogLine(statement, "Fuel expense", Money(-trip.FuelExpense));
LogLine(statement, "Loan interest", Money(-trip.LoanInterest));
LogLine(statement, "Principal repaid", Money(-trip.Principal));
var balances = Add(leaf, "log-totals");
LogLine(balances, "Net voyage profit", Money(trip.NetIncome), LogAmountColor(trip.NetIncome));
LogLine(balances, "Cash change on arrival", Money(trip.CashChange), LogAmountColor(trip.CashChange));
}
private void DrawAccounts(VisualElement left, VisualElement right)
{
AddText(left, $"COMPANY POSITION / DAY {company.Day}", "log-small-title");
AddDisplay(left, "Balances", "log-sheet-title");
var balances = Add(left, "log-statement log-account-statement");
LogLine(balances, "Cash in reserve", Money(company.Cash), "log-positive");
LogLine(balances, "Outstanding debt", Money(company.Debt));
LogLine(balances, "Lifetime voyage profit", Money(company.LifetimeProfit), LogAmountColor(company.LifetimeProfit));
LogLine(balances, "Completed voyages", company.Voyages.ToString("N0"));
AddText(left, "Voyage profit includes operating expenses and interest. Hull purchases and port permits are tracked as company outlays.", "log-note log-account-note");
AddText(right, "CREDIT ACCOUNT", "log-small-title");
AddDisplay(right, "Financing", "log-sheet-title");
var terms = Add(right, "log-statement log-account-statement");
if (company.Debt > 0)
{
LogLine(terms, "Interest rate", "13% APR");
LogLine(terms, "Principal per sailing day", Money(850));
int payment = Mathf.Min(company.Debt, 25000);
Button pay = Action($"Repay {Money(payment)} in principal",
() => Apply(company.PayDownDebt(), "Principal payment posted."), "log-paper-action", "pay-debt");
pay.SetEnabled(company.Cash >= payment);
right.Add(pay);
if (!pay.enabledSelf)
AddText(right, $"You need {Money(payment)} in cash to make this payment.", "log-note");
}
else
AddText(terms, "No outstanding loan.", "log-note");
if (!company.Bridge)
return;
var bridge = Add(right, "log-bridge");
AddText(bridge, "BRIDGE CREDIT", "log-small-title");
Button draw = Action("Draw $125,000",
() => Apply(company.DrawBridge(), "Bridge loan posted."), "log-paper-action", "draw-bridge");
draw.SetEnabled(company.CanDrawBridge);
bridge.Add(draw);
if (!company.CanDrawBridge)
AddText(bridge, "Available when cash reserves fall below $100,000.", "log-note");
}
private static void LogLine(VisualElement parent, string label, string value, string color = "")
{
var row = Add(parent, "log-line");
AddText(row, label, "log-line-description");
AddText(row, value, "log-line-value " + color);
}
private static string LogAmountColor(long amount) => amount >= 0 ? "log-positive" : "log-negative";
private static void DrawLedgerRuling(MeshGenerationContext context)
{
Rect area = context.visualElement.contentRect;
Painter2D rule = context.painter2D;
rule.strokeColor = new Color(.44f, .37f, .28f, .24f);
rule.lineWidth = 1;
rule.BeginPath();
for (int y = 23; y < area.height; y += 24)
{
rule.MoveTo(new Vector2(0, y));
rule.LineTo(new Vector2(area.width, y));
}
rule.Stroke();
}
private static void DrawLedgerCompass(MeshGenerationContext context)
{
Vector2 center = context.visualElement.contentRect.center;
Painter2D pen = context.painter2D;
pen.strokeColor = new Color(.45f, .34f, .22f, .56f);
pen.lineWidth = 1;
pen.BeginPath();
for (int i = 0; i < 32; i++)
{
float angle = i * Mathf.PI / 16;
Vector2 point = center + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * 40;
if (i == 0)
pen.MoveTo(point);
else
pen.LineTo(point);
}
pen.ClosePath();
pen.Stroke();
const float arm = 48;
const float shoulder = 9;
pen.BeginPath();
pen.MoveTo(center + Vector2.up * arm);
pen.LineTo(center + new Vector2(shoulder, shoulder));
pen.LineTo(center + Vector2.right * arm);
pen.LineTo(center + new Vector2(shoulder, -shoulder));
pen.LineTo(center + Vector2.down * arm);
pen.LineTo(center + new Vector2(-shoulder, -shoulder));
pen.LineTo(center + Vector2.left * arm);
pen.LineTo(center + new Vector2(-shoulder, shoulder));
pen.ClosePath();
pen.MoveTo(center + Vector2.up * arm);
pen.LineTo(center + Vector2.down * arm);
pen.MoveTo(center + Vector2.left * arm);
pen.LineTo(center + Vector2.right * arm);
pen.Stroke();
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bd107cb80e31fbd6c80077f8a6e702f4

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
@@ -7,113 +6,60 @@ namespace Soundings
{
public sealed partial class SoundingsApp
{
private void DrawOperations(VisualElement pageRoot)
private void DrawVoyageFolio(VisualElement folio, Ship ship, Voyage quote)
{
if (Ship == null)
{
var empty = Card(pageRoot, "No vessel in service");
AddText(empty, "Buy a pre-owned vessel or commission a hull from the shipyard.", "body-copy");
empty.Add(Action("Open shipyard →", () => ChangePage(2), "primary"));
return;
}
PortSpec origin = Market.Ports[quote.Origin];
AddText(folio, $"DEPARTURE FROM {origin.Name.ToUpperInvariant()}", "chart-paper-kicker chart-paper-section");
var passage = Add(folio, "chart-passage");
AddText(passage, $"{quote.Miles:N0} nm · {quote.Days} days", "chart-passage-distance");
AddText(passage, $"{quote.Guests} / {quote.Capacity} guests", "chart-passage-guests");
Ship ship = Ship;
Voyage quote = company.Forecast(ship, destination);
PortSpec port = Market.Ports[ship.Port];
var upper = Add(pageRoot, "columns");
var hero = Add(upper, "wide hero");
AddHarbor(hero);
var portTag = Add(hero, "hero-port");
AddText(portTag, $"● BERTHED IN {port.Name.ToUpperInvariant()}", "tag on-image");
var shipLabel = Add(hero, "hero-label");
AddDisplay(shipLabel, ship.Name, "hero-title");
AddText(shipLabel, $"{ship.Hull.Name.ToUpperInvariant()} / {ship.Decks.Count} DECKS", "eyebrow on-image");
var settlement = Add(folio, "chart-settlement");
AddText(settlement, "EST. VOYAGE PROFIT", "chart-paper-kicker");
AddDisplay(settlement, Money(quote.NetIncome), quote.NetIncome >= 0 ? "chart-projected-profit" : "chart-projected-profit chart-projected-loss");
var forecast = Card(upper, "Voyage forecast", "narrow forecast");
AddText(forecast, quote != null ? $"{port.Name} → {Market.Ports[destination].Name}" : "No itinerary selected", "forecast-route");
var paired = Add(forecast, "paired");
ForecastMetric(paired, "PROJECTED PROFIT", quote == null ? "—" : Money(quote.NetIncome),
quote == null ? "" : quote.NetIncome >= 0 ? "gain" : "loss");
ForecastMetric(paired, "EXPECTED GUESTS", quote == null ? "—" : $"{quote.Guests} / {quote.Capacity}");
AddLine(forecast, "Duration", quote == null ? "—" : $"{quote.Days} days");
AddLine(forecast, "Sailing distance", quote == null ? "—" : $"{quote.Miles:N0} nm");
AddLine(forecast, "Fuel burn + reserve", quote == null ? "—" : $"{quote.FuelBurn} + {quote.Reserve} t");
var lower = Add(pageRoot, "columns second-row");
var itinerary = Card(lower, "Itinerary & fares", "wide");
AddText(itinerary, "DESTINATION", "eyebrow control-label");
var choices = new List<string>();
var destinations = new List<int>();
foreach (Lane lane in Market.Lanes)
{
int other = lane.Other(ship.Port);
if (other < 0)
continue;
PortSpec candidate = Market.Ports[other];
string status = !company.Permits[other] ? " · Permit required" : ship.HullIndex < candidate.MinimumHull ? " · Larger hull" : "";
choices.Add($"{candidate.Name} · {lane.Miles:N0} nm{status}");
destinations.Add(other);
}
if (destinations.Count > 0)
{
int selected = destinations.IndexOf(destination);
var dropdown = new DropdownField(choices, selected) { name = "destination" };
dropdown.AddToClassList("field");
dropdown.RegisterValueChangedCallback(evt =>
{
destination = destinations[choices.IndexOf(evt.newValue)];
SetRecommendedFuel();
Notify(null);
Render();
});
itinerary.Add(dropdown);
}
var fare = Add(itinerary, "control-row");
var fareDescription = Add(fare, "control-copy");
AddText(fareDescription, "PASSENGER FARE", "eyebrow");
AddText(fareDescription, "Per guest, all sailing days", "muted");
Stepper(fare, Money(ship.Fare), "fare", () => ChangeFare(ship, -50), () => ChangeFare(ship, 50),
var fares = Add(folio, "chart-money-row");
AddText(fares, "Fare per guest", "chart-money-label");
ChartStepper(fares, Money(ship.Fare), "fare", () => ChangeFare(ship, -50), () => ChangeFare(ship, 50),
ship.Fare > Market.MinFare, ship.Fare < Market.MaxFare);
string reason = company.DepartureBlock(ship, quote);
var dispatch = Add(itinerary, "dispatch");
string readiness = reason ?? "Ready to depart. Settlement posts on arrival.";
AddText(dispatch, readiness, reason == null ? "readiness gain" : "readiness");
Button launch = Action("Dispatch voyage →", () =>
{
string failure = company.Sail(ship, destination);
if (failure == null)
{
ResetItinerary();
selectedVoyage = 0;
page = 4;
}
Apply(failure, $"Arrived in {Market.Ports[ship.Port].Name}. Voyage posted to the ledger.");
}, "primary", "dispatch");
launch.SetEnabled(reason == null);
dispatch.Add(launch);
var bunker = Card(lower, "Bunkering", "narrow bunker");
AddText(bunker, $"{port.Name} / {port.Country}", "muted");
AddLine(bunker, "Fuel aboard", $"{ship.Fuel} / {ship.Tank} t");
var meter = Add(bunker, "meter");
var fill = Add(meter, "meter-fill");
fill.style.width = Length.Percent(100f * ship.Fuel / ship.Tank);
AddLine(bunker, "Indicative safe range", $"{ship.SafeRange:N0} nm");
AddLine(bunker, "Local bunker price", $"{Money(Market.FuelPrice(ship.Port, company.Day))} / t");
var fuelControls = Add(bunker, "control-row fuel-controls");
Stepper(fuelControls, $"{bunkerTons} t", "tons", () => ChangeQuantity(ship, -10), () => ChangeQuantity(ship, 10),
DrawChartBunkering(folio, ship, quote);
string blocker = company.DepartureBlock(ship, quote);
if (!string.IsNullOrEmpty(blocker))
AddText(folio, blocker, "chart-paper-note chart-departure-blocker");
else
AddText(folio, "Cleared for departure", "chart-cleared");
Button launch = Action("Cast off →", () => BeginVoyage(quote), "chart-ink-button chart-wide-button chart-cast-off", "dispatch");
launch.SetEnabled(blocker == null);
folio.Add(launch);
}
private void DrawChartBunkering(VisualElement folio, Ship ship, Voyage quote = null)
{
PortSpec dock = Market.Ports[ship.Port];
AddText(folio, "FUEL AT BERTH", "chart-paper-kicker chart-paper-section");
ChartLine(folio, "Aboard / capacity", $"{ship.Fuel} / {ship.Tank} t");
var tank = Add(folio, "chart-tank");
Add(tank, "chart-tank-fill").style.width = Length.Percent(100f * ship.Fuel / ship.Tank);
if (quote != null)
ChartLine(folio, "Burn + reserve", $"{quote.FuelBurn} + {quote.Reserve} t");
else
ChartLine(folio, "Indicative safe range", $"{ship.SafeRange:N0} nm");
ChartLine(folio, $"Price in {dock.Name}", $"{Money(Market.FuelPrice(ship.Port, company.Day))} / t");
var buying = Add(folio, "chart-buying");
ChartStepper(buying, $"{bunkerTons} t", "tons", () => ChangeQuantity(ship, -10), () => ChangeQuantity(ship, 10),
bunkerTons > 0, bunkerTons < ship.Tank - ship.Fuel);
Button purchase = Action($"Buy · {Money(company.BunkerCost(ship, bunkerTons))}", () =>
Button buy = Action($"Buy {Money(company.BunkerCost(ship, bunkerTons))}", () =>
{
int quantity = bunkerTons;
string failure = company.Refuel(ship, quantity);
int ordered = bunkerTons;
string failure = company.Refuel(ship, ordered);
if (failure == null)
SetRecommendedFuel();
Apply(failure, $"Loaded {quantity} t of fuel in {port.Name}.");
}, "", "buy-fuel");
purchase.SetEnabled(bunkerTons > 0 && company.Cash >= company.BunkerCost(ship, bunkerTons));
fuelControls.Add(purchase);
Apply(failure, $"Loaded {ordered} t of fuel in {dock.Name}.");
}, "chart-ink-button chart-buy-fuel", "buy-fuel");
buy.SetEnabled(bunkerTons > 0 && company.Cash >= company.BunkerCost(ship, bunkerTons));
buying.Add(buy);
}
private void ChangeFare(Ship ship, int amount)
@@ -129,39 +75,26 @@ namespace Soundings
Render();
}
private static void Stepper(VisualElement parent, string value, string id, Action minus, Action plus, bool canMinus, bool canPlus)
private static void ChartStepper(VisualElement parent, string value, string id, Action minus, Action plus, bool canMinus, bool canPlus)
{
var stepper = Add(parent, "stepper");
Button down = Action("-", minus, "step", id + "-minus");
var stepper = Add(parent, "chart-stepper");
Button down = Action("-", minus, "chart-step", id + "-minus");
down.tooltip = id == "fare" ? "Lower passenger fare by $50" : "Buy 10 fewer tons";
down.SetEnabled(canMinus);
stepper.Add(down);
AddText(stepper, value, "step-value");
Button up = Action("+", plus, "step", id + "-plus");
AddText(stepper, value, "chart-step-value");
Button up = Action("+", plus, "chart-step", id + "-plus");
up.tooltip = id == "fare" ? "Raise passenger fare by $50" : "Buy 10 more tons";
up.SetEnabled(canPlus);
stepper.Add(up);
}
private static VisualElement Card(VisualElement parent, string titleText, string classes = "")
private static void ChartLine(VisualElement parent, string description, string value)
{
var card = Add(parent, "card " + classes);
AddText(card, titleText, "card-title");
return card;
var line = Add(parent, "chart-paper-line");
AddText(line, description, "chart-paper-caption");
AddText(line, value, "chart-paper-value");
}
private static void ForecastMetric(VisualElement parent, string caption, string value, string modifier = "")
{
var field = Add(parent, "forecast-metric");
AddText(field, caption, "eyebrow");
AddText(field, value, "forecast-value " + modifier);
}
private static void AddLine(VisualElement parent, string description, string value, string modifier = "")
{
var measure = Add(parent, "measure");
AddText(measure, description, "measure-label");
AddText(measure, value, "measure-value " + modifier);
}
}
}

View File

@@ -7,23 +7,25 @@ namespace Soundings
public sealed partial class SoundingsApp : MonoBehaviour
{
private const string SaveKey = "soundings.company.v1";
private static readonly string[] Pages = { "Operations", "Deck plans", "Shipyard", "Ports", "Finance" };
private static readonly int[] HotbarPages = { 0, 3, 1, 2, 4 };
private static readonly string[] HotbarNames = { "Harbor", "Chart", "Deck plans", "Shipyard", "Logbook" };
private static FontDefinition interfaceFont;
private Company company;
private Harbor harbor;
private PanelSettings panel;
private VisualElement root;
private Font displayFont;
private ScrollView pageScroll;
private bool title = true;
private Texture2D titleArt;
private bool title = true, guidedCareer = true, paused, fleetOpen, shipActionsOpen;
private bool? pendingStart;
private int page, renderedPage = -1, deckIndex, destination = -1, bunkerTons, yardSelection;
private int page, deckIndex, destination = -1, bunkerTons, yardSelection;
private Facility tool = Facility.Cabin;
private string shipName = "Peregrine";
private string notice;
private bool warning;
private bool autoSmoke;
private Ship Ship => company?.ActiveShip;
private bool HarborOnScreen => underway != null || page <= 2;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void Boot()
@@ -34,36 +36,37 @@ namespace Soundings
private void Initialize()
{
Culture();
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
autoSmoke = Array.IndexOf(Environment.GetCommandLineArgs(), "-soundings-smoke") >= 0;
Application.targetFrameRate = 60;
harbor = gameObject.AddComponent<Harbor>();
harbor.Initialize();
displayFont = Resources.Load<Font>("Display");
interfaceFont = FontDefinition.FromFont(Resources.Load<Font>("Interface"));
titleArt = Resources.Load<Texture2D>("Art/FlagshipTitle");
panel = ScriptableObject.CreateInstance<PanelSettings>();
panel.scaleMode = PanelScaleMode.ScaleWithScreenSize;
panel.referenceResolution = new Vector2Int(1440, 810);
panel.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
panel.match = 0;
panel.match = .36f;
panel.themeStyleSheet = Resources.Load<ThemeStyleSheet>("SoundingsTheme");
var document = gameObject.AddComponent<UIDocument>();
document.panelSettings = panel;
root = document.rootVisualElement;
root.style.flexGrow = 1;
root.style.unityFontDefinition = interfaceFont;
root.styleSheets.Add(Resources.Load<StyleSheet>("Soundings"));
foreach (string sheet in new[] { "Soundings", "Shipwork", "Ledger", "FirstVoyageGuide" })
{
StyleSheet stylesheet = Resources.Load<StyleSheet>(sheet);
if (stylesheet != null)
root.styleSheets.Add(stylesheet);
}
company = autoSmoke ? null : Load();
Render();
if (autoSmoke)
StartCoroutine(VisualSmoke());
}
private static void Culture()
{
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
}
private Company Load()
{
if (!PlayerPrefs.HasKey(SaveKey))
@@ -78,8 +81,7 @@ namespace Soundings
{
Debug.LogWarning("Could not read the company save. " + exception.Message);
}
notice = "The company save could not be read.";
warning = true;
Notify("The company save could not be read.", true);
return null;
}
@@ -94,18 +96,23 @@ namespace Soundings
private void StartCompany(bool financed)
{
company = Company.Start(financed);
title = false;
title = paused = fleetOpen = shipActionsOpen = false;
page = financed ? 2 : 0;
yardSelection = 1;
deckIndex = 0;
inspectedPort = 1;
selectedVoyage = 0;
ledgerRecordOffset = 0;
ledgerAccounts = false;
worldChart = false;
tool = Facility.Cabin;
shipName = "Peregrine";
pendingStart = null;
harbor.ResetView(true);
ResetItinerary();
Notify(financed ? "Choose a hull in the shipyard to begin." : "Meridian is fueled for its first sailing to Nassau.");
Notify(financed && !guidedCareer ? "Choose your first hull." : null);
if (guidedCareer)
StartGuide(financed);
Save();
Render();
}
@@ -139,7 +146,10 @@ namespace Soundings
private void ChangePage(int next)
{
if (underway != null || paused)
return;
page = next;
fleetOpen = shipActionsOpen = false;
if (destination < 0)
ResetItinerary();
Notify(null);
@@ -163,77 +173,80 @@ namespace Soundings
private void Render()
{
string focus = (root.focusController?.focusedElement as VisualElement)?.name;
float scrollOffset = page == renderedPage ? pageScroll?.verticalScroller.value ?? 0 : 0;
root.Clear();
bool showingVessel = !title && Ship != null && (page == 0 || page == 1);
harbor.SetVisible(showingVessel);
if (showingVessel)
bool showingHarbor = !title && company != null && HarborOnScreen;
harbor.SetVisible(showingHarbor);
if (showingHarbor)
harbor.Show(Ship);
if (title || company == null)
{
pageScroll = null;
renderedPage = -1;
DrawTitle();
}
else
{
renderedPage = page;
RefreshGuide();
DrawShell();
if (paused)
DrawPause();
}
if (pageScroll != null && scrollOffset > 0)
{
ScrollView scroll = pageScroll;
scroll.schedule.Execute(() => scroll.verticalScroller.value = scrollOffset);
}
if (!string.IsNullOrEmpty(focus))
if (!string.IsNullOrEmpty(focus) && root.Q<VisualElement>(focus) != null)
root.schedule.Execute(() => root.Q<VisualElement>(focus)?.Focus());
}
private void DrawTitle()
{
var screen = Add(root, "title-screen");
var intro = Add(screen, "title-intro");
var crest = Add(intro, "brand crest");
AddMark(crest);
AddText(intro, "CRUISE LINE SIMULATOR", "eyebrow");
AddDisplay(intro, "Soundings", "title-display");
AddText(intro, "From a single ship to a world-spanning cruise line.", "title-copy");
var screen = Add(root, "game-title-screen");
var artwork = new Image
{
image = titleArt,
scaleMode = ScaleMode.ScaleAndCrop,
pickingMode = PickingMode.Ignore
};
artwork.AddToClassList("title-picture");
screen.Add(artwork);
Shade(screen, false, (0f, new Color32(9, 16, 22, 253)), (.24f, new Color32(9, 16, 22, 249)),
(.35f, new Color32(9, 16, 22, 205)),
(.61f, new Color32(9, 16, 22, 38)), (1f, new Color32(9, 16, 22, 0)));
Shade(screen, true, (0f, new Color32(6, 12, 18, 12)), (.59f, new Color32(6, 12, 18, 20)),
(1f, new Color32(6, 12, 18, 143)));
var intro = Add(screen, "title-menu");
var crest = Add(intro, "title-crest");
GameIcon(crest, "compass");
AddText(crest, "Cruise line simulator", "eyebrow title-kicker");
AddDisplay(intro, "Soundings", "title-wordmark");
if (pendingStart.HasValue)
{
AddText(intro, "Replace your saved company?", "card-title");
AddText(intro, "Starting a new company overwrites your current fleet and voyage history.", "body-copy");
intro.Add(Action("Replace and start", () => StartCompany(pendingStart.Value), "primary title-action", "replace"));
intro.Add(Action("Keep current company", () => { pendingStart = null; Render(); }, "title-action", "keep"));
AddDisplay(intro, "Replace this company?", "title-question");
AddText(intro, "A new career replaces your saved fleet and voyages.", "title-confirm-copy");
intro.Add(Action("Start a new career", () => StartCompany(pendingStart.Value), "primary title-command", "replace"));
intro.Add(Action("Keep my company", () => { pendingStart = null; Render(); }, "title-command", "keep"));
}
else
{
if (company != null)
intro.Add(Action("Resume company →", () =>
intro.Add(Action("Continue career", () =>
{
title = false;
page = Ship == null ? 2 : 0;
ResetItinerary();
Notify(null);
Render();
}, "primary title-action", "resume"));
StartOption(intro, "Take over a regional ship", "Used coastal ship · $135,000 cash · No debt", false);
StartOption(intro, "Finance a new fleet", "$580,000 cash · $500,000 loan · Empty fleet", true);
}, "primary title-command", "resume"));
StartOption(intro, "Take the helm", "Used coastal ship / $135,000 cash / No debt", false);
StartOption(intro, "Start from the shipyard", "Empty fleet / $580,000 cash / $500,000 loan", true);
intro.Add(Action($"First voyage guide: {(guidedCareer ? "On" : "Off")}", () =>
{
guidedCareer = !guidedCareer;
Render();
}, "title-guide-toggle", "guide-toggle"));
}
AddNotice(intro);
var picture = Add(screen, "title-visual");
var artwork = new Image
{
image = Resources.Load<Texture2D>("Art/FlagshipTitle"),
scaleMode = ScaleMode.ScaleAndCrop,
pickingMode = PickingMode.Ignore
};
artwork.AddToClassList("harbor-image");
picture.Add(artwork);
var location = Add(picture, "splash-location");
AddText(location, "OCEAN CLASS", "eyebrow on-image");
AddText(location, "FLAGSHIP CONCEPT", "tag on-image");
if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
intro.Add(Action("Quit game", () => Application.Quit(), "title-quit", "title-quit"));
}
private void StartOption(VisualElement parent, string titleText, string description, bool financed)
@@ -247,41 +260,150 @@ namespace Soundings
pendingStart = financed;
Render();
}
}, "start-option", financed ? "start-financed" : "start-used");
AddText(option, titleText, "option-title");
AddText(option, description, "muted");
}, "career-option", financed ? "start-financed" : "start-used");
AddText(option, titleText, "career-option-name");
AddText(option, description, "career-option-balance");
parent.Add(option);
}
private void DrawShell()
{
var shell = Add(root, "shell");
var mast = Add(shell, "mast");
var brand = Add(mast, "brand mast-brand");
AddMark(brand);
AddText(brand, "Soundings", "brand-type");
AddText(brand, "CRUISE LINE SIMULATOR", "mast-sub");
var metrics = Add(mast, "mast-metrics");
HeadMetric(metrics, "CASH", Money(company.Cash), "gold");
HeadMetric(metrics, "REPUTATION", $"{company.Reputation} / 100");
HeadMetric(metrics, "DAY", company.Day.ToString("00"));
mast.Add(Action("Company menu", () => { title = true; Notify(null); Render(); }, "menu-button", "company-menu"));
var body = Add(shell, "body");
var rail = Add(body, "rail");
AddText(rail, "MANAGEMENT", "rail-heading eyebrow");
for (int i = 0; i < Pages.Length; i++)
var shell = Add(root, "game-shell");
var world = Add(shell, "harbor-viewport");
if (HarborOnScreen)
{
int target = i;
Button nav = Action("", () => ChangePage(target), page == i ? "nav current" : "nav", "nav-" + i);
AddText(nav, Pages[i], "nav-name");
rail.Add(nav);
AddHarbor(world);
if (page == 0 || underway != null)
{
AttachCamera(world);
Shade(shell, true, (0f, new Color32(5, 13, 19, 177)), (.23f, new Color32(5, 13, 19, 4)),
(.67f, new Color32(5, 13, 19, 4)), (1f, new Color32(5, 13, 19, 231)));
}
else
Add(shell, "workspace-veil").pickingMode = PickingMode.Ignore;
}
AddText(rail, $"FLEET / {company.Fleet.Count:00}", "rail-heading fleet-heading eyebrow");
var fleet = new ScrollView(ScrollViewMode.Vertical) { verticalScrollerVisibility = ScrollerVisibility.Auto };
fleet.AddToClassList("fleet-scroll");
rail.Add(fleet);
var scene = Add(shell, "game-scene");
scene.pickingMode = PickingMode.Ignore;
scene.SetEnabled(!paused);
if (underway != null)
DrawUnderway(scene);
else
{
switch (page)
{
case 0: DrawHarborScene(scene); break;
case 1: DrawDecks(scene); break;
case 2: DrawShipyard(scene); break;
case 3: DrawPorts(scene); break;
case 4: DrawFinance(scene); break;
}
}
var hud = Add(shell, "game-hud");
hud.pickingMode = PickingMode.Ignore;
hud.SetEnabled(!paused);
var hudLeft = Add(hud, "hud-left");
Button menu = Action("", () => { paused = true; Render(); }, "menu-icon", "company-menu");
menu.tooltip = "Pause menu (Esc)";
GameIcon(menu, "menu");
hudLeft.Add(menu);
AddDisplay(hudLeft, "Soundings", "hud-brand");
var instruments = Add(hud, "hud-instruments");
HeadMetric(instruments, "Day", company.Day.ToString("00"));
HeadMetric(instruments, "Reputation", company.Reputation.ToString());
HeadMetric(instruments, "Treasury", Money(company.Cash), "hud-money");
if (underway == null)
{
hudLeft.Add(Action($"Fleet {company.Fleet.Count}", () =>
{
fleetOpen = !fleetOpen;
shipActionsOpen = false;
Render();
}, "fleet-toggle", "fleet-toggle"));
DrawHotbar(shell).SetEnabled(!paused);
if (fleetOpen)
DrawFleet(shell).SetEnabled(!paused);
if (!paused && !fleetOpen)
DrawGuide(shell);
}
if (!string.IsNullOrEmpty(notice))
{
var toast = Add(shell, "game-toast");
toast.pickingMode = PickingMode.Ignore;
AddNotice(toast);
}
}
private void DrawHarborScene(VisualElement scene)
{
Ship ship = Ship;
PortSpec port = Market.Ports[ship?.Port ?? 0];
var location = Add(scene, "harbor-location");
location.pickingMode = PickingMode.Ignore;
AddText(location, "Port of", "eyebrow port-kicker");
AddDisplay(location, port.Name, "harbor-port-name");
AddText(location, $"{port.Region} / {port.Country}", "harbor-port-region");
if (ship == null)
{
var empty = Add(scene, "harbor-empty");
AddDisplay(empty, "The berth is empty", "harbor-vessel-name");
empty.Add(Action("Visit the shipyard", () => ChangePage(2), "primary helm-command", "open-yard"));
return;
}
var vessel = Add(scene, "harbor-docket");
vessel.pickingMode = PickingMode.Ignore;
AddText(vessel, $"{ship.Hull.Name} / {ship.Decks.Count} decks", "eyebrow berth-kicker");
AddDisplay(vessel, ship.Name, "harbor-vessel-name");
var details = Add(vessel, "berth-instruments");
AddText(details, $"Fuel {ship.Fuel:N0} / {ship.Tank:N0} t", "berth-value");
AddText(details, $"Condition {ship.Condition}%", "berth-value");
if (shipActionsOpen)
{
var actions = Add(vessel, "ship-action-strip");
actions.Add(Action("Refit decks", () => ChangePage(1), "", "ship-refit"));
actions.Add(Action("Overview", () => { shipActionsOpen = false; Render(); }, "", "ship-action-close"));
}
var commands = Add(scene, "helm-orders");
commands.pickingMode = PickingMode.Ignore;
Button plan = Action("Set course", OpenVoyageChart, "primary helm-command", "plan-voyage");
GameIcon(plan, "chart");
commands.Add(plan);
var camera = Add(commands, "camera-legend");
AddText(camera, "Drag to orbit / Scroll to zoom", "camera-copy");
Button reset = Action("Reset", () => harbor.ResetView(), "camera-reset", "reset-camera");
reset.tooltip = "Reset harbor camera (Home)";
camera.Add(reset);
}
private VisualElement DrawHotbar(VisualElement shell)
{
var bar = Add(shell, "game-hotbar");
var tools = Add(bar, "tool-belt");
for (int i = 0; i < HotbarPages.Length; i++)
{
int target = HotbarPages[i];
Button nav = Action("", () => ChangePage(target), page == target ? "game-tool selected" : "game-tool", "nav-" + target);
nav.tooltip = $"{HotbarNames[i]} ({i + 1})";
GameIcon(nav, target switch { 0 => "anchor", 1 => "decks", 2 => "yard", 3 => "chart", _ => "log" });
AddText(nav, HotbarNames[i], "game-tool-name");
AddText(nav, (i + 1).ToString(), "game-key");
tools.Add(nav);
}
return bar;
}
private VisualElement DrawFleet(VisualElement shell)
{
var popover = Add(shell, "fleet-manifest");
AddDisplay(popover, "Fleet", "fleet-title");
if (company.Fleet.Count == 0)
AddText(popover, "No ships in service.", "muted");
for (int i = 0; i < company.Fleet.Count; i++)
{
int selected = i;
@@ -290,39 +412,93 @@ namespace Soundings
{
company.SelectedShip = selected;
deckIndex = 0;
fleetOpen = false;
ResetItinerary();
Apply(null, null);
}, i == company.SelectedShip ? "ship-item selected" : "ship-item", "fleet-" + i);
AddText(entry, ship.Name, "ship-name");
AddText(entry, Market.Ports[ship.Port].Name + " · " + ship.Hull.Name, "ship-location");
fleet.Add(entry);
}, i == company.SelectedShip ? "fleet-entry fleet-active" : "fleet-entry", "fleet-" + i);
AddText(entry, ship.Name, "fleet-name");
AddText(entry, Market.Ports[ship.Port].Name, "muted");
popover.Add(entry);
}
if (company.Fleet.Count == 0)
AddText(fleet, "No ships yet", "fleet-empty");
popover.Add(Action("Close fleet", () => { fleetOpen = false; Render(); }, "fleet-close", "fleet-close"));
return popover;
}
var goal = Add(rail, "rail-goal");
AddText(goal, company.Flagship ? "MILESTONE REACHED" : "FLAGSHIP MILESTONE", "eyebrow");
AddText(goal, company.Flagship ? "Atlantic crossing complete" : "Bermuda → Lisbon", "goal-name");
AddText(goal, company.Flagship ? "Continue running your fleet." : "Ocean Class · 320 berths · 160 show seats", "goal-detail");
pageScroll = new ScrollView(ScrollViewMode.Vertical);
pageScroll.AddToClassList("page-scroll");
body.Add(pageScroll);
var canvas = Add(pageScroll, "page");
var head = Add(canvas, "page-head");
var heading = Add(head, "heading");
AddDisplay(heading, Pages[page], "page-title");
AddText(head, page == 0 && Ship != null ? Market.Ports[Ship.Port].Region.ToUpperInvariant()
: $"{company.Voyages:00} VOYAGES / GLOBAL NETWORK", "page-meta eyebrow");
AddNotice(canvas);
switch (page)
private void DrawPause()
{
var shade = Add(root, "pause-overlay");
var menu = Add(shade, "pause-sheet");
GameIcon(menu, "anchor");
AddDisplay(menu, "Paused", "pause-title");
menu.Add(Action("Resume", () => { paused = false; Render(); }, "primary pause-command", "resume-game"));
if (underway == null)
{
case 0: DrawOperations(canvas); break;
case 1: DrawDecks(canvas); break;
case 2: DrawShipyard(canvas); break;
case 3: DrawPorts(canvas); break;
case 4: DrawFinance(canvas); break;
menu.Add(Action("Restart first voyage guide", () =>
{
paused = false;
RestartGuide();
}, "pause-command", "restart-guide"));
menu.Add(Action("Title screen", () =>
{
paused = fleetOpen = shipActionsOpen = false;
title = true;
Notify(null);
Render();
}, "pause-command", "return-title"));
}
if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
menu.Add(Action("Quit to desktop", () => Application.Quit(), "pause-command", "quit-game"));
}
private void AttachCamera(VisualElement world)
{
int pointerId = -1;
Vector2 start = Vector2.zero, last = Vector2.zero;
bool dragging = false;
world.RegisterCallback<PointerDownEvent>(evt =>
{
if (paused || pointerId >= 0 || (evt.button != 0 && evt.button != 1))
return;
pointerId = evt.pointerId;
start = last = evt.localPosition;
dragging = false;
world.CapturePointer(pointerId);
evt.StopPropagation();
});
world.RegisterCallback<PointerMoveEvent>(evt =>
{
if (evt.pointerId != pointerId)
return;
Vector2 position = evt.localPosition;
if (dragging || (position - start).sqrMagnitude > 16)
{
dragging = true;
harbor.Orbit(position - last);
}
last = position;
});
world.RegisterCallback<PointerUpEvent>(evt =>
{
if (evt.pointerId != pointerId)
return;
pointerId = -1;
world.ReleasePointer(evt.pointerId);
if (!dragging && evt.button == 0 && underway == null && Ship != null &&
harbor.IsShipAt(new Vector2(evt.localPosition.x / world.resolvedStyle.width,
1 - evt.localPosition.y / world.resolvedStyle.height)))
{
shipActionsOpen = !shipActionsOpen;
Render();
}
});
world.RegisterCallback<PointerCaptureOutEvent>(_ => pointerId = -1);
world.RegisterCallback<WheelEvent>(evt =>
{
if (paused)
return;
harbor.Zoom(evt.delta.y);
evt.StopPropagation();
});
}
private void AddHarbor(VisualElement holder)
@@ -336,8 +512,6 @@ namespace Soundings
return;
float panelWidth = root.resolvedStyle.width;
float scale = panelWidth > 0 ? Screen.width / panelWidth : 1;
if (Application.platform != RuntimePlatform.WebGLPlayer)
scale *= Mathf.Clamp(1250 / (evt.newRect.width * scale), 1, 2);
int width = Mathf.Clamp(Mathf.RoundToInt(evt.newRect.width * scale), 32, SystemInfo.maxTextureSize);
int height = Mathf.Clamp(Mathf.RoundToInt(evt.newRect.height * scale), 32, SystemInfo.maxTextureSize);
harbor.Resize(width, height);
@@ -349,46 +523,15 @@ namespace Soundings
private void AddNotice(VisualElement parent)
{
if (string.IsNullOrEmpty(notice))
return;
Label banner = AddText(parent, notice, warning ? "notice warning" : "notice");
banner.SetEnabled(true);
}
private static void AddMark(VisualElement parent)
{
var mark = Add(parent, "brand-mark");
mark.generateVisualContent += context =>
{
Painter2D painter = context.painter2D;
painter.lineWidth = 1.35f;
painter.strokeColor = new Color(.91f, .74f, .48f);
painter.BeginPath();
painter.MoveTo(new Vector2(16, 2));
painter.LineTo(new Vector2(29, 10));
painter.LineTo(new Vector2(29, 24));
painter.LineTo(new Vector2(16, 32));
painter.LineTo(new Vector2(3, 24));
painter.LineTo(new Vector2(3, 10));
painter.ClosePath();
painter.Stroke();
painter.BeginPath();
painter.MoveTo(new Vector2(8, 20));
painter.LineTo(new Vector2(13, 15));
painter.LineTo(new Vector2(16, 19));
painter.LineTo(new Vector2(21, 13));
painter.LineTo(new Vector2(24, 17));
painter.MoveTo(new Vector2(8, 24));
painter.LineTo(new Vector2(24, 24));
painter.Stroke();
};
if (!string.IsNullOrEmpty(notice))
AddText(parent, notice, warning ? "notice warning" : "notice");
}
private static void HeadMetric(VisualElement parent, string label, string value, string modifier = "")
{
var metric = Add(parent, "head-metric");
AddText(metric, label, "eyebrow");
AddText(metric, value, "head-value " + modifier);
var metric = Add(parent, "hud-metric");
AddText(metric, label, "eyebrow hud-label");
AddText(metric, value, "hud-value " + modifier);
}
private static void Classes(VisualElement element, string classes)
@@ -406,17 +549,11 @@ namespace Soundings
return element;
}
private static Label Text(string value, string classes)
private static Label AddText(VisualElement parent, string value, string classes)
{
var label = new Label(value) { pickingMode = PickingMode.Ignore };
label.style.unityFontDefinition = interfaceFont;
Classes(label, classes);
return label;
}
private static Label AddText(VisualElement parent, string value, string classes)
{
var label = Text(value, classes);
parent.Add(label);
return label;
}

View File

@@ -22,19 +22,37 @@ namespace Soundings
Directory.CreateDirectory(directory);
yield return CaptureSmoke(directory, "01-title");
if (!SubmitSmoke("start-used") || !CheckSmoke(Ship?.Name == "MV Meridian", "Used start"))
if (!SubmitSmoke("guide-toggle") || !CheckSmoke(!guidedCareer, "Guide can be turned off at title")
|| !SubmitSmoke("guide-toggle") || !SubmitSmoke("start-used")
|| !CheckSmoke(Ship?.Name == "MV Meridian" && guideContext == GuideStep.SetCourse, "Guided used start"))
yield break;
yield return CaptureSmoke(directory, "02-operations");
yield return CaptureSmoke(directory, "02-harbor");
if (!SubmitSmoke("plan-voyage") || !CheckSmoke(page == 3 && destination == 1 && guideContext == GuideStep.Fare, "Set course and fare guide"))
yield break;
yield return CaptureSmoke(directory, "03-passage-chart");
int fare = Ship.Fare;
if (!SubmitSmoke("fare-plus") || !CheckSmoke(Ship.Fare == fare + 50, "Fare control"))
if (!SubmitSmoke("fare-plus") || !CheckSmoke(Ship.Fare == fare + 50 && guideContext == GuideStep.CastOff, "Fare control and departure guide"))
yield break;
if (!SubmitSmoke("dispatch") || !CheckSmoke(Ship.Port == 1 && company.Voyages == 1, "Dispatch control"))
if (!SubmitSmoke("dispatch") || !CheckSmoke(underway != null && Ship.Port == 0 && company.Voyages == 0, "Cast off"))
yield break;
yield return new WaitForSecondsRealtime(1.42f);
yield return CaptureSmoke(directory, "04-underway");
if (!SubmitSmoke("company-menu") || !CheckSmoke(paused, "Pause voyage"))
yield break;
float elapsed = passageElapsed;
yield return new WaitForSecondsRealtime(.15f);
if (!CheckSmoke(passageElapsed == elapsed, "Paused passage clock") || !SubmitSmoke("resume-game"))
yield break;
if (!SubmitSmoke("dock-now") || !CheckSmoke(Ship.Port == 1 && company.Voyages == 1 && page == 4 && guideContext == GuideStep.Review, "Arrival settles once and opens the guided log"))
yield break;
yield return CaptureSmoke(directory, "05-logbook");
if (!SubmitSmoke("voyage-0") || !SubmitSmoke("log-accounts") || !SubmitSmoke("log-voyages")
|| !SubmitSmoke("guide-finish") || !CheckSmoke(company.TutorialStep == 0, "Finish first voyage guide"))
yield break;
yield return CaptureSmoke(directory, "03-finance");
if (!SubmitSmoke("nav-1"))
yield break;
yield return CaptureSmoke(directory, "04-deck-plans");
yield return CaptureSmoke(directory, "06-deck-plans");
if (!SubmitSmoke("deck-1") || !SubmitSmoke("facility-4") || !SubmitSmoke("berth-0")
|| !CheckSmoke(Ship.Decks[1].Cells[0] == Facility.Tank, "Deck placement"))
yield break;
@@ -42,19 +60,43 @@ namespace Soundings
if (!SubmitSmoke("nav-3") || !SubmitSmoke("port-2") || !SubmitSmoke("permit")
|| !CheckSmoke(company.Permits[2], "Ports control"))
yield break;
yield return CaptureSmoke(directory, "05-ports");
yield return CaptureSmoke(directory, "07-ports");
if (!SubmitSmoke("chart-world") || !SubmitSmoke("port-12") || !CheckSmoke(inspectedPort == 12, "Global port chart"))
yield break;
yield return CaptureSmoke(directory, "06-world");
yield return CaptureSmoke(directory, "08-world");
if (!SubmitSmoke("company-menu") || !SubmitSmoke("start-financed") || !SubmitSmoke("replace")
|| !CheckSmoke(company.Debt == 500000 && company.Fleet.Count == 0, "Financed start"))
if (!SubmitSmoke("nav-0") || !SubmitSmoke("plan-voyage") || !SubmitSmoke("port-0") || !SubmitSmoke("dispatch"))
yield break;
yield return CaptureSmoke(directory, "07-shipyard");
if (!SubmitSmoke("buy-ship") || !CheckSmoke(Ship != null && Ship.Beds == 0 && page == 1, "Ship commissioning"))
float timeout = Time.realtimeSinceStartup + 15;
while (underway != null && Time.realtimeSinceStartup < timeout)
yield return null;
if (!CheckSmoke(underway == null && Ship.Port == 0 && company.Voyages == 2, "Timed passage and second settlement"))
yield break;
if (!SubmitSmoke("company-menu") || !SubmitSmoke("return-title") || !SubmitSmoke("start-financed") || !SubmitSmoke("replace")
|| !CheckSmoke(company.Debt == 500000 && company.Fleet.Count == 0 && guideContext == GuideStep.GetShip, "Guided financed start"))
yield break;
yield return CaptureSmoke(directory, "09-shipyard");
if (!SubmitSmoke("buy-ship") || !CheckSmoke(Ship != null && Ship.Beds == 0 && page == 1 && guideContext == GuideStep.Cabins, "Ship commissioning and cabin guide"))
yield break;
yield return CaptureSmoke(directory, "10-new-hull");
if (!SubmitSmoke("facility-1"))
yield break;
for (int i = 0; i < StarterCabinModules; i++)
if (!SubmitSmoke($"berth-{i}"))
yield break;
if (!CheckSmoke(guideContext == GuideStep.Dining, "Starter cabin block advances to dining")
|| !SubmitSmoke("facility-2") || !SubmitSmoke($"berth-{StarterCabinModules}")
|| !CheckSmoke(guideContext == GuideStep.SetCourse, "Dining advances to course planning")
|| !SubmitSmoke("nav-0") || !SubmitSmoke("plan-voyage")
|| !CheckSmoke(guideContext == GuideStep.Bunker && company.Forecast(Ship, destination).NetIncome > 0,
"Unfueled hull shows bunker lesson for a profitable first sailing"))
yield break;
yield return CaptureSmoke(directory, "11-bunker-lesson");
if (!SubmitSmoke("buy-fuel") || !CheckSmoke(Ship.Fuel > 0 && guideContext == GuideStep.Fare, "Bunkering and guide progress")
|| !SubmitSmoke("guide-skip") || !CheckSmoke(company.TutorialStep == 0, "Guide can be skipped"))
yield break;
yield return CaptureSmoke(directory, "08-new-hull");
Debug.Log($"Soundings player smoke passed at {Screen.width} × {Screen.height}.");
Application.Quit(0);
}

View File

@@ -0,0 +1,142 @@
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private Voyage underway;
private float passageElapsed;
private VisualElement passageFill;
private Label passageDistance;
private void Update()
{
if (root == null)
return;
if (Input.GetKeyDown(KeyCode.Escape))
{
if (title && pendingStart.HasValue)
{
pendingStart = null;
Render();
}
else if (!title)
{
paused = !paused;
Render();
}
}
if (underway != null)
{
if (!paused)
{
passageElapsed += Time.unscaledDeltaTime;
float duration = PassageDuration(underway);
float progress = Mathf.Clamp01(passageElapsed / duration);
harbor.SetPassage(progress);
UpdatePassageInstrument(progress);
if (progress >= 1)
FinishVoyage();
}
return;
}
if (title || paused || EditingText())
return;
for (int i = 0; i < HotbarPages.Length; i++)
{
if (Input.GetKeyDown((KeyCode)((int)KeyCode.Alpha1 + i)))
{
ChangePage(HotbarPages[i]);
break;
}
}
if (page == 0 && Input.GetKeyDown(KeyCode.Home))
harbor.ResetView();
}
private static float PassageDuration(Voyage voyage) => Mathf.Clamp(4.8f + voyage.Days * .56f, 6, 10);
private bool EditingText()
{
for (var item = root.focusController?.focusedElement as VisualElement; item != null; item = item.parent)
if (item is TextField)
return true;
return false;
}
private void BeginVoyage(Voyage quote)
{
if (underway != null || Ship == null)
return;
string failure = company.DepartureBlock(Ship, quote);
if (failure != null)
{
Apply(failure, null);
return;
}
underway = quote;
passageElapsed = 0;
fleetOpen = shipActionsOpen = false;
page = 0;
Notify(null);
harbor.BeginPassage();
Render();
}
private void FinishVoyage()
{
if (underway == null || paused)
return;
Voyage voyage = underway;
underway = null;
passageFill = null;
passageDistance = null;
harbor.EndPassage();
Ship ship = Ship;
string failure = company.Sail(ship, voyage.Destination);
if (failure == null)
{
ResetItinerary();
selectedVoyage = 0;
ledgerRecordOffset = 0;
ledgerAccounts = false;
page = 4;
ReviewGuideVoyage();
}
Apply(failure, $"Arrived in {Market.Ports[voyage.Destination].Name}.");
}
private void DrawUnderway(VisualElement workspace)
{
var passage = Add(workspace, "underway-instrument");
AddText(passage, "Underway", "eyebrow passage-kicker");
string route = $"{Market.Ports[underway.Origin].Name} → {Market.Ports[underway.Destination].Name}";
AddDisplay(passage, route, "passage-route");
var trace = Add(passage, "passage-trace");
passageFill = Add(trace, "passage-progress");
var footer = Add(passage, "passage-footer");
passageDistance = AddText(footer, "", "passage-distance");
footer.Add(Action("Skip to arrival", FinishVoyage, "passage-skip", "dock-now"));
float duration = PassageDuration(underway);
UpdatePassageInstrument(Mathf.Clamp01(passageElapsed / duration));
}
private void UpdatePassageInstrument(float progress)
{
if (passageFill == null || passageDistance == null)
return;
passageFill.style.width = Length.Percent(100 * progress);
int miles = Mathf.RoundToInt(underway.Miles * (1 - progress));
string label = $"{underway.ShipName} / {miles:N0} nm to port";
if (passageDistance.text != label)
passageDistance.text = label;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c876a5cf4fb4fe965a55bae54b3a4321