Files
josh 86ee1b99bf Add manual port pilotage and working bridge instruments
Scale docking momentum by hull, require manual mooring and channel maneuvers in Captain Career, and add rank-specific bridge instruments and voiced training.
2026-11-29 21:34:36 -05:00

617 lines
26 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using UnityEngine;
using UnityEngine.UIElements;
namespace BigShipTycoon
{
public sealed partial class TycoonApp : MonoBehaviour
{
private const string GameTitle = "Big Ship Tycoon";
private const int CrewOfficePage = 5;
private static readonly int[] HotbarPages = { 0, 3, 1, 2, 4, CrewOfficePage };
private static readonly string[] HotbarNames = { "Harbor", "Chart", "Deck plans", "Shipyard", "Logbook", "Crew office" };
private static FontDefinition interfaceFont;
private Company company;
private Harbor harbor;
private PassageAudio passageAudio;
private DeckAmbience deckAmbience;
private PanelSettings panel;
private VisualElement root;
private Font displayFont;
private Texture2D titleArt;
private bool title = true, guidedCareer = true, paused, fleetOpen, shipActionsOpen;
private enum CareerStart { Captain, Used, Financed }
private CareerStart? pendingStart;
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, brandingPreview;
private Ship Ship => company?.ActiveShip;
private bool HarborOnScreen => underway != null || page <= 2;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void Boot()
{
var game = new GameObject(GameTitle);
game.AddComponent<TycoonApp>().Initialize();
}
private void Initialize()
{
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
string[] arguments = Environment.GetCommandLineArgs();
int clipArgument = Array.IndexOf(arguments, "-big-ship-tycoon-port-clips");
bool exportClips = clipArgument >= 0 && clipArgument + 1 < arguments.Length;
autoSmoke = exportClips || Array.IndexOf(arguments, "-big-ship-tycoon-smoke") >= 0;
Application.targetFrameRate = 60;
harbor = gameObject.AddComponent<Harbor>();
harbor.Initialize();
passageAudio = gameObject.AddComponent<PassageAudio>();
passageAudio.Initialize();
InitializePilotageGuide();
deckAmbience = gameObject.AddComponent<DeckAmbience>();
deckAmbience.Initialize(harbor);
displayFont = Resources.Load<Font>("Display");
interfaceFont = FontDefinition.FromFont(Resources.Load<Font>("Interface"));
titleArt = Resources.Load<Texture2D>("Art/BigShipTycoonTitle") ?? 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 = .36f;
panel.themeStyleSheet = Resources.Load<ThemeStyleSheet>("TycoonTheme");
var document = gameObject.AddComponent<UIDocument>();
document.panelSettings = panel;
root = document.rootVisualElement;
root.style.flexGrow = 1;
root.style.unityFontDefinition = interfaceFont;
foreach (string sheet in new[] { "Tycoon", "Shipwork", "Ledger", "FirstVoyageGuide", "Passage", "ServiceControls", "FleetOverview", "Careers", "ShoreExcursions", "CrewOffice", "SunDeck" })
{
StyleSheet stylesheet = Resources.Load<StyleSheet>(sheet);
if (stylesheet != null)
root.styleSheets.Add(stylesheet);
}
InitializeCareers();
Render();
if (exportClips)
StartCoroutine(ExportPortClips(arguments[clipArgument + 1]));
else if (autoSmoke)
StartCoroutine(VisualSmoke());
}
private void StartCompany(bool financed, string name = null) =>
StartCompany(financed ? CareerStart.Financed : CareerStart.Used, name);
private void StartCompany(CareerStart start, string name = null)
{
bool financed = start == CareerStart.Financed;
ResetShorePlanning();
ResetFleetPassages();
company = start == CareerStart.Captain ? Company.StartCaptain() : Company.Start(financed);
careerId = Guid.NewGuid().ToString("N");
careerName = name ?? AvailableCareerName(DefaultCareerName(start));
careerMenu = CareerMenu.Closed;
careerError = null;
title = paused = fleetOpen = shipActionsOpen = false;
page = financed ? 2 : 0;
yardSelection = 1;
deckIndex = 0;
inspectedPort = company.IsCaptainCareer ? Market.Brickell : 1;
selectedVoyage = 0;
ledgerRecordOffset = 0;
ledgerAccounts = false;
worldChart = false;
ResetWeatherSelection();
tool = Facility.Cabin;
deckTools = DeckTools.GuestFacilities;
shipName = "Peregrine";
pendingStart = null;
harbor.ResetView(true);
ResetItinerary();
Notify(financed && !guidedCareer ? "Choose your first hull." : company.IsCaptainCareer
? "Plan a river run to Brickell Landing and practice piloting from the bridge." : null);
if (guidedCareer)
StartGuide(financed);
Save();
Render();
}
private void ResetItinerary()
{
destination = -1;
bunkerTons = 0;
if (Ship == null)
return;
if (Ship.Itinerary is { HasNext: true } itinerary)
{
destination = itinerary.NextPort;
SetRecommendedFuel();
return;
}
foreach (Lane lane in Market.Lanes)
{
int other = lane.Other(Ship.Port);
if (other >= 0 && company.Permits[other] && Market.CanVisit(Ship.HullIndex, other))
{
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)
{
if (underway != null || paused)
return;
ResetShorePlanning();
page = next;
fleetOpen = shipActionsOpen = false;
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;
SetPassageFreeLook(false);
root.Clear();
bool showingHarbor = !title && company != null && HarborOnScreen;
harbor.SetVisible(showingHarbor);
if (showingHarbor)
harbor.Show(Ship);
if (title || company == null)
DrawTitle();
else if (harbor.PortCinematicActive)
DrawPortCinematic();
else
{
RefreshGuide();
DrawShell();
if (ShorePlanningOpen)
DrawShorePlanning(root);
else if (crewManifestOpen && !paused && !fleetOpen && underway != null)
DrawCrewManifest(root);
if (paused)
DrawPause();
}
if (careerMenu != CareerMenu.Closed)
DrawCareerMenu();
else if (!string.IsNullOrEmpty(focus) && root.Q<VisualElement>(focus) != null)
root.schedule.Execute(() => root.Q<VisualElement>(focus)?.Focus());
}
private void DrawTitle()
{
var screen = Add(root, "game-title-screen");
var artwork = new Image
{
image = titleArt,
scaleMode = ScaleMode.ScaleAndCrop,
pickingMode = PickingMode.Ignore
};
artwork.AddToClassList("title-picture");
if (brandingPreview)
artwork.style.left = 0;
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");
if (brandingPreview)
intro.AddToClassList("title-thumbnail");
var crest = Add(intro, "title-crest");
GameIcon(crest, "compass");
AddText(crest, "Cruise line simulator", "eyebrow title-kicker");
DrawTitleWordmark(intro);
if (brandingPreview)
return;
if (pendingStart.HasValue)
{
AddDisplay(intro, "Name your new career", "title-question");
CareerNameField(intro);
if (!string.IsNullOrEmpty(careerError))
AddText(intro, careerError, "career-save-error");
intro.Add(Action("Start a new career", StartNamedCareer, "primary title-command", "replace"));
intro.Add(Action("Back", () => { pendingStart = null; careerError = null; Render(); }, "title-command", "keep"));
}
else
{
if (company != null)
{
Button resume = Action("Continue career", () => LoadCareer(careerId), "primary title-command", "resume");
resume.tooltip = careerName;
intro.Add(resume);
intro.Add(Action("Load game", () => OpenCareerMenu(CareerMenu.Load), "title-command", "career-load-open"));
}
StartOption(intro, "Captain career", "Riverboat / Learn the helm and earn larger commands", CareerStart.Captain, "start-captain");
StartOption(intro, "Take the helm", "Used coastal ship / $135,000 cash / No debt", CareerStart.Used, "start-used");
StartOption(intro, "Start from the shipyard", "Empty fleet / $580,000 cash / $500,000 loan", CareerStart.Financed, "start-financed");
intro.Add(Action($"First voyage guide: {(guidedCareer ? "On" : "Off")}", () =>
{
guidedCareer = !guidedCareer;
Render();
}, "title-guide-toggle", "guide-toggle"));
}
AddNotice(intro);
if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
intro.Add(Action("Quit game", () => Application.Quit(), "title-quit", "title-quit"));
}
private static string DefaultCareerName(CareerStart start) => start switch
{
CareerStart.Captain => "River Captain",
CareerStart.Financed => "Shipyard career",
_ => "Meridian Line"
};
private void StartOption(VisualElement parent, string titleText, string description, CareerStart start, string id)
{
Button option = Action("", () =>
{
pendingStart = start;
careerNameDraft = AvailableCareerName(DefaultCareerName(start));
careerError = null;
Notify(null);
Render();
}, "career-option", id);
AddText(option, titleText, "career-option-name");
AddText(option, description, "career-option-balance");
parent.Add(option);
}
private void DrawShell()
{
var shell = Add(root, "game-shell");
var world = Add(shell, "harbor-viewport");
if (HarborOnScreen)
{
AddHarbor(world);
if (page == 0 || underway != null)
{
if (!fleetOpen)
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;
}
var scene = Add(shell, "game-scene");
scene.pickingMode = PickingMode.Ignore;
scene.SetEnabled(!paused && !fleetOpen);
if (underway != null)
{
DrawUnderway(scene);
if (ActiveDockManeuver == null)
DrawServiceNavigation(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;
case CrewOfficePage: DrawCrewOffice(scene); break;
}
}
var hud = Add(shell, "game-hud");
hud.pickingMode = PickingMode.Ignore;
hud.SetEnabled(!paused && !fleetOpen);
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, GameTitle, "hud-brand");
var instruments = Add(hud, "hud-instruments");
fleetDayReadout = HeadMetric(instruments, "Day", company.Day.ToString("00"));
fleetReputationReadout = HeadMetric(instruments, "Reputation", company.Reputation.ToString());
fleetTreasuryReadout = HeadMetric(instruments, "Treasury", Money(company.Cash), "hud-money");
RefreshFleetMetrics();
Button fleet = Action($"Fleet {company.Fleet.Count}", ToggleFleetOverview, "fleet-toggle", "fleet-toggle");
fleet.tooltip = "Fleet overview (F2)";
hudLeft.Add(fleet);
if (underway == null)
{
DrawHotbar(shell).SetEnabled(!paused && !fleetOpen);
if (!paused && !fleetOpen)
DrawBerthExcursions(shell);
}
if (!paused && !fleetOpen)
DrawGuide(shell);
if (!string.IsNullOrEmpty(notice))
{
var toast = Add(shell, "game-toast");
toast.pickingMode = PickingMode.Ignore;
AddNotice(toast);
}
if (fleetOpen)
DrawFleetOverview(shell).SetEnabled(!paused);
}
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(ship.Itinerary is { HasNext: true, CompletedStops: > 0 } ? "Plan next leg" : "Set course",
OpenVoyageChart, "primary helm-command", "plan-voyage");
GameIcon(plan, "chart");
commands.Add(plan);
commands.Add(Action("Crew office", () => ChangePage(CrewOfficePage), "harbor-crew-link", "harbor-crew-office"));
var camera = Add(commands, "camera-legend");
AddText(camera, "Drag to orbit / Scroll to zoom / Middle-drag to pan", "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", CrewOfficePage => "crew", _ => "log" });
AddText(nav, HotbarNames[i], "game-tool-name");
AddText(nav, (i + 1).ToString(), "game-key");
tools.Add(nav);
}
return bar;
}
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"));
var saving = Add(menu, "career-pause-actions");
saving.Add(Action("Save game", SaveFromPause, "pause-command", "career-save"));
saving.Add(Action("Save as…", () => OpenCareerMenu(CareerMenu.SaveAs), "pause-command", "career-save-as"));
menu.Add(Action("Load game", () => OpenCareerMenu(CareerMenu.Load), "pause-command", "career-load-open"));
menu.Add(Action("Save and return to title", () => SaveAndLeave(false), "pause-command", "return-title"));
if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
menu.Add(Action("Save and quit", () => SaveAndLeave(true), "pause-command", "quit-game"));
menu.Add(Action("Restart first voyage guide", RestartGuide, "pause-command", "restart-guide"));
AddNotice(menu);
}
private void AttachCamera(VisualElement world)
{
int pointerId = -1;
bool freeLook = false, pan = false;
Vector2 start = Vector2.zero, last = Vector2.zero;
bool dragging = false;
world.RegisterCallback<PointerDownEvent>(evt =>
{
if (paused || pointerId >= 0 || evt.button < 0 || evt.button > 2)
return;
pointerId = evt.pointerId;
freeLook = underway != null && evt.button == 1 && (passageBridge || passageExploring);
pan = evt.button == 2;
SetPassageFreeLook(freeLook);
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;
if (pan)
{
Vector2 delta = position - last;
harbor.Pan(new Vector2(delta.x / world.layout.width, -delta.y / world.layout.height));
}
else if (!freeLook)
harbor.Orbit(position - last);
else if (!passageCursorLocked)
harbor.Look(position - last);
}
last = position;
});
world.RegisterCallback<PointerUpEvent>(evt =>
{
if (evt.pointerId != pointerId)
return;
pointerId = -1;
freeLook = false;
SetPassageFreeLook(false);
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;
freeLook = false;
if (!passageCursorLocked || !Input.GetMouseButton(1))
SetPassageFreeLook(false);
});
world.RegisterCallback<PointerCancelEvent>(evt =>
{
if (evt.pointerId == pointerId)
world.ReleasePointer(pointerId);
});
world.RegisterCallback<WheelEvent>(evt =>
{
if (paused)
return;
Vector2 point = world.WorldToLocal(evt.mousePosition);
harbor.Zoom(evt.delta.y, new Vector2(point.x / world.layout.width, 1f - point.y / world.layout.height));
evt.StopPropagation();
});
}
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;
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))
AddText(parent, notice, warning ? "notice warning" : "notice");
}
private static Label HeadMetric(VisualElement parent, string label, string value, string modifier = "")
{
var metric = Add(parent, "hud-metric");
AddText(metric, label, "eyebrow hud-label");
return AddText(metric, value, "hud-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 AddText(VisualElement parent, string value, string classes)
{
var label = new Label(value) { pickingMode = PickingMode.Ignore };
label.style.unityFontDefinition = interfaceFont;
Classes(label, 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 };
button.style.unityFontDefinition = interfaceFont;
Classes(button, "action " + classes);
return button;
}
private static string Money(long amount) => amount < 0 ? "−" + (-amount).ToString("C0") : amount.ToString("C0");
private void OnDestroy()
{
SetPassageFreeLook(false);
if (panel != null)
Destroy(panel);
}
}
}