Files
linuxdistro-roguelite/Assets/Scripts/UI/CombatSceneController.Repository.cs
T
2026-11-18 19:42:44 +01:00

462 lines
21 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
using KernelPanic.Run;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
public sealed partial class CombatSceneController
{
private VisualElement BuildRepositoryView()
{
VisualElement repo = new();
repo.AddToClassList("repository");
repo.AddToClassList("screen-frame");
repo.Add(BuildRepositoryHeader());
AddCampaignUnlockNotice(repo);
ScrollView body = new(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
VisualElement offers = new();
offers.AddToClassList("repository-offers");
VisualElement packageOperations = new();
packageOperations.AddToClassList("repository-package-operations");
packageOperations.Add(TerminalLayout.Heading("[ package operations ]", className: "repository-section-label"));
packageOperations.Add(TerminalLayout.BodyText("$ apt-cache search --upgradeable", className: "repository-command-heading"));
if (_runManager.RepositoryOffers.Count == 0)
{
offers.Add(EmptyState("repository clean: no offers left this visit"));
}
else
{
for (int i = 0; i < _runManager.RepositoryOffers.Count; i++)
{
offers.Add(RepositoryOfferTile(_runManager.RepositoryOffers[i]));
}
}
body.Add(DeckAnalysisView.Build(_runManager.RunDeck));
packageOperations.Add(offers);
packageOperations.Add(RemoveCardBlock());
body.Add(packageOperations);
repo.Add(body);
VisualElement footer = new();
footer.AddToClassList("repository-footer");
footer.AddToClassList("screen-frame-footer");
VisualElement packageControls = new();
packageControls.AddToClassList("repository-footer-group");
packageControls.AddToClassList("repository-package-controls");
packageControls.Add(TerminalLayout.BodyText("package cache", className: "repository-footer-label"));
Button reroll = new(() => _runManager.RerollRepositoryOffers(cardDatabase, languageDeckDatabase))
{
text = $"$ apt update {_runManager.RerollCost} bits"
};
reroll.AddToClassList("secondary-action");
reroll.AddToClassList("repository-footer-action");
reroll.AddToClassList("repository-reroll-action");
reroll.EnableInClassList("repo-unaffordable", _runManager.Bits < _runManager.RerollCost);
reroll.SetEnabled(_runManager.Bits >= _runManager.RerollCost);
packageControls.Add(reroll);
footer.Add(packageControls);
Button leave = new(() =>
{
if (_runManager.Journey.campaign) SetRouteSelectionOpen(true);
else _combatManager.ContinueToNextWave();
}) { name = "BootNextWaveButton", text = "$ boot --next-wave" };
leave.AddToClassList("primary-action");
leave.AddToClassList("repository-leave-action");
leave.AddToClassList("repository-primary-command");
leave.AddToClassList("repository-recommended-action");
leave.SetEnabled(!_runManager.IsSuspended);
VisualElement leaveBlock = new();
leaveBlock.AddToClassList("repository-leave-block");
leaveBlock.AddToClassList("repository-footer-group");
leaveBlock.Add(TerminalLayout.BodyText("recommended next action", className: "repository-footer-label repository-recommended-label"));
leaveBlock.Add(leave);
Label banked = new($"{_runManager.Bits} bits remaining");
banked.AddToClassList("repository-banked-hint");
banked.AddToClassList("screen-frame-hint");
leaveBlock.Add(banked);
var suspend = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "$ shutdown --save" };
suspend.AddToClassList("secondary-action");
suspend.AddToClassList("repository-leave-action");
suspend.AddToClassList("repository-save-action");
suspend.SetEnabled(!_runManager.IsSuspended);
leaveBlock.Add(suspend);
if (!string.IsNullOrEmpty(_checkpointError))
leaveBlock.Add(TerminalLayout.BodyText("Save failed: " + _checkpointError + " Stay here and retry.", className: "screen-frame-hint"));
footer.Add(leaveBlock);
repo.Add(footer);
return repo;
}
private void SetRouteSelectionOpen(bool open)
{
_routeSelectionOpen = open;
_routeEventOpen = false;
RefreshOverlay();
_overlay.Q<Button>(open ? "BackToRepositoryButton" : "BootNextWaveButton")?.Focus();
}
private VisualElement BuildRouteSelectionView()
{
bool reward = _runManager.BuildRewardPending;
bool eventScreen = !reward && _routeEventOpen && !_runManager.CampaignChoicePending;
bool committed = eventScreen && !_runManager.RouteEventPending;
var screen = new VisualElement { name = reward ? "BuildRewardScreen" : eventScreen ? "RouteEventScreen" : "RouteSelectionScreen" };
screen.AddToClassList("repository");
screen.AddToClassList("screen-frame");
screen.AddToClassList("route-map-screen");
var header = new VisualElement();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
var copy = new VisualElement();
copy.AddToClassList("repository-header-copy");
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : reward ? "claim your build reward"
: eventScreen ? RunRouteMap.Title(_runManager.Journey.selectedRoute) : "choose your route");
title.AddToClassList("screen-frame-title");
copy.Add(title);
var subtitle = new Label(_runManager.CampaignChoicePending
? "bank your rewards or continue into endless"
: reward ? "1. claim reward > 2. choose route > 3. enter stop"
: eventScreen ? committed ? "stop complete. ready for battle" : "choose your cards. nothing changes until you confirm"
: $"preparing wave {_runManager.CurrentWaveNumber} {_runManager.Bits} bits remaining");
subtitle.AddToClassList("repository-subtitle");
copy.Add(subtitle);
header.Add(copy);
screen.Add(header);
var body = new ScrollView(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
body.Add(reward ? RunRouteView.BuildReward(_runManager)
: eventScreen ? RunMapView.BuildEvent(_runManager) : RunRouteView.Build(_runManager, _combatManager));
if (!reward && !eventScreen && !_runManager.CampaignChoicePending)
{
body.AddToClassList("route-map-body");
body.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
{
var mapScroll = body.Q<ScrollView>("RouteMapScroll");
if (mapScroll != null)
mapScroll.style.height = Mathf.Max(260, evt.newRect.height - 20);
});
}
if (committed)
{
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit" };
save.AddToClassList("secondary-action"); body.Add(save);
}
screen.Add(body);
var footer = new VisualElement();
footer.AddToClassList("screen-frame-footer");
footer.AddToClassList("route-map-footer");
var back = new Button(() =>
{
if (!eventScreen) SetRouteSelectionOpen(false);
else if (_runManager.RouteEventPending)
{
_routeEventOpen = false; RefreshOverlay();
_overlay.Q<Button>("ConfirmRouteButton")?.Focus();
}
})
{ name = eventScreen ? "BackToRouteButton" : "BackToRepositoryButton",
text = committed ? "stop committed" : eventScreen ? "< back to map" : "< back to repository" };
back.SetEnabled(!committed);
back.AddToClassList("primary-action");
back.AddToClassList("route-map-back");
footer.Add(back);
screen.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode != KeyCode.Escape || !back.enabledSelf) return;
using var submit = NavigationSubmitEvent.GetPooled();
submit.target = back; back.SendEvent(submit); evt.StopPropagation();
});
void MoveAction(string name, string caption = null)
{
var button = body.Q<Button>(name);
if (button == null) return;
button.RemoveFromHierarchy();
if (caption != null) button.text = caption;
if (name == "ResolveRouteEventButton")
{
string fullCaption = button.text;
button.RegisterCallback<GeometryChangedEvent>(evt => button.text = evt.newRect.width < 160 ? "apply" : fullCaption);
}
button.AddToClassList("primary-action");
button.AddToClassList(name is "ClaimBuildRewardButton" or "ResolveRouteEventButton" ? "route-map-continue" : "route-map-back");
footer.Add(button);
}
if (reward)
{
back.text = "< back"; back.tooltip = "Back to repository";
MoveAction("RewardBits", $"{RunManager.BuildRewardBits} Bits");
MoveAction("ClaimBuildRewardButton", "claim");
}
else if (eventScreen && !committed)
{
back.text = "< map";
MoveAction("SkipRouteEventButton", "pass");
MoveAction("ResolveRouteEventButton");
}
else if (!_runManager.CampaignChoicePending)
{
var confirm = new Button(() =>
{
if (_runManager.RouteEventPending && !eventScreen)
{
_routeEventOpen = true; RefreshOverlay();
_overlay.Q<Button>("BackToRouteButton")?.Focus();
}
else _combatManager.ContinueToNextWave();
})
{
name = "ConfirmRouteButton",
text = eventScreen ? committed ? "> continue to battle" : "confirm or pass above"
: _runManager.RouteEventPending ? "> enter stop" : "> continue to battle"
};
confirm.AddToClassList("primary-action");
confirm.AddToClassList("route-map-continue");
confirm.SetEnabled((!eventScreen || committed) && !_runManager.IsSuspended);
footer.Add(confirm);
}
screen.Add(footer);
if (committed) screen.schedule.Execute(() => screen.Q<Button>("ConfirmRouteButton")?.Focus());
return screen;
}
private void SaveAndExitRun()
{
if (_runManager.IsSuspended || (!_combatManager.AwaitingWaveContinue && !_combatManager.CanSaveCombat)) return;
try
{
if (_dailyQuestTracker?.Flush() == false)
throw new IOException("Daily quest progress: " + _dailyQuestTracker.SaveError);
RunCheckpointService.SaveAndSuspend(_saveService, _runManager, _combatManager);
_checkpointError = null;
_overlay.SetEnabled(false);
SceneLoader.LoadMainMenu(_root);
}
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
{
_checkpointError = ex.Message;
if (_root.Q<Label>("CombatSaveError") is Label error)
{ error.text = "Save failed: " + ex.Message + " Retry when ready."; error.style.display = DisplayStyle.Flex; }
Refresh();
}
}
private VisualElement BuildRepositoryHeader()
{
VisualElement header = new();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
VisualElement copy = new();
copy.AddToClassList("repository-header-copy");
Label title = new("repository");
title.AddToClassList("repository-title");
title.AddToClassList("screen-frame-title");
Label subtitle = new($"wave {_runManager.CurrentWaveNumber - 1} cleared / {_runManager.RepositoryOffers.Count} packages indexed");
subtitle.AddToClassList("repository-subtitle");
copy.Add(title);
copy.Add(subtitle);
VisualElement wallet = new();
wallet.AddToClassList("repository-wallet");
Label walletLabel = new("available bits");
walletLabel.AddToClassList("status-label");
Label walletValue = new($"◆ {_runManager.Bits}");
walletValue.AddToClassList("repository-wallet-value");
wallet.Add(walletLabel);
wallet.Add(walletValue);
header.Add(copy);
header.Add(wallet);
return header;
}
private VisualElement RepositoryOfferTile(RepositoryOffer offer)
{
VisualElement tile = new();
tile.AddToClassList("repository-tile");
tile.AddToClassList(OfferTileClass(offer.Kind));
bool unavailable = offer.Sold || _runManager.Bits < offer.Price;
tile.EnableInClassList("repo-unaffordable", unavailable);
tile.EnableInClassList("repo-sold", offer.Sold);
VisualElement top = new();
top.AddToClassList("repository-tile-top");
Label kind = new($"{OfferKindIcon(offer.Kind)} {OfferKindText(offer.Kind)}");
kind.AddToClassList("repository-kind");
top.Add(kind);
top.Add(PriceBadge(offer.Price, unavailable));
tile.Add(top);
VisualElement content = offer.Kind switch
{
RepositoryOfferKind.NewCard => CardOfferContent(offer),
RepositoryOfferKind.CardUpgrade => UpgradeOfferContent(offer),
RepositoryOfferKind.StatUpgrade => StatOfferContent(offer),
_ => GenericOfferContent(offer)
};
tile.Add(content);
Button buy = new(() => _runManager.BuyOffer(offer, _combatManager.PlayerState))
{
text = offer.Sold ? "# installed" : "$ " + OfferActionText(offer.Kind)
};
buy.tooltip = OfferCommandText(offer);
buy.AddToClassList("repository-action");
buy.SetEnabled(!offer.Sold && _runManager.Bits >= offer.Price);
tile.Add(buy);
return tile;
}
private VisualElement CardOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-card-content");
CardInstance preview = new(offer.CardDefinition);
VisualElement card = CardFaceView(preview);
card.AddToClassList("repository-card-preview");
content.Add(card);
AddRepositoryRulesToggle(content, card, preview);
if (offer.CardDefinition != null && offer.CardDefinition.IsRunOnly)
{
content.Add(Tag("run-only", "repository-run-only-tag"));
}
return content;
}
private VisualElement UpgradeOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-upgrade-content");
if (offer.TargetCard != null)
{
VisualElement target = CardFaceView(offer.TargetCard);
target.AddToClassList("repository-upgrade-card");
content.Add(target);
AddRepositoryRulesToggle(content, target, offer.TargetCard);
}
VisualElement delta = new();
delta.AddToClassList("repository-delta");
Label arrow = new("▲");
arrow.AddToClassList("repository-delta-icon");
Label text = new(offer.Description);
text.AddToClassList("repository-delta-text");
delta.Add(arrow);
delta.Add(text);
content.Add(delta);
var comparison = new Foldout { text = "Before / after", name = "UpgradeComparison", value = false };
comparison.Add(TerminalLayout.BodyText(DeckAnalysisView.UpgradeComparison(offer, _runManager.CurrentConfig)));
content.Add(comparison);
return content;
}
private static void AddRepositoryRulesToggle(VisualElement content, VisualElement card, CardInstance instance)
{
string rules = instance?.Definition == null ? "" : CardEffectFactory.GetRulesText(instance);
// Short manifests already scan well. Long cards keep their first authoritative
// sentence visible and put restrictions/edge cases behind an explicit reveal.
if (rules.Length < 140 || card.Q<Label>(className: "software-conditions") == null) return;
card.AddToClassList("repository-card-collapsible");
Button toggle = null;
toggle = new Button(() =>
{
bool expanded = !card.ClassListContains("repository-card-expanded");
card.EnableInClassList("repository-card-expanded", expanded);
toggle.text = expanded ? "▾ hide full rules" : "▸ show full rules";
toggle.EnableInClassList("expanded", expanded);
})
{
name = "RepositoryRulesToggle_" + instance.Definition.Id,
text = "▸ show full rules",
tooltip = "Show or hide the complete card manifest."
};
toggle.AddToClassList("repository-rules-toggle");
content.Add(toggle);
}
private VisualElement StatOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-stat-content");
Label icon = new(StatOfferIcon(offer.StatUpgradeKind));
icon.AddToClassList("repository-stat-icon");
Label name = new(offer.DisplayName);
name.AddToClassList("repository-name");
Label description = new(offer.Description);
description.AddToClassList("repository-description");
content.Add(icon);
content.Add(name);
content.Add(description);
return content;
}
private static VisualElement GenericOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
Label name = new(offer.DisplayName);
name.AddToClassList("repository-name");
Label description = new(offer.Description);
description.AddToClassList("repository-description");
content.Add(name);
content.Add(description);
return content;
}
private static VisualElement PriceBadge(int price, bool warning)
{
Label badge = new($"◆ {price}");
badge.AddToClassList("repository-price");
badge.EnableInClassList("repository-price-warning", warning);
return badge;
}
private VisualElement RemoveCardBlock()
{
VisualElement block = new();
block.AddToClassList("repository-remove");
Label title = new($"installed deck maintenance / remove for {CombatTuning.RemoveCardCost} bit");
title.AddToClassList("repository-name");
block.Add(title);
VisualElement rows = new();
rows.AddToClassList("repository-remove-list");
for (int i = 0; i < _runManager.RunDeck.Count; i++)
{
CardInstance card = _runManager.RunDeck[i];
Button remove = new(() => _runManager.RemoveCard(card))
{
text = $"apt remove {DisplayName(card.Definition)}"
};
remove.AddToClassList("repo-remove-button");
remove.EnableInClassList("repo-unaffordable", _runManager.Bits < CombatTuning.RemoveCardCost || _runManager.RunDeck.Count <= 1);
remove.SetEnabled(_runManager.Bits >= CombatTuning.RemoveCardCost && _runManager.RunDeck.Count > 1);
rows.Add(remove);
}
block.Add(rows);
return block;
}
}
}