Build Soundings cruise management simulator

This commit is contained in:
josh
2026-11-27 20:50:28 -05:00
parent 250dc988a3
commit ba7902dd5e
88 changed files with 6226 additions and 0 deletions

View File

@@ -0,0 +1,394 @@
using System;
using System.Collections.Generic;
namespace Soundings
{
[Serializable]
public sealed class Deck
{
public Facility[] Cells;
public Deck(int size) => Cells = new Facility[size];
}
[Serializable]
public sealed class Ship
{
public string Name;
public int HullIndex, Port, Condition, Fare, Fuel;
public double FuelValue;
public List<Deck> Decks = new List<Deck>();
public HullSpec Hull => Market.Hulls[HullIndex];
public int Beds => Count(Facility.Cabin) * Market.Facilities[(int)Facility.Cabin].Capacity;
public int Meals => Count(Facility.Dining) * Market.Facilities[(int)Facility.Dining].Capacity * 3;
public int Entertainment => Count(Facility.Entertainment) * Market.Facilities[(int)Facility.Entertainment].Capacity;
public int Capacity => Math.Min(Beds, Meals);
public int Tank => Hull.Tank + Count(Facility.Tank) * Market.Facilities[(int)Facility.Tank].Capacity;
public double BurnPerMile => Hull.TonsPerMile * (1 + (100 - Condition) * .003);
public int SafeRange => Math.Max(0, (int)Math.Floor(Math.Min(Fuel - 6, Fuel * 100 / 112) / BurnPerMile));
public int Count(Facility facility)
{
int count = 0;
foreach (Deck deck in Decks)
foreach (Facility cell in deck.Cells)
if (cell == facility)
count++;
return count;
}
}
[Serializable]
public sealed class Voyage
{
public int Origin, Destination, Miles, Days, Day, Fare, Guests, Capacity, FuelBurn, Reserve,
TicketSales, OnboardSales, Crew, Catering, PortFees, FuelExpense, LoanInterest, Principal, ReputationChange;
public string ShipName;
public int OperatingCash => Crew + Catering + PortFees;
public int NetIncome => TicketSales + OnboardSales - OperatingCash - FuelExpense - LoanInterest;
public int CashChange => TicketSales + OnboardSales - OperatingCash - LoanInterest - Principal;
public int RequiredFuel => FuelBurn + Reserve;
}
[Serializable]
public sealed class Company
{
public const int SaveVersion = 1;
public const int MaxHistory = 30;
public int Version = SaveVersion;
public int Day = 1, Cash, Debt, Reputation, Voyages;
public long LifetimeProfit;
public bool Flagship, Bridge;
public int SelectedShip;
public bool[] Permits = new bool[Market.Ports.Count];
public List<Ship> Fleet = new List<Ship>();
public List<Voyage> History = new List<Voyage>();
public Ship ActiveShip => SelectedShip >= 0 && SelectedShip < Fleet.Count ? Fleet[SelectedShip] : null;
public static Company Start(bool financed)
{
var company = new Company
{
Cash = financed ? 580000 : 135000,
Debt = financed ? 500000 : 0,
Reputation = financed ? 12 : 15,
Bridge = financed,
SelectedShip = financed ? -1 : 0
};
company.Permits[0] = company.Permits[1] = true;
if (!financed)
company.Fleet.Add(CreateShip(0, "MV Meridian", true, true));
return company;
}
public bool CanLoad()
{
if (Version != SaveVersion || Day < 1 || Cash < 0 || Debt < 0 || Reputation < 0 || Reputation > 100
|| Voyages < 0 || Permits == null || Permits.Length != Market.Ports.Count || !Permits[0] || !Permits[1]
|| Fleet == null || Fleet.Count > Market.MaxFleet || History == null || History.Count > MaxHistory
|| (Fleet.Count == 0 ? SelectedShip != -1 : SelectedShip < 0 || SelectedShip >= Fleet.Count))
return false;
foreach (Ship ship in Fleet)
{
if (ship == null || string.IsNullOrWhiteSpace(ship.Name) || ship.HullIndex < 0 || ship.HullIndex >= Market.Hulls.Count
|| ship.Port < 0 || ship.Port >= Permits.Length || !Permits[ship.Port] || ship.Condition < 24
|| ship.Condition > 100 || ship.Fare < Market.MinFare || ship.Fare > Market.MaxFare
|| ship.Decks == null || ship.Decks.Count < Market.FirstDecks || ship.Decks.Count > ship.Hull.MaxDecks
|| ship.Fuel < 0 || double.IsNaN(ship.FuelValue) || double.IsInfinity(ship.FuelValue) || ship.FuelValue < 0)
return false;
foreach (Deck deck in ship.Decks)
{
if (deck?.Cells == null || deck.Cells.Length != ship.Hull.Columns * ship.Hull.Rows)
return false;
foreach (Facility cell in deck.Cells)
if ((int)cell < 0 || (int)cell >= Market.Facilities.Count)
return false;
}
if (ship.Fuel > ship.Tank)
return false;
}
foreach (Voyage voyage in History)
if (voyage == null || voyage.Origin < 0 || voyage.Origin >= Permits.Length
|| voyage.Destination < 0 || voyage.Destination >= Permits.Length)
return false;
return true;
}
public string ShipyardBlock(int hullIndex, bool used)
{
HullSpec hull = Market.Hulls[hullIndex];
if (used && hullIndex == Market.Ocean)
return "Ocean Class hulls are available as new commissions.";
if (Fleet.Count >= Market.MaxFleet)
return "The fleet has reached its eight-ship limit.";
if (Voyages < hull.Voyages || Reputation < hull.Reputation)
return $"Requires {hull.Voyages} voyages and {hull.Reputation} reputation.";
if (Cash < (used ? Market.UsedPrice(hullIndex) : hull.Price))
return "The company needs more cash.";
return null;
}
public string Acquire(int hullIndex, bool used, string name)
{
string block = ShipyardBlock(hullIndex, used);
if (block != null)
return block;
if (!used)
{
name = name?.Trim();
if (string.IsNullOrWhiteSpace(name) || name.Length > 24)
return "Enter a ship name of up to 24 characters.";
if (!name.StartsWith("MV ", StringComparison.OrdinalIgnoreCase))
name = "MV " + name;
}
else
name = $"MV Wayfarer {Fleet.Count + 1}";
foreach (Ship ship in Fleet)
if (string.Equals(ship.Name, name, StringComparison.OrdinalIgnoreCase))
return "A vessel already uses that name.";
Cash -= used ? Market.UsedPrice(hullIndex) : Market.Hulls[hullIndex].Price;
Fleet.Add(CreateShip(hullIndex, name, used, false));
SelectedShip = Fleet.Count - 1;
return null;
}
private static Ship CreateShip(int hullIndex, string name, bool used, bool original)
{
var ship = new Ship
{
Name = name,
HullIndex = hullIndex,
Condition = original ? 78 : used ? 72 : 100,
Fare = hullIndex == 0 ? 550 : hullIndex == 1 ? 850 : 1250,
Fuel = original ? 48 : used ? 25 : 0
};
ship.FuelValue = ship.Fuel * Market.FuelPrice(0, 1);
for (int i = 0; i < Market.FirstDecks; i++)
ship.Decks.Add(new Deck(ship.Hull.Columns * ship.Hull.Rows));
if (used)
{
for (int i = 0; i < 8; i++)
ship.Decks[0].Cells[i] = Facility.Cabin;
ship.Decks[1].Cells[1] = Facility.Dining;
ship.Decks[1].Cells[2] = Facility.Entertainment;
ship.Decks[1].Cells[4] = Facility.Dining;
}
return ship;
}
public int DeckPrice(Ship ship) => 29000 + ship.Decks.Count * 8500 + ship.HullIndex * 13000;
public string AddDeck(Ship ship)
{
int price = DeckPrice(ship);
if (ship.Decks.Count >= ship.Hull.MaxDecks)
return "The hull has reached its deck limit.";
if (Cash < price)
return "The company needs more cash.";
Cash -= price;
ship.Decks.Add(new Deck(ship.Hull.Columns * ship.Hull.Rows));
return null;
}
public string Build(Ship ship, int deckIndex, int cell, Facility plan)
{
Deck deck = ship.Decks[deckIndex];
Facility previous = deck.Cells[cell];
if (previous == plan)
return null;
if (previous != Facility.Empty && plan != Facility.Empty)
return "Clear this berth before building another facility.";
if (previous == Facility.Tank && ship.Fuel > ship.Tank - Market.Facilities[(int)Facility.Tank].Capacity)
return "Burn more fuel before removing this tank.";
int price = Market.Facilities[(int)plan].Price;
if (Cash < price)
return "The company needs more cash.";
Cash += Market.Facilities[(int)previous].Price / 4 - price;
deck.Cells[cell] = plan;
return null;
}
public string PermitBlock(int destination)
{
PortSpec port = Market.Ports[destination];
if (Permits[destination])
return "Permit held.";
if (Reputation < port.Reputation)
return $"Requires {port.Reputation} reputation.";
if (Cash < port.Permit)
return "The company needs more cash.";
return null;
}
public string Permit(int destination)
{
string block = PermitBlock(destination);
if (block != null)
return block;
Cash -= Market.Ports[destination].Permit;
Permits[destination] = true;
return null;
}
public int BunkerCost(Ship ship, int tons) => tons * Market.FuelPrice(ship.Port, Day);
public string Refuel(Ship ship, int tons)
{
if (tons <= 0 || tons > ship.Tank - ship.Fuel)
return "Select a fuel quantity that fits in the tank.";
int cost = BunkerCost(ship, tons);
if (Cash < cost)
return "The company needs more cash.";
Cash -= cost;
ship.Fuel += tons;
ship.FuelValue += cost;
return null;
}
public int ServiceCost(Ship ship) => (100 - ship.Condition) * ship.Hull.HullWearCost;
public string Service(Ship ship)
{
int cost = ServiceCost(ship);
if (Cash < cost)
return "The company needs more cash.";
Cash -= cost;
ship.Condition = 100;
return null;
}
public string PayDownDebt()
{
int payment = Math.Min(25000, Debt);
if (payment <= 0)
return "The company has no outstanding loan.";
if (Cash < payment)
return "The company needs more cash.";
Cash -= payment;
Debt -= payment;
return null;
}
public bool CanDrawBridge => Bridge && Cash < 100000;
public string DrawBridge()
{
if (!CanDrawBridge)
return "Bridge credit is available once when cash falls below $100,000.";
Cash += 125000;
Debt += 125000;
Bridge = false;
return null;
}
public Voyage Forecast(Ship ship, int destination)
{
if (!Market.TryDistance(ship.Port, destination, out int miles))
return null;
PortSpec from = Market.Ports[ship.Port];
PortSpec to = Market.Ports[destination];
int days = 1 + (int)Math.Ceiling(miles / 415.0);
int fuel = (int)Math.Ceiling(ship.BurnPerMile * miles);
int reserve = Math.Max(6, (int)Math.Ceiling(fuel * .12));
double referenceFare = 330 + days * 88 + to.Appeal * 125;
double fareFactor = Math.Pow(referenceFare / ship.Fare, 1.55);
double season = 1 + .13 * Math.Cos((Day + destination * 13) * 2 * Math.PI / 112);
int recentSailings = 0;
foreach (Voyage voyage in History)
{
if (Day - voyage.Day > 12 || Math.Min(voyage.Origin, voyage.Destination) != Math.Min(ship.Port, destination)
|| Math.Max(voyage.Origin, voyage.Destination) != Math.Max(ship.Port, destination))
continue;
recentSailings++;
}
double saturation = Math.Max(.66, 1 - recentSailings * .085);
double entertainment = Math.Min(1, (double)ship.Entertainment / Math.Max(1, ship.Capacity));
double marketDemand = (150 + ship.Capacity * .50) * from.MarketSize * to.Appeal * season * saturation;
double product = (.66 + Reputation * .006 + entertainment * .20) * (.8 + ship.Condition * .002);
int guests = Market.Clamp((int)Math.Round(marketDemand * fareFactor * product), 0, ship.Capacity);
double unitCost = ship.Fuel > 0 ? ship.FuelValue / ship.Fuel : Market.FuelPrice(ship.Port, Day);
return new Voyage
{
Origin = ship.Port,
Destination = destination,
ShipName = ship.Name,
Day = Day + days,
Days = days,
Miles = miles,
Fare = ship.Fare,
Guests = guests,
Capacity = ship.Capacity,
FuelBurn = fuel,
Reserve = reserve,
TicketSales = guests * ship.Fare,
OnboardSales = (int)Math.Round(guests * days * (13 + entertainment * 18)),
Crew = ship.Hull.CrewPerDay * days + ship.Decks.Count * 500 * days,
Catering = guests * days * 27,
PortFees = from.Fee / 2 + to.Fee,
FuelExpense = (int)Math.Round(Math.Min(fuel, ship.Fuel) * unitCost
+ Math.Max(0, fuel - ship.Fuel) * Market.FuelPrice(ship.Port, Day)),
LoanInterest = (int)Math.Ceiling(Debt * .13 * days / 365),
Principal = Math.Min(Debt, 850 * days),
ReputationChange = guests == 0 ? -3 : Math.Max(1, (int)Math.Round(2 + 2 * to.Appeal + entertainment * 3))
};
}
public string DepartureBlock(Ship ship, Voyage quote)
{
if (quote == null || quote.Destination == ship.Port)
return "Select a connected port from your itinerary.";
if (!Permits[quote.Destination])
return "Obtain a destination permit in Ports.";
if (ship.HullIndex < Market.Ports[quote.Destination].MinimumHull)
return "This destination requires a larger hull class.";
if (ship.Beds == 0 || ship.Meals == 0)
return "Build cabins and dining before carrying guests.";
if (ship.Condition < 25)
return "An overhaul is required before the ship can sail.";
if (quote.RequiredFuel > ship.Tank)
return $"This route needs {quote.RequiredFuel} t. Add a bunker tank or use a larger hull.";
if (ship.Fuel < quote.RequiredFuel)
return $"Buy {quote.RequiredFuel - ship.Fuel} t more fuel to cover the crossing and reserve.";
if (quote.Guests <= 0)
return "Raise demand or lower the fare to attract passengers.";
if (Cash < quote.OperatingCash + quote.LoanInterest + quote.Principal)
return "Cash must cover the voyage expenses and loan payment.";
return null;
}
public string Sail(Ship ship, int destination)
{
Voyage quote = Forecast(ship, destination);
string block = DepartureBlock(ship, quote);
if (block != null)
return block;
ship.FuelValue *= (double)(ship.Fuel - quote.FuelBurn) / ship.Fuel;
ship.Fuel -= quote.FuelBurn;
ship.Condition = Math.Max(24, ship.Condition - Math.Max(1, quote.Days / 2));
ship.Port = quote.Destination;
Day = quote.Day;
Cash += quote.CashChange;
Debt -= quote.Principal;
Reputation = Market.Clamp(Reputation + quote.ReputationChange, 0, 100);
Voyages++;
LifetimeProfit += quote.NetIncome;
Flagship |= ship.HullIndex == Market.Ocean && ship.Capacity >= 320 && ship.Entertainment >= 160
&& quote.Origin == Market.Bermuda && quote.Destination == Market.Lisbon;
History.Insert(0, quote);
if (History.Count > MaxHistory)
History.RemoveAt(MaxHistory);
return null;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 48e5695dbf9ccfc3db6ea9ff0725b178

View File

@@ -0,0 +1,270 @@
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private int inspectedPort = 1;
private int selectedVoyage;
private bool worldChart;
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;
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);
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);
}
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 index = Card(pageRoot, "Port directory", "second-row");
var grid = Add(index, "port-grid");
for (int i = 0; i < ChartPortCount; i++)
{
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);
}
}
private int ChartPortCount => worldChart ? Market.Ports.Count : Market.StarterPortCount;
private void ChangeChart(bool global)
{
worldChart = global;
if (inspectedPort >= ChartPortCount)
inspectedPort = Market.Lisbon;
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 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);
Painter2D painter = context.painter2D;
painter.strokeColor = new Color(.18f, .32f, .36f);
painter.lineWidth = 1;
painter.BeginPath();
for (int i = 1; i < 12; i++)
{
painter.MoveTo(Point(i / 12f, 0));
painter.LineTo(Point(i / 12f, 1));
}
for (int i = 1; i < 7; i++)
{
painter.MoveTo(Point(0, i / 7f));
painter.LineTo(Point(1, i / 7f));
}
painter.Stroke();
void Polygon(Vector2[] points)
{
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.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)
});
}
foreach (Lane lane in Market.Lanes)
{
if (lane.A >= ChartPortCount || lane.B >= ChartPortCount)
continue;
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)
{
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);
}
else
RouteSegment(a, b);
}
void RouteSegment(Vector2 a, Vector2 b)
{
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.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

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

View File

@@ -0,0 +1,156 @@
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private static readonly (int HullIndex, bool Used)[] Offers =
{ (0, true), (0, false), (1, true), (1, false), (2, false) };
private void DrawDecks(VisualElement pageRoot)
{
Ship ship = Ship;
if (ship == null)
{
var empty = Card(pageRoot, "Choose a vessel first");
empty.Add(Action("Open shipyard →", () => ChangePage(2), "primary"));
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");
var workbench = Add(pageRoot, "columns second-row");
var plan = Card(workbench, ship.Name, "wide deck-card");
var tabs = Add(plan, "deck-tabs");
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}"));
}
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");
for (int row = 0; row < ship.Hull.Rows; row++)
{
var strip = Add(diagram, "cell-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}";
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");
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");
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);
}
}
private void DrawShipyard(VisualElement pageRoot)
{
var columns = Add(pageRoot, "columns");
var inventory = Card(columns, "Available hulls", "wide");
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");
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)
{
AddText(purchase, "VESSEL NAME", "eyebrow control-label");
var field = new TextField { value = shipName, maxLength = 24, name = "vessel-name" };
field.AddToClassList("field");
field.RegisterValueChangedCallback(evt => shipName = evt.newValue);
purchase.Add(field);
}
string block = company.ShipyardBlock(hullIndex, secondhand);
Button buy = Action(secondhand ? "Purchase vessel →" : "Commission hull →", () =>
{
string failure = company.Acquire(hullIndex, secondhand, shipName);
if (failure == null)
{
deckIndex = 0;
ResetItinerary();
page = secondhand ? 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");
buy.SetEnabled(block == null);
if (block != null)
AddText(purchase, block, "body-copy");
purchase.Add(buy);
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");
int price = company.ServiceCost(ship);
Button overhaul = Action($"Overhaul · {Money(price)}", () =>
{
string failure = company.Service(ship);
if (failure == null)
SetRecommendedFuel();
Apply(failure, "The ship has been restored to 100% condition.");
}, "", "overhaul");
overhaul.SetEnabled(price > 0 && company.Cash >= price);
condition.Add(overhaul);
}
}
}

View File

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

View File

@@ -0,0 +1,215 @@
using System.Collections.Generic;
using UnityEngine;
namespace Soundings
{
public sealed class Harbor : MonoBehaviour
{
private readonly Dictionary<VesselExterior.Paint, Material> materials = new Dictionary<VesselExterior.Paint, Material>();
private readonly Dictionary<VesselExterior.Paint, Material> reflections = new Dictionary<VesselExterior.Paint, Material>();
private readonly Dictionary<string, Texture2D> backplates = new Dictionary<string, Texture2D>();
private readonly List<Mesh> shipMeshes = new List<Mesh>();
private Camera viewCamera;
private Transform vessel;
private Material water;
private Mesh waterMesh;
private Shader surface, reflection;
private float backplateRatio, vesselLength = 71;
private int lastHull = -2, lastDecks;
private string currentBackplate;
private ulong lastLayout;
public RenderTexture Frame { get; private set; }
public void Initialize()
{
surface = Resources.Load<Shader>("HarborSurface");
reflection = Resources.Load<Shader>("HarborReflection");
water = new Material(Resources.Load<Shader>("HarborWater"));
var cameraObject = new GameObject("Harbor camera", typeof(Camera));
cameraObject.transform.SetParent(transform, false);
viewCamera = cameraObject.GetComponent<Camera>();
viewCamera.orthographic = true;
viewCamera.clearFlags = CameraClearFlags.SolidColor;
viewCamera.backgroundColor = new Color(.09f, .17f, .23f);
viewCamera.nearClipPlane = .25f;
viewCamera.farClipPlane = 1050;
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);
var waterObject = new GameObject("Harbor backdrop and water", typeof(MeshFilter), typeof(MeshRenderer));
waterObject.layer = 8;
waterObject.transform.SetParent(transform, false);
var ocean = new HarborMesh();
ocean.Quad(new Vector3(-2000, 0, -2000), new Vector3(-2000, 0, 2000),
new Vector3(2000, 0, 2000), new Vector3(2000, 0, -2000));
waterMesh = ocean.Bake();
waterObject.GetComponent<MeshFilter>().sharedMesh = waterMesh;
waterObject.GetComponent<MeshRenderer>().sharedMaterial = water;
}
public void SetVisible(bool visible) => viewCamera.enabled = visible;
private void SetHarbor(string region)
{
string backdrop = region switch
{
"Caribbean" or "South Pacific" => "IslandHarbor",
"Europe" or "Azores" or "Mediterranean" => "IberianHarbor",
_ => "HarborPlate"
};
if (backdrop == currentBackplate)
return;
if (!backplates.TryGetValue(backdrop, out Texture2D plate))
{
plate = Resources.Load<Texture2D>("Art/" + backdrop);
plate.wrapMode = TextureWrapMode.Clamp;
backplates.Add(backdrop, plate);
}
currentBackplate = backdrop;
backplateRatio = (float)plate.width / plate.height;
water.SetTexture("_Backdrop", plate);
FitViewport();
}
public void Resize(int width, int height)
{
if (Frame != null && Frame.width == width && Frame.height == height)
return;
ReleaseFrame();
var descriptor = new RenderTextureDescriptor(width, height, RenderTextureFormat.ARGB32, 24) { msaaSamples = 4 };
descriptor.msaaSamples = Mathf.Max(1, SystemInfo.GetRenderTextureSupportedMSAASampleCount(descriptor));
Frame = new RenderTexture(descriptor) { name = "Harbor viewport" };
viewCamera.targetTexture = Frame;
FitViewport();
}
private void FitViewport()
{
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));
}
public void Show(Ship ship)
{
SetHarbor(Market.Ports[ship.Port].Region);
int hullIndex = ship.HullIndex;
int deckCount = ship.Decks.Count;
ulong layout = 0;
foreach (Deck deck in ship.Decks)
foreach (Facility cell in deck.Cells)
layout = unchecked(layout * 31 + (uint)cell + 1);
if (hullIndex == lastHull && deckCount == lastDecks && layout == lastLayout)
return;
lastHull = hullIndex;
lastDecks = deckCount;
lastLayout = layout;
ReleaseShip();
var root = new GameObject("Cruise vessel");
vessel = root.transform;
vessel.SetParent(transform, false);
vesselLength = 71 + hullIndex * 12;
float beam = 6.65f + hullIndex * .87f;
water.SetVector("_HullSpan", new Vector4(vesselLength, beam, 0, 0));
FitViewport();
var exterior = new VesselExterior(ship, vesselLength, beam);
foreach (var (paint, batch) in exterior.Meshes())
{
Mesh mesh = batch.Bake();
shipMeshes.Add(mesh);
(Material finish, Material reflected) = Materials(paint);
Batch(mesh, finish);
Batch(mesh, reflected);
}
}
private void Batch(Mesh mesh, Material material)
{
var draw = new GameObject(material.name, typeof(MeshFilter), typeof(MeshRenderer));
draw.layer = 8;
draw.transform.SetParent(vessel, false);
draw.GetComponent<MeshFilter>().sharedMesh = mesh;
draw.GetComponent<MeshRenderer>().sharedMaterial = material;
}
private (Material Surface, Material Reflection) Materials(VesselExterior.Paint paint)
{
if (materials.TryGetValue(paint, out Material material))
return (material, reflections[paint]);
var (hex, roughness, metal, emissive, weather) = paint switch
{
VesselExterior.Paint.Navy => ("162737", .29f, .26f, 0f, .38f),
VesselExterior.Paint.Ivory => ("DBD9CE", .43f, .08f, 0f, .15f),
VesselExterior.Paint.Pearl => ("EDF0E9", .32f, .26f, 0f, .08f),
VesselExterior.Paint.Gold => ("BB8250", .27f, .66f, .05f, .13f),
VesselExterior.Paint.Teak => ("AE8766", .78f, 0f, 0f, .58f),
VesselExterior.Paint.TeakSeam => ("675145", .91f, 0f, 0f, .25f),
VesselExterior.Paint.Steel => ("8A9DA6", .27f, .76f, 0f, .20f),
VesselExterior.Paint.Black => ("172029", .43f, .25f, 0f, .28f),
VesselExterior.Paint.Glass => ("273E49", .18f, .47f, 0f, .08f),
VesselExterior.Paint.BlueGlass => ("4B6474", .20f, .53f, 0f, .06f),
VesselExterior.Paint.LitGlass => ("BB7643", .23f, .25f, .78f, .04f),
VesselExterior.Paint.Lounge => ("CC9570", .25f, .20f, .62f, .04f),
VesselExterior.Paint.Lifeboat => ("BD542D", .41f, .15f, 0f, .15f),
_ => ("318994", .16f, .40f, .05f, .13f)
};
ColorUtility.TryParseHtmlString("#" + hex, out Color color);
material = new Material(surface) { color = color, name = paint.ToString() };
material.SetFloat("_Roughness", roughness);
material.SetFloat("_Metal", metal);
material.SetFloat("_Emissive", emissive);
material.SetFloat("_Weather", weather);
var reflected = new Material(reflection) { color = color, name = paint + " reflection" };
materials.Add(paint, material);
reflections.Add(paint, reflected);
return (material, reflected);
}
private void ReleaseFrame()
{
if (Frame == null)
return;
viewCamera.targetTexture = null;
Frame.Release();
Destroy(Frame);
}
private void ReleaseShip()
{
if (vessel != null)
{
vessel.gameObject.SetActive(false);
Destroy(vessel.gameObject);
}
foreach (Mesh mesh in shipMeshes)
Destroy(mesh);
shipMeshes.Clear();
}
private void OnDestroy()
{
ReleaseFrame();
ReleaseShip();
foreach (Material material in materials.Values)
Destroy(material);
foreach (Material material in reflections.Values)
Destroy(material);
Destroy(water);
Destroy(waterMesh);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3d7444c4ca424fa37b26816e433645bf

View File

@@ -0,0 +1,147 @@
using System.Collections.Generic;
using UnityEngine;
namespace Soundings
{
internal sealed class HarborMesh
{
private readonly List<Vector3> vertices = new List<Vector3>();
private readonly List<int> triangles = new List<int>();
public Mesh Bake()
{
var mesh = new Mesh();
if (vertices.Count > ushort.MaxValue)
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.SetVertices(vertices);
mesh.SetTriangles(triangles, 0);
mesh.RecalculateNormals();
return mesh;
}
public void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d)
{
int start = vertices.Count;
vertices.Add(a);
vertices.Add(b);
vertices.Add(c);
vertices.Add(d);
Face(start, start + 1, start + 2, start + 3);
}
public void Box(Vector3 center, Vector3 size)
{
Vector3 a = center - size * .5f;
Vector3 b = center + size * .5f;
var shape = new[]
{
new Vector2(a.x, a.z), new Vector2(b.x, a.z), new Vector2(b.x, b.z), new Vector2(a.x, b.z)
};
for (int i = 0; i < shape.Length; i++)
{
Vector2 p = shape[i];
Vector2 q = shape[(i + 1) % shape.Length];
Quad(Point(q, a.y), Point(p, a.y), Point(p, b.y), Point(q, b.y));
}
Quad(Point(shape[0], b.y), Point(shape[3], b.y), Point(shape[2], b.y), Point(shape[1], b.y));
Quad(Point(shape[0], a.y), Point(shape[1], a.y), Point(shape[2], a.y), Point(shape[3], a.y));
}
public void Loft(Vector2[] outline, Vector2 center, bool lid, params Vector3[] sections)
{
int start = vertices.Count;
int points = outline.Length;
foreach (Vector3 section in sections)
{
foreach (Vector2 p in outline)
{
Vector2 offset = p - center;
vertices.Add(new Vector3(center.x + offset.x * section.x, section.y, center.y + offset.y * section.z));
}
}
for (int height = 0; height < sections.Length - 1; height++)
for (int point = 0; point < points; point++)
{
int a = start + height * points + point;
int b = start + height * points + (point + 1) % points;
Face(b, a, a + points, b + points);
}
if (!lid)
return;
int cap = vertices.Count;
Vector3 top = sections[sections.Length - 1];
for (int i = 0; i < points; i++)
vertices.Add(vertices[start + (sections.Length - 1) * points + i]);
vertices.Add(new Vector3(center.x, top.y, center.y));
for (int i = 0; i < points; i++)
AddTriangle(cap + i, cap + points, cap + (i + 1) % points);
}
public void Rod(Vector3 from, Vector3 to, float radius, int sides = 6)
{
Vector3 axis = (to - from).normalized;
Vector3 cross = Vector3.Cross(axis, Vector3.up);
if (cross.sqrMagnitude < .001f)
cross = Vector3.Cross(axis, Vector3.forward);
Vector3 u = cross.normalized * radius;
Vector3 v = Vector3.Cross(axis, u);
int start = vertices.Count;
for (int i = 0; i < sides; i++)
{
float angle = i * Mathf.PI * 2 / sides;
Vector3 offset = u * Mathf.Cos(angle) + v * Mathf.Sin(angle);
vertices.Add(from + offset);
vertices.Add(to + offset);
}
for (int i = 0; i < sides; i++)
{
int a = start + i * 2;
int b = start + ((i + 1) % sides) * 2;
Face(a, b, b + 1, a + 1);
}
}
public void Radome(Vector3 center, float radius)
{
int start = vertices.Count;
const int bands = 8;
const int slices = 12;
for (int j = 0; j <= bands; j++)
{
float elevation = Mathf.Lerp(-Mathf.PI * .5f, Mathf.PI * .5f, j / (float)bands);
for (int i = 0; i < slices; i++)
{
float rotation = i * Mathf.PI * 2 / slices;
Vector3 normal = new Vector3(Mathf.Cos(rotation) * Mathf.Cos(elevation), Mathf.Sin(elevation),
Mathf.Sin(rotation) * Mathf.Cos(elevation));
vertices.Add(center + normal * radius);
}
}
for (int j = 0; j < bands; j++)
for (int i = 0; i < slices; i++)
{
int a = start + j * slices + i;
int b = start + j * slices + (i + 1) % slices;
Face(b, a, a + slices, b + slices);
}
}
public static Vector3 Point(Vector2 position, float height) => new Vector3(position.x, height, position.y);
private void Face(int a, int b, int c, int d)
{
AddTriangle(a, b, c);
AddTriangle(a, c, d);
}
private void AddTriangle(int a, int b, int c)
{
triangles.Add(a);
triangles.Add(b);
triangles.Add(c);
}
}
}

View File

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

View File

@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
namespace Soundings
{
public enum Facility { Empty, Cabin, Dining, Entertainment, Tank }
public sealed class FacilitySpec
{
public readonly string Name, Mark, Details;
public readonly int Price, Capacity;
public FacilitySpec(string name, string mark, string details, int price, int capacity)
{
Name = name;
Mark = mark;
Details = details;
Price = price;
Capacity = capacity;
}
}
public sealed class HullSpec
{
public readonly string Name, Description;
public readonly int Columns, Rows, MaxDecks, Price, Voyages, Reputation, Tank, CrewPerDay, HullWearCost;
public readonly double TonsPerMile;
public HullSpec(string name, string description, int columns, int rows, int maxDecks, int price,
int voyages, int reputation, int tank, double tonsPerMile, int crewPerDay, int hullWearCost)
{
Name = name;
Description = description;
Columns = columns;
Rows = rows;
MaxDecks = maxDecks;
Price = price;
Voyages = voyages;
Reputation = reputation;
Tank = tank;
TonsPerMile = tonsPerMile;
CrewPerDay = crewPerDay;
HullWearCost = hullWearCost;
}
}
public sealed class PortSpec
{
public readonly string Name, Country, Region;
public readonly int FuelPrice, Fee, Permit, Reputation, MinimumHull;
public readonly double Appeal, MarketSize;
public readonly float MapX, MapY, Longitude, Latitude;
public PortSpec(string name, string country, string region, int fuelPrice, int fee, int permit,
int reputation, int minimumHull, double appeal, double marketSize, float mapX, float mapY, float longitude, float latitude)
{
Name = name;
Country = country;
Region = region;
FuelPrice = fuelPrice;
Fee = fee;
Permit = permit;
Reputation = reputation;
MinimumHull = minimumHull;
Appeal = appeal;
MarketSize = marketSize;
MapX = mapX;
MapY = mapY;
Longitude = longitude;
Latitude = latitude;
}
}
public readonly struct Lane
{
public readonly int A, B, Miles;
public Lane(int a, int b, int miles)
{
A = a;
B = b;
Miles = miles;
}
public int Other(int port) => port == A ? B : port == B ? A : -1;
}
public static class Market
{
public const int StarterPortCount = 8;
public static int UsedPrice(int hull) => hull == 0 ? 105000 : 245000;
public const int FirstDecks = 2;
public const int MaxFleet = 8;
public const int Ocean = 2;
public const int Bermuda = 5;
public const int Lisbon = 7;
public const int MinFare = 150;
public const int MaxFare = 4000;
public static readonly IReadOnlyList<FacilitySpec> Facilities = new[]
{
new FacilitySpec("Clear berth", "–", "Recover 25% of the build cost", 0, 0),
new FacilitySpec("Cabins", "CB", "32 guest berths", 8400, 32),
new FacilitySpec("Dining hall", "DH", "48 seats · 3 services", 11800, 48),
new FacilitySpec("Show lounge", "SL", "80 seats · improves demand", 15400, 80),
new FacilitySpec("Bunker tank", "BT", "+65 t of fuel capacity", 14200, 65)
};
public static readonly IReadOnlyList<HullSpec> Hulls = new[]
{
new HullSpec("Coastal", "A compact hull for short Caribbean crossings.", 6, 2, 3, 210000, 0, 0, 74, .092, 7200, 1200),
new HullSpec("Regional", "More deck space and range for island chains.", 8, 3, 4, 355000, 3, 24, 185, .121, 12800, 2300),
new HullSpec("Ocean Class", "A transatlantic hull for a world-class flagship.", 10, 3, 6, 690000, 9, 42, 440, .152, 21800, 4700)
};
public static readonly IReadOnlyList<PortSpec> Ports = new[]
{
new PortSpec("Miami", "United States", "Florida", 685, 9200, 0, 0, 0, .94, 1.12, .14f, .63f, -80.2f, 25.8f),
new PortSpec("Nassau", "The Bahamas", "Caribbean", 825, 7600, 0, 0, 0, 1.14, .87, .24f, .67f, -77.4f, 25.1f),
new PortSpec("Key West", "United States", "Florida", 725, 5600, 14500, 15, 0, .91, .77, .11f, .78f, -81.8f, 24.6f),
new PortSpec("Cozumel", "Mexico", "Caribbean", 590, 8700, 21000, 21, 0, 1.10, .90, .06f, .94f, -87, 20.5f),
new PortSpec("San Juan", "Puerto Rico, U.S.", "Caribbean", 650, 10500, 34000, 25, 1, 1.17, 1.00, .39f, .86f, -66.1f, 18.5f),
new PortSpec("Bermuda", "United Kingdom", "North Atlantic", 910, 12100, 48000, 32, 1, 1.22, .83, .46f, .45f, -64.8f, 32.3f),
new PortSpec("Ponta Delgada", "Portugal", "Azores", 625, 9500, 57000, 42, 2, 1.20, .73, .69f, .42f, -25.7f, 37.7f),
new PortSpec("Lisbon", "Portugal", "Europe", 670, 14200, 71000, 45, 2, 1.37, 1.15, .87f, .26f, -9.1f, 38.7f),
new PortSpec("Barcelona", "Spain", "Mediterranean", 688, 16200, 37000, 46, 2, 1.33, 1.18, 0, 0, 2.2f, 41.4f),
new PortSpec("Port Said", "Egypt", "Mediterranean", 604, 19200, 33000, 48, 2, 1.20, .99, 0, 0, 32.3f, 31.3f),
new PortSpec("Salalah", "Oman", "Indian Ocean", 559, 11900, 31000, 48, 2, 1.25, .94, 0, 0, 54.1f, 17.0f),
new PortSpec("Mumbai", "India", "Indian Ocean", 588, 15100, 45000, 50, 2, 1.32, 1.19, 0, 0, 72.8f, 19.1f),
new PortSpec("Singapore", "Singapore", "Southeast Asia", 570, 16800, 52000, 52, 2, 1.37, 1.27, 0, 0, 103.8f, 1.3f),
new PortSpec("Benoa", "Indonesia", "Southeast Asia", 634, 12800, 42000, 52, 2, 1.35, 1.02, 0, 0, 115.2f, -8.7f),
new PortSpec("Sydney", "Australia", "Oceania", 740, 16700, 51000, 55, 2, 1.42, 1.20, 0, 0, 151.2f, -33.9f),
new PortSpec("Auckland", "New Zealand", "Oceania", 721, 13400, 46000, 55, 2, 1.36, 1.11, 0, 0, 174.8f, -36.8f),
new PortSpec("Papeete", "French Polynesia", "South Pacific", 771, 13800, 42000, 55, 2, 1.44, 1.12, 0, 0, -149.6f, -17.5f),
new PortSpec("Honolulu", "United States", "North Pacific", 757, 16200, 52000, 58, 2, 1.41, 1.16, 0, 0, -157.9f, 21.3f),
new PortSpec("San Diego", "United States", "Pacific Coast", 718, 15300, 51000, 58, 2, 1.35, 1.21, 0, 0, -117.2f, 32.7f),
new PortSpec("Puerto Vallarta", "Mexico", "Pacific Coast", 606, 11900, 36000, 58, 2, 1.29, 1.03, 0, 0, -105.2f, 20.7f),
new PortSpec("Balboa", "Panama", "Central America", 635, 22700, 43000, 58, 2, 1.26, 1.07, 0, 0, -79.6f, 8.9f),
new PortSpec("Cartagena", "Colombia", "South America", 599, 14600, 45000, 58, 2, 1.35, 1.12, 0, 0, -75.5f, 10.4f)
};
public static readonly IReadOnlyList<Lane> Lanes = new[]
{
new Lane(0, 1, 185), new Lane(0, 2, 150), new Lane(1, 2, 270), new Lane(2, 3, 455),
new Lane(0, 3, 590), new Lane(0, 4, 985), new Lane(1, 4, 735), new Lane(1, 5, 840),
new Lane(0, 5, 913), new Lane(4, 5, 865), new Lane(5, 6, 1920), new Lane(5, 7, 2790),
new Lane(6, 7, 815), new Lane(7, 8, 605), new Lane(8, 9, 1630), new Lane(9, 10, 1645),
new Lane(10, 11, 1160), new Lane(11, 12, 2510), new Lane(12, 13, 920), new Lane(13, 14, 2540),
new Lane(14, 15, 1165), new Lane(15, 16, 2250), new Lane(16, 17, 2380), new Lane(17, 18, 2270),
new Lane(18, 19, 1110), new Lane(19, 20, 1585), new Lane(20, 21, 265), new Lane(21, 0, 1080)
};
public static int FuelPrice(int port, int day)
{
int weeklyMove = ((day / 7 * 13 + port * 9) % 31) - 15;
return Ports[port].FuelPrice + weeklyMove;
}
public static bool TryDistance(int origin, int destination, out int miles)
{
foreach (Lane lane in Lanes)
{
if (lane.Other(origin) == destination && destination >= 0)
{
miles = lane.Miles;
return true;
}
}
miles = 0;
return false;
}
public static int Clamp(int value, int min, int max) => Math.Max(min, Math.Min(max, value));
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 96e5e10e080e77a3db442f211cc172f4

View File

@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private void DrawOperations(VisualElement pageRoot)
{
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;
}
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 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),
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),
bunkerTons > 0, bunkerTons < ship.Tank - ship.Fuel);
Button purchase = Action($"Buy · {Money(company.BunkerCost(ship, bunkerTons))}", () =>
{
int quantity = bunkerTons;
string failure = company.Refuel(ship, quantity);
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);
}
private void ChangeFare(Ship ship, int amount)
{
ship.Fare = Market.Clamp(ship.Fare + amount, Market.MinFare, Market.MaxFare);
Apply(null, null);
}
private void ChangeQuantity(Ship ship, int amount)
{
bunkerTons = Mathf.Clamp(bunkerTons + amount, 0, ship.Tank - ship.Fuel);
Notify(null);
Render();
}
private static void Stepper(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");
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");
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 = "")
{
var card = Add(parent, "card " + classes);
AddText(card, titleText, "card-title");
return card;
}
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

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 259d045921e5a0e0ebe842b2de501337

View File

@@ -0,0 +1,442 @@
using System;
using UnityEngine;
using UnityEngine.UIElements;
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 Company company;
private Harbor harbor;
private PanelSettings panel;
private VisualElement root;
private Font displayFont;
private ScrollView pageScroll;
private bool title = true;
private bool? pendingStart;
private int page, renderedPage = -1, 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;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void Boot()
{
var game = new GameObject("Soundings");
game.AddComponent<SoundingsApp>().Initialize();
}
private void Initialize()
{
Culture();
autoSmoke = Array.IndexOf(Environment.GetCommandLineArgs(), "-soundings-smoke") >= 0;
Application.targetFrameRate = 60;
harbor = gameObject.AddComponent<Harbor>();
harbor.Initialize();
displayFont = Resources.Load<Font>("Display");
panel = ScriptableObject.CreateInstance<PanelSettings>();
panel.scaleMode = PanelScaleMode.ScaleWithScreenSize;
panel.referenceResolution = new Vector2Int(1440, 810);
panel.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
panel.match = 0;
panel.themeStyleSheet = Resources.Load<ThemeStyleSheet>("SoundingsTheme");
var document = gameObject.AddComponent<UIDocument>();
document.panelSettings = panel;
root = document.rootVisualElement;
root.style.flexGrow = 1;
root.styleSheets.Add(Resources.Load<StyleSheet>("Soundings"));
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))
return null;
try
{
Company loaded = JsonUtility.FromJson<Company>(PlayerPrefs.GetString(SaveKey));
if (loaded != null && loaded.CanLoad())
return loaded;
}
catch (ArgumentException exception)
{
Debug.LogWarning("Could not read the company save. " + exception.Message);
}
notice = "The company save could not be read.";
warning = true;
return null;
}
private void Save()
{
if (autoSmoke)
return;
PlayerPrefs.SetString(SaveKey, JsonUtility.ToJson(company));
PlayerPrefs.Save();
}
private void StartCompany(bool financed)
{
company = Company.Start(financed);
title = false;
page = financed ? 2 : 0;
yardSelection = 1;
deckIndex = 0;
inspectedPort = 1;
selectedVoyage = 0;
worldChart = false;
tool = Facility.Cabin;
shipName = "Peregrine";
pendingStart = null;
ResetItinerary();
Notify(financed ? "Choose a hull in the shipyard to begin." : "Meridian is fueled for its first sailing to Nassau.");
Save();
Render();
}
private void ResetItinerary()
{
destination = -1;
bunkerTons = 0;
if (Ship == null)
return;
foreach (Lane lane in Market.Lanes)
{
int other = lane.Other(Ship.Port);
if (other >= 0 && company.Permits[other] && Ship.HullIndex >= Market.Ports[other].MinimumHull)
{
destination = other;
break;
}
}
SetRecommendedFuel();
}
private void SetRecommendedFuel()
{
if (Ship == null)
return;
Voyage quote = company.Forecast(Ship, destination);
int preferred = Mathf.Max(10, (quote?.RequiredFuel ?? 10) - Ship.Fuel);
bunkerTons = Mathf.Clamp(preferred, 0, Ship.Tank - Ship.Fuel);
}
private void ChangePage(int next)
{
page = next;
if (destination < 0)
ResetItinerary();
Notify(null);
Render();
}
private void Notify(string message, bool failed = false)
{
notice = message;
warning = failed;
}
private void Apply(string failure, string success)
{
Notify(failure ?? success, failure != null);
if (failure == null)
Save();
Render();
}
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)
harbor.Show(Ship);
if (title || company == null)
{
pageScroll = null;
renderedPage = -1;
DrawTitle();
}
else
{
renderedPage = page;
DrawShell();
}
if (pageScroll != null && scrollOffset > 0)
{
ScrollView scroll = pageScroll;
scroll.schedule.Execute(() => scroll.verticalScroller.value = scrollOffset);
}
if (!string.IsNullOrEmpty(focus))
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");
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"));
}
else
{
if (company != null)
intro.Add(Action("Resume company →", () =>
{
title = false;
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);
}
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");
}
private void StartOption(VisualElement parent, string titleText, string description, bool financed)
{
Button option = Action("", () =>
{
if (company == null)
StartCompany(financed);
else
{
pendingStart = financed;
Render();
}
}, "start-option", financed ? "start-financed" : "start-used");
AddText(option, titleText, "option-title");
AddText(option, description, "muted");
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++)
{
int target = i;
Button nav = Action("", () => ChangePage(target), page == i ? "nav current" : "nav", "nav-" + i);
AddText(nav, Pages[i], "nav-name");
rail.Add(nav);
}
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);
for (int i = 0; i < company.Fleet.Count; i++)
{
int selected = i;
Ship ship = company.Fleet[i];
Button entry = Action("", () =>
{
company.SelectedShip = selected;
deckIndex = 0;
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);
}
if (company.Fleet.Count == 0)
AddText(fleet, "No ships yet", "fleet-empty");
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)
{
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;
}
}
private void AddHarbor(VisualElement holder)
{
var view = new Image { scaleMode = ScaleMode.StretchToFill, pickingMode = PickingMode.Ignore };
view.AddToClassList("harbor-image");
holder.Add(view);
holder.RegisterCallback<GeometryChangedEvent>(evt =>
{
if (evt.newRect.width < 32 || evt.newRect.height < 32)
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);
view.image = harbor.Frame;
});
if (harbor.Frame != null)
view.image = harbor.Frame;
}
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();
};
}
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);
}
private static void Classes(VisualElement element, string classes)
{
foreach (string item in classes.Split(' '))
if (item.Length != 0)
element.AddToClassList(item);
}
private static VisualElement Add(VisualElement parent, string classes)
{
var element = new VisualElement();
Classes(element, classes);
parent.Add(element);
return element;
}
private static Label Text(string value, string classes)
{
var label = new Label(value) { pickingMode = PickingMode.Ignore };
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;
}
private Label AddDisplay(VisualElement parent, string value, string classes)
{
Label label = AddText(parent, value, classes);
label.style.unityFontDefinition = FontDefinition.FromFont(displayFont);
return label;
}
private static Button Action(string text, Action clicked, string classes = "", string id = null)
{
var button = new Button(clicked) { text = text, name = id ?? text };
Classes(button, "action " + classes);
return button;
}
private static string Money(long amount) => amount < 0 ? "−" + (-amount).ToString("C0") : amount.ToString("C0");
private void OnDestroy()
{
if (panel != null)
Destroy(panel);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 098c820e940ee8cb89ed6d3b22bb3384

View File

@@ -0,0 +1,269 @@
using System.Collections.Generic;
using UnityEngine;
namespace Soundings
{
internal sealed class VesselExterior
{
internal enum Paint { Navy, Ivory, Pearl, Gold, Teak, TeakSeam, Steel, Black, Glass, BlueGlass, LitGlass, Lounge, Lifeboat, Pool }
private readonly Dictionary<Paint, HarborMesh> batches = new Dictionary<Paint, HarborMesh>();
private readonly Ship ship;
private readonly float length, beam;
private readonly int balconies;
public VesselExterior(Ship ship, float length, float beam)
{
this.ship = ship;
this.length = length;
this.beam = beam;
balconies = 21 + ship.HullIndex * 6;
}
public IReadOnlyDictionary<Paint, HarborMesh> Meshes()
{
BuildHull();
for (int deck = 0; deck < ship.Decks.Count; deck++)
BuildPassengerDeck(deck);
BuildBridgeAndRoof();
BuildLifeboats();
return batches;
}
private HarborMesh Coat(Paint paint)
{
if (!batches.TryGetValue(paint, out HarborMesh batch))
batches.Add(paint, batch = new HarborMesh());
return batch;
}
private void BuildHull()
{
Vector2[] outline = Outline(length, beam, 0);
Vector2 center = Vector2.zero;
Coat(Paint.Navy).Loft(outline, center, false, new Vector3(.88f, -2.65f, .55f),
new Vector3(.967f, -.83f, .87f), new Vector3(.99f, .28f, .97f),
new Vector3(1, 2.34f, 1), new Vector3(1.01f, 4.65f, 1.03f));
Coat(Paint.Gold).Loft(outline, center, false, new Vector3(1.013f, 3.54f, 1.025f),
new Vector3(1.013f, 3.69f, 1.026f));
Coat(Paint.Ivory).Loft(outline, center, true, new Vector3(.998f, 4.47f, 1.015f),
new Vector3(1.013f, 5.14f, 1.027f), new Vector3(1.003f, 5.32f, 1.015f));
Vector2[] promenade = Outline(length * .971f, beam * .979f, 0);
Coat(Paint.Teak).Loft(promenade, center, true, new Vector3(.997f, 5.32f, 1),
new Vector3(1, 5.38f, 1));
Rails(promenade, 5.39f, 5.99f, 2.7f);
for (int side = -1; side <= 1; side += 2)
{
for (int i = 0; i < 24; i++)
{
float x = -length * .40f + i * length * .0285f;
float z = side * beam * 1.024f * SideWidth(x / length + .50f);
Coat(Paint.Black).Box(new Vector3(x, 2.7f, z), new Vector3(.46f, .56f, .18f));
Paint pane = (i + 3 * side) % 5 == 0 ? Paint.LitGlass : Paint.BlueGlass;
Coat(pane).Box(new Vector3(x, 2.72f, z + side * .09f), new Vector3(.31f, .38f, .09f));
}
}
float fore = length * .397f;
Coat(Paint.Steel).Rod(new Vector3(fore, 5.35f, 0), new Vector3(fore, 7.24f, 0), .13f);
Coat(Paint.Gold).Rod(new Vector3(fore, 6.48f, -.82f), new Vector3(fore, 6.48f, .82f), .048f);
for (int side = -1; side <= 1; side += 2)
for (int i = 0; i < 3; i++)
{
float x = length * (.32f + i * .032f);
float z = side * beam * (.52f - i * .135f);
Coat(Paint.Black).Rod(new Vector3(x, 5.37f, z), new Vector3(x, 5.74f, z), .15f);
Coat(Paint.Steel).Box(new Vector3(x, 5.73f, z), new Vector3(.50f, .085f, .32f));
}
}
private void BuildPassengerDeck(int deck)
{
float y = 5.38f + deck * 1.88f;
var (deckLength, deckBeam, offset) = DeckFootprint(deck);
Vector2 center = new Vector2(offset, 0);
Vector2[] outline = Outline(deckLength, deckBeam, offset);
Coat(Paint.Ivory).Loft(outline, center, false, new Vector3(.97f, y, .77f),
new Vector3(.99f, y + .25f, .83f), new Vector3(.99f, y + 1.49f, .83f));
Coat(Paint.Pearl).Loft(outline, center, true, new Vector3(.993f, y + 1.49f, .96f),
new Vector3(1.017f, y + 1.57f, 1.01f), new Vector3(1.017f, y + 1.73f, 1.015f),
new Vector3(1, y + 1.82f, 1));
Coat(Paint.Teak).Loft(outline, center, true, new Vector3(.992f, y + 1.82f, .989f),
new Vector3(.994f, y + 1.88f, .992f));
Rails(outline, y + 1.88f, y + 2.38f, 2.4f);
float width = .70f * deckLength / balconies;
for (int i = 0; i < balconies; i++)
{
float x = offset + Mathf.Lerp(-.39f, .31f, (float)i / (balconies - 1)) * deckLength;
float cross = SideWidth((x - offset) / deckLength + .5f);
int column = i * ship.Hull.Columns / balconies;
for (int side = -1; side <= 1; side += 2)
{
int row = side < 0 ? 0 : ship.Hull.Rows - 1;
Facility facility = ship.Decks[deck].Cells[row * ship.Hull.Columns + column];
float z = side * deckBeam * cross;
Vector3 glass = new Vector3(x, y + .91f, z * .846f);
Coat(Paint.Black).Box(glass, new Vector3(width * 1.01f, 1.21f, .17f));
float divider = width * .21f;
Paint illumination = facility switch
{
Facility.Dining => Paint.LitGlass,
Facility.Entertainment => Paint.Lounge,
Facility.Cabin when (i + deck * 5 + row * 3) % 7 < 4 => Paint.LitGlass,
Facility.Tank => Paint.Black,
_ => Paint.Glass
};
for (int pane = -1; pane <= 1; pane += 2)
Coat(pane < 0 ? illumination : Paint.BlueGlass).Box(glass + new Vector3(pane * divider, .025f, side * .09f),
new Vector3(width * .38f, .98f, .09f));
if (facility == Facility.Tank)
continue;
Coat(Paint.Teak).Box(new Vector3(x, y + .28f, z * .935f), new Vector3(width * 1.10f, .12f, Mathf.Abs(z) * .19f));
Coat(Paint.BlueGlass).Box(new Vector3(x, y + .48f, z * 1.016f), new Vector3(width * .96f, .32f, .05f));
Coat(Paint.Pearl).Box(new Vector3(x, y + .67f, z * 1.02f), new Vector3(width * 1.045f, .047f, .055f));
Coat(Paint.Pearl).Box(new Vector3(x + width * .52f, y + .52f, z * 1.02f), new Vector3(.055f, .32f, .075f));
}
}
}
private void BuildBridgeAndRoof()
{
int deck = ship.Decks.Count - 1;
var (deckLength, deckBeam, offset) = DeckFootprint(deck);
float top = 5.38f + ship.Decks.Count * 1.88f;
float bridge = offset + deckLength * .30f;
Vector2 center = new Vector2(bridge, 0);
Vector2[] capsule = Outline(deckLength * .27f, deckBeam * .83f, bridge);
Coat(Paint.Ivory).Loft(capsule, center, false, new Vector3(.91f, top, .91f),
new Vector3(1, top + .32f, 1));
Coat(Paint.Glass).Loft(capsule, center, false, new Vector3(1, top + .32f, 1),
new Vector3(.90f, top + 1.09f, .95f));
Coat(Paint.Pearl).Loft(capsule, center, true, new Vector3(.905f, top + 1.07f, .955f),
new Vector3(.975f, top + 1.22f, 1.025f), new Vector3(.82f, top + 1.40f, .90f));
foreach (Vector2 point in capsule)
if (point.x > bridge - .5f)
Coat(Paint.Steel).Rod(HarborMesh.Point(center + (point - center), top + .34f),
HarborMesh.Point(center + (point - center) * .937f, top + 1.08f), .026f);
float mast = bridge + 1.15f;
Coat(Paint.Ivory).Rod(new Vector3(mast, top + 1.38f, 0), new Vector3(mast - .48f, top + 4.22f, 0), .135f, 8);
for (int i = 0; i < 3; i++)
{
float y = top + 1.85f + i * .66f;
float span = 1.98f - i * .36f;
Coat(Paint.Pearl).Rod(new Vector3(mast - .27f, y, -span), new Vector3(mast - .27f, y, span), .055f);
Coat(Paint.Black).Rod(new Vector3(mast - .24f, y, span * .84f), new Vector3(mast - .24f, y + .40f, span * .84f), .022f);
}
Coat(Paint.LitGlass).Radome(new Vector3(mast - .48f, top + 4.27f, 0), .13f);
float stack = offset - deckLength * .24f;
for (int side = -1; side <= 1; side += 2)
{
float z = side * deckBeam * .26f;
Vector2 foot = new Vector2(stack, z);
Vector2[] funnel = Outline(3.85f, .94f, stack, z);
Coat(Paint.Ivory).Loft(funnel, foot, false, new Vector3(1.13f, top, 1.12f),
new Vector3(.99f, top + .82f, .985f));
Coat(Paint.Navy).Loft(funnel, foot, false, new Vector3(.99f, top + .82f, .985f),
new Vector3(.95f, top + 2.37f, .86f));
Coat(Paint.Gold).Loft(funnel, foot, false, new Vector3(.95f, top + 2.37f, .86f),
new Vector3(.90f, top + 2.91f, .80f));
Coat(Paint.Black).Loft(funnel, foot, true, new Vector3(.90f, top + 2.91f, .80f),
new Vector3(.87f, top + 3.23f, .77f));
Coat(Paint.Steel).Rod(new Vector3(stack + 7.8f, top, z * 2), new Vector3(stack + 7.8f, top + .59f, z * 2), .16f);
Coat(Paint.Pearl).Radome(new Vector3(stack + 7.8f, top + .93f, z * 2), .49f);
}
float pool = offset + deckLength * .01f;
Coat(Paint.Pearl).Box(new Vector3(pool, top + .075f, 0), new Vector3(5.67f, .17f, 3.32f));
Coat(Paint.Pool).Box(new Vector3(pool, top + .17f, 0), new Vector3(5.21f, .073f, 2.89f));
for (int i = 0; i < 8; i++)
{
Coat(Paint.TeakSeam).Box(new Vector3(pool, top + .032f, (i - 3.5f) * .69f), new Vector3(10, .014f, .032f));
float x = pool - 3.4f + i * .94f;
Coat(Paint.Pearl).Box(new Vector3(x, top + .19f, deckBeam * .67f), new Vector3(.56f, .13f, .92f));
Coat(Paint.Steel).Box(new Vector3(x, top + .34f, deckBeam * .67f + .31f), new Vector3(.52f, .17f, .26f));
}
}
private void BuildLifeboats()
{
for (int i = 0; i < 5 + ship.HullIndex * 2; i++)
for (int side = -1; side <= 1; side += 2)
{
float x = -length * .31f + i * (ship.HullIndex == 0 ? 5.52f : 4.7f);
float z = side * beam * .974f;
Vector2 center = new Vector2(x, z);
Vector2[] capsule = Outline(4.31f, .60f, x, z);
Coat(Paint.Lifeboat).Loft(capsule, center, false, new Vector3(.86f, 6.27f, .59f),
new Vector3(1, 6.49f, .99f), new Vector3(1, 6.65f, 1));
Coat(Paint.Pearl).Loft(capsule, center, true, new Vector3(1, 6.65f, 1),
new Vector3(.875f, 6.94f, .82f), new Vector3(.78f, 7.04f, .65f));
Coat(Paint.Glass).Box(new Vector3(x + .96f, 6.94f, z + side * .44f), new Vector3(.50f, .15f, .13f));
for (int arm = -1; arm <= 1; arm += 2)
{
float mount = x + arm * 1.73f;
Vector3 from = new Vector3(mount, 6.15f, z - side * .67f);
Vector3 elbow = new Vector3(mount, 7.47f, z - side * .52f);
Vector3 tip = new Vector3(mount, 7.53f, z + side * .20f);
Coat(Paint.Ivory).Rod(from, elbow, .07f);
Coat(Paint.Ivory).Rod(elbow, tip, .065f);
Coat(Paint.Steel).Rod(tip, new Vector3(mount, 6.94f, tip.z), .021f);
}
}
}
private void Rails(Vector2[] contour, float low, float high, float stride)
{
HarborMesh metal = Coat(Paint.Pearl);
for (int i = 0; i < contour.Length; i++)
{
Vector2 a = contour[i];
Vector2 b = contour[(i + 1) % contour.Length];
metal.Rod(HarborMesh.Point(a, high), HarborMesh.Point(b, high), .031f);
metal.Rod(HarborMesh.Point(a, (high + low) * .5f), HarborMesh.Point(b, (high + low) * .5f), .021f);
int studs = Mathf.Max(1, Mathf.CeilToInt(Vector2.Distance(a, b) / stride));
for (int stud = 0; stud < studs; stud++)
{
Vector2 foot = Vector2.Lerp(a, b, stud / (float)studs);
metal.Rod(HarborMesh.Point(foot, low), HarborMesh.Point(foot, high), .035f);
}
}
}
private (float Length, float Beam, float Offset) DeckFootprint(int deck)
{
return (length * (.79f - .038f * deck), beam * (.84f - .030f * deck), -length * .034f - deck * .51f);
}
private static float SideWidth(float t)
{
if (t < .16f)
return Mathf.Lerp(.52f, 1, Mathf.Sin(Mathf.Clamp01(t / .16f) * Mathf.PI * .5f));
if (t < .69f)
return 1;
return Mathf.Cos(Mathf.Clamp01((t - .69f) / .31f) * Mathf.PI * .5f);
}
private static Vector2[] Outline(float length, float beam, float x, float z = 0)
{
const int intervals = 20;
var outline = new Vector2[intervals * 2 + 1];
for (int i = 0; i < intervals; i++)
{
float position = i / (float)intervals;
float width = beam * SideWidth(position);
float station = (position - .5f) * length + x;
outline[i] = new Vector2(station, z - width);
outline[outline.Length - 1 - i] = new Vector2(station, z + width);
}
outline[intervals] = new Vector2(length * .5f + x, z);
return outline;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 56c9464ba78c278c797f9b446ca863d9

View File

@@ -0,0 +1,93 @@
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp
{
private IEnumerator VisualSmoke()
{
string[] args = Environment.GetCommandLineArgs();
int index = Array.IndexOf(args, "-soundings-smoke");
if (index + 1 >= args.Length)
{
Application.Quit(1);
yield break;
}
string directory = args[index + 1];
Directory.CreateDirectory(directory);
yield return CaptureSmoke(directory, "01-title");
if (!SubmitSmoke("start-used") || !CheckSmoke(Ship?.Name == "MV Meridian", "Used start"))
yield break;
yield return CaptureSmoke(directory, "02-operations");
int fare = Ship.Fare;
if (!SubmitSmoke("fare-plus") || !CheckSmoke(Ship.Fare == fare + 50, "Fare control"))
yield break;
if (!SubmitSmoke("dispatch") || !CheckSmoke(Ship.Port == 1 && company.Voyages == 1, "Dispatch control"))
yield break;
yield return CaptureSmoke(directory, "03-finance");
if (!SubmitSmoke("nav-1"))
yield break;
yield return CaptureSmoke(directory, "04-deck-plans");
if (!SubmitSmoke("deck-1") || !SubmitSmoke("facility-4") || !SubmitSmoke("berth-0")
|| !CheckSmoke(Ship.Decks[1].Cells[0] == Facility.Tank, "Deck placement"))
yield break;
if (!SubmitSmoke("nav-3") || !SubmitSmoke("port-2") || !SubmitSmoke("permit")
|| !CheckSmoke(company.Permits[2], "Ports control"))
yield break;
yield return CaptureSmoke(directory, "05-ports");
if (!SubmitSmoke("chart-world") || !SubmitSmoke("port-12") || !CheckSmoke(inspectedPort == 12, "Global port chart"))
yield break;
yield return CaptureSmoke(directory, "06-world");
if (!SubmitSmoke("company-menu") || !SubmitSmoke("start-financed") || !SubmitSmoke("replace")
|| !CheckSmoke(company.Debt == 500000 && company.Fleet.Count == 0, "Financed start"))
yield break;
yield return CaptureSmoke(directory, "07-shipyard");
if (!SubmitSmoke("buy-ship") || !CheckSmoke(Ship != null && Ship.Beds == 0 && page == 1, "Ship commissioning"))
yield break;
yield return CaptureSmoke(directory, "08-new-hull");
Debug.Log($"Soundings player smoke passed at {Screen.width} × {Screen.height}.");
Application.Quit(0);
}
private bool SubmitSmoke(string element)
{
Button button = root.Q<Button>(element);
if (!CheckSmoke(button != null && button.enabledInHierarchy, "Available control: " + element))
return false;
using NavigationSubmitEvent navigation = NavigationSubmitEvent.GetPooled();
navigation.target = button;
button.SendEvent(navigation);
return true;
}
private static bool CheckSmoke(bool condition, string label)
{
if (!condition)
{
Debug.LogError("Soundings player smoke failed: " + label);
Application.Quit(1);
}
return condition;
}
private static IEnumerator CaptureSmoke(string directory, string name)
{
yield return null;
yield return null;
yield return new WaitForEndOfFrame();
Texture2D image = ScreenCapture.CaptureScreenshotAsTexture();
File.WriteAllBytes(Path.Combine(directory, name + ".png"), image.EncodeToPNG());
Destroy(image);
}
}
}

View File

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

View File

@@ -0,0 +1,38 @@
using UnityEngine;
namespace Soundings
{
// Simplified outlines for the network diagram, using the same projection as its port markers.
internal static class WorldCoastlines
{
public static readonly Vector2[][] Shapes =
{
Coast(-172,62, -146,61, -134,57, -127,49, -123,39, -117,32, -107,27, -97,22, -89,19, -83,22,
-90,30, -83,28, -80,26, -78,34, -72,41, -60,49, -57,55, -67,61, -82,62, -96,71, -121,73, -144,69),
Coast(-117,32, -111,26, -105,20, -96,18, -89,17, -85,12, -82,9, -77,8, -74,11, -78,12, -88,23,
-96,22, -107,26),
Coast(-81,10, -72,12, -62,8, -54,4, -48,0, -36,-7, -40,-16, -44,-21, -54,-32, -63,-41,
-66,-55, -74,-51, -77,-29, -81,-9),
Coast(-59,64, -48,60, -41,60, -28,69, -22,75, -49,76),
Coast(-11,36, -10,43, -4,49, 4,53, 11,54, 18,60, 20,68, 34,69, 44,66, 62,71, 92,74, 116,73,
140,70, 176,66, 163,58, 141,52, 134,43, 126,38, 122,30, 117,22, 109,17, 105,9, 101,2, 98,9,
94,17, 88,22, 83,17, 77,8, 72,16, 69,23, 58,25, 53,17, 43,13, 38,20, 33,30, 26,37, 20,39,
15,44, 9,43, 6,39, -1,35),
Coast(-9,35, 12,36, 25,32, 32,30, 38,18, 43,13, 51,11, 45,3, 41,-6, 40,-15, 34,-25, 27,-34,
17,-35, 11,-21, 6,-9, 8,4, -5,5, -17,14, -16,24),
Coast(113,-24, 117,-17, 125,-15, 134,-12, 141,-18, 143,-12, 148,-22, 153,-29,
151,-36, 142,-39, 132,-34, 123,-34, 115,-33),
Coast(95,6, 103,2, 108,-3, 119,-8, 116,-10, 105,-7, 100,-3),
Coast(109,1, 117,7, 119,2, 116,-4, 111,-2),
Coast(173,-34, 178,-38, 175,-41, 170,-45, 166,-47, 168,-42, 173,-38)
};
private static Vector2[] Coast(params float[] coordinates)
{
var polygon = new Vector2[coordinates.Length / 2];
for (int i = 0; i < polygon.Length; i++)
polygon[i] = new Vector2((coordinates[i * 2] + 180) / 360, (76 - coordinates[i * 2 + 1]) / 137);
return polygon;
}
}
}

View File

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