38 Commits

Author SHA1 Message Date
aeab16757f keep an auto-recipe building's summary between its cycles
A Smelter's recipe summary was dropped whenever it sat between cycles and shown
again when the next one started, as REQ-UI-RECIPE-SUMMARY asked. It is the
widest row of the card and a row of its own height, so the panel changed width
and height every time the building started or stopped -- which is exactly when
its status caption changes, and why the two looked connected.

It now keeps describing the recipe it ran last until another one runs, which
also holds the input chips' per-cycle amounts still instead of letting them
fall back to bare item names each time. A building that has never run a cycle
still has nothing to describe and shows no summary.

A Miner or Assembler never had this: its recipe is player-selected and outlives
the cycle.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-09 14:32:24 +02:00
b97347329f measure the card against every one of its layouts
Changing a label's text posts a LayoutRequest to the widget holding it, and
that event is only delivered when the event loop next runs. The panel measured
its card by invalidating the body's own layout alone, so any layout nested
inside the card -- which is all of them -- still answered with the width of the
text before the change. The panel therefore placed itself against the previous
values and corrected itself on the following refresh, a frame late.

Measured on a BarRow: with the value going idle, 0%, 42%, 100% the panel's
measurement reported 16, 16, 17, 23 where the settled widths were 16, 17, 23,
29 -- one change behind throughout. Re-activating every layout in the card
gives the settled answer without waiting for the event loop.

This is not the size change the player reported, which I could not reproduce
here; it is a second, quieter one found while looking for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-09 14:16:23 +02:00
352beda47c let the world renderer hold the simulation by const reference
The renderer documented itself as reading the simulation and never writing it,
while holding a mutable reference to it -- because hasAll() forced that on
every caller. With hasAll const the claim and the type can agree, and the const
overloads of getAdmin, forEach and get cover everything the renderer does.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-08 19:42:24 +02:00
256c4b5492 make EntityAdmin::hasAll const
Asking whether an entity has components does not write to the registry, and
entt's all_of is const. Callers that only read were forced to take the admin --
and through it the whole simulation -- by non-const reference to ask; the
selection bounds helpers now say what they mean.

Widening a member to const breaks nothing: every existing caller still binds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-08 19:31:33 +02:00
997cbc65d3 place the selection panel beside what it describes
The panel was anchored to the right edge of the view, which is nowhere near
whatever the player just clicked. It now stands beside the selection: right of
it where it fits, otherwise left, otherwise the roomier side pushed inside the
view -- the one case where it covers part of what it describes.

Nothing told the panel where the selection was. The selection events carry ids
only, and the mode that separates a fresh selection from an expanded one is
consumed inside SelectionController before they are built, so the view now
publishes the selection's screen bounds itself, immediately before selecting and
only when the selection is starting. Freezing that rectangle is what holds the
panel still: it does not chase a scrolling view, a ship flying off, or a
selection being added to. Only the panel's own size still moves it, and even
then it keeps its side and the edge facing the selection.

The rectangles come from what the renderer was already computing for the
selection outlines, now shared rather than duplicated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-08 19:18:58 +02:00
e66eb7a81f place the floating widgets in one ordered pass
The three widgets over the game world view each cached a rect handed to them by
MainWindow's resize, then re-placed themselves from it. But the build button bar
re-centers on a building unlock and the controls panel re-fits on a 50 ms timer,
neither of which goes through MainWindow, so the rects the others held went
stale -- and each widget re-implemented its own avoidance against them.

They now implement FloatingPanel and are placed in one ordered pass: the bar
takes what it wants, the controls panel steps around the bar, and the selection
panel keeps clear of both. A widget that changed size or visibility publishes
FloatingLayoutInvalidatedEvent instead of moving itself, because what it may
take depends on the widgets placed before it.

The rule they step around each other by is one function in lib, where it can be
tested without a display -- the only way any of this geometry gets automated
cover, screen capture of the world view being blank here.

The selection panel keeps its right edge and its vertical centering, but the
space it centers in is now what its own column has left free rather than the
full-width strip the bar used to reserve. It therefore sits lower than before
where the centered bar does not reach it, and it now clears the controls panel,
which it previously ignored.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-08 19:10:00 +02:00
37899ea964 place the selection panel beside what it describes
The panel was anchored to the view's right edge and centered in the band above
the build button bar. Requiring it beside the selection instead splits its
placement inputs in two: the anchor rectangle and the side are frozen when the
selection starts, so the panel neither chases a scrolling view nor moves as the
selection grows, while its geometry is re-solved from them whenever its own size
changes.

Two neighbouring requirements described the old placement and had to follow:
the build bar's "the panel confines itself to the band above the bar", and the
controls panel's claim that the two panels sit on opposite sides of the view --
a selection in the lower left now puts them in the same corner, and keeping them
apart is the selection panel's job.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-08 14:26:18 +02:00
a6152b9998 hold the header's width against a changing status caption
The panel is sized to its card, so anything that changes the card's width drags
the panel with it. The status caption changes as a building works -- "producing"
is shorter than "missing input", which is shorter than "output full" -- and the
panel twitched every time it did. On a Smelter it also changed height, because a
narrower card wraps its item chips differently.

The pill now reserves room for the widest caption it can ever show, so the
header keeps one width whatever the state is. The captions were spelled out in
the switch that chose them, which left no way to ask for the set; they come from
one function now, and the set is what the reservation is built from.

Ship cards do the same with the behaviour names (REQ-UI-SHIP-BEHAVIOR), which
change just as often while a ship fights.

Miner card, sampled every tick for 900 ticks across two different-length
captions: one distinct width, one distinct height. The reservation is what does
it -- the same run without it sits at 138px, with it at 155px, the width of the
longest caption.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-07 22:07:49 +02:00
7d0f3e6daf order the selection card by what the player reads first
Six things the player reported, five of them about where things sit and what is
listed:

- HP goes to the top of the runtime group, above everything else a card shows.
  Only the HQ had it elsewhere; the ship and station cards already led with it.
- A construction site's progress moves out of the runtime group's place and
  directly under the header, so how far along the site is reads before what it
  is configured to become.
- The production bar moves between the input and output buffers, so a producing
  building reads in the direction its materials flow: what goes in, what is
  being made of it, what has come out. BufferSection held both buffer sections
  and so could not be split around it; the two sections and the production
  section are now the card's own, in that order.
- Locked items are left out of the buffers. An auto-recipe building's buffers
  are sized over every recipe of its type, so a Smelter carried an input for
  quartz -- which the player cannot mine yet -- and an output for the silicon it
  would smelt into. Both are dropped now, as everywhere else that hides what is
  not unlocked.
- An idle auto-recipe building lists what it handles rather than nothing. It has
  no selected recipe to name, so a Reprocessing Plant between cycles showed no
  output buffer at all. Its sections now list the unlocked items of every recipe
  of its type -- the union its buffers were sized over -- without a per-cycle
  denominator, since no one recipe is in force.

The sixth was the bars vanishing whenever the window lost focus, to a modal
dialog or to another application. They were filled with the palette's current
highlight, and the palette follows the window's focus: the inactive group's
highlight sits close enough to the card's background to read as gone. They ask
for the active group by name now.

Measured on a freshly built Smelter, which is the case that showed three of
these at once:

  INPUT BUFFERS  0 Copper Ore | 0 Iron Ore | 0 Scrap
  PRODUCTION     idle
  OUTPUT BUFFER  0/2 Copper Ingot | 0/2 Iron Ingot

Quartz and silicon filtered out, production between the buffers, and an idle
building still saying what it handles.

Requirements updated for the ordering, the locked-item rule and the idle
auto-recipe listing (REQ-UI-SELECTION-CARD, REQ-UI-SINGLE-SELECTION,
REQ-UI-PRODUCTION-PROGRESS, REQ-UI-HQ-PANEL).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-07 21:39:39 +02:00
44af3184d3 let the selection panel decide its own scroll bar
Selecting a building after a piece of debris left a scroll bar on a card that
had nothing to scroll.

Two faults, both found by driving the panel through the reported sequences and
printing what it measured itself to:

The bar was Qt's decision. Asked for ScrollBarAsNeeded, the scroll area shows a
bar the moment the card is larger than its viewport -- which is true while the
card is being measured, since measuring means giving it a width -- and does not
take it back when the range turns out to be empty. The panel already works out
whether the card fits its band and widens itself for the bar when it does not,
so it now sets the policy itself: AlwaysOn when it decided to scroll, AlwaysOff
when it did not. The previous commit's resize-to-cap made this visible;
removing that alone traded the phantom bar for a real one, because the card's
height depends on the width it is measured at.

The measurement was also a pass short. A card's width follows from the room it
is given and its height from that width, so refit() measures twice: once at the
cap to learn the width the card wants, once at that width for the height. The
whole thing then runs twice, because parts of a freshly built card report an
unstyled size until the style reaches them during the first round -- that gap
was leaving the panel a few pixels short of what the card turned out to need,
which is a scroll bar over a card that looks like it fits.

Measured before and after, HQ card, roomy band:
  before  panel=113x114  card wants 111x121  bar visible, range empty
  after   panel=113x123  card wants 111x121  no bar
And in a 90px band it still scrolls: panel=130x74, range 47, bar shown.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-07 21:13:32 +02:00
6fa3ba7f0c show the selection card before measuring the panel against it
Clicking something sometimes left the panel collapsed to its scroll bar, most
often for field entities.

Same cause as the controls panel's collapse in d7c6734: a widget created under
an already-visible parent starts hidden, and a layout counts a hidden item as
empty. rebuildContent() built the card, added it to the body layout and
measured immediately, so the body reported nothing but its own margins. A width
of nearly zero makes heightForWidth() on the wrapped labels enormous, that
overflows the band, and refit() then caps the height and widens by the scroll
bar -- leaving the panel exactly one scroll bar wide.

It could not recover on the next tick either, because a word-wrapped label's
size hint follows its current width: once narrow, it keeps reporting narrow and
tall. So refit() now measures the body at the width cap rather than at whatever
width the panel currently has, and invalidates the body layout before reading
it -- cards are built and discarded whole, so its cached hint otherwise
describes the card before this one.

Field entities hit it more often because a field selection publishes twice,
actors then debris, so one click rebuilds the card twice.

The same defect existed one level down, where parts are rebuilt while the card
is already visible: ItemChipRow::rebuildChips() and RecipeSummaryRow::rebuild()
now show what they create. Those were measuring the buffer section and the
recipe line as empty on every recipe change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-07 20:56:18 +02:00
f06d79e60d document the player-input design in architecture.md
The doc's job is the invariants that are easy to break, and this change added
three of them that only existed as comments in the files enforcing them. The
one that matters most is the first: adding a shortcut straight to InputMapper's
switch is the natural next edit, it works, and it silently reintroduces exactly
the drift the action table was built to prevent.

Also records the two distinctions that cost the most to rediscover -- that an
action can be available in a context the panel does not advertise it in, and
that gesture state belongs to the shared mode rather than to an action, because
it decides what other bindings mean.

The ui target's contents were listed without the controls panel too.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 20:40:03 +02:00
97c269576e scroll the controls panel's rows instead of clipping them
REQ-UI-CONTROLS-PANEL said the content scrolls once it outgrows the space
available; only the height cap was implemented, so the surplus rows were simply
cut off. Silent row loss is the one failure this panel must not have, and it
was reachable: the Selection context runs to fifteen rows, and a panel that has
also had to rise above the build button bar can be left with less room than
that.

The rows move into a scroll area. The heading stays outside it, so it remains
visible and remains the collapse control whatever the rows are doing.

The size can no longer come from the panel's own layout -- a scroll area's hint
describes a viewport, not its contents -- so the heading and the rows are
measured directly and the chrome added. Verified against a forced rebuild and
an artificially cramped view:

  roomy:    heading 56x13 + rows 124x188 -> 142x223, no scrollbar
  collapsed:                             ->  74x31, same bottom edge
  cramped:  wanted 223, band 124         -> 159x124, +17 for the scrollbar

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 20:39:06 +02:00
a5c51f08f8 put the controls panel in the corner and let it step around the build bar
It was confined to the band above the build button bar's strip, borrowing the
selection panel's rule. That rule exists because the selection panel is
full-height on the right, where the bar's strip is genuinely in the way. This
panel is short and in the corner, and the bar is centered and sized to its
buttons, so the corner is normally free -- reserving the whole strip pushed the
panel up for a collision that was not happening.

It now sits in the bottom-left corner and shares the view's bottom edge with
the bar, rising only when the panel's rectangle would actually intersect the
bar's, in which case it clears the bar's top by the usual margin and caps its
height at what is left. So it moves for a wide bar and a wide panel, and drops
back into the corner as soon as they no longer meet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 20:07:22 +02:00
3c4688bdb6 mark the exit row on its chips instead of its label
The label was painted palette(bright-text), which is not a destructive color at
all: Qt has no such role, and bright-text is white by design, meant for text
over dark highlights. On this panel's light chrome it was white on grey.

The chips carry the warning now and the label keeps the ordinary text color, so
the row stays legible whatever the palette and only the binding is marked --
which is what REQ-UI-CONTROLS-CARD asked for in the first place, and what the
mockup shows. The red is a literal because no palette role means it, chosen to
read on a light and a dark background alike, and it is widget chrome, so like
the rest of this stylesheet it is deliberately not a visuals.toml color.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 19:47:56 +02:00
d7c6734a2b show the controls panel's rows before measuring them
A widget created under an already-visible parent starts hidden, and a layout
counts a hidden item as empty -- it adds nothing to the size hint. Nothing
showed the freshly built rows until the event loop next ran, long after the
panel had measured itself, so every rebuild measured an empty card.

That one fact explains both symptoms. Originally refit() read a stale cached
hint, which described the previous context and so drew the card one rebuild
behind. Invalidating that cache to fix it replaced a plausible wrong answer
with the true one for a card whose rows were all still hidden, which is why the
panel then collapsed to its heading on every mode change.

Measured on a forced rebuild, with the rows shown and without:

  shown:   rowItems=10 hidden=0  rowsHint=188  needed=140x221
  hidden:  rowItems=10 hidden=10 rowsHint=6    needed=72x39

39px being heading plus margins -- the collapsed card exactly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 19:36:24 +02:00
1604dc02a2 measure the controls panel against its content, not its old geometry
The previous fix went too far: it activated the panel's own layout before
resizing, which lays the heading and the rows out inside the geometry left over
from the previous context. The panel then took that stale frame as its answer
and collapsed to almost nothing whenever the mode changed.

Only the rows layout is activated now -- that part was right, and is what makes
freshly added rows visible and so measurable. The size comes from
layout()->totalSizeHint(), which says how big the content needs to be without
reference to how big the panel currently is; setGeometry re-runs the outer
layout afterwards on its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 19:28:15 +02:00
b346f3dfc1 size the controls panel to the rows it is actually showing
The card was drawn one rebuild behind: selecting something for the first time
sized it for the context before it, and the next selection sized it for that
one. refit() activated the panel's outer layout but never the rows layout
underneath it, so it read a size hint describing rows that were no longer
there, while the freshly added ones were not yet shown and so counted for
nothing. Both layouts are now invalidated and re-run innermost first, and the
rows are polished before being measured -- the badge chips carry border and
padding, which a label reports only once the stylesheet has reached it.

Also drops letter-spacing from the stylesheet. Qt has no such property and
warned once per widget it was applied to, which was most of the console. The
heading and the caption set it on their QFont, where it works.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 19:21:28 +02:00
b634da70fb record that additive selection is offered only once something is selected
Ctrl+click works with an empty selection -- it picks the object under the
cursor much as a plain click does -- so leaving it out of the General card is
an omission rather than a claim the panel declines to make. The catalog already
implied that by listing it under Selection only; the accuracy rule now says so
outright, alongside the three omissions it already named.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 19:06:24 +02:00
37d9166348 divide the always-available rows in the General context too
The General card was the one that ran its context rows and the global ones
together as a flat list. That made it the exception a player has to notice: the
same six rows sit under a caption everywhere else, so leaving them uncaptioned
here asks the reader to work out that they are the same six.

Requirement wording corrected with it -- it claimed the always-available rows
were the General context's entire content, which was never true. General has
Select, Select area and Deconstruct mode of its own above the divider, exactly
like the other contexts.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 19:06:01 +02:00
fe69921b8e show the available controls in a panel over the world
The panel decides nothing about what the controls are: it asks the same
resolver the key handling and the mouse dispatch ask, and renders each badge
from the binding that resolver matches. A chip cannot claim a key that does
nothing, and a label cannot describe a click that does something else, because
neither is written here.

Display text is the one part that is not shared -- lib/core says what is
available and what triggers it, ControlActionText.cpp says what it is called.
That split is why the table can stay free of UI strings and still be the single
source of the pairing.

It refreshes on a timer rather than by subscribing. Two things that change a
row -- a belt drag starting, the ghost crossing a transfer target -- happen on
mouse movement and publish nothing, and they must still show while the game is
paused, so there is no event and no tick to hang it on. Resolving is comparing
two vectors of enums, and the rebuild is skipped unless they differ.

Left edge, bottom-aligned in the same band the selection panel is confined to,
so it clears the build bar's strip and never meets the panel on the opposite
edge. Clicking the heading collapses it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 17:30:22 +02:00
3e79b09fec resolve mouse gestures through the action table too
The panel has to say what the left button does right now -- "Place" or "Apply
settings", "Select" or "Toggle deconstruct" -- and that answer lived in the
if-chain at the top of mousePressEvent, where the panel could not reach it.
So the chain becomes a switch on the resolved action, and the panel will read
the same resolver. Which branch runs is now decided in one place; what each
branch does is untouched, drag state machines and all.

Right-click gets the clearest win: cancel-the-drag versus leave-the-mode was
two nested conditions inspecting belt state, and is now the two actions the
table already distinguishes for the panel's sake.

Ctrl variants fall back to the plain gesture wherever nothing claims them,
which is what keeps Ctrl+click placing a building in builder mode and Ctrl+drag
deconstructing an area -- the modifier means something only where an action
says it does, rather than every handler re-deciding whether to ignore it.

Behaviour is unchanged. Full suite passes; the app runs clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 17:24:25 +02:00
77bbd58d02 resolve keyboard shortcuts through one action table instead of a switch
The controls panel needs to say what each key does right now, and a panel that
keeps its own list of that is a list that goes stale. So the list moves into
lib/core/ControlAction.h: which actions exist, what each is bound to, and when
each does something. InputMapper stops deciding that and switches on the
resolved action instead, so the panel and the key handling cannot disagree
about what Q means -- there is only one place that says.

The table declares; it never performs. It holds no simulation access, fires no
events, and names nothing: display strings live in the ui target, which formats
the bindings this hands it, so a badge is rendered from the real binding rather
than typed beside it. What an action *does* stays exactly where it was.

ControlContext is the snapshot the rules read, which is what keeps this
testable without a world. Two of its facts come from BlueprintLibrary, which is
built after the world view and so arrives by setter; one comes from the new
hovered-transfer flag on BuildModeController, resolved once on mouse-move
through the same classifier the click and the ghost colour already use.

Behaviour is unchanged, deliberately. Ctrl still separates the chords and every
other modifier is still ignored, so Shift+A pans as before; matching modifiers
exactly would have silently swallowed those presses. Build hotkeys and F3/F4
stay outside the table -- the first are advertised on the build buttons and
already derive their badges from the handler's own table, the second are
development controls the panel must never offer.

The tests are the point of putting this in lib: every row's bindings must
resolve back to that row's action in that same context, which fails the moment
a shown row and its handler part ways.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 17:20:44 +02:00
02f2314588 specify a context-sensitive controls panel floating over the game world
Adds REQ-UI-CONTROLS-PANEL/-CARD/-CONTENT/-ACCURACY: a left-anchored panel,
bottom-aligned within the same band the selection panel uses, collapsed and
expanded by clicking its header. Five control contexts derived from the build
mode and the selection, each with its own rows above a shared always-available
block.

The accuracy rule is the load-bearing part: a row must have the effect its
label names, or not be shown -- no greyed rows. That makes four rows
conditional on more than the context (C/Ctrl+C on the selection holding a
placeable building, the belt-drag row on the builder type, the RMB/Q split on a
drag being in progress, and Place vs Apply settings on the hovered ghost
resolving to a configuration transfer), and it makes the context-to-rows
mapping testable against the real bindings.

Also names the panel in the layout diagram, REQ-UI-WORLD-SIZE, and
REQ-UI-MODAL-DIM, and records in REQ-UI-HOTKEYS that the panel and the build
button badges display bindings rather than define them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YHcUerKAZKWNvSKJxYKbnG
2026-08-07 14:43:46 +02:00
246cfc3935 give the selection cards their own parts instead of label blobs
The cards were assembled from plain labels carrying whole blocks of text.
Replace those with the widget vocabulary the requirements describe, so a part
means the same thing wherever it appears and a card is a list of parts rather
than a string builder.

The parts, all free of Simulation and GameConfig -- they take prepared values,
and the contents work out what those are:
- StatRow, BarRow, SectionBox: label/value line, captioned fill bar, captioned
  group. The bar is one part for three things: construction progress,
  production progress, and HP.
- ItemChip / ItemChipRow: buffered items as icon, count and sub-line
  (REQ-UI-SINGLE-SELECTION). An input chip carries its per-cycle amount, an
  output chip its count against the buffer capacity. The chips are rebuilt only
  when the set of items changes, so a 30 Hz refresh moves numbers rather than
  widgets.
- RecipeSummaryRow: inputs, arrow, outputs, cycle time (REQ-UI-RECIPE-SUMMARY),
  which is now the panel's only display of the cycle time.
- CountRow, StatusPill, EmptyNote.

Behaviour that changed with them:
- The station card shows damage, range and fire rate as the requirement asks
  (REQ-UI-STATION-STATS-PANEL) rather than the combined DPS it showed before.
- A ship's behaviour moves from a stats row into the card header
  (REQ-UI-SHIP-BEHAVIOR). ShipStatsPanel keeps setBehavior for the balancing
  tool's inspect window, which has no header to put it in.
- A construction site's card shows a progress bar and the "no buffers until
  built" note (REQ-UI-SELECTION-CARD), and now also its recipe summary, since
  that is configuration and a site carries it (REQ-BLD-SITE-CONFIG). Costing a
  shipyard site's schematic needed computeShipyardRequiredMaterials to take a
  stored configuration as well as a live building -- one overload, so the
  module sum still exists once.

ShipStatsPanel is rebuilt on StatRow, BarRow and SectionBox, so the selection
card, the layout dialog's design preview and the balancing tool read alike.
Those three parts are compiled into the balancing target, which does not link
the ui library; keeping them sim-free is what makes that possible, and the
build enforces it.

Build clean, 541 tests pass, app and balancing tool both run with no Qt
warnings. Visual check pending.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-07 12:37:11 +02:00
89e984ec76 split the selection panel into one card per kind of selection
The panel rendered every selection out of a single pool of member widgets,
hidden and shown per branch, so each build path had to remember to hide the
other branches' widgets. That coupling produced the two defects fixed in
668ce0f, and the per-type detail the requirements now ask for would only add
more of it.

The pool is gone. SelectionPanel keeps the category arbitration, the float and
the hide-when-empty behaviour, and hosts exactly one SelectionContent at a
time; SelectionContentFactory picks which one from the selection alone. Each
card is one row of the catalog in REQ-UI-SELECTION-CONTENT and owns only its
own widgets.

The card structure (REQ-UI-SELECTION-CARD) lives in the base class: a header
with an identity symbol, a name and one right slot, then a configuration group
and a runtime group. A construction site keeps its configuration and has its
whole runtime group replaced by the construction progress, decided once there
rather than in every card (REQ-BLD-SITE-CONFIG).

Also implemented here:
- REQ-UI-SELECTION-STATUS: the header status dot, taken from the simulation's
  own getProductionStatus() so the panel and the world's status light cannot
  disagree.
- REQ-UI-SELECTION-AGGREGATE: belt-subsystem tiles and debris-only selections
  collapse into one card with a count instead of a count summary.
- REQ-UI-HQ-PANEL: the HQ shows the global block stock and its HP, neither of
  which is a buffer.
- BuildingIconCache, extracted from BuildButtonBar's file-local chip loading so
  the card headers and the build buttons rasterize the same SVGs once.

FieldSelectionPanel is deleted: ships, stations, debris and the field count
summary are four more cards in the same factory, so the two-panel arbitration
collapses into one decision.

The card parts are still today's labels and buttons; the item chips, bars,
recipe summary and stat rows follow.

Build clean, 541 tests pass, app runs with no Qt warnings. Visual check
pending.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-07 12:18:33 +02:00
90e40dddbc define the selection panel as a catalog of per-selection contents
The panel's content requirements described one panel that changes shape.
Restate them as one card structure plus a catalog of contents picked by
what is selected, so each selection has a named content and the parts
mean the same thing wherever they appear.

New:
- REQ-UI-SELECTION-CARD: header (symbol, name, one optional right slot),
  configuration group, runtime group. A construction site replaces the
  whole runtime group with a Construction bar and keeps its configuration
  group, per REQ-BLD-SITE-CONFIG.
- REQ-UI-SELECTION-CONTENT: the catalog table.
- REQ-UI-SELECTION-STATUS: the header status dot, derived from
  REQ-UI-STATUS-LIGHT's evaluation rather than a second definition.
- REQ-UI-SELECTION-AGGREGATE: a homogeneous multi-selection collapses into
  one content with a count, but only where every part aggregates -- belt
  subsystem tiles and debris. Splitters mixed with belts and several
  production buildings fall back to the count summary.
- REQ-UI-RECIPE-SUMMARY: the inputs -> outputs, duration line, including a
  shipyard's module contributions.
- REQ-UI-HQ-PANEL: global block stock plus HP, because blocks bypass the
  buffers into the global stock (REQ-HQ-BELT-INPUT).

Rewritten: REQ-UI-SINGLE-SELECTION (item chips; an output chip's
denominator is now the buffer capacity, not the per-cycle amount),
REQ-UI-PRODUCTION-PROGRESS (bar, and no longer the cycle time's home),
REQ-UI-MULTI-SELECTION (count rows and a total cost row), REQ-UI-BELT-CLEAR,
REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL, REQ-UI-SHIP-BEHAVIOR
(moves into the header slot), REQ-UI-FIELD-MULTI-SELECTION and
REQ-UI-DEBRIS-PANEL (debris-only selections now aggregate).

Requirements only; no code changes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-07 09:59:26 +02:00
668ce0fcb8 float the selection panel over the game world instead of a side column
Implements REQ-UI-SELECTION-PANEL and the full-width REQ-UI-WORLD-SIZE /
REQ-UI-HEADER: MainWindow drops the 25% side column and its 75/25 math, so
the header bar and world view span the window, and the panel joins the
build button bar as a widget floating over the world.

The panel follows the bar's pattern -- an opaque sibling built after the
world view, so it sits above the vignettes, below the dim overlay, and
swallows the mouse events that would otherwise reach the world. It sizes
itself to its content within a band the window hands it (the world view
less the bar's strip, so the bar never has to move for it), right-aligned
and centered in that band, and scrolls once the content outgrows it. Its
content moved into a scroll area for that; the width is capped at 320 px
because the wrapped labels and the splitter filter lists have no natural
width of their own. With nothing selected the panel now hides entirely
rather than showing an empty box (REQ-UI-EMPTY-SELECTION).

Two defects that content sizing exposed: buildEmpty() left the selected
ids behind when the building vanished under the panel, which would have
held an empty panel on screen, and buildMulti() let a shipyard's layout
preview survive from a previous single selection (REQ-UI-MULTI-SELECTION).

Renames SelectedBuildingPanel to SelectionPanel throughout, matching the
requirements: the panel has long shown ships, stations, and debris too.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-06 21:58:36 +02:00
7ddb4a1bb5 float the selection panel over the game world instead of a side column
Remove the 25% side panel column: the header bar and game world view now
span the full window width, and the selection panel floats over the world
at its right edge, content-sized and shown only while something is
selected.

REQ-UI-PANEL-COLUMN is replaced by REQ-UI-SELECTION-PANEL, which defines
the panel's geometry, visibility, overlay, and input rules. The panel is
centered within the view height less its margins and the build button
bar's strip, so the bar never has to move out of its way. Rename the
"selected building panel" to "selection panel" throughout, since it has
long shown ships, stations, and debris too.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JcReq7hVk4KUPhTDKWAG7K
2026-08-06 21:17:43 +02:00
3b37b0ecf8 target single-building transfers by hovering, not by footprint coincidence 2026-08-06 20:31:51 +02:00
98deab932a let any blueprint transfer configuration, not just single-building ones (if the orientation matches) 2026-08-06 20:29:20 +02:00
08d8b0dd90 re-cover copy-settings through single-building blueprints 2026-08-06 19:44:55 +02:00
9a3b6c10d6 fix bug where selecting the same layout for a shipyard discarded the current progress and buffers 2026-08-06 19:18:45 +02:00
cd31af2611 remove the Shift copy-building-settings gesture 2026-08-06 19:09:11 +02:00
fd6a7c5815 rekey the temporary blueprint to C, add V to re-place it 2026-08-06 19:07:13 +02:00
18cfe238f6 move blueprints out of the sidebar into Ctrl+C / Ctrl+V dialogs 2026-08-06 19:03:59 +02:00
2cbcf1554f add the ASCII-only source rule and the visual-verification note to CLAUDE.md 2026-08-06 08:28:57 +02:00
c1af58d80c float the build buttons as a horizontal bar over the game world and show key bindings inside build buttons 2026-08-06 08:28:40 +02:00
132 changed files with 8037 additions and 2342 deletions

View File

@@ -348,7 +348,7 @@ deconstruct_tint = "#ff000033" # deconstruct-mode hover tint
selection_rect = "#00ff00" # box-drag selection rectangle (REQ-UI-MULTI-SELECT) selection_rect = "#00ff00" # box-drag selection rectangle (REQ-UI-MULTI-SELECT)
tile_highlight = "#ffffff22" # tile under cursor tile_highlight = "#ffffff22" # tile under cursor
selected_outline = "#ffff00" # outline drawn around currently-selected building(s) selected_outline = "#ffff00" # outline drawn around currently-selected building(s)
copy_config = "#33ccff66" # copy-settings eligible-target tint + copy/paste flash (REQ-BLD-COPY-CONFIG-FEEDBACK) config_transfer = "#33ccff66" # blueprint ghost over a configuration-transfer target (REQ-UI-BLUEPRINT-TRANSFER)
locked_asteroid = "#0000007f" # tint over the asteroid left of the buildable edge (not yet unlocked by expansion) locked_asteroid = "#0000007f" # tint over the asteroid left of the buildable edge (not yet unlocked by expansion)
modal_dim = "#00000099" # semi-transparent black dim behind modal dialogs/menus (REQ-UI-MODAL-DIM) modal_dim = "#00000099" # semi-transparent black dim behind modal dialogs/menus (REQ-UI-MODAL-DIM)
tunnel_preview = "#00ff0055" # tunnel connection preview: matched end + tiles between (REQ-BLD-TUNNEL-MODE) tunnel_preview = "#00ff0055" # tunnel connection preview: matched end + tiles between (REQ-BLD-TUNNEL-MODE)

View File

@@ -124,12 +124,31 @@ Within a single simulation tick, subsystems run in this fixed order. The order i
Three product targets plus tests: Three product targets plus tests:
- `lib/` — simulation + config. Depends on Qt Core + Qt Gui, toml++, tinyexpr. No QtWidgets. - `lib/` — simulation + config. Depends on Qt Core + Qt Gui, toml++, tinyexpr. No QtWidgets.
- `ui/` — QtWidgets + `QOpenGLWidget` code: header bar, game world view, selected building panel, build button bar. Depends on `lib` and on Qt's OpenGL widgets module. - `ui/` — QtWidgets + `QOpenGLWidget` code: header bar, game world view, selection panel, build button bar, controls panel. Depends on `lib` and on Qt's OpenGL widgets module.
- `ui/selection/` — the selection panel's contents. `SelectionPanel` itself only arbitrates between the two selection categories, picks a card from the catalog (`SelectionContentFactory`), and hosts one at a time; each kind of selection has its own `SelectionContent` subclass assembled from shared parts (REQ-UI-SELECTION-CARD, REQ-UI-SELECTION-CONTENT).
- `app/` — thin `main()` that creates the simulation, the UI, and wires them together. Depends on `ui`. - `app/` — thin `main()` that creates the simulation, the UI, and wires them together. Depends on `ui`.
- `tests/` — Catch2 tests. Links only against `lib`. - `tests/` — Catch2 tests. Links only against `lib`.
Directory discipline inside `lib/` keeps the internal sim/config seam clear; sim code must not reach into config parsing and vice versa. Directory discipline inside `lib/` keeps the internal sim/config seam clear; sim code must not reach into config parsing and vice versa.
## Player Input
Every player control is declared once, in `lib/core/ControlAction.h`, and read by three consumers that must never disagree about it:
* **`ControlsPanel`** asks which actions apply and draws a row per action (REQ-UI-CONTROLS-CONTENT).
* **`InputMapper`** resolves a key press to an action and fires the event that action stands for.
* **`GameWorldView`** resolves a mouse gesture to an action and runs the branch that carries it out.
The file declares; it never performs. It holds no simulation access, fires no events, and names nothing — display strings live in `ui/ControlActionText.h`, which renders each badge from the binding the resolver actually matches, so a chip cannot claim a key that does nothing. What an action *does* stays in the widget that always did it: the drag state machines, hit-testing, and command enqueuing were not moved.
Three invariants are easy to break here:
* **Do not add a shortcut straight to `InputMapper`'s switch or `mousePressEvent`'s branches.** Add the action and its binding to the table; the handler switches on the resolved action. A binding added directly is invisible to the panel, which is the drift the table exists to prevent. (Build hotkeys and `F3`/`F4` are deliberate exceptions, documented in the header and in REQ-UI-CONTROLS-ACCURACY.)
* **Availability and display are different questions.** An action can be live in a context the panel does not advertise it in — `Ctrl`+click with an empty selection is the standing example. `isControlActionAvailable` answers the first, the per-context row lists answer the second, and `ControlActionTest` asserts the pairing that matters: every row's bindings resolve back to that row's action.
* **Gesture state is shared, not owned by an action.** Whether a belt drag is in progress decides what the right mouse button means, so it lives on `BuildModeController` where the resolver can see it — as does the hovered-transfer flag. `m_boxSelecting` is likewise one gesture serving two actions (box select and deconstruct area).
`ControlContext` is a plain snapshot rather than references to the live controllers, which is what keeps the rules testable without a world and stops an action reaching into the simulation: if a rule needs a fact, the fact is named in the struct and the caller supplies it. When bindings become player-configurable, only the binding tables in `ControlAction.cpp` turn from hard-coded data into loaded data.
## Belt Subsystem ## Belt Subsystem
Belts and splitters are their own specialized subsystem. Belt items are **not** entities — they are transient data flowing through the belt representation. They do not have identities that persist across ticks. Belts and splitters are their own specialized subsystem. Belt items are **not** entities — they are transient data flowing through the belt representation. They do not have identities that persist across ticks.
@@ -333,7 +352,7 @@ The game world is drawn into a single `GameWorldView` widget that inherits `QOpe
The drawing itself lives in `WorldRenderer`, not in the widget. `paintGL` is a call sequence: build the frame's `WorldCoordinates`, hand the renderer a `WorldRenderFrame`, then draw the screen-anchored chrome. The split is the world-space / screen-space line, and it is exact: the renderer draws everything positioned in tiles, while everything positioned in pixels — the pause and deconstruct vignettes, the replay overlay, the debug stats panel — stays with the widget. A useful consequence is that the renderer draws no translatable text at all (its text is config-driven glyphs, ASCII port arrows, and numbers), so it needs no `tr()` and no tie to the meta-object system. The drawing itself lives in `WorldRenderer`, not in the widget. `paintGL` is a call sequence: build the frame's `WorldCoordinates`, hand the renderer a `WorldRenderFrame`, then draw the screen-anchored chrome. The split is the world-space / screen-space line, and it is exact: the renderer draws everything positioned in tiles, while everything positioned in pixels — the pause and deconstruct vignettes, the replay overlay, the debug stats panel — stays with the widget. A useful consequence is that the renderer draws no translatable text at all (its text is config-driven glyphs, ASCII port arrows, and numbers), so it needs no `tr()` and no tie to the meta-object system.
`WorldRenderFrame` is what makes the renderer independent of the widget. The renderer reads the simulation directly, but everything else it draws is interaction state the widget owns — the selection, the active build mode, live beams, the copy-settings feedback, the box-select rectangle. Those are gathered into the frame each `paintGL` and passed by reference, so the renderer keeps no copy that a later click could invalidate. The renderer knows nothing about input: the widget resolves clicks and hit-tests, and the renderer only draws the result. `WorldRenderFrame` is what makes the renderer independent of the widget. The renderer reads the simulation directly, but everything else it draws is interaction state the widget owns — the selection, the active build mode, live beams, the box-select rectangle. Those are gathered into the frame each `paintGL` and passed by reference, so the renderer keeps no copy that a later click could invalidate. The renderer knows nothing about input: the widget resolves clicks and hit-tests, and the renderer only draws the result.
### Render Loop ### Render Loop

View File

@@ -390,11 +390,11 @@ Reshape mutations to flow through one path; behaviour unchanged.
before the tick batch (runs even at 0× → build-while-paused preserved). A drained `Reset` before the tick batch (runs even at 0× → build-while-paused preserved). A drained `Reset`
triggers the view reset. triggers the view reset.
- Refactored every UI mutation site: `GameWorldView` owns the `CommandManager` and enqueues - Refactored every UI mutation site: `GameWorldView` owns the `CommandManager` and enqueues
directly; `MainWindow` and `SelectedBuildingPanel` emit `CommandRequestedEvent` (carrying a directly; `MainWindow` and `SelectionPanel` emit `CommandRequestedEvent` (carrying a
`shared_ptr<const Command>`) which `GameWorldView` subscribes to and enqueues. `shared_ptr<const Command>`) which `GameWorldView` subscribes to and enqueues.
- **Files:** new `lib/sim/Command.h`, `CommandManager.{h,cpp}`; `CommandRequestedEvent.h`; - **Files:** new `lib/sim/Command.h`, `CommandManager.{h,cpp}`; `CommandRequestedEvent.h`;
`Simulation.{h,cpp}` (`apply`); `GameWorldView.{h,cpp}`, `MainWindow.cpp`, `Simulation.{h,cpp}` (`apply`); `GameWorldView.{h,cpp}`, `MainWindow.cpp`,
`SelectedBuildingPanel.cpp`; new `CommandTest.cpp`. `SelectionPanel.cpp`; new `CommandTest.cpp`.
- **Exit criteria:** game plays identically (including build-while-paused); determinism test - **Exit criteria:** game plays identically (including build-while-paused); determinism test
still passes; `[command]` equivalence tests pass; no production call site can mutate the sim still passes; `[command]` equivalence tests pass; no production call site can mutate the sim
directly (compile-enforced: the `Simulation` mutators are private, tests excepted via directly (compile-enforced: the `Simulation` mutators are private, tests excepted via

View File

@@ -127,8 +127,8 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- REQ-BLD-GHOST: While in builder mode, a ghost of the building is rendered at the tile under the cursor, showing where it would be placed. The ghost is drawn semi-transparently in the building type's own visuals — its `fill` and `outline` colors and `glyph` from `visuals.toml` — so that different building types are visually distinguishable in builder mode rather than all looking alike. When the current cursor position is invalid, the ghost instead uses the distinct "invalid" color (REQ-BLD-PLACE-VALID), which overrides the per-building coloring. - REQ-BLD-GHOST: While in builder mode, a ghost of the building is rendered at the tile under the cursor, showing where it would be placed. The ghost is drawn semi-transparently in the building type's own visuals — its `fill` and `outline` colors and `glyph` from `visuals.toml` — so that different building types are visually distinguishable in builder mode rather than all looking alike. When the current cursor position is invalid, the ghost instead uses the distinct "invalid" color (REQ-BLD-PLACE-VALID), which overrides the per-building coloring.
- REQ-BLD-ROTATE: While in builder mode, pressing Shift+R rotates the ghost 90° clockwise and R rotates it 90° counter-clockwise. Rotation affects the direction of the output port. - REQ-BLD-ROTATE: While in builder mode, pressing Shift+R rotates the ghost 90° clockwise and R rotates it 90° counter-clockwise. Rotation affects the direction of the output port.
- REQ-BLD-PLACE: Clicking a valid tile in builder mode places a construction site and adds it to the build queue, consuming building blocks from the global stock. (For belts, placement is instead deferred to a drag gesture and happens on mouse release — REQ-BLD-BELT-DRAG.) - REQ-BLD-PLACE: Clicking a valid tile in builder mode places a construction site and adds it to the build queue, consuming building blocks from the global stock. (For belts, placement is instead deferred to a drag gesture and happens on mouse release — REQ-BLD-BELT-DRAG.)
- REQ-BLD-PLACE-VALID: A placement position is valid only if (a) every footprint cell in the rotated `surface_mask` is satisfied by the underlying terrain — `A` cells coincide with asteroid tiles, `S` cells coincide with space tiles — (b) no footprint cell overlaps an existing placed building or construction site, except as allowed by REQ-BLD-ROTATE-IN-PLACE, and (c) the player has enough building blocks to afford the building. The ghost (REQ-BLD-GHOST) is rendered in a distinct "invalid" color — overriding its per-building coloring (REQ-BLD-GHOST) — when the current cursor position fails any of these conditions. - REQ-BLD-PLACE-VALID: A placement position is valid only if (a) every footprint cell in the rotated `surface_mask` is satisfied by the underlying terrain — `A` cells coincide with asteroid tiles, `S` cells coincide with space tiles — (b) no footprint cell overlaps an existing placed building or construction site, except as allowed by REQ-BLD-ROTATE-IN-PLACE (builder mode) or REQ-UI-BLUEPRINT-OVERLAP and REQ-UI-BLUEPRINT-TRANSFER (blueprint placement mode), and (c) the player has enough building blocks to afford the building. The ghost (REQ-BLD-GHOST) is rendered in a distinct "invalid" color — overriding its per-building coloring (REQ-BLD-GHOST) — when the current cursor position fails any of these conditions.
- REQ-BLD-ROTATE-IN-PLACE: If the ghost's footprint exactly coincides with the footprint of an existing placed building or construction site of the same building type, clicking places no new construction site and consumes no building blocks. Instead, the existing building or site is rotated to match the ghost's rotation. If the target is a construction site, its construction progress is preserved. **Exception:** Tunnel Entries and Tunnel Exits are never rotated in place — re-orienting a tunnel requires deconstructing and re-placing it (REQ-BLD-TUNNEL-MODE). A tunnel ghost whose footprint coincides with an existing tunnel is therefore treated as an ordinary occupied-tile placement (invalid in normal builder mode; skipped in blueprint placement mode). This applies in both normal builder mode and blueprint placement mode; in blueprint placement mode it is evaluated per building in the blueprint independently — buildings in the blueprint whose footprint coincides with an existing same-type building or site are rotated in place, while the remaining buildings in the blueprint are placed as normal construction sites (subject to the usual validity checks and total cost). - REQ-BLD-ROTATE-IN-PLACE: If the ghost's footprint exactly coincides with the footprint of an existing placed building or construction site of the same building type, clicking places no new construction site and consumes no building blocks. Instead, the existing building or site is rotated to match the ghost's rotation. If the target is a construction site, its construction progress is preserved. **Exception:** Tunnel Entries and Tunnel Exits are never rotated in place — re-orienting a tunnel requires deconstructing and re-placing it (REQ-BLD-TUNNEL-MODE). A tunnel ghost whose footprint coincides with an existing tunnel is therefore treated as an ordinary occupied-tile placement, which is invalid. This applies **only in normal builder mode**, including the belt drag of REQ-BLD-BELT-DRAG. Blueprint placement mode never rotates an existing building in place: there, a ghost whose footprint coincides with an existing same-type building or site is a configuration-transfer target (REQ-UI-BLUEPRINT-TRANSFER), or a compatible overlap that is left untouched (REQ-UI-BLUEPRINT-OVERLAP), or else an ordinary occupied-tile overlap, which is invalid.
- REQ-BLD-BELT-DRAG: **Belt drag placement.** For belts, placement is a deferred drag gesture rather than immediate per-tile placement: construction sites are not placed while the cursor hovers new tiles, but only once the player releases the left mouse button. Pressing the left mouse button in the game world while in belt builder mode starts a drag anchored at the tile under the cursor. As the cursor moves, a **rectilinear (L-shaped) path** of belt tiles is computed from the anchor tile to the tile under the cursor: the path first runs along the axis **parallel to the belt's current orientation** (REQ-BLD-ROTATE) — stepping toward the cursor's coordinate on that axis to a corner tile — and then runs along the orthogonal axis to the cursor tile. When the cursor shares the anchor's row or column the path degenerates to a straight line, and when it is on the anchor tile the path is a single tile. - REQ-BLD-BELT-DRAG: **Belt drag placement.** For belts, placement is a deferred drag gesture rather than immediate per-tile placement: construction sites are not placed while the cursor hovers new tiles, but only once the player releases the left mouse button. Pressing the left mouse button in the game world while in belt builder mode starts a drag anchored at the tile under the cursor. As the cursor moves, a **rectilinear (L-shaped) path** of belt tiles is computed from the anchor tile to the tile under the cursor: the path first runs along the axis **parallel to the belt's current orientation** (REQ-BLD-ROTATE) — stepping toward the cursor's coordinate on that axis to a corner tile — and then runs along the orthogonal axis to the cursor tile. When the cursor shares the anchor's row or column the path degenerates to a straight line, and when it is on the anchor tile the path is a single tile.
- **Snapping to a building.** When the tile under the cursor is occupied by a non-belt building or construction site (the **target**), the path does not end on that occupied tile. Instead the end tile is the tile **closest to the cursor** (by distance from the cursor position to the tile) among the tiles orthogonally adjacent to the target across one of its **input-capable edges** — any footprint edge that is not one of the target's output ports, i.e. an edge on which the target can accept an incoming item (REQ-MAT-INPUT-PORTS for buildings, REQ-MAT-ACCEPT-DIR for splitters and tunnels). The geometrically closest such tile is **always** used, even if it turns out not to be a valid belt endpoint — in that case it is previewed and applied by the ordinary rules below (invalid color and skipped if occupied by a non-belt building or invalid terrain; re-oriented if it already holds a belt). The rest of the L-shaped path is computed from the anchor to this end tile exactly as above. The end tile's belt direction points **toward the target** (across the shared input edge), overriding the "final tile keeps its incoming step" rule; this applies whether the end tile is a newly placed belt or an existing belt re-oriented in place, and is reflected both in the ghost preview and in the placement on release. - **Snapping to a building.** When the tile under the cursor is occupied by a non-belt building or construction site (the **target**), the path does not end on that occupied tile. Instead the end tile is the tile **closest to the cursor** (by distance from the cursor position to the tile) among the tiles orthogonally adjacent to the target across one of its **input-capable edges** — any footprint edge that is not one of the target's output ports, i.e. an edge on which the target can accept an incoming item (REQ-MAT-INPUT-PORTS for buildings, REQ-MAT-ACCEPT-DIR for splitters and tunnels). The geometrically closest such tile is **always** used, even if it turns out not to be a valid belt endpoint — in that case it is previewed and applied by the ordinary rules below (invalid color and skipped if occupied by a non-belt building or invalid terrain; re-oriented if it already holds a belt). The rest of the L-shaped path is computed from the anchor to this end tile exactly as above. The end tile's belt direction points **toward the target** (across the shared input edge), overriding the "final tile keeps its incoming step" rule; this applies whether the end tile is a newly placed belt or an existing belt re-oriented in place, and is reflected both in the ghost preview and in the placement on release.
- **Rotating during the drag.** Rotating the belt with R / Shift+R (REQ-BLD-ROTATE) while a drag is in progress re-picks the path's primary axis immediately from the new orientation and re-derives the whole path from the anchor to the current cursor tile, without waiting for the next cursor movement. - **Rotating during the drag.** Rotating the belt with R / Shift+R (REQ-BLD-ROTATE) while a drag is in progress re-picks the path's primary axis immediately from the new orientation and re-derives the whole path from the anchor to the current cursor tile, without waiting for the next cursor movement.
@@ -146,13 +146,7 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- REQ-BLD-DECON-QUEUE: Fully-built factory buildings marked for demolition (REQ-BLD-DECONSTRUCT) enter a **deconstruction queue** that is processed one building at a time and runs in parallel with the construction queue (REQ-BLD-QUEUE) — the two queues advance independently and simultaneously. Each building takes `world.toml [world].deconstruction_time_seconds` (default 0.1) to deconstruct, the same duration for every building type. When a building's deconstruction completes it is removed from the world and its refund is credited (REQ-BLD-DECONSTRUCT). A building **stops operating the moment it enters the queue**: it runs no production and transports no items, and no longer participates as a live building (its tunnel pairing is re-evaluated as if it were gone, REQ-BLD-TUNNEL-PAIR), but it still physically occupies its tiles until removed, so those tiles stay blocked for placement. A queued building can be taken back out of the deconstruction queue before it is removed (REQ-BLD-DECONSTRUCT-CLICK, REQ-BLD-DECONSTRUCT-BOX) — including the one currently being deconstructed; doing so discards any deconstruction progress, credits no refund, and the building resumes operating (and re-pairs, REQ-BLD-TUNNEL-PAIR). Construction sites never enter the deconstruction queue (REQ-BLD-DECONSTRUCT). Every building in the deconstruction queue is rendered with the deconstruct tint — the `visuals.toml [overlays].deconstruct_tint` color, the same tint applied to a building hovered in deconstruct mode (REQ-UI-DECONSTRUCT-BORDER) — so queued buildings are visually distinct. - REQ-BLD-DECON-QUEUE: Fully-built factory buildings marked for demolition (REQ-BLD-DECONSTRUCT) enter a **deconstruction queue** that is processed one building at a time and runs in parallel with the construction queue (REQ-BLD-QUEUE) — the two queues advance independently and simultaneously. Each building takes `world.toml [world].deconstruction_time_seconds` (default 0.1) to deconstruct, the same duration for every building type. When a building's deconstruction completes it is removed from the world and its refund is credited (REQ-BLD-DECONSTRUCT). A building **stops operating the moment it enters the queue**: it runs no production and transports no items, and no longer participates as a live building (its tunnel pairing is re-evaluated as if it were gone, REQ-BLD-TUNNEL-PAIR), but it still physically occupies its tiles until removed, so those tiles stay blocked for placement. A queued building can be taken back out of the deconstruction queue before it is removed (REQ-BLD-DECONSTRUCT-CLICK, REQ-BLD-DECONSTRUCT-BOX) — including the one currently being deconstructed; doing so discards any deconstruction progress, credits no refund, and the building resumes operating (and re-pairs, REQ-BLD-TUNNEL-PAIR). Construction sites never enter the deconstruction queue (REQ-BLD-DECONSTRUCT). Every building in the deconstruction queue is rendered with the deconstruct tint — the `visuals.toml [overlays].deconstruct_tint` color, the same tint applied to a building hovered in deconstruct mode (REQ-UI-DECONSTRUCT-BORDER) — so queued buildings are visually distinct.
- REQ-BLD-DECONSTRUCT-CLICK: While in deconstruct mode (REQ-UI-HOTKEYS, REQ-UI-DECONSTRUCT-BUTTON), left-clicking a placed factory building or construction site in the game world marks it for demolition, following the rules of REQ-BLD-DECONSTRUCT: a fully-built building is added to the deconstruction queue (REQ-BLD-DECON-QUEUE), and a construction site is removed instantly with the full refund. Left-clicking a fully-built building that is **already in the deconstruction queue** instead removes it from the queue (un-queues it, REQ-BLD-DECON-QUEUE), with no refund; repeated clicks on the same building therefore alternate between queueing and un-queueing it. Clicking a building that cannot be deconstructed (the HQ or a player defence station, per REQ-BLD-DECONSTRUCT), or clicking empty world space, has no effect. Deconstruct mode stays active after each action so the player can continue without re-entering the mode; it is exited via the Q toggle (REQ-UI-HOTKEYS) or the Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON). - REQ-BLD-DECONSTRUCT-CLICK: While in deconstruct mode (REQ-UI-HOTKEYS, REQ-UI-DECONSTRUCT-BUTTON), left-clicking a placed factory building or construction site in the game world marks it for demolition, following the rules of REQ-BLD-DECONSTRUCT: a fully-built building is added to the deconstruction queue (REQ-BLD-DECON-QUEUE), and a construction site is removed instantly with the full refund. Left-clicking a fully-built building that is **already in the deconstruction queue** instead removes it from the queue (un-queues it, REQ-BLD-DECON-QUEUE), with no refund; repeated clicks on the same building therefore alternate between queueing and un-queueing it. Clicking a building that cannot be deconstructed (the HQ or a player defence station, per REQ-BLD-DECONSTRUCT), or clicking empty world space, has no effect. Deconstruct mode stays active after each action so the player can continue without re-entering the mode; it is exited via the Q toggle (REQ-UI-HOTKEYS) or the Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON).
- REQ-BLD-DECONSTRUCT-BOX: While in deconstruct mode (REQ-UI-HOTKEYS, REQ-UI-DECONSTRUCT-BUTTON), the player can click and drag a selection box in the game world. A selection rectangle is drawn while dragging, using the same box-drag gesture and coverage semantics as the multi-select box (REQ-UI-MULTI-SELECT). On mouse up, following the rules of REQ-BLD-DECONSTRUCT: every construction site covered by the box is removed instantly with the full refund; and among the fully-built deconstructible buildings covered by the box, if **all** of them are already in the deconstruction queue they are all removed from it (un-queued, REQ-BLD-DECON-QUEUE), otherwise every covered building not yet in the queue is added to the deconstruction queue (already-queued ones stay). Buildings that cannot be deconstructed (the HQ and player defence stations, per REQ-BLD-DECONSTRUCT) are excluded from the box demolition; ships and defence stations are never affected. - REQ-BLD-DECONSTRUCT-BOX: While in deconstruct mode (REQ-UI-HOTKEYS, REQ-UI-DECONSTRUCT-BUTTON), the player can click and drag a selection box in the game world. A selection rectangle is drawn while dragging, using the same box-drag gesture and coverage semantics as the multi-select box (REQ-UI-MULTI-SELECT). On mouse up, following the rules of REQ-BLD-DECONSTRUCT: every construction site covered by the box is removed instantly with the full refund; and among the fully-built deconstructible buildings covered by the box, if **all** of them are already in the deconstruction queue they are all removed from it (un-queued, REQ-BLD-DECON-QUEUE), otherwise every covered building not yet in the queue is added to the deconstruction queue (already-queued ones stay). Buildings that cannot be deconstructed (the HQ and player defence stations, per REQ-BLD-DECONSTRUCT) are excluded from the box demolition; ships and defence stations are never affected.
- REQ-BLD-SITE-CONFIG: A construction site — a building that has been placed but is still queued or under construction (REQ-BLD-QUEUE) — can be selected and configured exactly like the equivalent operational building, before it finishes building. Whatever configuration the building type supports is available on the site: the recipe for a Miner or Assembler (REQ-UI-SELECT-BUTTON), the produced-ship schematic and its module layout for a Shipyard (REQ-UI-SELECT-BUTTON, REQ-MOD-UI-PREVIEW, REQ-MOD-UI-DIALOG), and the output filters for a Splitter (REQ-BLD-SPLITTER) — all set through the same Selected Building Panel controls (REQ-UI-CONFIG-INLINE). Only currently unlocked recipes and schematics are offered, exactly as for operational buildings (REQ-LOCK-UI-RECIPE, REQ-LOCK-UI-SCHEMATIC, REQ-LOCK-UI-SPLITTER). The configuration is stored on the construction site and carries over unchanged when construction completes, so the building becomes operational already configured. A construction site has no input/output buffers and runs no production cycle, so the buffer and production-progress portions of the panel (REQ-UI-SINGLE-SELECTION, REQ-UI-PRODUCTION-PROGRESS) are not shown for it; only its construction progress (REQ-UI-CONSTRUCTION-PROGRESS) and its configuration controls appear. (Blueprint placement already applies a stored recipe or schematic to a construction site on placement per REQ-UI-BLUEPRINT-PLACE; this requirement additionally lets the player set or change that configuration directly on an existing site.) - REQ-BLD-SITE-CONFIG: A construction site — a building that has been placed but is still queued or under construction (REQ-BLD-QUEUE) — can be selected and configured exactly like the equivalent operational building, before it finishes building. Whatever configuration the building type supports is available on the site: the recipe for a Miner or Assembler (REQ-UI-SELECT-BUTTON), the produced-ship schematic and its module layout for a Shipyard (REQ-UI-SELECT-BUTTON, REQ-MOD-UI-PREVIEW, REQ-MOD-UI-DIALOG), and the output filters for a Splitter (REQ-BLD-SPLITTER) — all set through the same selection panel controls (REQ-UI-CONFIG-INLINE). Only currently unlocked recipes and schematics are offered, exactly as for operational buildings (REQ-LOCK-UI-RECIPE, REQ-LOCK-UI-SCHEMATIC, REQ-LOCK-UI-SPLITTER). The configuration is stored on the construction site and carries over unchanged when construction completes, so the building becomes operational already configured. A construction site has no input/output buffers and runs no production cycle, so the buffer and production-progress portions of the panel (REQ-UI-SINGLE-SELECTION, REQ-UI-PRODUCTION-PROGRESS) are not shown for it; only its construction progress (REQ-UI-CONSTRUCTION-PROGRESS) and its configuration controls appear. (Blueprint placement already applies a stored recipe or schematic to a construction site on placement per REQ-UI-BLUEPRINT-PLACE; this requirement additionally lets the player set or change that configuration directly on an existing site.)
- REQ-BLD-COPY-CONFIG: **Copy building settings (hold Shift).** While the Shift key is held, the player can copy one building's settings onto other buildings of the same type, so several identical machines can be set up without opening each one's panel. This gesture is available only in the default selection mode; while a builder, blueprint placement, or deconstruct mode is active it is disabled, so it never clashes with placement or demolition clicks.
- **Shift + right-click** a building copies its current settings into a temporary cache, along with the building's type. The settings copied are whatever that building type supports: the selected recipe (Miner, Assembler), the selected schematic together with its module layout (Shipyard), or the two output filters (Splitter, REQ-BLD-SPLITTER). Copying succeeds only when there is something to copy — a Miner or Assembler with a recipe selected, a Shipyard with a schematic selected, or any Splitter (whose output filters, even when empty/accept-all, always constitute valid settings). Shift + right-clicking a configurable building with nothing yet selected, a building type that has no settings at all (Smelter, Reprocessing Plant, Salvage Bay, belt/tunnel tiles, the HQ), or empty world space, has no effect and leaves any existing cache unchanged.
- **Shift + left-click** a building of the **same type** as the cached one applies the cached settings to it, exactly as if the player had made that selection through the selected building panel — with the same effects as a normal selection change (buffer clearing per REQ-MAT-INPUT-BUFFER and REQ-MAT-OUTPUT-BUFFER, and, for a Shipyard, in-progress cycle cancellation per REQ-BLD-SHIPYARD). This can be repeated on any number of same-type buildings while Shift stays held. Shift + left-clicking a building of a different type than the cached one, any building while the cache is empty, or empty world space, has no effect.
- Both operational buildings and construction sites take part as source and target (REQ-BLD-SITE-CONFIG); settings applied to a construction site carry over unchanged when it finishes building.
- **Releasing Shift clears the temporary cache.** It is never persisted and does not survive Shift being released; the next copy starts fresh.
- Because the cached settings were already valid on a same-type source building, they remain valid and available on the target (a selected recipe/schematic stays unlocked per REQ-LOCK-UI-RECIPE and REQ-LOCK-UI-SCHEMATIC; splitter filter item types stay unlocked per REQ-LOCK-UI-SPLITTER).
## Building Types ## Building Types
@@ -160,10 +154,10 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- REQ-BLD-SMELTER: **Smelter** (2×2): Converts ore or scrap into basic materials. No recipe selection required. Inputs, outputs, and rates are defined in `recipes.toml [[recipe]]` entries with `building = "smelter"`. - REQ-BLD-SMELTER: **Smelter** (2×2): Converts ore or scrap into basic materials. No recipe selection required. Inputs, outputs, and rates are defined in `recipes.toml [[recipe]]` entries with `building = "smelter"`.
- REQ-BLD-ASSEMBLER: **Assembler** (3×3): The player selects a recipe from the config-defined crafting tree. Produces the selected output item at the rate defined in the corresponding `recipes.toml [[recipe]]` entry with `building = "assembler"`. Only implicitly unlocked recipes are available for selection (REQ-LOCK-UI-RECIPE). - REQ-BLD-ASSEMBLER: **Assembler** (3×3): The player selects a recipe from the config-defined crafting tree. Produces the selected output item at the rate defined in the corresponding `recipes.toml [[recipe]]` entry with `building = "assembler"`. Only implicitly unlocked recipes are available for selection (REQ-LOCK-UI-RECIPE).
- REQ-BLD-REPROCESSING: **Reprocessing Plant** (3×3): Consumes scrap per cycle and produces exactly one higher-level intermediate product per cycle via weighted random pick. The input quantity, possible output items, per-output weights, and amounts are defined in `recipes.toml [[recipe]]` entries with `building = "reprocessing_plant"` (`inputs`, `outputs[].item`, `outputs[].amount`, `outputs[].weight`). Weights are normalized at load time; their sum does not need to equal 1. The output is rolled at cycle start (see REQ-MAT-CYCLE); the pool of eligible outputs is restricted to implicitly unlocked item types (REQ-LOCK-REPROCESSING-POOL). The output buffer holds at most one cycle's output — see REQ-MAT-OUTPUT-BUFFER-REPROCESSING. - REQ-BLD-REPROCESSING: **Reprocessing Plant** (3×3): Consumes scrap per cycle and produces exactly one higher-level intermediate product per cycle via weighted random pick. The input quantity, possible output items, per-output weights, and amounts are defined in `recipes.toml [[recipe]]` entries with `building = "reprocessing_plant"` (`inputs`, `outputs[].item`, `outputs[].amount`, `outputs[].weight`). Weights are normalized at load time; their sum does not need to equal 1. The output is rolled at cycle start (see REQ-MAT-CYCLE); the pool of eligible outputs is restricted to implicitly unlocked item types (REQ-LOCK-REPROCESSING-POOL). The output buffer holds at most one cycle's output — see REQ-MAT-OUTPUT-BUFFER-REPROCESSING.
- REQ-BLD-SHIPYARD: **Shipyard** (4×2): The player selects a schematic. When all required materials — the ship's base materials (`[ship.schematic].materials`) plus the materials of all modules in the configured layout (REQ-MOD-MATERIALS) — are present in its input buffer, the shipyard consumes them and begins a production cycle lasting the ship's base `[ship.schematic].production_time_seconds` plus the sum of production times contributed by all module instances in the configured layout (REQ-MOD-PRODUCTION-TIME). One ship of that type is spawned with the configured modules when the cycle completes. The shipyard cannot start a new cycle while one is in progress. If the player confirms a layout change (REQ-MOD-UI-DIALOG) while a production cycle is in progress, the current cycle is cancelled and all consumed materials are discarded; the shipyard returns to idle with the new layout configuration. - REQ-BLD-SHIPYARD: **Shipyard** (4×2): The player selects a schematic. When all required materials — the ship's base materials (`[ship.schematic].materials`) plus the materials of all modules in the configured layout (REQ-MOD-MATERIALS) — are present in its input buffer, the shipyard consumes them and begins a production cycle lasting the ship's base `[ship.schematic].production_time_seconds` plus the sum of production times contributed by all module instances in the configured layout (REQ-MOD-PRODUCTION-TIME). One ship of that type is spawned with the configured modules when the cycle completes. The shipyard cannot start a new cycle while one is in progress. If the player confirms a layout change (REQ-MOD-UI-DIALOG) while a production cycle is in progress, the current cycle is cancelled and all consumed materials are discarded; the shipyard returns to idle with the new layout configuration. Confirming a layout identical to the one already configured is not a change and cancels nothing (REQ-MAT-INPUT-BUFFER).
- REQ-BLD-SALVAGE-BAY: **Salvage Bay** (3×2): A dedicated drop-off point for salvage ships. It has an output buffer whose holding capacity is defined by the `output_buffer_capacity` field of the `salvage_bay` entry in `buildings.toml` (rather than by a production cycle, since the Salvage Bay has no recipe). A ship at the bay hands over one unit of scrap per tick while the buffer has free space; a full buffer blocks further drop-off until space frees up (consistent with the buffer-full semantics of REQ-MAT-OUTPUT-BUFFER). Held scrap is pushed onto connected output belts. - REQ-BLD-SALVAGE-BAY: **Salvage Bay** (3×2): A dedicated drop-off point for salvage ships. It has an output buffer whose holding capacity is defined by the `output_buffer_capacity` field of the `salvage_bay` entry in `buildings.toml` (rather than by a production cycle, since the Salvage Bay has no recipe). A ship at the bay hands over one unit of scrap per tick while the buffer has free space; a full buffer blocks further drop-off until space frees up (consistent with the buffer-full semantics of REQ-MAT-OUTPUT-BUFFER). Held scrap is pushed onto connected output belts.
- REQ-BLD-BELT: **Belt** (1×1): Transports items. A belt tile has one direction (N, S, E, W) set at placement (modified by rotation). Curved belts are auto-derived: when a belt tile's outgoing direction leads into another belt whose direction is orthogonal, the downstream belt is rendered and behaves as a curve. Belt speed is defined in `world.toml [world].belt_speed_tiles_per_second` (REQ-GW-BELT-SPEED). A belt accepts items only through a non-output edge (REQ-MAT-ACCEPT-DIR). - REQ-BLD-BELT: **Belt** (1×1): Transports items. A belt tile has one direction (N, S, E, W) set at placement (modified by rotation). Curved belts are auto-derived: when a belt tile's outgoing direction leads into another belt whose direction is orthogonal, the downstream belt is rendered and behaves as a curve. Belt speed is defined in `world.toml [world].belt_speed_tiles_per_second` (REQ-GW-BELT-SPEED). A belt accepts items only through a non-output edge (REQ-MAT-ACCEPT-DIR).
- REQ-BLD-SPLITTER: **Splitter** (1×1): Distributes incoming items between two output directions. Incoming items are accepted only through the splitter's non-output edges (REQ-MAT-ACCEPT-DIR). Each output can optionally have a filter (a list of item types), configurable via the selected building panel; only implicitly unlocked item types are available as filter options (REQ-LOCK-UI-SPLITTER). Routing rules: - REQ-BLD-SPLITTER: **Splitter** (1×1): Distributes incoming items between two output directions. Incoming items are accepted only through the splitter's non-output edges (REQ-MAT-ACCEPT-DIR). Each output can optionally have a filter (a list of item types), configurable via the selection panel; only implicitly unlocked item types are available as filter options (REQ-LOCK-UI-SPLITTER). Routing rules:
- An item matching only one output's filter is routed to that output. - An item matching only one output's filter is routed to that output.
- An item matching both outputs' filters is distributed by strict alternation between those outputs. - An item matching both outputs' filters is distributed by strict alternation between those outputs.
- An item matching neither output's filter is routed to the unfiltered output. If both outputs have a filter and the item matches neither, the splitter stalls and moves no items until the situation is resolved. - An item matching neither output's filter is routed to the unfiltered output. If both outputs have a filter and the item matches neither, the splitter stalls and moves no items until the situation is resolved.
@@ -204,7 +198,8 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- **Scope.** Direct coupling is the only case in which materials move between buildings without a belt, splitter, or tunnel (REQ-MAT-BELT-ONLY); it bridges only two buildings that are directly adjacent with meeting output/input ports. Transport tiles feeding a building (belt, splitter, or tunnel exit) continue to work through the normal pull, and a producer still hands off to a transport tile placed in the gap as before; a single such tile between two buildings is unaffected by this requirement. - **Scope.** Direct coupling is the only case in which materials move between buildings without a belt, splitter, or tunnel (REQ-MAT-BELT-ONLY); it bridges only two buildings that are directly adjacent with meeting output/input ports. Transport tiles feeding a building (belt, splitter, or tunnel exit) continue to work through the normal pull, and a producer still hands off to a transport tile placed in the gap as before; a single such tile between two buildings is unaffected by this requirement.
- REQ-MAT-ACCEPT-DIR: A transport tile (belt, splitter, tunnel entry, or tunnel exit) accepts an incoming item only through a non-output edge; an item that would enter through one of the tile's output edges is refused. For a belt or a tunnel entry/exit the sole output edge is the one in its facing direction; for a splitter either of its two output directions is an output edge. This applies both to items pushed from an adjacent transport tile and to items deposited by a building's output port (REQ-MAT-OUTPUT-PORT). - REQ-MAT-ACCEPT-DIR: A transport tile (belt, splitter, tunnel entry, or tunnel exit) accepts an incoming item only through a non-output edge; an item that would enter through one of the tile's output edges is refused. For a belt or a tunnel entry/exit the sole output edge is the one in its facing direction; for a splitter either of its two output directions is an output edge. This applies both to items pushed from an adjacent transport tile and to items deposited by a building's output port (REQ-MAT-OUTPUT-PORT).
- REQ-MAT-INPUT-BUFFER: Each building has one input buffer per required input material. Each per-material buffer holds up to twice that material's per-cycle requirement. When the player selects a new recipe or schematic, all items in all input buffers are cleared. - REQ-MAT-INPUT-BUFFER: Each building has one input buffer per required input material. Each per-material buffer holds up to twice that material's per-cycle requirement. When the player selects a new recipe or schematic, all items in all input buffers are cleared.
- REQ-MAT-OUTPUT-BUFFER: Each building has an output buffer that holds up to twice the quantity produced by one production cycle. If the output buffer is full, production stops until space is available. When the player selects a new recipe or schematic, all items in the output buffer are cleared (relevant when the adjacent belt is jammed and items have accumulated). - **Setting a configuration to the value it already holds is a no-op.** Selecting the recipe or schematic already set, or applying a ship layout identical to the one already configured, changes nothing: buffers are not cleared, an in-progress production cycle is not cancelled (REQ-BLD-SHIPYARD), and a construction site's progress and stored settings are untouched. This holds however the setting is applied — through the selection dialog (REQ-UI-SELECT-BUTTON), the layout configuration dialog (REQ-MOD-UI-DIALOG), a blueprint placement (REQ-UI-BLUEPRINT-PLACE), or a blueprint configuration transfer (REQ-UI-BLUEPRINT-TRANSFER). Only a setting that genuinely differs has effects.
- REQ-MAT-OUTPUT-BUFFER: Each building has an output buffer that holds up to twice the quantity produced by one production cycle. If the output buffer is full, production stops until space is available. When the player selects a new recipe or schematic, all items in the output buffer are cleared (relevant when the adjacent belt is jammed and items have accumulated). Re-applying a setting the building already has clears nothing, per REQ-MAT-INPUT-BUFFER.
- REQ-MAT-OUTPUT-BUFFER-REPROCESSING: Exception to REQ-MAT-OUTPUT-BUFFER — the Reprocessing Plant's output buffer holds at most one cycle's output. This prevents exploits where the player stalls the output belt to force the plant to reroll. - REQ-MAT-OUTPUT-BUFFER-REPROCESSING: Exception to REQ-MAT-OUTPUT-BUFFER — the Reprocessing Plant's output buffer holds at most one cycle's output. This prevents exploits where the player stalls the output belt to force the plant to reroll.
- REQ-MAT-CYCLE: Production cycle lifecycle. When a building is idle, it attempts to start a new cycle: (a) all required inputs must be present in the per-material input buffers, and (b) the cycle's output must fit in the output buffer. For the Reprocessing Plant, the output is picked at cycle start (weighted pick); the cycle only starts if that chosen output fits. On cycle start, inputs are consumed immediately and the production timer begins. On cycle completion, the (already-decided) output is deposited into the output buffer and the building returns to idle. - REQ-MAT-CYCLE: Production cycle lifecycle. When a building is idle, it attempts to start a new cycle: (a) all required inputs must be present in the per-material input buffers, and (b) the cycle's output must fit in the output buffer. For the Reprocessing Plant, the output is picked at cycle start (weighted pick); the cycle only starts if that chosen output fits. On cycle start, inputs are consumed immediately and the production timer begins. On cycle completion, the (already-decided) output is deposited into the output buffer and the building returns to idle.
- REQ-MAT-GLOBAL-STOCK: The building blocks stock is the only global inventory. All other materials exist only in building buffers or on belt tiles. - REQ-MAT-GLOBAL-STOCK: The building blocks stock is the only global inventory. All other materials exist only in building buffers or on belt tiles.
@@ -311,7 +306,7 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
### Module UI ### Module UI
- REQ-MOD-UI-PREVIEW: For a selected shipyard (operational building or construction site), the selected building panel always shows a small non-interactive **ship layout preview** widget below the schematic selection button (REQ-UI-SELECT-BUTTON) and a "Configure" button below the preview. Both are **disabled while no schematic is selected**, and enabled once one is; the preview then shows an empty placeholder in place of a layout grid. When a schematic is selected, the preview renders the ship's layout grid at a reduced scale: buildable cells without a module are shown as white, non-buildable cells are shown as black, and cells occupied by a module are shown in that module's `fill_color` with the module's `glyph` character. For non-shipyard buildings, neither the preview nor the "Configure" button is shown. - REQ-MOD-UI-PREVIEW: For a selected shipyard (operational building or construction site), the selection panel always shows a small non-interactive **ship layout preview** widget below the schematic selection button (REQ-UI-SELECT-BUTTON) and a "Configure" button below the preview. Both are **disabled while no schematic is selected**, and enabled once one is; the preview then shows an empty placeholder in place of a layout grid. When a schematic is selected, the preview renders the ship's layout grid at a reduced scale: buildable cells without a module are shown as white, non-buildable cells are shown as black, and cells occupied by a module are shown in that module's `fill_color` with the module's `glyph` character. For non-shipyard buildings, neither the preview nor the "Configure" button is shown.
- REQ-MOD-UI-DIALOG: Clicking the "Configure" button opens the **layout configuration dialog** as a modal. While the dialog is open, the game is paused (speed set to 0×). On close, the game speed is restored to what it was before the dialog was opened. - REQ-MOD-UI-DIALOG: Clicking the "Configure" button opens the **layout configuration dialog** as a modal. While the dialog is open, the game is paused (speed set to 0×). On close, the game speed is restored to what it was before the dialog was opened.
The dialog contains: The dialog contains:
@@ -319,11 +314,11 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- **Left** (below the grid): The ship stats panel (see REQ-MOD-UI-STATS-PANEL). - **Left** (below the grid): The ship stats panel (see REQ-MOD-UI-STATS-PANEL).
- **Center** (below the grid): A grid of module selection buttons (one per **unlocked** module type; see REQ-DEF-SCHEMATIC-DROP) plus a "Remove" button. Each module button shows the module id and its glyph. - **Center** (below the grid): A grid of module selection buttons (one per **unlocked** module type; see REQ-DEF-SCHEMATIC-DROP) plus a "Remove" button. Each module button shows the module id and its glyph.
- **Right** (below the grid): The layout blueprint panel (see REQ-MOD-UI-BLUEPRINT-PANEL through REQ-MOD-UI-BLUEPRINT-FILE-LOAD). - **Right** (below the grid): The layout blueprint panel (see REQ-MOD-UI-BLUEPRINT-PANEL through REQ-MOD-UI-BLUEPRINT-FILE-LOAD).
- **Bottom**: A "Confirm" button and a "Cancel" button. Cancel discards all changes made in this dialog session and closes the dialog. Confirm applies the changes: the shipyard's configured layout is updated, the required materials and cycle time displayed in the selected building panel are recalculated, and the ship layout preview is refreshed. - **Bottom**: A "Confirm" button and a "Cancel" button. Cancel discards all changes made in this dialog session and closes the dialog. Confirm applies the changes: the shipyard's configured layout is updated, the required materials and cycle time displayed in the selection panel are recalculated, and the ship layout preview is refreshed.
- REQ-MOD-UI-EMPTY-PULSE: While a module is selected for placement in the layout configuration dialog (REQ-MOD-UI-DIALOG), the empty buildable cells of the layout grid pulse smoothly around their normal fill shade, oscillating between a slightly darker and a slightly brighter shade at approximately 1 Hz (one full cycle per second), to draw the player's attention to where the module can be placed. All empty buildable cells pulse in phase. When no module is selected for placement (including remove mode), empty buildable cells render at their normal static shade. Non-buildable cells and cells occupied by a placed module do not pulse. - REQ-MOD-UI-EMPTY-PULSE: While a module is selected for placement in the layout configuration dialog (REQ-MOD-UI-DIALOG), the empty buildable cells of the layout grid pulse smoothly around their normal fill shade, oscillating between a slightly darker and a slightly brighter shade at approximately 1 Hz (one full cycle per second), to draw the player's attention to where the module can be placed. All empty buildable cells pulse in phase. When no module is selected for placement (including remove mode), empty buildable cells render at their normal static shade. Non-buildable cells and cells occupied by a placed module do not pulse.
- REQ-MOD-UI-AUTO-DIALOG: When the player selects a schematic for a shipyard (operational building or construction site) through the schematic selection dialog (REQ-UI-SELECT-BUTTON), and the chosen schematic **differs** from the shipyard's current schematic, the layout configuration dialog (REQ-MOD-UI-DIALOG) opens automatically and immediately once the selection dialog closes — exactly as if the player had then clicked "Configure". Re-selecting the schematic already set does not reopen the dialog. This auto-open applies only to the manual schematic selection dialog; schematic changes applied via the copy-settings gesture (REQ-BLD-COPY-CONFIG) or blueprint placement (REQ-UI-BLUEPRINT-PLACE) do **not** auto-open the dialog. The player may still cancel the auto-opened dialog (REQ-MOD-UI-DIALOG), which leaves the newly selected schematic in place with its default empty layout; the "Configure" button (REQ-MOD-UI-PREVIEW) remains available to open the dialog again later. - REQ-MOD-UI-AUTO-DIALOG: When the player selects a schematic for a shipyard (operational building or construction site) through the schematic selection dialog (REQ-UI-SELECT-BUTTON), and the chosen schematic **differs** from the shipyard's current schematic, the layout configuration dialog (REQ-MOD-UI-DIALOG) opens automatically and immediately once the selection dialog closes — exactly as if the player had then clicked "Configure". Re-selecting the schematic already set does not reopen the dialog. This auto-open applies only to the manual schematic selection dialog; a schematic applied by blueprint placement (REQ-UI-BLUEPRINT-PLACE) does **not** auto-open the dialog. The player may still cancel the auto-opened dialog (REQ-MOD-UI-DIALOG), which leaves the newly selected schematic in place with its default empty layout; the "Configure" button (REQ-MOD-UI-PREVIEW) remains available to open the dialog again later.
- REQ-MOD-UI-MODULE-TOOLTIP: Each module selection button in the layout configuration dialog (REQ-MOD-UI-DIALOG) shows a hover tooltip with the descriptive text defined for that module type in `modules.toml` (the optional per-module tooltip field). If a module type defines no tooltip text, its button shows no tooltip. The "Remove" button is not a module type and has no config-defined tooltip. - REQ-MOD-UI-MODULE-TOOLTIP: Each module selection button in the layout configuration dialog (REQ-MOD-UI-DIALOG) shows a hover tooltip with the descriptive text defined for that module type in `modules.toml` (the optional per-module tooltip field). If a module type defines no tooltip text, its button shows no tooltip. The "Remove" button is not a module type and has no config-defined tooltip.
@@ -433,24 +428,25 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
### Layout ### Layout
The screen is divided into two columns: a main column (75% width) containing the header bar and game world, and a side panel column (25% width) holding the selected building panel. The build button bar (REQ-UI-BUILD-BAR) is not part of either column — it floats over the game world at its bottom center. Blueprints have no permanent screen real estate; they are reached through modal dialogs (REQ-UI-BLUEPRINT-DIALOG): The screen is a single column: a header bar across the top and the game world view filling the whole area below it. There is no side panel. All three permanent UI widgets float over the game world — the build button bar (REQ-UI-BUILD-BAR) at its bottom center, the selection panel (REQ-UI-SELECTION-PANEL) beside whatever is currently selected, shown only while something is selected and holding its place on the screen until the next selection, and the controls panel (REQ-UI-CONTROLS-PANEL) in its bottom-left corner, beside the build button bar and rising above it only when the two would overlap. Blueprints have no permanent screen real estate; they are reached through modal dialogs (REQ-UI-BLUEPRINT-DIALOG):
``` ```
+--------------------------------------+--------------+ +-----------------------------------------------------------+
| Header Bar | | | Header Bar |
+--------------------------------------+ Selected | +-----------------------------------------------------------+
| | Building | | +-----------+ |
| | Panel | | | Selection | |
| Game World | | | Game World | Panel | |
| | | | +-----------+ |
| | | | |
| +------------------+ | | | +----------+ |
| | Build Button Bar | | | | | Controls | +------------------+ |
+--------+------------------+----------+--------------+ | | Panel | | Build Button Bar | |
(75% width) (25% width) +-+----------+-----+------------------+---------------------+
(full window width)
``` ```
- REQ-UI-HEADER: The header bar spans the width of the game world column (75% of the screen width) and always shows the elapsed survival time, the current global building blocks stock, and the artifact count (REQ-WIN-ARTIFACT-COUNT) displayed as `Artifacts: x/y` (where `x` is the current artifact count and `y` is `world.toml [world].artifact_win_count`) on the left, the boss wave counter and boss countdown (REQ-UI-BOSS-STATUS) and an asteroid expansion button (REQ-UI-EXPAND-BUTTON) to the left of the speed buttons, and game speed controls on the right. - REQ-UI-HEADER: The header bar spans the full width of the game window and always shows the elapsed survival time, the current global building blocks stock, and the artifact count (REQ-WIN-ARTIFACT-COUNT) displayed as `Artifacts: x/y` (where `x` is the current artifact count and `y` is `world.toml [world].artifact_win_count`) on the left, the boss wave counter and boss countdown (REQ-UI-BOSS-STATUS) and an asteroid expansion button (REQ-UI-EXPAND-BUTTON) to the left of the speed buttons, and game speed controls on the right.
- REQ-UI-BLOCKS-ICON: In the header bar (REQ-UI-HEADER), the global building blocks stock is displayed as `Stock: <n>` followed by the `building_block` item icon (REQ-UI-ITEM-ICON) — e.g. `Stock: 200` then a small block icon — replacing the `Building Blocks: <n>` text label. The icon is sized to the header text height. When no icon file exists for `building_block` (a missing icon is not an error, REQ-UI-ITEM-ICON), the display falls back to the `Stock: <n> Blocks` text. The hover tooltip (REQ-UI-BLOCKS-TOOLTIP) applies in either form. - REQ-UI-BLOCKS-ICON: In the header bar (REQ-UI-HEADER), the global building blocks stock is displayed as `Stock: <n>` followed by the `building_block` item icon (REQ-UI-ITEM-ICON) — e.g. `Stock: 200` then a small block icon — replacing the `Building Blocks: <n>` text label. The icon is sized to the header text height. When no icon file exists for `building_block` (a missing icon is not an error, REQ-UI-ITEM-ICON), the display falls back to the `Stock: <n> Blocks` text. The hover tooltip (REQ-UI-BLOCKS-TOOLTIP) applies in either form.
- REQ-UI-BLOCKS-TOOLTIP: The header bar's building blocks stock display (REQ-UI-HEADER) shows a hover tooltip with the descriptive text defined in `world.toml [world].building_blocks_tooltip` — intended to tell the player what building blocks are used for and how to obtain them. If the field is unset, the stock display shows no tooltip. This tooltip is distinct from the build/module button tooltips (REQ-UI-BUILD-TOOLTIP, REQ-MOD-UI-MODULE-TOOLTIP). - REQ-UI-BLOCKS-TOOLTIP: The header bar's building blocks stock display (REQ-UI-HEADER) shows a hover tooltip with the descriptive text defined in `world.toml [world].building_blocks_tooltip` — intended to tell the player what building blocks are used for and how to obtain them. If the field is unset, the stock display shows no tooltip. This tooltip is distinct from the build/module button tooltips (REQ-UI-BUILD-TOOLTIP, REQ-MOD-UI-MODULE-TOOLTIP).
- REQ-UI-ARTIFACTS-TOOLTIP: The header bar's artifact count display (REQ-UI-HEADER) shows a hover tooltip with the descriptive text defined in `world.toml [world].artifact_tooltip` — intended to tell the player what artifacts are, how they are obtained (REQ-DEF-SCHEMATIC-DROP), and that collecting `world.toml [world].artifact_win_count` of them wins the game (REQ-WIN-ARTIFACT-COUNT). If the field is unset, the artifact count display shows no tooltip. This tooltip is distinct from the building blocks tooltip (REQ-UI-BLOCKS-TOOLTIP) and the build/module button tooltips (REQ-UI-BUILD-TOOLTIP, REQ-MOD-UI-MODULE-TOOLTIP). - REQ-UI-ARTIFACTS-TOOLTIP: The header bar's artifact count display (REQ-UI-HEADER) shows a hover tooltip with the descriptive text defined in `world.toml [world].artifact_tooltip` — intended to tell the player what artifacts are, how they are obtained (REQ-DEF-SCHEMATIC-DROP), and that collecting `world.toml [world].artifact_win_count` of them wins the game (REQ-WIN-ARTIFACT-COUNT). If the field is unset, the artifact count display shows no tooltip. This tooltip is distinct from the building blocks tooltip (REQ-UI-BLOCKS-TOOLTIP) and the build/module button tooltips (REQ-UI-BUILD-TOOLTIP, REQ-MOD-UI-MODULE-TOOLTIP).
@@ -459,9 +455,17 @@ The screen is divided into two columns: a main column (75% width) containing the
- REQ-UI-PAUSE-BORDER: While the game is paused (speed 0×, whether set via the speed controls (REQ-UI-SPEED), the Space toggle (REQ-UI-HOTKEYS), or an auto-pausing modal), a vignette border is drawn around the edges of the game world view to make the paused state hard to miss. The border is black and fades in the alpha channel from fully transparent at its inner (center-facing) edge to 50% opacity at the viewport edge, over a thickness of 100 pixels (capped at half the smaller viewport dimension on very small views). - REQ-UI-PAUSE-BORDER: While the game is paused (speed 0×, whether set via the speed controls (REQ-UI-SPEED), the Space toggle (REQ-UI-HOTKEYS), or an auto-pausing modal), a vignette border is drawn around the edges of the game world view to make the paused state hard to miss. The border is black and fades in the alpha channel from fully transparent at its inner (center-facing) edge to 50% opacity at the viewport edge, over a thickness of 100 pixels (capped at half the smaller viewport dimension on very small views).
- REQ-UI-DECONSTRUCT-BORDER: While deconstruct mode is active (REQ-UI-DECONSTRUCT-BUTTON, REQ-UI-HOTKEYS), a vignette border is drawn around the edges of the game world view to signal the mode, matching the geometry of the paused-state vignette (REQ-UI-PAUSE-BORDER): a 100-pixel thickness (capped at half the smaller viewport dimension on very small views) with the four sides meeting along mitred corner diagonals. It fades in the alpha channel from fully transparent at its inner (center-facing) edge to the deconstruct tint color at the viewport edge. The color — including its alpha, which sets the peak opacity at the viewport edge — is read from `visuals.toml [overlays].deconstruct_tint`, the same deconstruct-mode color used for the hover tint. The border is presentation-only and has no effect on the simulation. If the game is both paused and in deconstruct mode, both vignettes are drawn and compose over each other. - REQ-UI-DECONSTRUCT-BORDER: While deconstruct mode is active (REQ-UI-DECONSTRUCT-BUTTON, REQ-UI-HOTKEYS), a vignette border is drawn around the edges of the game world view to signal the mode, matching the geometry of the paused-state vignette (REQ-UI-PAUSE-BORDER): a 100-pixel thickness (capped at half the smaller viewport dimension on very small views) with the four sides meeting along mitred corner diagonals. It fades in the alpha channel from fully transparent at its inner (center-facing) edge to the deconstruct tint color at the viewport edge. The color — including its alpha, which sets the peak opacity at the viewport edge — is read from `visuals.toml [overlays].deconstruct_tint`, the same deconstruct-mode color used for the hover tint. The border is presentation-only and has no effect on the simulation. If the game is both paused and in deconstruct mode, both vignettes are drawn and compose over each other.
- REQ-UI-EXPAND-BUTTON: The header bar shows an asteroid expansion button captioned `Expand: <x>` followed by the `building_block` item icon (REQ-UI-BLOCKS-ICON, REQ-UI-ITEM-ICON) in place of the trailing `Blocks` word, where `<x>` is the current expansion cost computed from `world.toml [expansion].cost_building_blocks_formula` at the current number of purchased expansions (REQ-EXP-COST). When no icon file exists for `building_block`, the caption falls back to the `Expand: <x> Blocks` text. Clicking the button unlocks the next asteroid expansion (REQ-EXP-UNLOCK, REQ-GW-ASTEROID-EXPAND), spending that many building blocks from the global stock. The button is disabled when the player cannot currently afford the cost (consistent with REQ-UI-BUILD-DISABLED). The caption updates as the cost changes with each purchased expansion. - REQ-UI-EXPAND-BUTTON: The header bar shows an asteroid expansion button captioned `Expand: <x>` followed by the `building_block` item icon (REQ-UI-BLOCKS-ICON, REQ-UI-ITEM-ICON) in place of the trailing `Blocks` word, where `<x>` is the current expansion cost computed from `world.toml [expansion].cost_building_blocks_formula` at the current number of purchased expansions (REQ-EXP-COST). When no icon file exists for `building_block`, the caption falls back to the `Expand: <x> Blocks` text. Clicking the button unlocks the next asteroid expansion (REQ-EXP-UNLOCK, REQ-GW-ASTEROID-EXPAND), spending that many building blocks from the global stock. The button is disabled when the player cannot currently afford the cost (consistent with REQ-UI-BUILD-DISABLED). The caption updates as the cost changes with each purchased expansion.
- REQ-UI-WORLD-SIZE: The game world view occupies the full height below the header bar in the main column (75% of the screen width). - REQ-UI-WORLD-SIZE: The game world view occupies the full width of the game window and the full height below the header bar. No widget insets it: the build button bar (REQ-UI-BUILD-BAR), the selection panel (REQ-UI-SELECTION-PANEL), and the controls panel (REQ-UI-CONTROLS-PANEL) float over it.
- REQ-UI-PANEL-COLUMN: The side panel column occupies 25% of the screen width and the full screen height. It holds a single panel filling that full height: the selected building panel. The build buttons are not part of this column; they float over the game world (REQ-UI-BUILD-BAR). Blueprints are not part of this column either; they are reached through the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG). - REQ-UI-SELECTION-PANEL: The **selection panel** (the panel described under Selection Panel, REQ-UI-SINGLE-SELECTION and following) is a widget that **floats over the game world view** (REQ-UI-WORLD-SIZE), placed **beside the objects it describes** rather than at a fixed corner of the view, so it appears where the player is already looking. It is **sized to its content in both width and height**, so it grows and shrinks as the content changes. It keeps the same small margin from the view's edges that it uses as its gap from the selection.
- REQ-UI-MODAL-DIM: While a modal dialog, menu, or full-screen state screen is open on top of the game, a transparent black overlay (a dim/scrim) is drawn over the **entire game window** — the header bar, the game world view, and the side panel column — behind that modal, so the game reads as inactive while the modal holds focus. The overlay is shown for every modal that auto-pauses the simulation — the escape menu (REQ-UI-GAME-MENU), the recipe/schematic selection dialog (REQ-UI-SELECT-BUTTON), the layout configuration dialog (REQ-MOD-UI-DIALOG), the schematic choice dialog (REQ-DEF-SCHEMATIC-DROP), the blueprint save dialog (REQ-UI-BLUEPRINT-CREATE), and the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG) — as well as the game-over screen (REQ-HQ-GAME-OVER) and the win screen (REQ-WIN-SCREEN), which end rather than pause the game. When modals are nested (for example the Create Blueprint name dialog (REQ-MOD-UI-BLUEPRINT-CREATE) opened from the layout configuration dialog), only a single dim is shown over the game window; nested modals do not stack additional overlays. The same applies when one modal hands directly off to another — the blueprint save dialog opening the blueprint selection dialog on confirm (REQ-UI-BLUEPRINT-CREATE): the dim persists across the handoff rather than flickering off and back on, and the simulation is not resumed in between. The dim color and opacity are read from `visuals.toml [overlays]` (a semi-transparent black modal-dim color), consistent with the other overlay colors. The overlay is presentation-only and has no effect on the simulation. - **Anchor rectangle.** The panel is placed against the screen rectangle of the selection **at the moment that selection started**: the footprint of the single object selected (a building or construction site, an actor, or a piece of debris), or, when the selection started as a multi-selection (REQ-UI-MULTI-SELECT), the bounding box of all the objects it started with.
- **Side.** The panel goes to the **right** of the anchor rectangle, separated from it by the panel's margin, whenever it fits within the view there. Otherwise it goes to the **left** of the anchor rectangle by that same margin. When it fits on neither side — a bounding box spanning most of the view, or an object too close to an edge — it is placed on whichever side leaves more room and then pushed inside the view. That is the one case in which the panel covers part of the selection.
- **Vertical placement.** The panel's **top edge is aligned with the anchor rectangle's top edge** and it extends downward. Its bottom is limited by the lowest of: the view's bottom edge less the panel's margin; and the top edge, less that margin, of the build button bar (REQ-UI-BUILD-BAR) or the controls panel (REQ-UI-CONTROLS-PANEL) — but each of those two only where the panel's own horizontal extent actually overlaps that widget's current rectangle, so a panel whose column misses them is not shortened by them. Should the panel not fit above that limit, it is shifted up, as far as the view's top margin and no further; if it still does not fit, its height is capped at the space available there and the content scrolls vertically within it.
- **Fixed for the life of the selection.** The anchor rectangle and the side are determined once, when the selection starts, and are not revisited while that selection lasts; the panel's own size is the only thing that may still move it (see **Resizing in place** below). The panel **keeps its place on the screen** when the player scrolls the view (REQ-UI-SCROLL) and when a selected object moves under it (a selected ship flying away), rather than following the object — which may leave it beside nothing, or beside an object that has left the view entirely. It likewise does not move when the selection is **expanded** by adding objects or reduced by removing them (REQ-UI-MULTI-SELECT), nor when a selected object is destroyed or deconstructed. Starting a **new** selection — clicking a different object, or a box drag that replaces the selection — places the panel anew against the new anchor rectangle.
- **Resizing in place.** Only the anchor rectangle and the chosen side are fixed for the life of the selection; the panel's geometry is **re-solved from them** whenever its content size changes (a section appearing or disappearing as the selection's state changes), the view is resized, or the build button bar's or controls panel's rectangle changes. Re-solving keeps the two edges the panel was placed by — its top edge, and the edge facing the anchor rectangle (its left edge when it sits to the right of the selection, its right edge when it sits to the left) — so the panel grows away from the selection rather than over it, and it never switches sides for as long as the selection lasts. What re-solving may change is the vertical result: growth that would take the panel outside the view or into either of those two widgets is resolved as in **Vertical placement** above, by shifting it up and capping its height, and a panel that shrinks again regains the room.
- **Visibility.** The panel is shown only while at least one object is selected. With an empty selection it is not shown at all (REQ-UI-EMPTY-SELECTION), leaving the full game world view visible.
- **Overlay behavior.** As for the build button bar (REQ-UI-BUILD-BAR): the panel occludes the strip of the game world it covers; the world view itself keeps its full extent and the view's scrolling, ghost rendering, and tile geometry are unaffected. It is drawn above the pause and deconstruct vignettes (REQ-UI-PAUSE-BORDER, REQ-UI-DECONSTRUCT-BORDER), which keep their full band underneath it, and below the modal dim (REQ-UI-MODAL-DIM), which covers the entire game window including the panel. The panel never overlaps the build button bar or the controls panel, because it stays above both wherever their rectangles meet its own; neither of them ever moves on the panel's account (REQ-UI-BUILD-BAR, REQ-UI-CONTROLS-PANEL).
- **Input.** Mouse events over the panel are consumed by the panel and never reach the game world: hovering it shows no builder-mode ghost at the tile beneath, and clicking it neither places a building nor changes the selection. Right-clicking the panel does not exit builder mode (REQ-BLD-BUILDER-MODE) or cancel a belt drag (REQ-BLD-BELT-DRAG).
- REQ-UI-MODAL-DIM: While a modal dialog, menu, or full-screen state screen is open on top of the game, a transparent black overlay (a dim/scrim) is drawn over the **entire game window** — the header bar, the game world view, and the widgets floating over it (the build button bar, REQ-UI-BUILD-BAR, the selection panel, REQ-UI-SELECTION-PANEL, and the controls panel, REQ-UI-CONTROLS-PANEL) — behind that modal, so the game reads as inactive while the modal holds focus. The overlay is shown for every modal that auto-pauses the simulation — the escape menu (REQ-UI-GAME-MENU), the recipe/schematic selection dialog (REQ-UI-SELECT-BUTTON), the layout configuration dialog (REQ-MOD-UI-DIALOG), the schematic choice dialog (REQ-DEF-SCHEMATIC-DROP), the blueprint save dialog (REQ-UI-BLUEPRINT-CREATE), and the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG) — as well as the game-over screen (REQ-HQ-GAME-OVER) and the win screen (REQ-WIN-SCREEN), which end rather than pause the game. When modals are nested (for example the Create Blueprint name dialog (REQ-MOD-UI-BLUEPRINT-CREATE) opened from the layout configuration dialog), only a single dim is shown over the game window; nested modals do not stack additional overlays. The same applies when one modal hands directly off to another — the blueprint save dialog opening the blueprint selection dialog on confirm (REQ-UI-BLUEPRINT-CREATE): the dim persists across the handoff rather than flickering off and back on, and the simulation is not resumed in between. The dim color and opacity are read from `visuals.toml [overlays]` (a semi-transparent black modal-dim color), consistent with the other overlay colors. The overlay is presentation-only and has no effect on the simulation.
### Game World ### Game World
@@ -495,7 +499,8 @@ The screen is divided into two columns: a main column (75% width) containing the
- **A / D** — scroll the view left / right (REQ-UI-SCROLL). - **A / D** — scroll the view left / right (REQ-UI-SCROLL).
- **Q** — context-sensitive. If a build mode is active (builder mode or blueprint placement mode), pressing Q exits it. Otherwise, pressing Q toggles deconstruct mode: it enters deconstruct mode if inactive, or exits deconstruct mode if already active. (See also REQ-UI-DECONSTRUCT-BUTTON for the equivalent button.) - **Q** — context-sensitive. If a build mode is active (builder mode or blueprint placement mode), pressing Q exits it. Otherwise, pressing Q toggles deconstruct mode: it enters deconstruct mode if inactive, or exits deconstruct mode if already active. (See also REQ-UI-DECONSTRUCT-BUTTON for the equivalent button.)
- **R / Shift+R** — in builder mode, rotate the ghost counter-clockwise / clockwise (REQ-BLD-ROTATE). - **R / Shift+R** — in builder mode, rotate the ghost counter-clockwise / clockwise (REQ-BLD-ROTATE).
- **T** — create a temporary blueprint from the current selection and enter its placement mode (REQ-UI-BLUEPRINT-TEMP). - **C** — create a temporary blueprint from the current selection and enter its placement mode (REQ-UI-BLUEPRINT-TEMP). Has effect only when at least one player-placeable building is selected; otherwise it does nothing.
- **V** — re-enter placement mode for the last temporary blueprint created with C (REQ-UI-BLUEPRINT-TEMP). Does nothing when no temporary blueprint exists.
- **Ctrl+C** — save the current selection as a named blueprint: opens the blueprint save dialog (REQ-UI-BLUEPRINT-CREATE). Has effect only when at least one player-placeable building is selected; otherwise it does nothing. - **Ctrl+C** — save the current selection as a named blueprint: opens the blueprint save dialog (REQ-UI-BLUEPRINT-CREATE). Has effect only when at least one player-placeable building is selected; otherwise it does nothing.
- **Ctrl+V** — opens the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG), from which a saved blueprint is picked for placement. It is available whenever the game is being played, regardless of the current selection or of which build mode is active, and opens the dialog even when no blueprints are saved yet. - **Ctrl+V** — opens the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG), from which a saved blueprint is picked for placement. It is available whenever the game is being played, regardless of the current selection or of which build mode is active, and opens the dialog even when no blueprints are saved yet.
- **Escape** — opens the escape menu (REQ-UI-GAME-MENU). While a blueprint dialog is open, Escape closes that dialog instead (REQ-UI-BLUEPRINT-DIALOG). - **Escape** — opens the escape menu (REQ-UI-GAME-MENU). While a blueprint dialog is open, Escape closes that dialog instead (REQ-UI-BLUEPRINT-DIALOG).
@@ -503,6 +508,8 @@ The screen is divided into two columns: a main column (75% width) containing the
- **1** — Belt, **2** — Splitter, **3** — Tunnel (the unified tunnel build mode, REQ-BLD-TUNNEL-MODE). Hotkey 4 is unused. - **1** — Belt, **2** — Splitter, **3** — Tunnel (the unified tunnel build mode, REQ-BLD-TUNNEL-MODE). Hotkey 4 is unused.
- **Shift+1** — Miner, **Shift+2** — Smelter, **Shift+3** — Assembler, **Shift+4** — Shipyard, **Shift+5** — Salvage Bay, **Shift+6** — Reprocessing Plant. - **Shift+1** — Miner, **Shift+2** — Smelter, **Shift+3** — Assembler, **Shift+4** — Shipyard, **Shift+5** — Salvage Bay, **Shift+6** — Reprocessing Plant.
These shortcuts are the definition; the controls panel (REQ-UI-CONTROLS-PANEL) displays the subset of them that applies to the player's current situation, and the build buttons carry the build hotkeys on their badges (REQ-UI-BUILD-COST). Neither display defines a binding of its own.
### Debug Draw ### Debug Draw
- REQ-UI-DEBUG-DRAW: A debug draw mode can be toggled on and off with the **F3** key. It is inactive by default. While active, the sensor range of every ship — both player and enemy — is drawn as a circle centered on the ship, using that ship schematic's outline color from `visuals.toml`. - REQ-UI-DEBUG-DRAW: A debug draw mode can be toggled on and off with the **F3** key. It is inactive by default. While active, the sensor range of every ship — both player and enemy — is drawn as a circle centered on the ship, using that ship schematic's outline color from `visuals.toml`.
@@ -522,24 +529,68 @@ The screen is divided into two columns: a main column (75% width) containing the
- **Quit** — closes the application. - **Quit** — closes the application.
Pressing Escape while the escape menu is open is equivalent to clicking Continue. Pressing Escape while the escape menu is open is equivalent to clicking Continue.
### Selected Building Panel ### Selection Panel
- REQ-UI-EMPTY-SELECTION: When nothing is selected (no building, construction site, ship, defence station, or piece of debris), the panel is empty. The selection panel shows the details of the current selection, whatever its category (REQ-UI-SELECTION-CATEGORIES): buildings and construction sites, ships, defence stations, and debris. Its position, size, and overlay behavior are defined in REQ-UI-SELECTION-PANEL; the requirements below define its content.
The panel shows exactly one **content** at a time, picked from the catalog in REQ-UI-SELECTION-CONTENT by what is selected. Every content is assembled from the same small set of parts and follows the same card structure (REQ-UI-SELECTION-CARD), so different selections read alike and a part means the same thing wherever it appears.
- REQ-UI-EMPTY-SELECTION: When nothing is selected (no building, construction site, ship, defence station, or piece of debris), the selection panel is not shown at all — it is hidden rather than shown empty, so the full game world view is visible (REQ-UI-SELECTION-PANEL). It reappears as soon as an object is selected.
- REQ-UI-SELECTION-CATEGORIES: **Selection categories and precedence.** Every selectable object belongs to one of two mutually exclusive selection categories: **buildings** (buildings and construction sites) and **field objects** (ships and defence stations — player or enemy — together with debris). A single selection holds objects from only one category at a time. Field objects of different kinds may be selected together (e.g. several ships plus debris, freely mixing player and enemy actors). Buildings are exclusive and take precedence — **buildings win**: selecting a building (by click, Ctrl+click, or a box-drag covering at least one building) clears any field selection and yields a buildings-only selection, and conversely selecting any field object clears any building selection. Point hit-testing prefers a building over a coincident field object, and among field objects prefers an actor (ship or defence station) over a coincident piece of debris (REQ-UI-ENTITY-CLICK-SELECT, REQ-UI-DEBRIS-CLICK-SELECT). - REQ-UI-SELECTION-CATEGORIES: **Selection categories and precedence.** Every selectable object belongs to one of two mutually exclusive selection categories: **buildings** (buildings and construction sites) and **field objects** (ships and defence stations — player or enemy — together with debris). A single selection holds objects from only one category at a time. Field objects of different kinds may be selected together (e.g. several ships plus debris, freely mixing player and enemy actors). Buildings are exclusive and take precedence — **buildings win**: selecting a building (by click, Ctrl+click, or a box-drag covering at least one building) clears any field selection and yields a buildings-only selection, and conversely selecting any field object clears any building selection. Point hit-testing prefers a building over a coincident field object, and among field objects prefers an actor (ship or defence station) over a coincident piece of debris (REQ-UI-ENTITY-CLICK-SELECT, REQ-UI-DEBRIS-CLICK-SELECT).
- REQ-UI-SINGLE-SELECTION: When one building is selected, the panel shows: building name, current recipe or schematic selection, input buffer contents, and output buffer contents. Buffer counts are displayed as `a/b` where `a` is the current item count and `b` is the per-cycle amount (items consumed per run for inputs; items produced per run for outputs). For a selected construction site, the recipe/schematic selection (and, for a shipyard, the layout preview and "Configure" button) are shown but the buffer rows are omitted (REQ-BLD-SITE-CONFIG). - REQ-UI-SELECTION-CARD: **Card structure.** Every panel content is a card with the same three parts, top to bottom:
- REQ-UI-PRODUCTION-PROGRESS: For buildings that produce items or ships (miner, smelter, assembler, reprocessing plant, shipyard), the selected building panel also shows: (a) the cycle time of the currently selected recipe or schematic in seconds, and (b) the completion percentage of the active production cycle as an integer (e.g. `42%`), or the text `idle` when no production cycle is active. When no recipe or schematic is selected, neither the cycle time nor the progress indicator is shown. - **Header** — always shown. It holds the selection's identity symbol on the left — the building's icon glyph (REQ-UI-WORLD-ICON), a ship's schematic color swatch, or the kind symbol of a defence station or piece of debris — the selection's name beside it, and one optional **right slot**. The right slot holds a status indicator (REQ-UI-SELECTION-STATUS), a ship's current behavior (REQ-UI-SHIP-BEHAVIOR), or an object count — never more than one of them; which one applies is stated per content in REQ-UI-SELECTION-CONTENT.
- **Configuration group** — the controls that change how the selected object is set up: the recipe/schematic selection control (REQ-UI-SELECT-BUTTON), a shipyard's layout preview and Configure button (REQ-MOD-UI-PREVIEW), and a splitter's output filters (REQ-BLD-SPLITTER). It is shown identically for an operational building and for a construction site of the same type (REQ-BLD-SITE-CONFIG).
- **Runtime group** — what the object is currently doing: buffer contents, production progress, HP, remaining scrap, and the belt clear action (REQ-UI-BELT-CLEAR). Where the object has **HP**, its bar is the first thing in this group, above everything else the card shows (REQ-UI-HQ-PANEL, REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL) — how close the thing is to dying outranks what it is holding. For a **construction site** the entire runtime group is replaced by a captioned `Construction` section: a progress bar filled to the site's construction completion with that completion as an integer percentage beside the caption — the same value the world draws on the footprint (REQ-UI-CONSTRUCTION-PROGRESS) — followed by a note that buffers appear once the building is built, because a site has neither buffers nor a production cycle (REQ-BLD-SITE-CONFIG). That section sits **directly below the header, above the configuration group**, so how far along the site is reads first; the configuration group is otherwise unaffected and stays visible on a site.
A group with nothing to show takes no space, so a content may consist of a header alone. Within a group, related parts form **sections** carrying a short caption above them (e.g. `Layout`, `Input buffers`, `Production`, `Output buffer`); a section and its caption are shown only while that section has content, so e.g. a Miner (which consumes nothing) shows no input buffer section.
- REQ-UI-SELECTION-CONTENT: **Content catalog.** Which content the panel shows follows from the selection alone:
| Selection | Header right slot | Configuration group | Runtime group |
|---|---|---|---|
| Miner, Assembler | status | recipe control + recipe summary | buffers + production |
| Smelter, Reprocessing Plant | status | recipe summary | buffers + production |
| Shipyard | status | schematic control + layout preview + Configure | buffers + production |
| Salvage Bay | status | — | buffers |
| HQ | — | — | block stock + HP |
| Belt, Tunnel Entry, Tunnel Exit | count | — | clear action |
| Splitter | — | output filters | clear action |
| Several buildings | — | — | type counts + total cost |
| One ship | behavior | — | HP + hull stats + module summaries |
| One defence station | — | — | HP + stats |
| Debris (one or several) | count | — | remaining scrap |
| Several mixed field objects | count | — | type counts + scrap total |
Selections sharing a row of this table get the same content and differ only in the name and symbol in the header. A count in the right slot appears only for an aggregated multi-selection (REQ-UI-SELECTION-AGGREGATE); a single selection of those types shows an empty slot.
- REQ-UI-SELECTION-STATUS: **Status indicator.** For a building whose production state is already rendered in the world as a status light (REQ-UI-STATUS-LIGHT) — Miner, Smelter, Assembler, Reprocessing Plant, Shipyard, Salvage Bay — the header's right slot repeats that same state as a colored dot with a short caption beside it, so the panel and the world never disagree. The state is derived from the evaluation defined in REQ-UI-STATUS-LIGHT rather than from a second definition, and the dot uses that state's fill color from `visuals.toml [status_light]`. The captions name the state: `no recipe` (grey), `producing` (green), `missing input` (red), `output full` (yellow); for the Salvage Bay, `holding scrap` (green) and `empty` (red). A selected **construction site** shows the caption `constructing` with no dot, whatever its type. Buildings with no status light — belts, splitters, tunnel ends, the HQ — show nothing in the slot.
- REQ-UI-SELECTION-AGGREGATE: **Aggregating a homogeneous multi-selection.** When several objects are selected and their content can be shown as one — the same content, with its values aggregated over the whole selection — the panel shows that single content with the number of selected objects in the header's right slot (`x<count>`), instead of the count summary of REQ-UI-MULTI-SELECTION / REQ-UI-FIELD-MULTI-SELECTION. This applies exactly where every part of the content aggregates:
- **Belt-subsystem tiles** — any mix of belts, tunnel entries, and tunnel exits. Their content is the clear action alone, which already acts on the whole selection (REQ-UI-BELT-CLEAR).
- **Debris** — several pieces of debris and nothing else. Their remaining scrap sums into one value (REQ-UI-DEBRIS-PANEL).
Every other multi-selection falls back to the count summary. In particular a selection mixing a splitter with belts does not aggregate (a splitter carries per-object output filters, which have no aggregate), and neither do several production buildings of one type (per-building buffers and cycle progress have no aggregate).
- REQ-UI-SINGLE-SELECTION: When one building is selected, the panel shows its symbol and name in the header (REQ-UI-SELECTION-CARD), its current recipe or schematic selection (REQ-UI-SELECT-BUTTON) and recipe summary (REQ-UI-RECIPE-SUMMARY) in the configuration group, and its input and output buffer contents in the runtime group. Each buffered item is shown as an **item chip** bearing that item's icon (REQ-UI-ITEM-ICON) and its current count:
- an **input** chip shows the per-cycle amount below the count (the items consumed per run, e.g. `/ 2 per cycle`), or the count alone when the building has no selected recipe or schematic to give one;
- an **output** chip shows the count against the output buffer's capacity as `a / b` (REQ-MAT-OUTPUT-BUFFER), with the item's name below.
Input and output chips form separately captioned sections (REQ-UI-SELECTION-CARD). A section lists a chip for **every item the building's cycle involves**, and for an auto-recipe building every item it handles at all, whether or not the buffer currently holds any: an empty buffer reads `0` rather than its chip disappearing, so the card keeps one shape while the building runs. A section left with no chips at all is not shown. The production section (REQ-UI-PRODUCTION-PROGRESS) sits **between them**, so the card reads in the direction the materials flow: what goes in, what is being made of it, what has come out. For a selected construction site the buffer sections are omitted (REQ-BLD-SITE-CONFIG).
**Only unlocked items are listed.** A building's buffers may carry entries for items the player cannot make yet — an auto-recipe building's buffers are sized over *every* recipe of its type (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING), including recipes that are still locked. Those entries are left out of both sections, consistent with the rest of the UI hiding what is not unlocked yet (REQ-LOCK-UI-RECIPE, REQ-LOCK-UI-SPLITTER), so a Smelter shows the ores it can actually smelt rather than every ore in the game.
**An idle auto-recipe building still shows what it handles.** Having no selected recipe (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING), it would otherwise show empty sections whenever it happens to be between cycles. Its input and output sections instead list the unlocked items of every recipe of its type — the same union its buffers were sized over — with a count and no per-cycle denominator, since no one recipe is in force. While a cycle is running, that cycle's recipe supplies the denominators as for any other building.
- REQ-UI-RECIPE-SUMMARY: Below the recipe/schematic selection control, a building running a recipe or schematic shows a one-line **recipe summary**: each input item's icon with its per-cycle amount, an arrow, each output item's icon with its per-cycle amount, and the cycle time in seconds. It restates what the building will do without opening the selection dialog, and it is the panel's only display of the cycle time. For a Shipyard the summary is built from the schematic's materials and production time including the placed modules' contributions (REQ-BLD-SHIPYARD, REQ-MOD-STAT-CALC), matching the buffers beneath it. Auto-recipe buildings (Smelter, Reprocessing Plant — REQ-BLD-SMELTER, REQ-BLD-REPROCESSING) have no player-selected recipe and so show no selection control; they show the summary of the recipe currently in production and, while between cycles, of the one they ran last. They keep it rather than dropping it, because a summary that came and went with each cycle would resize the card in step with the building's status (REQ-UI-SELECTION-STATUS), which is the one thing the panel must not do while the player is reading it (REQ-UI-SELECTION-PANEL). Such a building shows no summary only until it has run its first cycle. A building with no recipe or schematic selected shows no summary.
- REQ-UI-PRODUCTION-PROGRESS: For buildings that produce items or ships (miner, smelter, assembler, reprocessing plant, shipyard), the panel's runtime group shows a captioned **production section** between the input and output buffer sections (REQ-UI-SINGLE-SELECTION): a horizontal progress bar filled to the completion of the active production cycle, with that completion beside the caption as an integer percentage (e.g. `72%`), or the text `idle` in place of the percentage and an empty bar when no production cycle is active. The cycle time is shown in the recipe summary (REQ-UI-RECIPE-SUMMARY) rather than repeated here. When no recipe or schematic is selected, the production section is not shown at all.
- REQ-UI-MULTI-SELECT: The player selects multiple objects by box-drag or by Ctrl+clicking individual objects to add or remove them from the selection. Multi-select operates within a single category (REQ-UI-SELECTION-CATEGORIES). A box-drag that covers at least one building selects buildings (any field objects within the box are ignored — buildings win); a box-drag that covers no building but does cover ships, defence stations, or debris selects all of those field objects together (REQ-UI-ENTITY-CLICK-SELECT, REQ-UI-DEBRIS-MULTI-SELECT). - REQ-UI-MULTI-SELECT: The player selects multiple objects by box-drag or by Ctrl+clicking individual objects to add or remove them from the selection. Multi-select operates within a single category (REQ-UI-SELECTION-CATEGORIES). A box-drag that covers at least one building selects buildings (any field objects within the box are ignored — buildings win); a box-drag that covers no building but does cover ships, defence stations, or debris selects all of those field objects together (REQ-UI-ENTITY-CLICK-SELECT, REQ-UI-DEBRIS-MULTI-SELECT).
- REQ-UI-MULTI-SELECTION: When multiple buildings are selected, the panel shows how many of each building type are selected. No per-building detail is shown. The panel additionally shows the **total building block cost** of the selection — the sum of each selected building's placement cost (`buildings.toml [[building]].cost`, per REQ-BLD-COST), counting only player-placeable buildings (buildings with a button in the build button bar); non-player-placeable buildings (the HQ and defence stations) are excluded from the total, consistent with the blueprint total (REQ-UI-BLUEPRINT-CARD). Construction sites count at their building type's full placement cost regardless of construction progress. - REQ-UI-MULTI-SELECTION: When multiple buildings are selected and the selection does not aggregate (REQ-UI-SELECTION-AGGREGATE), the panel shows a count summary. Its header names the size of the selection as `<n> buildings` in place of an object name, and carries no symbol and nothing in its right slot. Below it is one row per selected building type — the type's symbol, its name, and the number selected as `x<count>` — one type per row, and no per-building detail. A final row shows the **total building block cost** of the selection, captioned `Total cost` with the value followed by the `building_block` item icon (REQ-UI-BLOCKS-ICON, REQ-UI-ITEM-ICON): the sum of each selected building's placement cost (`buildings.toml [[building]].cost`, per REQ-BLD-COST), counting only player-placeable buildings (buildings with a button in the build button bar); non-player-placeable buildings (the HQ and defence stations) are excluded from the total, consistent with the blueprint total (REQ-UI-BLUEPRINT-CARD). Construction sites count at their building type's full placement cost regardless of construction progress.
- REQ-UI-CONFIG-INLINE: Recipe and schematic configuration for a selected building is shown within this panel. Recipe selection (miner, assembler) and schematic selection (shipyard) use the selection button and dialog (REQ-UI-SELECT-BUTTON) rather than an inline control. For shipyards, the panel additionally shows the ship layout preview and "Configure" button below the schematic selection button (REQ-MOD-UI-PREVIEW). - REQ-UI-CONFIG-INLINE: Recipe and schematic configuration for a selected building is shown within this panel, in its configuration group (REQ-UI-SELECTION-CARD). Recipe selection (miner, assembler) and schematic selection (shipyard) use the selection button and dialog (REQ-UI-SELECT-BUTTON) rather than an inline control. For shipyards, the panel additionally shows the ship layout preview and "Configure" button below the schematic selection button (REQ-MOD-UI-PREVIEW).
- REQ-UI-SELECT-BUTTON: **Recipe and schematic selection control.** Recipe selection (Miner ore type, Assembler recipe) and schematic selection (Shipyard) are each presented in the selected building panel as a single **selection button** whose caption is the name of the currently selected recipe or schematic, or a placeholder ("Select recipe" / "Select schematic") when none is selected. Clicking the button opens a modal **selection dialog** that pauses the game (speed set to 0×; on close, the speed is restored to what it was before the dialog was opened). The dialog contains a grid of option buttons, one per selectable option — only options that are currently unlocked are shown (REQ-LOCK-UI-RECIPE for recipes, REQ-LOCK-UI-SCHEMATIC for schematics). Hovering an option button shows the selection info tooltip (REQ-UI-SELECT-TOOLTIP). Clicking an option button selects that recipe/schematic, closes the dialog, and updates the selection button's caption in the selected building panel. The dialog can be dismissed without changing the current selection (e.g. closing it without clicking an option). Selecting a new recipe or schematic has the same effects as before (REQ-MAT-INPUT-BUFFER, REQ-MAT-OUTPUT-BUFFER, REQ-BLD-SHIPYARD). - REQ-UI-SELECT-BUTTON: **Recipe and schematic selection control.** Recipe selection (Miner ore type, Assembler recipe) and schematic selection (Shipyard) are each presented in the selection panel as a single **selection button** whose caption is the name of the currently selected recipe or schematic, or a placeholder ("Select recipe" / "Select schematic") when none is selected. Clicking the button opens a modal **selection dialog** that pauses the game (speed set to 0×; on close, the speed is restored to what it was before the dialog was opened). The dialog contains a grid of option buttons, one per selectable option — only options that are currently unlocked are shown (REQ-LOCK-UI-RECIPE for recipes, REQ-LOCK-UI-SCHEMATIC for schematics). Hovering an option button shows the selection info tooltip (REQ-UI-SELECT-TOOLTIP). Clicking an option button selects that recipe/schematic, closes the dialog, and updates the selection button's caption in the selection panel. The dialog can be dismissed without changing the current selection (e.g. closing it without clicking an option). Selecting a new recipe or schematic has the same effects as before (REQ-MAT-INPUT-BUFFER, REQ-MAT-OUTPUT-BUFFER, REQ-BLD-SHIPYARD).
- REQ-UI-SELECT-TOOLTIP: **Selection info tooltip.** Hovering an option button in the selection dialog (REQ-UI-SELECT-BUTTON), and hovering the selection button in the selected building panel when a selection is set, displays an info tooltip: - REQ-UI-SELECT-TOOLTIP: **Selection info tooltip.** Hovering an option button in the selection dialog (REQ-UI-SELECT-BUTTON), and hovering the selection button in the selection panel when a selection is set, displays an info tooltip:
- For a **recipe** (Miner or Assembler): the recipe name; the name and quantity of each input item (no inputs are listed for miner recipes, which consume nothing); the completion time (`duration_seconds`); and the name and quantity of the produced output item. - For a **recipe** (Miner or Assembler): the recipe name; the name and quantity of each input item (no inputs are listed for miner recipes, which consume nothing); the completion time (`duration_seconds`); and the name and quantity of the produced output item.
- For a **ship schematic** (Shipyard): the ship's `display_name`; the name and quantity of each base required material (`[ship.schematic].materials`, excluding any module contributions); the base production time (`[ship.schematic].production_time_seconds`); and "Produces: 1 <ship display name>". - For a **ship schematic** (Shipyard): the ship's `display_name`; the name and quantity of each base required material (`[ship.schematic].materials`, excluding any module contributions); the base production time (`[ship.schematic].production_time_seconds`); and "Produces: 1 <ship display name>".
- REQ-UI-RECIPE-ICON: In the recipe-selection dialog (REQ-UI-SELECT-BUTTON) for a Miner or Assembler, each recipe option button shows the icon of the recipe's produced item **instead of** its name caption (icon-only). The item shown is the recipe's `icon` field if set, otherwise its first output item; the icon is that item's icon per REQ-UI-ITEM-ICON. When the item has no icon file, the button falls back to the recipe/item name caption. The recipe name and details remain available on hover via the selection info tooltip (REQ-UI-SELECT-TOOLTIP). The `(None)` option keeps its text caption. This applies only to recipe options; the Shipyard schematic-selection dialog is unaffected and continues to show ship name captions. - REQ-UI-RECIPE-ICON: In the recipe-selection dialog (REQ-UI-SELECT-BUTTON) for a Miner or Assembler, each recipe option button shows the icon of the recipe's produced item **instead of** its name caption (icon-only). The item shown is the recipe's `icon` field if set, otherwise its first output item; the icon is that item's icon per REQ-UI-ITEM-ICON. When the item has no icon file, the button falls back to the recipe/item name caption. The recipe name and details remain available on hover via the selection info tooltip (REQ-UI-SELECT-TOOLTIP). The `(None)` option keeps its text caption. This applies only to recipe options; the Shipyard schematic-selection dialog is unaffected and continues to show ship name captions.
- REQ-UI-BELT-CLEAR: When one or more belt, splitter, tunnel entry, or tunnel exit tiles are selected, the panel shows a "Clear" button that removes all items from the selected tiles. Clearing a tunnel entry or exit also discards all items currently in transit through that tunnel (REQ-BLD-TUNNEL-TRANSIT). This can be used to resolve stalled belts, splitters, and tunnels. - REQ-UI-BELT-CLEAR: When one or more belt, splitter, tunnel entry, or tunnel exit tiles are selected, the panel's runtime group shows a **"Clear stuck items"** button that removes all items from the selected tiles. Clearing a tunnel entry or exit also discards all items currently in transit through that tunnel (REQ-BLD-TUNNEL-TRANSIT). This can be used to resolve stalled belts, splitters, and tunnels. The button acts on every selected tile, which is why a selection of belts and tunnel ends aggregates into one content rather than a count summary (REQ-UI-SELECTION-AGGREGATE).
- REQ-UI-HQ-PANEL: When the HQ is selected, the panel shows the HQ's **HP** as a bar labelled `current / maximum` (REQ-HQ-STATS, REQ-UI-HP-BARS) and, beneath it, the **global building blocks stock** — the same value as the header bar's stock display (REQ-UI-BLOCKS-ICON), rendered as an item chip (REQ-UI-SINGLE-SELECTION) carrying the `building_block` icon. The HP comes first, as it does on every card that has it (REQ-UI-SELECTION-CARD). The HQ has no input or output buffers of its own: building blocks delivered by belt go straight into the global stock (REQ-HQ-BELT-INPUT), and showing that stock on the HQ is what tells the player to route blocks there. The HQ has no configuration group and no status indicator (REQ-UI-SELECTION-STATUS), and it is never a construction site.
- REQ-UI-ENTITY-CLICK-SELECT: The player can click any ship (player or enemy) or any defence station (player or enemy) in the game world to select it. A plain click on a ship or defence station makes it the sole selection, clearing any previous selection. Ships and defence stations can be multi-selected — by Ctrl+clicking individual actors to add or remove them, or by box-drag (REQ-UI-MULTI-SELECT) — and can be selected together with debris and with one another in a single field selection (REQ-UI-SELECTION-CATEGORIES), freely mixing player and enemy actors. Actors cannot be selected together with buildings: selecting a ship or defence station clears any building selection, and selecting a building clears the actors (buildings win). Clicking a piece of debris adds to or establishes a field selection (REQ-UI-DEBRIS-CLICK-SELECT). Clicking empty world space (no building, ship, defence station, or piece of debris) clears the selection. - REQ-UI-ENTITY-CLICK-SELECT: The player can click any ship (player or enemy) or any defence station (player or enemy) in the game world to select it. A plain click on a ship or defence station makes it the sole selection, clearing any previous selection. Ships and defence stations can be multi-selected — by Ctrl+clicking individual actors to add or remove them, or by box-drag (REQ-UI-MULTI-SELECT) — and can be selected together with debris and with one another in a single field selection (REQ-UI-SELECTION-CATEGORIES), freely mixing player and enemy actors. Actors cannot be selected together with buildings: selecting a ship or defence station clears any building selection, and selecting a building clears the actors (buildings win). Clicking a piece of debris adds to or establishes a field selection (REQ-UI-DEBRIS-CLICK-SELECT). Clicking empty world space (no building, ship, defence station, or piece of debris) clears the selection.
- REQ-UI-SHIP-STATS-PANEL: When exactly one ship is selected (REQ-UI-ENTITY-CLICK-SELECT) and no debris is selected, the selected building panel shows a **ship stats panel**. (If debris is also selected, the panel shows the compact count summary instead, per REQ-UI-FIELD-MULTI-SELECTION.) The panel structure mirrors REQ-MOD-UI-STATS-PANEL but reflects the ship's actual live state: stats are computed from its installed modules per REQ-MOD-STAT-CALC. The panel always shows all hull stats: HP (current / maximum), max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, and max rotation speed. In addition, capability module summaries are shown conditioned on which module types are installed, using the same aggregation rules as REQ-MOD-UI-STATS-PANEL: weapons (combined DPS, maximum range), salvage (combined collection rate, maximum range), and repair (combined repair rate, maximum range), each section appearing only if at least one instance of that module type is installed. While debug draw mode is active (REQ-UI-DEBUG-DRAW), the panel additionally shows the ship's derived threat cost (REQ-MOD-THREAT). - REQ-UI-SHIP-STATS-PANEL: When exactly one ship is selected (REQ-UI-ENTITY-CLICK-SELECT) and no debris is selected, the selection panel shows a **ship stats panel**. (If debris is also selected, the panel shows the compact count summary instead, per REQ-UI-FIELD-MULTI-SELECTION.) The panel structure mirrors REQ-MOD-UI-STATS-PANEL but reflects the ship's actual live state: stats are computed from its installed modules per REQ-MOD-STAT-CALC. Its header (REQ-UI-SELECTION-CARD) carries the schematic's color swatch and display name, with the ship's current behavior in the right slot (REQ-UI-SHIP-BEHAVIOR). The panel always shows all hull stats: HP (current / maximum) as a **bar** with the two values beside its caption, then max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, and max rotation speed as label/value rows. In addition, capability module summaries are shown below the hull stats, each as its own outlined row, conditioned on which module types are installed and using the same aggregation rules as REQ-MOD-UI-STATS-PANEL: weapons (combined DPS, maximum range), salvage (combined collection rate, maximum range), and repair (combined repair rate, maximum range), each appearing only if at least one instance of that module type is installed. While debug draw mode is active (REQ-UI-DEBUG-DRAW), the panel additionally shows the ship's derived threat cost (REQ-MOD-THREAT).
- REQ-UI-SHIP-BEHAVIOR: The ship stats panel (REQ-UI-SHIP-STATS-PANEL) additionally displays the selected ship's **current behavior** — a single label naming the top-priority behavior currently governing the ship's navigation, as resolved by the fixed-priority behavior arbitration. Only the winning behavior is named; lower-priority behaviors that are suppressed are not shown, and neither are the salvage/repair cycles that run regardless of the active behavior (REQ-SHP-SALVAGE, REQ-SHP-REPAIR). The label updates live as the ship's behavior changes, and it is always shown (independent of debug draw mode, unlike the threat-cost line of REQ-UI-SHIP-STATS-PANEL). This applies to both player and enemy ships (REQ-UI-ENTITY-CLICK-SELECT); enemy ships only ever show **Engaging** or **Advancing**. The behavior labels (all wrapped in `tr()`) are: - REQ-UI-SHIP-BEHAVIOR: The ship stats panel (REQ-UI-SHIP-STATS-PANEL) additionally displays the selected ship's **current behavior** in its header's right slot (REQ-UI-SELECTION-CARD) — a single label naming the top-priority behavior currently governing the ship's navigation, as resolved by the fixed-priority behavior arbitration. Only the winning behavior is named; lower-priority behaviors that are suppressed are not shown, and neither are the salvage/repair cycles that run regardless of the active behavior (REQ-SHP-SALVAGE, REQ-SHP-REPAIR). The label updates live as the ship's behavior changes, and it is always shown (independent of debug draw mode, unlike the threat-cost line of REQ-UI-SHIP-STATS-PANEL). This applies to both player and enemy ships (REQ-UI-ENTITY-CLICK-SELECT); enemy ships only ever show **Engaging** or **Advancing**. The behavior labels (all wrapped in `tr()`) are:
- **Retreating** — the ship is retreating (REQ-SHP-RETREAT). - **Retreating** — the ship is retreating (REQ-SHP-RETREAT).
- **Engaging** — the ship is engaging a combat target (player: REQ-SHP-COMBAT; enemy: REQ-SHP-ENEMY-AI). - **Engaging** — the ship is engaging a combat target (player: REQ-SHP-COMBAT; enemy: REQ-SHP-ENEMY-AI).
- **Salvaging** — the ship is executing salvage navigation: seeking debris, collecting, or delivering to a Salvage Bay (REQ-SHP-SALVAGE). - **Salvaging** — the ship is executing salvage navigation: seeking debris, collecting, or delivering to a Salvage Bay (REQ-SHP-SALVAGE).
@@ -547,16 +598,17 @@ The screen is divided into two columns: a main column (75% width) containing the
- **Rallying** — the ship is moving to or orbiting the rally point (REQ-SHP-RALLY). - **Rallying** — the ship is moving to or orbiting the rally point (REQ-SHP-RALLY).
- **Standby** — the ship is holding with its fleet (REQ-SHP-STANDBY). - **Standby** — the ship is holding with its fleet (REQ-SHP-STANDBY).
- **Advancing** — the ship is executing the baseline forward advance with no higher-priority behavior active (player: REQ-SHP-COMBAT advance toward the enemy; enemy: REQ-SHP-ENEMY-AI advance toward the asteroid). - **Advancing** — the ship is executing the baseline forward advance with no higher-priority behavior active (player: REQ-SHP-COMBAT advance toward the enemy; enemy: REQ-SHP-ENEMY-AI advance toward the asteroid).
- REQ-UI-STATION-STATS-PANEL: When exactly one defence station is selected (REQ-UI-ENTITY-CLICK-SELECT) and no debris is selected, the selected building panel shows a **station stats panel** displaying the station's stats computed at its current level: HP (current / maximum), damage, range, and fire rate. (If debris is also selected, the panel shows the compact count summary instead, per REQ-UI-FIELD-MULTI-SELECTION.) - REQ-UI-STATION-STATS-PANEL: When exactly one defence station is selected (REQ-UI-ENTITY-CLICK-SELECT) and no debris is selected, the selection panel shows a **station stats panel** displaying the station's stats computed at its current level: HP (current / maximum) as a **bar** with the two values beside its caption, then damage, range, and fire rate as label/value rows, matching the ship stats panel's rendering (REQ-UI-SHIP-STATS-PANEL). Its header carries no right slot: a station has no behavior label and no status light. (If debris is also selected, the panel shows the compact count summary instead, per REQ-UI-FIELD-MULTI-SELECTION.)
- REQ-UI-FIELD-MULTI-SELECTION: A full single-object stats panel (REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL, REQ-UI-DEBRIS-PANEL) is shown only when the field selection holds exactly one object — one ship, one defence station, or one piece of debris. Whenever the selection holds more than one field object — multiple actors, multiple pieces of debris, or any mix of actors and debris — the panel shows a **compact summary** instead: a count per type, one line per type rendered as "<type> x <count>" (the same `x`-count notation as the recipe tooltip and the building multi-selection, REQ-UI-MULTI-SELECTION). Ships are grouped by schematic display name and defence stations as a group, distinguishing player from enemy; all selected pieces of debris are grouped into a single "Debris x <count>" line whose count is the number of selected debris pieces. No per-object detail and no total-object-count header are shown (consistent with the building panel). If debris is part of the selection, a final "Scrap x <total>" line is appended after the "Debris" line, summing the remaining scrap across all selected debris (REQ-UI-DEBRIS-PANEL), so all lines share uniform spacing. Building selections use REQ-UI-SINGLE-SELECTION / REQ-UI-MULTI-SELECTION instead. - REQ-UI-FIELD-MULTI-SELECTION: A full single-object stats panel (REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL, REQ-UI-DEBRIS-PANEL) is shown when the field selection holds exactly one object — one ship, one defence station, or one piece of debris — and, for debris only, when it holds several pieces of debris and nothing else, which aggregate into that same content (REQ-UI-SELECTION-AGGREGATE). Every other field selection of more than one object — multiple actors, or any mix of actors and debris — shows a **count summary** instead. Its header reads `Mixed selection` with the total number of selected objects in the right slot (REQ-UI-SELECTION-CARD). Below it is one row per type — the type's symbol, its name, and the number selected as `x<count>`, the same `x`-count notation as the recipe tooltip and the building multi-selection (REQ-UI-MULTI-SELECTION). Ships are grouped by schematic display name and defence stations as a group, distinguishing player from enemy; all selected pieces of debris are grouped into a single `Debris` row whose count is the number of selected pieces. No per-object detail is shown. If debris is part of the selection, its row is followed by an indented sub-row giving the summed remaining scrap across all selected debris (REQ-UI-DEBRIS-PANEL). Building selections use REQ-UI-SINGLE-SELECTION / REQ-UI-MULTI-SELECTION instead.
- REQ-UI-DEBRIS-CLICK-SELECT: The player can click any piece of debris (REQ-RES-DEBRIS-DROP) in the game world to select it. Debris are field objects (REQ-UI-SELECTION-CATEGORIES) and can be selected together with ships and defence stations, but not with buildings. A plain click on a piece of debris makes it the sole selection, clearing any previous selection; selecting a building clears any debris (buildings win), and selecting a piece of debris clears any building selection. Hit-testing prefers a building over a coincident actor or piece of debris, and an actor (ship or defence station) over a coincident piece of debris: a piece of debris is selected only when no building or actor is under the cursor. A selected piece of debris that despawns or is fully collected (REQ-RES-DEBRIS-DROP) is removed from the selection; if no selected object remains, the panel becomes empty (REQ-UI-EMPTY-SELECTION). - REQ-UI-DEBRIS-CLICK-SELECT: The player can click any piece of debris (REQ-RES-DEBRIS-DROP) in the game world to select it. Debris are field objects (REQ-UI-SELECTION-CATEGORIES) and can be selected together with ships and defence stations, but not with buildings. A plain click on a piece of debris makes it the sole selection, clearing any previous selection; selecting a building clears any debris (buildings win), and selecting a piece of debris clears any building selection. Hit-testing prefers a building over a coincident actor or piece of debris, and an actor (ship or defence station) over a coincident piece of debris: a piece of debris is selected only when no building or actor is under the cursor. A selected piece of debris that despawns or is fully collected (REQ-RES-DEBRIS-DROP) is removed from the selection; if no selected object remains, the panel becomes empty (REQ-UI-EMPTY-SELECTION).
- REQ-UI-DEBRIS-MULTI-SELECT: Multiple pieces of debris can be selected by box-drag or by Ctrl+clicking individual pieces to add or remove them, mirroring building multi-select (REQ-UI-MULTI-SELECT). Debris shares the field-object category with ships and defence stations (REQ-UI-SELECTION-CATEGORIES), so a field selection may hold debris and actors together. Ctrl+clicking a piece of debris while a field selection is active adds or removes that piece within the same selection; Ctrl+clicking a piece of debris while a building selection is active first clears the buildings and begins a field selection (buildings win). Conversely, selecting a building while a field selection is active clears it. Box-drag disambiguation follows REQ-UI-MULTI-SELECT (a box covering any building selects buildings; a box covering no building selects the ships, defence stations, and debris within it). - REQ-UI-DEBRIS-MULTI-SELECT: Multiple pieces of debris can be selected by box-drag or by Ctrl+clicking individual pieces to add or remove them, mirroring building multi-select (REQ-UI-MULTI-SELECT). Debris shares the field-object category with ships and defence stations (REQ-UI-SELECTION-CATEGORIES), so a field selection may hold debris and actors together. Ctrl+clicking a piece of debris while a field selection is active adds or removes that piece within the same selection; Ctrl+clicking a piece of debris while a building selection is active first clears the buildings and begins a field selection (buildings win). Conversely, selecting a building while a field selection is active clears it. Box-drag disambiguation follows REQ-UI-MULTI-SELECT (a box covering any building selects buildings; a box covering no building selects the ships, defence stations, and debris within it).
- REQ-UI-DEBRIS-PANEL: When exactly one piece of debris is selected (and no actors, REQ-UI-FIELD-MULTI-SELECTION), the selected building panel shows a **debris stats panel** structured like the ship and station stats panels (REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL): a **"Debris"** heading followed by a single stat row, **"Scrap"**, showing that piece's current remaining scrap amount (REQ-RES-DEBRIS-DROP), rendered in the same label/value style as a ship hull stat row. When more than one field object is selected — multiple pieces of debris, or debris together with actors the debris are instead summarized within the compact count summary (REQ-UI-FIELD-MULTI-SELECTION): a "Debris x <count>" line giving the number of selected debris pieces, followed by a "Scrap x <total>" line summing the remaining scrap across all selected debris. The displayed scrap value(s) update as selected debris are partially collected or despawn (REQ-UI-DEBRIS-CLICK-SELECT). - REQ-UI-DEBRIS-PANEL: When debris is selected and no actors are (REQ-UI-FIELD-MULTI-SELECTION), the selection panel shows a **debris stats panel** structured like the ship and station stats panels (REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL): a header reading **"Debris"**, followed by a single stat row, **"Scrap remaining"**, in the same label/value style as a ship hull stat row. With one piece selected the row shows that piece's remaining scrap amount (REQ-RES-DEBRIS-DROP) and the header's right slot is empty. With several pieces selected the same content is shown aggregated (REQ-UI-SELECTION-AGGREGATE): the number of selected pieces appears in the header's right slot as `x<count>` and the row shows the summed remaining scrap across them. When debris is selected together with actors, the debris are instead summarized within the count summary (REQ-UI-FIELD-MULTI-SELECTION): a `Debris` row giving the number of selected pieces, followed by an indented sub-row with their summed remaining scrap. The displayed scrap value updates as selected debris are partially collected or despawn (REQ-UI-DEBRIS-CLICK-SELECT).
### Build Button Bar ### Build Button Bar
- REQ-UI-BUILD-BAR: All placeable building types are shown as a **single horizontal row** of buttons with no grouping and no wrapping, inside a widget that **floats over the game world view** (REQ-UI-WORLD-SIZE), horizontally centered and anchored at the bottom edge with a small margin. Tunnel Entry and Tunnel Exit share a single **Tunnel** button (REQ-BLD-TUNNEL-MODE) rather than one button each. The bar is sized to its buttons and re-centers whenever the set of shown buttons changes (REQ-LOCK-BUILDING) or the view is resized. - REQ-UI-BUILD-BAR: All placeable building types are shown as a **single horizontal row** of buttons with no grouping and no wrapping, inside a widget that **floats over the game world view** (REQ-UI-WORLD-SIZE), horizontally centered and anchored at the bottom edge with a small margin. Tunnel Entry and Tunnel Exit share a single **Tunnel** button (REQ-BLD-TUNNEL-MODE) rather than one button each. The bar is sized to its buttons and re-centers whenever the set of shown buttons changes (REQ-LOCK-BUILDING) or the view is resized.
- **Overlay behavior.** The bar occludes the strip of the game world it covers; the world view itself keeps its full extent and the view's scrolling, ghost rendering, and tile geometry are unaffected (the world is not inset for the bar). The bar is drawn above the pause and deconstruct vignettes (REQ-UI-PAUSE-BORDER, REQ-UI-DECONSTRUCT-BORDER), which keep their full 100-pixel bottom band underneath it, and below the modal dim (REQ-UI-MODAL-DIM), which covers the entire game window including the bar. - **Overlay behavior.** The bar occludes the strip of the game world it covers; the world view itself keeps its full extent and the view's scrolling, ghost rendering, and tile geometry are unaffected (the world is not inset for the bar). The bar is drawn above the pause and deconstruct vignettes (REQ-UI-PAUSE-BORDER, REQ-UI-DECONSTRUCT-BORDER), which keep their full 100-pixel bottom band underneath it, and below the modal dim (REQ-UI-MODAL-DIM), which covers the entire game window including the bar.
- **No overlap with the selection panel.** The bar and the selection panel (REQ-UI-SELECTION-PANEL) never overlap, and keeping them apart is entirely the panel's job: the bar's position depends only on its own button set and the view size, and it never moves, re-centers, or resizes because the panel appears, disappears, or changes size. The panel instead steps around the bar's current rectangle wherever its own column would meet it (REQ-UI-SELECTION-PANEL).
- **Input.** Mouse events over the bar are consumed by the bar and never reach the game world: hovering it shows no builder-mode ghost at the tile beneath, and clicking it neither places a building nor changes the selection. Right-clicking the bar does not exit builder mode (REQ-BLD-BUILDER-MODE) or cancel a belt drag (REQ-BLD-BELT-DRAG). - **Input.** Mouse events over the bar are consumed by the bar and never reach the game world: hovering it shows no builder-mode ghost at the tile beneath, and clicking it neither places a building nor changes the selection. Right-clicking the bar does not exit builder mode (REQ-BLD-BUILDER-MODE) or cancel a belt drag (REQ-BLD-BELT-DRAG).
- REQ-UI-BUILD-COST: Each button is **icon-only with a cost**, its face composed of three elements: the button's **hotkey badge** in the top-left corner, the building's icon (REQ-UI-BUILD-ICON) centered below it, and the building block cost centered under the icon, shown with the `building_block` item icon (REQ-UI-BLOCKS-ICON, REQ-UI-ITEM-ICON) to the right of the number in place of the trailing `Blocks` word, e.g. `2` then a small block icon. The building name is not shown on the button; it is shown in the button's hover tooltip instead (REQ-UI-BUILD-TOOLTIP). When no icon file exists for `building_block`, the cost is shown as the bare number. The Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON) has no cost and shows its name as a text caption in the cost's place. - REQ-UI-BUILD-COST: Each button is **icon-only with a cost**, its face composed of three elements: the button's **hotkey badge** in the top-left corner, the building's icon (REQ-UI-BUILD-ICON) centered below it, and the building block cost centered under the icon, shown with the `building_block` item icon (REQ-UI-BLOCKS-ICON, REQ-UI-ITEM-ICON) to the right of the number in place of the trailing `Blocks` word, e.g. `2` then a small block icon. The building name is not shown on the button; it is shown in the button's hover tooltip instead (REQ-UI-BUILD-TOOLTIP). When no icon file exists for `building_block`, the cost is shown as the bare number. The Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON) has no cost and shows its name as a text caption in the cost's place.
- **Hotkey badge.** The badge names the build hotkey that activates the button (REQ-UI-HOTKEYS), so the player can learn the shortcuts from the bar itself. It is rendered dimmer than the cost so it reads as secondary, but at the same size and in bold, because a smaller badge is not legible. A plain-digit hotkey is shown as the bare digit (`1`, `2`, `3`); a Shift+digit hotkey is shown with an upwards arrow prefixed and no separator (`↑1``↑6`); the Deconstruct button shows `Q`. A button whose building type has no build hotkey shows no badge and keeps the same face size, so the row stays even. - **Hotkey badge.** The badge names the build hotkey that activates the button (REQ-UI-HOTKEYS), so the player can learn the shortcuts from the bar itself. It is rendered dimmer than the cost so it reads as secondary, but at the same size and in bold, because a smaller badge is not legible. A plain-digit hotkey is shown as the bare digit (`1`, `2`, `3`); a Shift+digit hotkey is shown with an upwards arrow prefixed and no separator (`↑1``↑6`); the Deconstruct button shows `Q`. A button whose building type has no build hotkey shows no badge and keeps the same face size, so the row stays even.
@@ -565,9 +617,82 @@ The screen is divided into two columns: a main column (75% width) containing the
- REQ-UI-BUILD-DISABLED: Buttons for buildings the player cannot currently afford are shown as disabled. A disabled button's icon (REQ-UI-BUILD-ICON) is rendered in a greyed variant, with its colored chip background recolored grey while the white glyph is retained. - REQ-UI-BUILD-DISABLED: Buttons for buildings the player cannot currently afford are shown as disabled. A disabled button's icon (REQ-UI-BUILD-ICON) is rendered in a greyed variant, with its colored chip background recolored grey while the white glyph is retained.
- REQ-UI-DECONSTRUCT-BUTTON: A dedicated **Deconstruct** button is shown in the build button bar (REQ-UI-BUILD-BAR), as the last entry of the row and **visually separated** from the building-type buttons by a gap (not a divider line), because it toggles a mode rather than selecting a building type. Its face follows REQ-UI-BUILD-COST with two differences: its hotkey badge reads `Q`, and because it has no building block cost it shows its **Deconstruct** name as a text caption where the building-type buttons show their cost — so it is the one labelled button in the bar. It is therefore wider than the building-type buttons, which share a uniform width. Clicking it toggles deconstruct mode on and off, equivalent to the Q deconstruct toggle (REQ-UI-HOTKEYS). The button is shown in a visually active/pressed state while deconstruct mode is active. The button shows a hover tooltip stating the deconstruction refund (REQ-BLD-DECONSTRUCT): that deconstructing a fully-built building returns `world.toml [world].refund_percentage` percent of its building block cost once deconstruction completes, and that a construction site removed before it finishes building is refunded in full. When `refund_percentage` is 100% both cases yield the same refund, and the tooltip is simplified to state the single refund percentage without distinguishing the two cases. Unlike the building-type button tooltips (REQ-UI-BUILD-TOOLTIP), this tooltip is not config-defined text but is composed from the refund percentage. - REQ-UI-DECONSTRUCT-BUTTON: A dedicated **Deconstruct** button is shown in the build button bar (REQ-UI-BUILD-BAR), as the last entry of the row and **visually separated** from the building-type buttons by a gap (not a divider line), because it toggles a mode rather than selecting a building type. Its face follows REQ-UI-BUILD-COST with two differences: its hotkey badge reads `Q`, and because it has no building block cost it shows its **Deconstruct** name as a text caption where the building-type buttons show their cost — so it is the one labelled button in the bar. It is therefore wider than the building-type buttons, which share a uniform width. Clicking it toggles deconstruct mode on and off, equivalent to the Q deconstruct toggle (REQ-UI-HOTKEYS). The button is shown in a visually active/pressed state while deconstruct mode is active. The button shows a hover tooltip stating the deconstruction refund (REQ-BLD-DECONSTRUCT): that deconstructing a fully-built building returns `world.toml [world].refund_percentage` percent of its building block cost once deconstruction completes, and that a construction site removed before it finishes building is refunded in full. When `refund_percentage` is 100% both cases yield the same refund, and the tooltip is simplified to state the single refund percentage without distinguishing the two cases. Unlike the building-type button tooltips (REQ-UI-BUILD-TOOLTIP), this tooltip is not config-defined text but is composed from the refund percentage.
### Controls Panel
The controls panel tells the player which controls are available right now. It is context-sensitive: the game is always in exactly one **control context**, derived from the active build mode and the current selection, and the panel shows that context's rows and no others. Its position, size, and overlay behavior are defined in REQ-UI-CONTROLS-PANEL; its structure in REQ-UI-CONTROLS-CARD; and which rows each context shows in REQ-UI-CONTROLS-CONTENT. The panel never defines a binding: every row restates one already defined in REQ-UI-HOTKEYS or in the mouse gestures cited beside it.
- REQ-UI-CONTROLS-PANEL: The **controls panel** is a widget that **floats over the game world view** (REQ-UI-WORLD-SIZE), anchored to the view's **bottom-left corner** with a small margin on both edges. It is **sized to its content in both width and height**, growing and shrinking upward from that corner as the context changes. Should its content ever be taller than the view, the panel's height is capped at the view height less its margins and the content scrolls vertically within it. The selection panel is placed beside the current selection (REQ-UI-SELECTION-PANEL) and so can reach this corner; the two never overlap, and keeping them apart is entirely the selection panel's job — this panel's position depends only on its own content, the view size, and the build button bar, and it never moves or resizes because the selection panel appears, disappears, or changes size.
- **Stepping around the build button bar.** Like the selection panel (REQ-UI-SELECTION-PANEL), the panel does **not** confine itself to the band above the build button bar's strip: the bar is horizontally centered and sized to its buttons (REQ-UI-BUILD-BAR), so it normally leaves this corner free, and the panel shares the view's bottom edge with it. The panel **rises only to avoid an actual overlap**: whenever the panel at the bottom-left corner would intersect the bar's current rectangle, it is moved up so that its bottom edge clears the bar's top by the same margin it keeps from the view's edges, and its height is capped at the space that leaves. Whether it rises therefore depends on how wide the bar and the panel currently are, and it returns to the corner as soon as they no longer meet. The bar never moves on the panel's account (REQ-UI-BUILD-BAR).
- **Visibility.** The panel is shown whenever the game is being played. Unlike the selection panel it has no empty state (REQ-UI-EMPTY-SELECTION): every context has rows, so there is never nothing to show.
- **Collapsing.** Clicking anywhere on the panel's header (REQ-UI-CONTROLS-CARD) toggles the panel between **expanded** and **collapsed**. Collapsed, it shows its header alone, keeping the context name visible and the header clickable so the panel can be expanded again; expanded, it shows the header followed by every row of the current context. The panel starts **expanded**. Changing context does not change the collapsed state: a panel collapsed in one context stays collapsed in the next, and its header updates in place. The collapsed state is presentation-only — it is not a player command, never enters the replay stream, and has no effect on the simulation. It persists for as long as the application runs, including across a restart from the escape menu (REQ-UI-GAME-MENU), and is not saved to disk.
- **Overlay behavior.** As for the build button bar and the selection panel (REQ-UI-BUILD-BAR, REQ-UI-SELECTION-PANEL): the panel occludes the strip of the game world it covers; the world view itself keeps its full extent and the view's scrolling, ghost rendering, and tile geometry are unaffected. It is drawn above the pause and deconstruct vignettes (REQ-UI-PAUSE-BORDER, REQ-UI-DECONSTRUCT-BORDER), which keep their full left-hand band underneath it, and below the modal dim (REQ-UI-MODAL-DIM), which covers the entire game window including the panel.
- **Input.** Mouse events over the panel are consumed by the panel and never reach the game world: hovering it shows no builder-mode ghost at the tile beneath, and clicking it neither places a building nor changes the selection. Right-clicking the panel does not exit builder mode (REQ-BLD-BUILDER-MODE) or cancel a belt drag (REQ-BLD-BELT-DRAG). The only control the panel itself offers is the header click that collapses and expands it.
- REQ-UI-CONTROLS-CARD: **Card structure.** The panel is a card with two parts, top to bottom:
- **Header** — always shown, and the panel's only interactive element (REQ-UI-CONTROLS-PANEL). It holds a colored context dot on the left, the context's name beside it in upper case, and, for contexts that define one, a **detail suffix** separated by a middle dot (`BUILD MODE · Assembler`). The name and detail per context are given in REQ-UI-CONTROLS-CONTENT.
- **Rows** — one per available control, shown only while the panel is expanded. Each row is one or more **key badges** on the left — the key or mouse button drawn as a small bordered chip — and a **label** beside them naming what it does. An action reachable two ways carries both badges in the same row (`RMB` `Q` — Exit placement) rather than occupying two rows. A row whose action leaves the current mode is drawn with the destructive badge styling, distinguishing it from the rows that act within the mode. No row is ever drawn greyed or otherwise disabled: a control the player cannot currently use is not shown at all (REQ-UI-CONTROLS-ACCURACY).
The rows that are live in every context (REQ-UI-CONTROLS-CONTENT) are shown last, under a divider and the caption `ALWAYS AVAILABLE`. This holds in every context including the General one, which has context rows of its own above the divider like any other, so the card is read the same way wherever the player is.
- REQ-UI-CONTROLS-CONTENT: **Content catalog.** The control context follows from the active build mode and the selection alone. Build modes are mutually exclusive (REQ-BLD-BUILDER-MODE), so exactly one context applies at any moment:
| Context | When | Header name | Header detail |
|---|---|---|---|
| General | no build mode active, nothing selected | `GENERAL` | — |
| Selection | no build mode active, at least one object selected | `SELECTION` | `<n> buildings` or `<n> objects` |
| Build | builder mode active (REQ-BLD-BUILDER-MODE) | `BUILD MODE` | the building type's name |
| Blueprint | blueprint placement mode active (REQ-UI-BLUEPRINT-MODE) | `BLUEPRINT MODE` | the blueprint's name, or `Temporary` for a temporary blueprint (REQ-UI-BLUEPRINT-TEMP) |
| Deconstruct | deconstruct mode active (REQ-UI-DECONSTRUCT-BUTTON) | `DECONSTRUCT MODE` | — |
The Selection context's detail counts the selection and names its category (REQ-UI-SELECTION-CATEGORIES): `<n> buildings` for a building selection, `<n> objects` for a field selection, in the singular at a count of one. The Build and Blueprint contexts show **the same rows** and differ only in their header.
**Always-available rows**, shown in every context:
| Badges | Label | Shown |
|---|---|---|
| `A` `D` | Move | always |
| `W` `S` | Game speed | always |
| `Space` | Toggle pause | always |
| `V` | Paste last | only while a temporary blueprint exists (REQ-UI-BLUEPRINT-TEMP) |
| `Ctrl` `V` | Blueprints | always |
| `Esc` | Menu | always |
**Context rows**, shown above the always-available block:
| Context | Badges | Label |
|---|---|---|
| General | `LMB` | Select |
| | `LMB` drag | Select area |
| | `Q` | Deconstruct mode |
| Selection | `LMB` | Select / clear selection |
| | `LMB` drag | Select area |
| | `Ctrl` `LMB` | Add / remove from selection |
| | `Ctrl` `LMB` drag | Add area to selection |
| | `Q` | Deconstruct mode |
| | `C` | Copy to temporary blueprint |
| | `Ctrl` `C` | Create blueprint |
| Build, Blueprint | `LMB` | Place |
| | `LMB` drag | Place belt line |
| | `R` / `Shift` `R` | Rotate |
| | `RMB` `Q` | Exit placement |
| Deconstruct | `LMB` | Toggle deconstruct |
| | `LMB` drag | Deconstruct area |
| | `RMB` `Q` | Exit deconstruct mode |
Four rows are conditional on more than the context, because the binding behind them is:
- **`C` / `Ctrl` `C`** are shown only while the selection holds at least one player-placeable building, the condition under which those keys do anything (REQ-UI-HOTKEYS). A selection of ships, defence stations, or debris shows neither.
- **`LMB` drag — Place belt line** is shown only in builder mode for the Belt type, the only type placed by dragging (REQ-BLD-BELT-DRAG). Every other builder type and blueprint placement omit the row.
- **`RMB` `Q` — Exit placement** splits into two rows **while a belt drag is in progress**, because the two bindings then part company (REQ-BLD-BELT-DRAG): `RMB` reads **Cancel belt line** and cancels the drag while leaving builder mode active, and `Q` reads **Exit placement** and leaves the mode outright.
- **`LMB` — Place** reads **Apply settings** instead whenever the ghost under the cursor resolves to a configuration transfer (REQ-UI-BLUEPRINT-TRANSFER) — a single-building blueprint hovering a same-type building of a configurable type, which is the case in which clicking hands over settings rather than placing anything. A blueprint holding more than one building keeps the `Place` label, since its click both places and transfers (REQ-UI-BLUEPRINT-PLACE).
- REQ-UI-CONTROLS-ACCURACY: **The panel never advertises a binding that would do nothing.** Every row shown must, if triggered in the situation the panel is showing it in, have the effect its label names; a binding that is inert in the current context is omitted rather than shown greyed (REQ-UI-CONTROLS-CARD). The relation holds in one direction only: the panel may omit a binding that is available, and deliberately does so in three cases:
- **Build hotkeys** (REQ-UI-HOTKEYS) are live in every context, but are advertised on the build buttons' badges (REQ-UI-BUILD-COST) instead of taking eleven rows in every context of this panel.
- **`C` and `Ctrl` `C`** are omitted from the Build, Blueprint, and Deconstruct contexts even though a selection surviving into a build mode keeps them working. They belong to the Selection context, and repeating them in every mode would defeat the panel's purpose of showing what the player's current situation affords.
- **`Ctrl` `LMB` and `Ctrl` `LMB` drag** work with nothing selected — they select the object under the cursor much as a plain click would — but are shown only in the Selection context. "Add / remove from selection" names an operation on a selection, and there is none to operate on until something is selected; the plain `LMB` row already covers what the gesture does before then.
- **`F3` and `F4`** (REQ-UI-DEBUG-DRAW) are development controls rather than player controls and appear in no context.
This asymmetry between what is available and what is shown is why the two are separate questions in the implementation, and why the tests assert that a resolvable input is *available* rather than that it is displayed.
### Blueprints ### Blueprints
Blueprints occupy no permanent screen space. They are saved with **Ctrl+C** from the current selection (REQ-UI-BLUEPRINT-CREATE) and picked for placement from the blueprint selection dialog, opened with **Ctrl+V** (REQ-UI-BLUEPRINT-DIALOG). There is no blueprint panel in the side panel column (REQ-UI-PANEL-COLUMN). (The ship layout blueprint panel of the layout configuration dialog, REQ-MOD-UI-BLUEPRINT-PANEL, is a separate feature and is unaffected.) Blueprints occupy no permanent screen space. They are saved with **Ctrl+C** from the current selection (REQ-UI-BLUEPRINT-CREATE) and picked for placement from the blueprint selection dialog, opened with **Ctrl+V** (REQ-UI-BLUEPRINT-DIALOG). The unmodified **C** and **V** keys are the throwaway counterparts of the same two gestures: they capture and re-place a single unnamed temporary blueprint that is never saved and never listed (REQ-UI-BLUEPRINT-TEMP). Blueprints have no widget on the game screen at all. (The ship layout blueprint panel of the layout configuration dialog, REQ-MOD-UI-BLUEPRINT-PANEL, is a separate feature and is unaffected.)
- REQ-UI-BLUEPRINT-CREATE: Pressing **Ctrl+C** (REQ-UI-HOTKEYS) opens the modal **blueprint save dialog**, which pauses the simulation and dims the game window (REQ-UI-MODAL-DIM). It has effect only when at least one player-placeable building (i.e. a building with a button in the build button bar) is currently selected; non-player-placeable buildings (HQ, defence stations) in the selection do not count toward this condition, and pressing Ctrl+C with an empty selection or a selection of only non-player-placeable buildings does nothing (no dialog opens). A selected player-placeable building may be either an operational building or a construction site (a building placed but not yet fully built, REQ-BLD-SITE-CONFIG); both count toward this condition and are captured identically (REQ-UI-BLUEPRINT-STORAGE). The dialog prompts the player to enter a name and has Confirm and Cancel buttons. Clicking Cancel — or pressing Escape, or closing the dialog — closes it with no effect and does not open the blueprint selection dialog. Clicking Confirm with a non-empty name creates a blueprint from the current selection, silently excluding any non-player-placeable buildings, appends it to the blueprint list, closes the save dialog, and immediately opens the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG) showing the new blueprint among the others. - REQ-UI-BLUEPRINT-CREATE: Pressing **Ctrl+C** (REQ-UI-HOTKEYS) opens the modal **blueprint save dialog**, which pauses the simulation and dims the game window (REQ-UI-MODAL-DIM). It has effect only when at least one player-placeable building (i.e. a building with a button in the build button bar) is currently selected; non-player-placeable buildings (HQ, defence stations) in the selection do not count toward this condition, and pressing Ctrl+C with an empty selection or a selection of only non-player-placeable buildings does nothing (no dialog opens). A selected player-placeable building may be either an operational building or a construction site (a building placed but not yet fully built, REQ-BLD-SITE-CONFIG); both count toward this condition and are captured identically (REQ-UI-BLUEPRINT-STORAGE). The dialog prompts the player to enter a name and has Confirm and Cancel buttons. Clicking Cancel — or pressing Escape, or closing the dialog — closes it with no effect and does not open the blueprint selection dialog. Clicking Confirm with a non-empty name creates a blueprint from the current selection, silently excluding any non-player-placeable buildings, appends it to the blueprint list, closes the save dialog, and immediately opens the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG) showing the new blueprint among the others.
@@ -592,7 +717,11 @@ Blueprints occupy no permanent screen space. They are saved with **Ctrl+C** from
+------------------------------------------------------+ +------------------------------------------------------+
``` ```
- REQ-UI-BLUEPRINT-TEMP: Pressing the **T** key (REQ-UI-HOTKEYS) creates a **temporary blueprint** from the current selection and immediately enters blueprint placement mode for it, without opening the naming dialog. It has effect only when at least one player-placeable building is currently selected — the same condition as REQ-UI-BLUEPRINT-CREATE; pressing T with an empty selection, or a selection containing only non-player-placeable buildings (HQ, defence stations), does nothing. Entering this mode replaces any currently active build, blueprint placement, or deconstruct mode. The temporary blueprint is captured exactly as a saved blueprint (REQ-UI-BLUEPRINT-STORAGE), silently excluding any non-player-placeable buildings from the selection, but it is never named, never shown in the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG), and never persisted to `blueprints.toml` (REQ-UI-BLUEPRINT-SAVE). Placement behaves identically to a saved blueprint's placement mode (REQ-UI-BLUEPRINT-MODE, REQ-UI-BLUEPRINT-PLACE): a ghost is rendered per building, R / Shift+R rotate the entire constellation, placement follows the same per-building validity and total-cost rules, and after a successful placement the mode stays active so the blueprint can be placed again. Right-clicking in the game world exits placement mode, at which point the temporary blueprint is discarded. - REQ-UI-BLUEPRINT-TEMP: Pressing the **C** key (REQ-UI-HOTKEYS) creates a **temporary blueprint** from the current selection and immediately enters blueprint placement mode for it, without opening the naming dialog. It has effect only when at least one player-placeable building is currently selected — the same condition as REQ-UI-BLUEPRINT-CREATE; pressing C with an empty selection, or a selection containing only non-player-placeable buildings (HQ, defence stations), does nothing at all, and in particular leaves any existing temporary blueprint in place. Entering this mode replaces any currently active build, blueprint placement, or deconstruct mode. The temporary blueprint is captured exactly as a saved blueprint (REQ-UI-BLUEPRINT-STORAGE), silently excluding any non-player-placeable buildings from the selection, but it is never named, never shown in the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG), and never persisted to `blueprints.toml` (REQ-UI-BLUEPRINT-SAVE). Placement behaves identically to a saved blueprint's placement mode (REQ-UI-BLUEPRINT-MODE, REQ-UI-BLUEPRINT-PLACE): a ghost is rendered per building, R / Shift+R rotate the entire constellation, placement follows the same per-building validity and total-cost rules, and after a successful placement the mode stays active so the blueprint can be placed again. Right-clicking in the game world exits placement mode; unlike the mode, the temporary blueprint itself survives, so it can be entered again with V.
Pressing the **V** key re-enters blueprint placement mode for the temporary blueprint, capturing nothing new: it is independent of the current selection, can be pressed any number of times, and yields exactly the mode described above. Like C it replaces any currently active build, blueprint placement, or deconstruct mode, and it does not test whether the player can currently afford the blueprint — cost is enforced at placement (REQ-UI-BLUEPRINT-PLACE), consistently with C. Pressing V when no temporary blueprint exists does nothing: no mode is entered and any currently active mode is left untouched.
There is at most one temporary blueprint at a time; pressing C replaces the previous one. It is held only in memory for the current run: it is discarded when the application closes and when the simulation is restarted from the escape menu (REQ-UI-GAME-MENU), after which V does nothing until C captures a new one.
- REQ-UI-BLUEPRINT-STORAGE: A blueprint stores its name and, for each building in the selection, the building type, its rotation, its tile offset (integer dx, dy) from the center of the bounding box of all selected buildings' footprints, and — where applicable — the selected recipe ID (miners and assemblers) or schematic ID (shipyards), and for splitters the two output filters (each a list of item types; an empty list means accept-all), at the time of capture. A source building may be either an operational building or a construction site (REQ-BLD-SITE-CONFIG); a construction site is captured identically, storing whatever configuration it currently holds and never any buffer or construction-progress state. If no recipe or schematic was selected at capture time, none is stored; for a splitter with no filters set, no filter lists are stored. This structure maps directly to a TOML representation (e.g. one `[[building]]` array entry per constituent building, with the splitter filters as `filter_a`/`filter_b` arrays of item-type ids). - REQ-UI-BLUEPRINT-STORAGE: A blueprint stores its name and, for each building in the selection, the building type, its rotation, its tile offset (integer dx, dy) from the center of the bounding box of all selected buildings' footprints, and — where applicable — the selected recipe ID (miners and assemblers) or schematic ID (shipyards), and for splitters the two output filters (each a list of item types; an empty list means accept-all), at the time of capture. A source building may be either an operational building or a construction site (REQ-BLD-SITE-CONFIG); a construction site is captured identically, storing whatever configuration it currently holds and never any buffer or construction-progress state. If no recipe or schematic was selected at capture time, none is stored; for a splitter with no filters set, no filter lists are stored. This structure maps directly to a TOML representation (e.g. one `[[building]]` array entry per constituent building, with the splitter filters as `filter_a`/`filter_b` arrays of item-type ids).
@@ -606,9 +735,39 @@ Blueprints occupy no permanent screen space. They are saved with **Ctrl+C** from
Clicking anywhere on an enabled card other than its delete icon closes the dialog and enters blueprint placement mode for that blueprint (REQ-UI-BLUEPRINT-MODE). A card is disabled when the player cannot currently afford its total cost; a disabled card is rendered dimmed and clicking it does nothing (consistent with REQ-UI-BUILD-DISABLED), and neither closes the dialog nor enters placement mode. The delete icon is always enabled regardless of whether the player can afford the blueprint. Clicking anywhere on an enabled card other than its delete icon closes the dialog and enters blueprint placement mode for that blueprint (REQ-UI-BLUEPRINT-MODE). A card is disabled when the player cannot currently afford its total cost; a disabled card is rendered dimmed and clicking it does nothing (consistent with REQ-UI-BUILD-DISABLED), and neither closes the dialog nor enters placement mode. The delete icon is always enabled regardless of whether the player can afford the blueprint.
- REQ-UI-BLUEPRINT-MODE: In blueprint placement mode a ghost is rendered for every building in the blueprint (excluding any of a currently locked building type, REQ-LOCK-BUILDING, which is omitted entirely per REQ-LOCK-UI-BLUEPRINT) at the position determined by its stored tile offset from the bounding-box center, which is anchored to the tile under the cursor. Each ghost is rendered individually as valid or invalid, applying REQ-BLD-PLACE-VALID conditions (a) and (b) per building (the other ghosts in the same blueprint do not count as existing buildings for the overlap check). A valid ghost uses its building type's semi-transparent per-building coloring (REQ-BLD-GHOST); an invalid ghost uses the distinct "invalid" color, as in single-building builder mode. Pressing R / Shift+R rotates the entire constellation 90° counter-clockwise / clockwise: each building's tile offset is rotated around the bounding-box center and each building's own rotation is updated, consistent with REQ-BLD-ROTATE. Blueprint placement mode is exited by right-clicking in the game world. Opening the blueprint selection dialog while placement mode is active (REQ-UI-BLUEPRINT-DIALOG) leaves the mode active — closing the dialog without picking a card returns to it unchanged — while clicking a card exits the current mode and enters blueprint placement mode for the newly picked blueprint. - REQ-UI-BLUEPRINT-MODE: In blueprint placement mode a ghost is rendered for every building in the blueprint (excluding any of a currently locked building type, REQ-LOCK-BUILDING, which is omitted entirely per REQ-LOCK-UI-BLUEPRINT) at the position determined by its stored tile offset from the bounding-box center, which is anchored to the tile under the cursor. Each ghost is rendered individually as valid or invalid, applying REQ-BLD-PLACE-VALID conditions (a) and (b) per building (the other ghosts in the same blueprint do not count as existing buildings for the overlap check). A valid ghost uses its building type's semi-transparent per-building coloring (REQ-BLD-GHOST); an invalid ghost uses the distinct "invalid" color, as in single-building builder mode; a ghost over a configuration-transfer target uses the distinct "transfer" color instead of either and, for a single-building blueprint, is drawn snapped onto the target rather than at the blueprint's own position (REQ-UI-BLUEPRINT-TRANSFER); a ghost over a compatible overlap counts as valid and keeps the ordinary per-building coloring (REQ-UI-BLUEPRINT-OVERLAP). Pressing R / Shift+R rotates the entire constellation 90° counter-clockwise / clockwise: each building's tile offset is rotated around the bounding-box center and each building's own rotation is updated, consistent with REQ-BLD-ROTATE. Blueprint placement mode is exited by right-clicking in the game world. Opening the blueprint selection dialog while placement mode is active (REQ-UI-BLUEPRINT-DIALOG) leaves the mode active — closing the dialog without picking a card returns to it unchanged — while clicking a card exits the current mode and enters blueprint placement mode for the newly picked blueprint.
- REQ-UI-BLUEPRINT-PLACE: Buildings of a currently locked building type (REQ-LOCK-BUILDING) are first excluded from the blueprint for this placement, per REQ-LOCK-UI-BLUEPRINT — they are not ghosted, not validity-checked, not placed, and their cost is excluded from the total. Left-clicking in blueprint placement mode then places the (remaining) blueprint if (a) every building in the constellation satisfies REQ-BLD-PLACE-VALID conditions (a) and (b) at its resolved tile, and (b) the player has enough building blocks to afford the total cost. If both conditions are met, a construction site is added to the build queue for each building in the blueprint and the full total cost is deducted from the global building blocks stock in one transaction. If a recipe ID is stored for a building, it is applied to the construction site immediately. If a schematic ID is stored, it is applied only if that schematic is currently unlocked; if it is not unlocked, the shipyard's schematic is left unset. If splitter output filters are stored, they are applied to the construction site immediately and carry over when it finishes building (REQ-BLD-SITE-CONFIG). Locked recipe IDs and splitter filter entries for locked item types are handled on placement per REQ-LOCK-UI-BLUEPRINT. After a successful placement the game remains in blueprint placement mode, allowing the player to place the same blueprint again immediately. - REQ-UI-BLUEPRINT-PLACE: This describes placing the blueprint's buildings as new construction sites. Ghosts sitting on a building that is already there are handled elsewhere and place nothing: a configuration-transfer target receives the blueprint's stored settings instead (REQ-UI-BLUEPRINT-TRANSFER), and a compatible overlap is left alone (REQ-UI-BLUEPRINT-OVERLAP). Both still take part in the single all-or-nothing click described here. Buildings of a currently locked building type (REQ-LOCK-BUILDING) are first excluded from the blueprint for this placement, per REQ-LOCK-UI-BLUEPRINT — they are not ghosted, not validity-checked, not placed, and their cost is excluded from the total. Left-clicking in blueprint placement mode then places the (remaining) blueprint if (a) every building in the constellation satisfies REQ-BLD-PLACE-VALID conditions (a) and (b) at its resolved tile, and (b) the player has enough building blocks to afford the total cost. Buildings that are compatible overlaps (REQ-UI-BLUEPRINT-OVERLAP) or configuration-transfer targets (REQ-UI-BLUEPRINT-TRANSFER) are excluded from the total cost and are not placed, but do not block the placement; a transfer target additionally receives the blueprint's stored settings. If both conditions are met, a construction site is added to the build queue for each remaining building in the blueprint and the full total cost is deducted from the global building blocks stock in one transaction. If a recipe ID is stored for a building, it is applied to the construction site immediately. If a schematic ID is stored, it is applied only if that schematic is currently unlocked; if it is not unlocked, the shipyard's schematic is left unset. If splitter output filters are stored, they are applied to the construction site immediately and carry over when it finishes building (REQ-BLD-SITE-CONFIG). Locked recipe IDs and splitter filter entries for locked item types are handled on placement per REQ-LOCK-UI-BLUEPRINT. After a successful placement the game remains in blueprint placement mode, allowing the player to place the same blueprint again immediately.
- REQ-UI-BLUEPRINT-OVERLAP: **Compatible overlap.** In blueprint placement mode, a ghost whose footprint **exactly coincides** with the footprint of an existing placed building or construction site that is of the **same building type** and has the **same rotation** is a *compatible overlap*: the building the blueprint wants is already there. Such a ghost is **valid** despite the occupied tiles (REQ-BLD-PLACE-VALID condition (b)), so it does not block the placement of the rest of the constellation — dropping a blueprint over a partially-built copy of itself fills in what is missing. It is drawn in the ordinary per-building ghost color (REQ-BLD-GHOST), like any other valid ghost.
On placement the overlapped building is **left completely untouched**: no construction site is placed on it, no building blocks are charged for it (it is excluded from the total cost of REQ-UI-BLUEPRINT-PLACE), its rotation is not changed, and a construction site's progress is preserved. This applies per building in the blueprint, independently, and to blueprints of any size. Unlike REQ-BLD-ROTATE-IN-PLACE, which it replaces in this mode, it applies to Tunnel Entries and Tunnel Exits too — nothing is re-oriented, so the reason for their exception does not arise.
A coinciding same-type building whose **rotation differs** is not a compatible overlap: the blueprint cannot rotate it (REQ-BLD-ROTATE-IN-PLACE no longer applies here), so the position is an ordinary occupied-tile overlap and therefore invalid.
**Order of the two rules.** A ghost is tested for a configuration transfer (REQ-UI-BLUEPRINT-TRANSFER) first, and this requirement governs only what that test does not claim. Because a coinciding building of a **configurable** type always transfers, this requirement covers exactly the types that have nothing to configure:
- **Configurable type** (Miner, Assembler, Shipyard, Splitter) — a transfer, never a compatible overlap. It is drawn in the transfer color and hands the blueprint's settings over.
- **Type with no settings** (Smelter, Reprocessing Plant, Salvage Bay, belt, tunnel end) — a compatible overlap if the rotation matches, invalid otherwise. There is nothing to hand over, so the building is simply left as it is and the ghost keeps its ordinary color. This holds for a single-building blueprint too: the cursor hit-test of REQ-UI-BLUEPRINT-TRANSFER applies only to configurable types, so hovering a belt with a belt blueprint still just overlaps it.
A single blueprint can hold both kinds at once, and each ghost is judged on its own: dropping a constellation over a partial copy of itself may reconfigure some of the buildings already there (cyan) while leaving others untouched (ordinary color) and placing the rest as new construction sites.
- REQ-UI-BLUEPRINT-TRANSFER: **Configuration transfer.** A blueprint hands its stored settings to buildings that are already standing where it wants them, instead of only to ones it places. A single-building blueprint therefore doubles as a way to copy one building's settings onto others of the same type: select a configured building, press **C** to capture it as a temporary blueprint and enter placement mode (REQ-UI-BLUEPRINT-TEMP), then click same-type buildings to stamp its settings onto them. **V** re-enters that mode later. A multi-building blueprint does the same for each of its buildings as it is placed.
A blueprint ghost is a **configuration-transfer target** when all of the following hold:
- The building is of a **configurable building type** — one with player-facing settings: Miner and Assembler (recipe), Shipyard (schematic and module layout), Splitter (output filters). Whether anything was actually configured at capture time is irrelevant; an unconfigured source transfers its unconfigured state (see below). Building types with no settings at all (Smelter, Reprocessing Plant, Salvage Bay, belts, tunnel entries and exits, the HQ) never transfer; a coinciding building of those types is a compatible overlap instead (REQ-UI-BLUEPRINT-OVERLAP).
- There is a target, found in one of two ways depending on the blueprint's size, because the two are different gestures:
- **Single-building blueprint** — the target is the building or construction site **under the cursor**, if it is of the same type. There is no coincidence test at all: the target's rotation, its footprint, and its alignment with the ghost are all irrelevant. The ghost is drawn **snapped onto the target**, at the target's own anchor and rotation, so it shows what the click will act on rather than where a building would go. This is the copying gesture, and a footprint test made it unusable for buildings that are not square: a Shipyard rotated 90° covers different tiles altogether, so no amount of lining up would ever match a differently-facing one.
- **Multi-building blueprint** — the ghost's footprint must **exactly coincide** with the footprint of an existing building or site of the same type (the coincidence test of REQ-BLD-ROTATE-IN-PLACE), and that target must have the **same rotation** as the ghost, which is what makes the position valid at all (REQ-UI-BLUEPRINT-OVERLAP). A constellation is placed as a layout, so its ghosts stay where the blueprint puts them: nothing snaps to the cursor and nothing is re-oriented.
At a transfer target:
- The ghost is drawn in a distinct **transfer** color read from `visuals.toml [overlays]`, overriding both the per-building coloring and the "invalid" color (REQ-BLD-GHOST, REQ-BLD-PLACE-VALID). The position counts as valid despite the occupied tiles (REQ-BLD-PLACE-VALID condition (b)).
- **Left-clicking transfers the configuration** to the existing building or site, making the target's settings **identical to the source's**: the recipe ID (Miner, Assembler), the schematic ID together with the ship layout (Shipyard), or the two output filters (Splitter). No construction site is placed, no building blocks are consumed (it is excluded from the total cost of REQ-UI-BLUEPRINT-PLACE), and the target's **rotation is not changed** — a transfer never rotates.
- The transfer is a **full mirror, including the absence of a setting**: where the blueprint stores no configuration for a field (REQ-UI-BLUEPRINT-STORAGE stores nothing for an unselected recipe or schematic, and no filter lists for a splitter whose filters were empty at capture time), the target's corresponding setting is **cleared** rather than left as it was. So a splitter captured with no filters clears the target splitter's filters back to accept-all, and a miner captured with no recipe selected clears the target miner's recipe. This holds for every blueprint size, so a constellation captured from unconfigured buildings clears the settings of every matching building it is dropped on.
- The transfer has the same effects as making that selection through the selection panel, clearing included: buffer clearing per REQ-MAT-INPUT-BUFFER and REQ-MAT-OUTPUT-BUFFER, and, for a Shipyard, in-progress cycle cancellation per REQ-BLD-SHIPYARD. It inherits the no-op rule of REQ-MAT-INPUT-BUFFER with them: a transfer onto a building whose settings already match the source changes nothing at all — no buffers cleared, no production cycle cancelled, no construction progress lost — so repeatedly clicking already-matching buildings is harmless. Each field is judged on its own, so transferring an identical recipe with a differing layout affects only the layout. The layout configuration dialog does not auto-open (REQ-MOD-UI-AUTO-DIALOG).
- Unlock gating matches placement (REQ-UI-BLUEPRINT-PLACE): a stored schematic is applied only if it is currently unlocked, and locked recipe IDs and splitter filter entries for locked item types are handled per REQ-LOCK-UI-BLUEPRINT.
- Both operational buildings and construction sites are transfer targets (REQ-BLD-SITE-CONFIG); a configuration applied to a site carries over unchanged when it finishes building.
- After the transfer the game stays in blueprint placement mode, so further same-type buildings can be clicked in turn.
- A blueprint placement applies every transfer among its ghosts in the same click that places its new construction sites (REQ-UI-BLUEPRINT-PLACE); the placement is all-or-nothing, so if any ghost is invalid nothing is placed and nothing is transferred.
- REQ-UI-BLUEPRINT-DELETE: Clicking the delete icon ("×") on a blueprint card (REQ-UI-BLUEPRINT-CARD) immediately removes that blueprint from the list, without a confirmation prompt. The blueprint selection dialog stays open and its card grid reflows to close the gap. If the deleted blueprint was active in blueprint placement mode, that mode is exited. - REQ-UI-BLUEPRINT-DELETE: Clicking the delete icon ("×") on a blueprint card (REQ-UI-BLUEPRINT-CARD) immediately removes that blueprint from the list, without a confirmation prompt. The blueprint selection dialog stays open and its card grid reflows to close the gap. If the deleted blueprint was active in blueprint placement mode, that mode is exited.

View File

@@ -10,7 +10,12 @@ set(TARGET_LIB_INCLUDE_DIRS
"${CMAKE_CURRENT_SOURCE_DIR}/lib" "${CMAKE_CURRENT_SOURCE_DIR}/lib"
"${CMAKE_CURRENT_SOURCE_DIR}/external" "${CMAKE_CURRENT_SOURCE_DIR}/external"
) )
set(TARGET_UI_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/ui") set(TARGET_UI_INCLUDE_DIRS
"${CMAKE_CURRENT_SOURCE_DIR}/ui"
# The balancing target compiles a few ui files into itself rather than linking the
# ui library, and the ship stats panel is built from the selection card's parts.
"${CMAKE_CURRENT_SOURCE_DIR}/ui/selection"
)
set(TARGET_TEST_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/test") set(TARGET_TEST_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/test")
set(TARGET_BALANCING_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/balancing") set(TARGET_BALANCING_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/balancing")
@@ -78,6 +83,7 @@ unset(SRCS)
set(HDRS) set(HDRS)
set(SRCS) set(SRCS)
set(UI_INCLUDE_PATH)
add_subdirectory(ui) add_subdirectory(ui)
@@ -106,6 +112,7 @@ set_target_properties(${TARGET_UI_NAME} PROPERTIES
) )
target_include_directories(${TARGET_UI_NAME} PUBLIC target_include_directories(${TARGET_UI_NAME} PUBLIC
"${TARGET_UI_INCLUDE_DIRS}" "${TARGET_UI_INCLUDE_DIRS}"
"${UI_INCLUDE_PATH}"
"${TARGET_LIB_INCLUDE_DIRS}" "${TARGET_LIB_INCLUDE_DIRS}"
"${LIB_INCLUDE_PATH}" "${LIB_INCLUDE_PATH}"
) )

View File

@@ -7,6 +7,12 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/BalancingWindow.h ${CMAKE_CURRENT_SOURCE_DIR}/BalancingWindow.h
${CMAKE_CURRENT_SOURCE_DIR}/InspectWindow.h ${CMAKE_CURRENT_SOURCE_DIR}/InspectWindow.h
${CMAKE_CURRENT_SOURCE_DIR}/../ui/ShipStatsPanel.h ${CMAKE_CURRENT_SOURCE_DIR}/../ui/ShipStatsPanel.h
# The card parts the ship stats panel is built from. They are deliberately free of
# Simulation and GameConfig, which is what lets them come along here.
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/StatRow.h
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/BarRow.h
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/SectionBox.h
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/SelectionNames.h
${CMAKE_CURRENT_SOURCE_DIR}/../ui/VisualsConfig.h ${CMAKE_CURRENT_SOURCE_DIR}/../ui/VisualsConfig.h
${CMAKE_CURRENT_SOURCE_DIR}/../ui/VisualsLoader.h ${CMAKE_CURRENT_SOURCE_DIR}/../ui/VisualsLoader.h
# Shared world-space shapes so the arena keeps looking like the game # Shared world-space shapes so the arena keeps looking like the game
@@ -26,6 +32,10 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/BalancingWindow.cpp ${CMAKE_CURRENT_SOURCE_DIR}/BalancingWindow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/InspectWindow.cpp ${CMAKE_CURRENT_SOURCE_DIR}/InspectWindow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ui/ShipStatsPanel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../ui/ShipStatsPanel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/StatRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/BarRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/SectionBox.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ui/selection/SelectionNames.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ui/VisualsLoader.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../ui/VisualsLoader.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ui/WorldPrimitives.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../ui/WorldPrimitives.cpp
PARENT_SCOPE PARENT_SCOPE

View File

@@ -72,6 +72,7 @@ void BuildModeController::enterMode(BuildMode mode)
std::make_shared<BuilderModeExitedEvent>()); std::make_shared<BuilderModeExitedEvent>());
break; break;
case BuildMode::Blueprint: case BuildMode::Blueprint:
m_hoveredGhostIsTransfer = false;
EventManager::getInstance()->sendEventImmediately( EventManager::getInstance()->sendEventImmediately(
std::make_shared<BlueprintModeExitedEvent>()); std::make_shared<BlueprintModeExitedEvent>());
break; break;
@@ -249,6 +250,16 @@ void BuildModeController::setBlueprintGhostTile(QPoint tile)
m_blueprintGhostTile = tile; m_blueprintGhostTile = tile;
} }
bool BuildModeController::isHoveredGhostTransfer() const
{
return m_hoveredGhostIsTransfer;
}
void BuildModeController::setHoveredGhostTransfer(bool transfer)
{
m_hoveredGhostIsTransfer = transfer;
}
const std::optional<BuildingId>& const std::optional<BuildingId>&
BuildModeController::getDeconstructHoverBuildingId() const BuildModeController::getDeconstructHoverBuildingId() const
{ {

View File

@@ -95,6 +95,15 @@ public:
QPoint getBlueprintGhostTile() const; QPoint getBlueprintGhostTile() const;
void setBlueprintGhostTile(QPoint tile); void setBlueprintGhostTile(QPoint tile);
// Whether the ghost under the cursor would hand its settings to the building
// already there rather than place anything (REQ-UI-BLUEPRINT-TRANSFER). Classifying
// it needs the factory state, so the caller resolves it and stores the answer here,
// as with setGhostValidity. Kept here rather than recomputed per reader so the
// click, the ghost's colour, and the controls panel cannot disagree about what the
// cursor is over.
bool isHoveredGhostTransfer() const;
void setHoveredGhostTransfer(bool transfer);
// --- deconstruct mode ----------------------------------------------------- // --- deconstruct mode -----------------------------------------------------
const std::optional<BuildingId>& getDeconstructHoverBuildingId() const; const std::optional<BuildingId>& getDeconstructHoverBuildingId() const;
void setDeconstructHoverBuildingId(std::optional<BuildingId> id); void setDeconstructHoverBuildingId(std::optional<BuildingId> id);
@@ -118,6 +127,7 @@ private:
Blueprint m_blueprint; Blueprint m_blueprint;
QPoint m_blueprintGhostTile; QPoint m_blueprintGhostTile;
bool m_hoveredGhostIsTransfer = false;
std::optional<BuildingId> m_deconstructHoverBuildingId; std::optional<BuildingId> m_deconstructHoverBuildingId;
}; };

View File

@@ -53,6 +53,20 @@ bool isBeltSubsystemType(BuildingType type)
|| type == BuildingType::TunnelExit; || type == BuildingType::TunnelExit;
} }
bool isConfigurableBuildingType(BuildingType type)
{
switch (type)
{
case BuildingType::Miner: // recipe (REQ-BLD-MINER)
case BuildingType::Assembler: // recipe (REQ-BLD-ASSEMBLER)
case BuildingType::Shipyard: // schematic and layout (REQ-BLD-SHIPYARD, REQ-MOD-LAYOUT)
case BuildingType::Splitter: // output filters (REQ-BLD-SPLITTER)
return true;
default:
return false;
}
}
bool isProductionBuildingType(BuildingType type) bool isProductionBuildingType(BuildingType type)
{ {
switch (type) switch (type)

View File

@@ -43,3 +43,9 @@ bool isProductionBuildingType(BuildingType type);
// rather than in the Building instance, so placing/removing them must register or // rather than in the Building instance, so placing/removing them must register or
// unregister a tile with BeltSystem. // unregister a tile with BeltSystem.
bool isBeltSubsystemType(BuildingType type); bool isBeltSubsystemType(BuildingType type);
// Building types with player-facing settings that a blueprint can carry and hand to an
// existing building (REQ-UI-BLUEPRINT-TRANSFER): Miner and Assembler (recipe), Shipyard
// (schematic and module layout), Splitter (output filters). Every other type has nothing
// to configure, so a blueprint of one has nothing to transfer.
bool isConfigurableBuildingType(BuildingType type);

View File

@@ -16,8 +16,10 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/TunnelCompletion.h ${CMAKE_CURRENT_SOURCE_DIR}/TunnelCompletion.h
${CMAKE_CURRENT_SOURCE_DIR}/WorldCoordinates.h ${CMAKE_CURRENT_SOURCE_DIR}/WorldCoordinates.h
${CMAKE_CURRENT_SOURCE_DIR}/WorldCamera.h ${CMAKE_CURRENT_SOURCE_DIR}/WorldCamera.h
${CMAKE_CURRENT_SOURCE_DIR}/FloatingPanelPlacement.h
${CMAKE_CURRENT_SOURCE_DIR}/SelectionController.h ${CMAKE_CURRENT_SOURCE_DIR}/SelectionController.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildModeController.h ${CMAKE_CURRENT_SOURCE_DIR}/BuildModeController.h
${CMAKE_CURRENT_SOURCE_DIR}/ControlAction.h
PARENT_SCOPE PARENT_SCOPE
) )
@@ -31,8 +33,10 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/TunnelCompletion.cpp ${CMAKE_CURRENT_SOURCE_DIR}/TunnelCompletion.cpp
${CMAKE_CURRENT_SOURCE_DIR}/WorldCoordinates.cpp ${CMAKE_CURRENT_SOURCE_DIR}/WorldCoordinates.cpp
${CMAKE_CURRENT_SOURCE_DIR}/WorldCamera.cpp ${CMAKE_CURRENT_SOURCE_DIR}/WorldCamera.cpp
${CMAKE_CURRENT_SOURCE_DIR}/FloatingPanelPlacement.cpp
${CMAKE_CURRENT_SOURCE_DIR}/SelectionController.cpp ${CMAKE_CURRENT_SOURCE_DIR}/SelectionController.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BuildModeController.cpp ${CMAKE_CURRENT_SOURCE_DIR}/BuildModeController.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ControlAction.cpp
PARENT_SCOPE PARENT_SCOPE
) )

View File

@@ -0,0 +1,263 @@
#include "ControlAction.h"
namespace
{
// A binding that a belt drag can take over. Availability is a property of the action,
// but a binding can be claimed by a different action while a gesture is in progress:
// right-click cancels the drag instead of leaving builder mode (REQ-BLD-BELT-DRAG), so
// ExitMode's right-click drops out and it is left with Q alone.
enum class BindingCondition
{
Always,
NotDraggingBelt
};
struct KeyBindingEntry
{
ControlAction action;
int key;
// Shown on the badge, and Ctrl additionally participates in matching. Every other
// modifier is display only -- see resolveKeyAction.
Qt::KeyboardModifiers modifiers;
};
struct MouseBindingEntry
{
ControlAction action;
MouseBinding binding;
BindingCondition condition;
};
// Resolution is first-match-wins over these tables, so an entry that must beat another
// on the same input is listed above it -- CancelBeltLine before ExitMode on the right
// mouse button. Everything else is disjoint by availability.
const KeyBindingEntry KEY_BINDINGS[] = {
{ControlAction::Move, Qt::Key_A, Qt::NoModifier},
{ControlAction::Move, Qt::Key_D, Qt::NoModifier},
{ControlAction::GameSpeed, Qt::Key_W, Qt::NoModifier},
{ControlAction::GameSpeed, Qt::Key_S, Qt::NoModifier},
{ControlAction::TogglePause, Qt::Key_Space, Qt::NoModifier},
{ControlAction::CopyTemporary, Qt::Key_C, Qt::NoModifier},
{ControlAction::CreateBlueprint, Qt::Key_C, Qt::ControlModifier},
{ControlAction::PasteTemporary, Qt::Key_V, Qt::NoModifier},
{ControlAction::OpenBlueprints, Qt::Key_V, Qt::ControlModifier},
// One binding, two badges: Shift picks the rotation direction and is read by the
// handler, the way a build hotkey's digit is (REQ-BLD-ROTATE). Both entries match
// the same press, and both resolve to the same action, so listing them twice costs
// nothing and is what puts "R" and "Shift+R" on the row.
{ControlAction::Rotate, Qt::Key_R, Qt::NoModifier},
{ControlAction::Rotate, Qt::Key_R, Qt::ShiftModifier},
{ControlAction::EnterDeconstruct, Qt::Key_Q, Qt::NoModifier},
{ControlAction::ExitMode, Qt::Key_Q, Qt::NoModifier},
{ControlAction::OpenMenu, Qt::Key_Escape, Qt::NoModifier},
};
const MouseBindingEntry MOUSE_BINDINGS[] = {
{ControlAction::Select, MouseBinding::LeftClick, BindingCondition::Always},
{ControlAction::Place, MouseBinding::LeftClick, BindingCondition::Always},
{ControlAction::ApplySettings, MouseBinding::LeftClick, BindingCondition::Always},
{ControlAction::ToggleDeconstruct, MouseBinding::LeftClick, BindingCondition::Always},
{ControlAction::SelectArea, MouseBinding::LeftDrag, BindingCondition::Always},
{ControlAction::PlaceBeltLine, MouseBinding::LeftDrag, BindingCondition::Always},
{ControlAction::DeconstructArea, MouseBinding::LeftDrag, BindingCondition::Always},
{ControlAction::AddToSelection, MouseBinding::CtrlLeftClick, BindingCondition::Always},
{ControlAction::AddAreaToSelection, MouseBinding::CtrlLeftDrag, BindingCondition::Always},
{ControlAction::CancelBeltLine, MouseBinding::RightClick, BindingCondition::Always},
{ControlAction::ExitMode, MouseBinding::RightClick, BindingCondition::NotDraggingBelt},
};
bool isConditionMet(BindingCondition condition, const ControlContext& context)
{
if (condition == BindingCondition::NotDraggingBelt) { return !context.draggingBelt; }
return true;
}
bool isPlacementMode(const ControlContext& context)
{
return context.mode == BuildMode::Builder || context.mode == BuildMode::Blueprint;
}
std::vector<ControlAction> filterAvailable(const std::vector<ControlAction>& actions,
const ControlContext& context)
{
std::vector<ControlAction> available;
for (ControlAction action : actions)
{
if (isControlActionAvailable(action, context)) { available.push_back(action); }
}
return available;
}
} // namespace
bool isControlActionAvailable(ControlAction action, const ControlContext& context)
{
switch (action)
{
case ControlAction::None:
return false;
case ControlAction::Move:
case ControlAction::GameSpeed:
case ControlAction::TogglePause:
case ControlAction::OpenBlueprints:
case ControlAction::OpenMenu:
return true;
// Does nothing until something has been captured with C, so it is not offered
// before then (REQ-UI-BLUEPRINT-TEMP, REQ-UI-CONTROLS-ACCURACY).
case ControlAction::PasteTemporary:
return context.temporaryBlueprintExists;
case ControlAction::Select:
case ControlAction::SelectArea:
case ControlAction::AddToSelection:
case ControlAction::AddAreaToSelection:
case ControlAction::EnterDeconstruct:
return context.mode == BuildMode::None;
// Both need something a blueprint can be made of; a selection of ships or debris
// leaves them inert (REQ-UI-HOTKEYS).
case ControlAction::CopyTemporary:
case ControlAction::CreateBlueprint:
return context.mode == BuildMode::None && context.placeableBuildingSelected;
// Place and ApplySettings are the same click; which one it is depends on whether
// the ghost under the cursor is a transfer target (REQ-UI-BLUEPRINT-TRANSFER).
case ControlAction::Place:
return isPlacementMode(context) && !context.hoveredGhostIsTransfer;
case ControlAction::ApplySettings:
return context.mode == BuildMode::Blueprint && context.hoveredGhostIsTransfer;
// The only building type placed by dragging (REQ-BLD-BELT-DRAG).
case ControlAction::PlaceBeltLine:
return context.mode == BuildMode::Builder
&& context.builderType == BuildingType::Belt;
case ControlAction::Rotate:
return isPlacementMode(context);
case ControlAction::CancelBeltLine:
return context.draggingBelt;
case ControlAction::ExitMode:
return context.mode != BuildMode::None;
case ControlAction::ToggleDeconstruct:
case ControlAction::DeconstructArea:
return context.mode == BuildMode::Deconstruct;
}
return false;
}
std::vector<ControlBinding> getControlActionBindings(ControlAction action,
const ControlContext& context)
{
std::vector<ControlBinding> bindings;
for (const MouseBindingEntry& entry : MOUSE_BINDINGS)
{
if (entry.action != action) { continue; }
if (!isConditionMet(entry.condition, context)) { continue; }
ControlBinding binding;
binding.isMouse = true;
binding.mouse = entry.binding;
bindings.push_back(binding);
}
for (const KeyBindingEntry& entry : KEY_BINDINGS)
{
if (entry.action != action) { continue; }
ControlBinding binding;
binding.key = entry.key;
binding.modifiers = entry.modifiers;
bindings.push_back(binding);
}
return bindings;
}
ControlContextKind getControlContextKind(const ControlContext& context)
{
switch (context.mode)
{
case BuildMode::Builder: return ControlContextKind::Build;
case BuildMode::Blueprint: return ControlContextKind::Blueprint;
case BuildMode::Deconstruct: return ControlContextKind::Deconstruct;
case BuildMode::None: break;
}
return context.selection == ControlSelection::None ? ControlContextKind::General
: ControlContextKind::Selection;
}
std::vector<ControlAction> getContextActions(const ControlContext& context)
{
// The candidates of each context, in the order REQ-UI-CONTROLS-CONTENT lists them,
// then filtered by availability.
//
// The General and Selection lists differ rather than one filtered list serving
// both, because the additive-selection rows are an omission and not an
// unavailability: Ctrl+click does work with nothing selected, it just picks the
// object like a plain click would. "Add / remove from selection" is a row that
// means nothing until there is a selection to add to, so it waits for one
// (REQ-UI-CONTROLS-ACCURACY permits omitting an available binding).
switch (getControlContextKind(context))
{
case ControlContextKind::Build:
case ControlContextKind::Blueprint:
return filterAvailable({ControlAction::Place, ControlAction::ApplySettings,
ControlAction::PlaceBeltLine, ControlAction::Rotate,
ControlAction::CancelBeltLine, ControlAction::ExitMode},
context);
case ControlContextKind::Deconstruct:
return filterAvailable({ControlAction::ToggleDeconstruct,
ControlAction::DeconstructArea, ControlAction::ExitMode},
context);
case ControlContextKind::Selection:
return filterAvailable({ControlAction::Select, ControlAction::SelectArea,
ControlAction::AddToSelection,
ControlAction::AddAreaToSelection,
ControlAction::EnterDeconstruct,
ControlAction::CopyTemporary,
ControlAction::CreateBlueprint},
context);
case ControlContextKind::General:
break;
}
return filterAvailable({ControlAction::Select, ControlAction::SelectArea,
ControlAction::EnterDeconstruct},
context);
}
std::vector<ControlAction> getAlwaysAvailableActions(const ControlContext& context)
{
return filterAvailable({ControlAction::Move, ControlAction::GameSpeed,
ControlAction::TogglePause, ControlAction::PasteTemporary,
ControlAction::OpenBlueprints, ControlAction::OpenMenu},
context);
}
ControlAction resolveKeyAction(int key, Qt::KeyboardModifiers modifiers,
const ControlContext& context)
{
// Ctrl distinguishes a chord from the bare key (Ctrl+C is not C); every other
// modifier is ignored, so Shift+A still pans and Shift+R still rotates. This is
// what the key handler has always done, and matching modifiers exactly instead
// would silently drop those presses.
const bool controlHeld = (modifiers & Qt::ControlModifier) != 0;
for (const KeyBindingEntry& entry : KEY_BINDINGS)
{
if (entry.key != key) { continue; }
const bool entryNeedsControl = (entry.modifiers & Qt::ControlModifier) != 0;
if (entryNeedsControl != controlHeld) { continue; }
if (isControlActionAvailable(entry.action, context)) { return entry.action; }
}
return ControlAction::None;
}
ControlAction resolveMouseAction(MouseBinding binding, const ControlContext& context)
{
for (const MouseBindingEntry& entry : MOUSE_BINDINGS)
{
if (entry.binding != binding) { continue; }
if (!isConditionMet(entry.condition, context)) { continue; }
if (isControlActionAvailable(entry.action, context)) { return entry.action; }
}
return ControlAction::None;
}

View File

@@ -0,0 +1,164 @@
#pragma once
#include <vector>
#include <Qt>
#include "BuildModeController.h"
#include "BuildingType.h"
// The single statement of what the player can do right now, and which input does it
// (REQ-UI-CONTROLS-CONTENT, REQ-UI-CONTROLS-ACCURACY).
//
// This file declares actions; it never performs them and it never names them. It knows
// an action's bindings and the situations in which it does something -- nothing about
// the simulation, the widgets, the events an action ends up firing, or the words shown
// to the player. Display text lives in ui/ControlActionText.h, which formats the
// bindings this hands it, so a badge is derived from the real binding rather than
// typed beside it.
//
// Three readers, all of them consuming this and none of them extending it:
//
// * ControlsPanel calls getContextActions()/getAlwaysAvailableActions() and draws them.
// * InputMapper calls resolveKeyAction() and fires the event the action stands for.
// * GameWorldView calls resolveMouseAction() and runs the branch it already ran.
//
// Two bindings are deliberately absent. Build hotkeys (REQ-UI-HOTKEYS) are advertised
// on the build buttons instead of in the panel, and InputMapper::getBuildHotkeyLabel
// already derives their badges from the same table the handler switches on, so they
// have no drift to fix. F3/F4 are development controls and appear nowhere
// (REQ-UI-CONTROLS-ACCURACY).
//
// When bindings become player-configurable, only the binding tables in the .cpp turn
// from hard-coded data into loaded data. The actions, the availability rules, the
// panel, and every handler are unaffected.
enum class ControlAction
{
None, // no action is bound to the queried input in the queried context
// Always available (REQ-UI-CONTROLS-CONTENT).
Move,
GameSpeed,
TogglePause,
PasteTemporary,
OpenBlueprints,
OpenMenu,
// No build mode active.
Select,
SelectArea,
AddToSelection,
AddAreaToSelection,
EnterDeconstruct,
// No build mode active, with something selected.
CopyTemporary,
CreateBlueprint,
// Builder and blueprint placement mode.
Place,
ApplySettings,
PlaceBeltLine,
Rotate,
CancelBeltLine,
ExitMode,
// Deconstruct mode.
ToggleDeconstruct,
DeconstructArea
};
// The mouse gestures that carry a binding. Each is a whole gesture rather than a raw
// event: a drag is one binding, not a press plus a release, because that is the unit
// the player and the panel both think in. Which events make up the gesture, and the
// state it runs on, stay with the widget that owns them.
enum class MouseBinding
{
LeftClick,
LeftDrag,
CtrlLeftClick,
CtrlLeftDrag,
RightClick
};
// Which selection category is held, mirroring REQ-UI-SELECTION-CATEGORIES without
// depending on SelectionController.
enum class ControlSelection
{
None,
Buildings,
FieldObjects
};
// Which card the panel is showing (REQ-UI-CONTROLS-CONTENT). Named rather than
// spelled, so the heading text stays a presentation concern.
enum class ControlContextKind
{
General,
Selection,
Build,
Blueprint,
Deconstruct
};
// Everything the availability rules are allowed to depend on, as a plain snapshot.
//
// Taking a snapshot rather than references to the live controllers is what keeps this
// testable without a world, and it is what stops an action from reaching into the
// simulation: if a rule needs a fact, the fact is named here and the caller supplies it.
struct ControlContext
{
BuildMode mode = BuildMode::None;
BuildingType builderType = BuildingType::Belt; // while mode == Builder
bool draggingBelt = false;
// A single-building blueprint whose ghost is over a configuration-transfer target,
// so clicking hands over settings rather than placing (REQ-UI-BLUEPRINT-TRANSFER).
bool hoveredGhostIsTransfer = false;
ControlSelection selection = ControlSelection::None;
int selectionCount = 0;
// At least one selected building is player-placeable, the condition under which
// C and Ctrl+C do anything (REQ-UI-HOTKEYS).
bool placeableBuildingSelected = false;
bool temporaryBlueprintExists = false;
};
// One input an action answers to, in structured form so the badge can be rendered from
// it. `modifiers` is what the badge shows; matching is looser than equality, see
// resolveKeyAction.
struct ControlBinding
{
bool isMouse = false;
MouseBinding mouse = MouseBinding::LeftClick;
int key = 0; // Qt::Key_*, when !isMouse
Qt::KeyboardModifiers modifiers = Qt::NoModifier;
};
// True when triggering the action in this context would do what its label says. The
// panel shows exactly the available actions, and the resolvers return only available
// ones, which is REQ-UI-CONTROLS-ACCURACY expressed as one function.
bool isControlActionAvailable(ControlAction action, const ControlContext& context);
// The inputs an action answers to, in the order the panel should badge them.
// Context-dependent because a binding can be taken over: while a belt drag is in
// progress the right mouse button cancels the drag, so ExitMode is left with its key
// binding alone (REQ-BLD-BELT-DRAG).
std::vector<ControlBinding> getControlActionBindings(ControlAction action,
const ControlContext& context);
// Which card is showing, and the rows it holds -- the context's own, then the block
// available everywhere (REQ-UI-CONTROLS-CARD). Both lists are already filtered to the
// available actions and ordered as REQ-UI-CONTROLS-CONTENT lists them.
ControlContextKind getControlContextKind(const ControlContext& context);
std::vector<ControlAction> getContextActions(const ControlContext& context);
std::vector<ControlAction> getAlwaysAvailableActions(const ControlContext& context);
// The action a key press or a mouse gesture triggers here, or None when the input is
// unbound in this context. Both return only actions that are available, so a caller can
// act on the result without re-checking the situation.
//
// Rotation direction is not part of the action: R and Shift+R are one Rotate, and the
// caller reads the modifier for the direction, exactly as the digit of a build hotkey
// is read from the key. An action with a parameter keeps the parameter at the handler.
ControlAction resolveKeyAction(int key, Qt::KeyboardModifiers modifiers,
const ControlContext& context);
ControlAction resolveMouseAction(MouseBinding binding, const ControlContext& context);

View File

@@ -28,7 +28,7 @@ public:
void forEach(Func&& f) const; void forEach(Func&& f) const;
template <typename... Ts> template <typename... Ts>
bool hasAll(entt::entity entity); bool hasAll(entt::entity entity) const;
template <typename T> template <typename T>
T& get(entt::entity entity); T& get(entt::entity entity);
@@ -101,7 +101,7 @@ void EntityAdmin::forEach(Func&& f) const
} }
template <typename... Ts> template <typename... Ts>
bool EntityAdmin::hasAll(entt::entity entity) bool EntityAdmin::hasAll(entt::entity entity) const
{ {
return m_registry.all_of<Ts...>(entity); return m_registry.all_of<Ts...>(entity);
} }

View File

@@ -0,0 +1,76 @@
#include "FloatingPanelPlacement.h"
#include <algorithm>
int getAvailableBottomPx(const QRect& band, const std::vector<QRect>& occupiedRects,
int leftPx, int rightPx, int marginPx)
{
int bottomPx = band.bottom();
for (const QRect& occupied : occupiedRects)
{
if (occupied.isEmpty())
{
continue;
}
// Only what is actually in the way counts: a widget entirely to one side of this
// span is not below it, however tall it is.
if (occupied.right() < leftPx || occupied.left() > rightPx)
{
continue;
}
bottomPx = std::min(bottomPx, occupied.top() - marginPx - 1);
}
return bottomPx;
}
PanelSide chooseSide(const QRect& band, const QRect& anchorRect, int widthPx,
int marginPx)
{
// What each side offers: the gap between the anchor and that edge of the band, less
// the margin the panel keeps from the anchor.
const int roomRightPx = band.right() - anchorRect.right() - marginPx;
const int roomLeftPx = anchorRect.left() - band.left() - marginPx;
if (roomRightPx >= widthPx)
{
return PanelSide::Right;
}
if (roomLeftPx >= widthPx)
{
return PanelSide::Left;
}
// Neither side can hold it without covering the selection, so it goes where it
// covers the least of it.
return (roomRightPx >= roomLeftPx) ? PanelSide::Right : PanelSide::Left;
}
QRect placeBesideAnchor(const QRect& band, const QRect& anchorRect, PanelSide side,
QSize wantedSize, const std::vector<QRect>& occupiedRects,
int marginPx)
{
const int widthPx = std::min(wantedSize.width(), band.width());
// Against the anchor on the chosen side, growing away from it: the edge facing the
// selection is the one that stays put as the panel's content resizes.
int leftPx = (side == PanelSide::Right) ? anchorRect.right() + marginPx + 1
: anchorRect.left() - marginPx - widthPx;
// A panel that does not fit there is pushed back inside the view rather than hanging
// off it, which is what puts it over the selection when neither side had room.
leftPx = std::min(leftPx, band.right() - widthPx + 1);
leftPx = std::max(leftPx, band.left());
// Only the widgets its own column meets can shorten it.
const int bottomPx = getAvailableBottomPx(band, occupiedRects, leftPx,
leftPx + widthPx - 1, marginPx);
const int heightPx =
std::min(wantedSize.height(), std::max(0, bottomPx - band.top() + 1));
// Top-aligned with the anchor, then lifted by however much of it hangs below what is
// free. Never above the band: a panel taller than the space left is capped instead,
// and scrolls.
int topPx = std::max(anchorRect.top(), band.top());
topPx = std::min(topPx, bottomPx - heightPx + 1);
topPx = std::max(topPx, band.top());
return QRect(leftPx, topPx, widthPx, heightPx);
}

View File

@@ -0,0 +1,43 @@
#pragma once
#include <vector>
#include <QRect>
#include <QSize>
// Geometry for the widgets floating over the game world view (REQ-UI-WORLD-SIZE). Their
// owner places them in one ordered pass, each into the space the earlier ones left free,
// and these are the rules they place themselves by. Pure geometry -- no widget is
// involved, which is what lets the rules be tested without a display.
// The lowest bottom edge available to a widget occupying the horizontal span
// [leftPx, rightPx] inside band: the band's own bottom, or marginPx above the topmost
// occupied rectangle whose horizontal extent meets that span. A rectangle beside the
// span is not in the way and does not shorten it (REQ-UI-SELECTION-PANEL,
// REQ-UI-CONTROLS-PANEL). The result is inclusive, as QRect::bottom() is.
int getAvailableBottomPx(const QRect& band, const std::vector<QRect>& occupiedRects,
int leftPx, int rightPx, int marginPx);
// Which side of the selection the panel stands on (REQ-UI-SELECTION-PANEL).
enum class PanelSide
{
Right,
Left
};
// The side a panel widthPx wide takes beside anchorRect: the right of it where it fits
// within band, otherwise the left, and where it fits on neither, whichever side leaves
// more room -- the one case in which the panel ends up over the selection
// (REQ-UI-SELECTION-PANEL). Decided once when the selection starts and kept for as long
// as it lasts, so a card that grows later never flips the panel across the object.
PanelSide chooseSide(const QRect& band, const QRect& anchorRect, int widthPx,
int marginPx);
// Where a panel of wantedSize stands beside anchorRect on the given side: separated from
// it by marginPx and growing away from it, its top edge on the anchor's top edge, pushed
// inside band and above whatever occupies it. The returned height is short of
// wantedSize's when there was not enough room, which is the caller's cue to scroll its
// content (REQ-UI-SELECTION-PANEL).
QRect placeBesideAnchor(const QRect& band, const QRect& anchorRect, PanelSide side,
QSize wantedSize, const std::vector<QRect>& occupiedRects,
int marginPx);

View File

@@ -9,7 +9,9 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/BossWaveUpdatedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/BossWaveUpdatedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/SchematicChoicesAvailableEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/SchematicChoicesAvailableEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/SelectionChangedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/SelectionChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/SelectionAnchorChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/GameOverEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/GameOverEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/GameResetEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/WinEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/WinEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/ArtifactCountChangedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/ArtifactCountChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/UnlockedBuildingsChangedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/UnlockedBuildingsChangedEvent.h
@@ -31,7 +33,8 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/DeconstructModeToggleRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/DeconstructModeToggleRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintPlacementRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/BlueprintPlacementRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/ExitBlueprintModeRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/ExitBlueprintModeRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/TemporaryBlueprintRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/TemporaryBlueprintCaptureRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/TemporaryBlueprintPlaceRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/SpeedChangeRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/SpeedChangeRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/LayoutDialogRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/LayoutDialogRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionRequestedEvent.h
@@ -41,6 +44,7 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/BeamFiredEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/BeamFiredEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/DebugDrawToggledEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/DebugDrawToggledEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/CommandRequestedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/CommandRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/FloatingLayoutInvalidatedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/PlayerCommandsAppliedEvent.h ${CMAKE_CURRENT_SOURCE_DIR}/PlayerCommandsAppliedEvent.h
PARENT_SCOPE PARENT_SCOPE
) )

View File

@@ -0,0 +1,12 @@
#pragma once
#include "Event.h"
// Asks the owner of the widgets floating over the game world view to re-run its placement
// pass (see ui/FloatingPanel.h). Published by a floating widget whose content or
// visibility changed: what space that widget may take depends on the ones placed before
// it, so it cannot re-place itself alone (REQ-UI-BUILD-BAR, REQ-UI-CONTROLS-PANEL,
// REQ-UI-SELECTION-PANEL). Carries no payload -- the pass re-reads every widget.
class FloatingLayoutInvalidatedEvent : public Event
{
};

View File

@@ -0,0 +1,13 @@
#pragma once
#include "Event.h"
// Emitted once per restart, after a queued ResetCommand has been applied and the view has
// been reset for the new run (REQ-UI-GAME-MENU). It lets presentation state that does not
// live in the simulation -- e.g. the temporary blueprint, REQ-UI-BLUEPRINT-TEMP -- be
// dropped for the fresh run. Sent from GameWorldView::resetForNewGame(), which is where a
// restart actually lands: the escape menu, game over, and win dialogs only enqueue the
// command.
class GameResetEvent : public Event
{
};

View File

@@ -0,0 +1,25 @@
#pragma once
#include <QRect>
#include "Event.h"
// Where on the screen the selection that is about to be made sits: the bounds of the one
// object selected, or of all of them when the selection starts as a multi-selection
// (REQ-UI-SELECTION-PANEL). The rectangle is in the game world view's own widget
// coordinates.
//
// Published only when a selection *starts* -- a plain click or drag, or an additive one
// onto an empty selection -- and always immediately before the selection itself. Adding
// to a selection publishes nothing, which is what leaves the selection panel where it
// is while the selection grows; and because the rectangle is screen space frozen at that
// moment, scrolling the view or a selected ship flying off does not move the panel
// either.
class SelectionAnchorChangedEvent : public Event
{
public:
explicit SelectionAnchorChangedEvent(QRect rectPx)
: rectPx(rectPx) {}
const QRect rectPx;
};

View File

@@ -0,0 +1,9 @@
#pragma once
#include "Event.h"
// Emitted when the player presses C to capture a temporary blueprint (REQ-UI-BLUEPRINT-TEMP).
// Carries no payload: the blueprint is built from the current selection by the receiver.
class TemporaryBlueprintCaptureRequestedEvent : public Event
{
};

View File

@@ -0,0 +1,10 @@
#pragma once
#include "Event.h"
// Emitted when the player presses V to re-enter placement mode for the temporary blueprint
// captured with C (REQ-UI-BLUEPRINT-TEMP). Carries no payload: the receiver holds the
// blueprint, and nothing is captured from the current selection.
class TemporaryBlueprintPlaceRequestedEvent : public Event
{
};

View File

@@ -1,9 +0,0 @@
#pragma once
#include "Event.h"
// Emitted when the player presses the temporary-blueprint hotkey (REQ-UI-BLUEPRINT-TEMP).
// Carries no payload: the blueprint is built from the current selection by the receiver.
class TemporaryBlueprintRequestedEvent : public Event
{
};

View File

@@ -157,9 +157,9 @@ Blueprint captureBlueprintFromSelection(const Simulation& sim,
building.type = e.type; building.type = e.type;
building.rotation = e.rotation; building.rotation = e.rotation;
building.offset = e.anchor - center; building.offset = e.anchor - center;
// Recipe / schematic / layout / splitter-filter capture is shared with the // Recipe / schematic / layout / splitter-filter capture goes through
// copy-settings gesture (REQ-BLD-COPY-CONFIG) via readBuildingConfig, which // readBuildingConfig, which handles operational buildings and construction
// handles operational buildings and construction sites alike. // sites alike.
const std::optional<BuildingConfig> config = readBuildingConfig(sim, e.id); const std::optional<BuildingConfig> config = readBuildingConfig(sim, e.id);
if (config.has_value()) if (config.has_value())
{ {

View File

@@ -15,8 +15,8 @@ struct BuildingsConfig;
// The user-configurable settings of a single building or construction site: the // The user-configurable settings of a single building or construction site: the
// selected recipe / ship schematic, the shipyard module layout, and (for // selected recipe / ship schematic, the shipyard module layout, and (for
// splitters) the two output filters. Shared by the copy-settings gesture // splitters) the two output filters. This is what blueprint capture records per
// (REQ-BLD-COPY-CONFIG) and blueprint capture (REQ-UI-BLUEPRINT-STORAGE). // constituent building (REQ-UI-BLUEPRINT-STORAGE).
struct BuildingConfig struct BuildingConfig
{ {
BuildingType type = BuildingType::Miner; BuildingType type = BuildingType::Miner;

View File

@@ -284,6 +284,21 @@ void BuildingSystem::setShipLayout(FactoryState& state, BuildingId id, const Shi
{ {
if (building.id == id) if (building.id == id)
{ {
// No-op if the layout is unchanged, so re-applying the layout a shipyard
// already has does not cancel its production cycle or wipe its buffers
// (REQ-MAT-INPUT-BUFFER, REQ-BLD-SHIPYARD). Confirming the layout dialog
// without editing anything, and a blueprint configuration transfer onto an
// already-matching shipyard (REQ-UI-BLUEPRINT-TRANSFER), both land here.
// An unset layout counts as an empty one: the two are equivalent for
// buffers, production, and the spawned ship (see the spawn path below),
// so an empty layout arriving at an unconfigured shipyard changes nothing.
const bool unchanged = building.shipLayout.has_value()
? *building.shipLayout == layout
: layout.placedModules.empty();
if (unchanged)
{
return;
}
if (building.production.has_value()) if (building.production.has_value())
{ {
building.production = std::nullopt; building.production = std::nullopt;

View File

@@ -69,16 +69,9 @@ bool isPlacementValid(const FactoryState& state, const GameConfig& config,Buildi
} }
std::optional<BuildingId> findRotateInPlaceTarget(const FactoryState& state, const GameConfig& config, std::optional<CoincidingBuilding> findCoincidingSameTypeBuilding(const FactoryState& state,
BuildingType type, QPoint anchor, Rotation rot) const GameConfig& config, BuildingType type, QPoint anchor, Rotation rot)
{ {
// Tunnel Entries and Tunnel Exits cannot be rotated in place; re-orienting a
// tunnel requires deconstructing and re-placing it (REQ-BLD-ROTATE-IN-PLACE).
if (type == BuildingType::TunnelEntry || type == BuildingType::TunnelExit)
{
return std::nullopt;
}
const BuildingDef* def = config.buildings.findBuildingDef(type); const BuildingDef* def = config.buildings.findBuildingDef(type);
if (!def) { return std::nullopt; } if (!def) { return std::nullopt; }
@@ -106,20 +99,138 @@ std::optional<BuildingId> findRotateInPlaceTarget(const FactoryState& state, con
if (site.id != candidateId) { continue; } if (site.id != candidateId) { continue; }
if (site.type != type) { return std::nullopt; } if (site.type != type) { return std::nullopt; }
if (site.bodyCells.size() != mask.bodyCells.size()) { return std::nullopt; } if (site.bodyCells.size() != mask.bodyCells.size()) { return std::nullopt; }
return candidateId; return CoincidingBuilding{candidateId, site.rotation};
} }
for (const Building& b : state.buildings) for (const Building& b : state.buildings)
{ {
if (b.id != candidateId) { continue; } if (b.id != candidateId) { continue; }
if (b.type != type) { return std::nullopt; } if (b.type != type) { return std::nullopt; }
if (b.bodyCells.size() != mask.bodyCells.size()) { return std::nullopt; } if (b.bodyCells.size() != mask.bodyCells.size()) { return std::nullopt; }
return candidateId; return CoincidingBuilding{candidateId, b.rotation};
} }
return std::nullopt; return std::nullopt;
} }
std::optional<BuildingId> findRotateInPlaceTarget(const FactoryState& state, const GameConfig& config,
BuildingType type, QPoint anchor, Rotation rot)
{
// Tunnel Entries and Tunnel Exits cannot be rotated in place; re-orienting a
// tunnel requires deconstructing and re-placing it (REQ-BLD-ROTATE-IN-PLACE).
if (type == BuildingType::TunnelEntry || type == BuildingType::TunnelExit)
{
return std::nullopt;
}
const std::optional<CoincidingBuilding> target =
findCoincidingSameTypeBuilding(state, config, type, anchor, rot);
if (!target.has_value()) { return std::nullopt; }
return target->id;
}
namespace
{
// The building or construction site occupying `tile`, if it is of `type`, together with
// where it stands. The single-building transfer gesture hit-tests the cursor with this
// instead of comparing footprints (REQ-UI-BLUEPRINT-TRANSFER).
std::optional<CoincidingBuilding> findSameTypeBuildingAt(const FactoryState& state,
BuildingType type, QPoint tile,
QPoint& anchorOut)
{
const std::optional<BuildingId> owner = state.grid.findOwner(tile);
if (!owner.has_value()) { return std::nullopt; }
if (const ConstructionSite* site = findSite(state, *owner))
{
if (site->type != type) { return std::nullopt; }
anchorOut = site->anchor;
return CoincidingBuilding{site->id, site->rotation};
}
if (const Building* building = findBuilding(state, *owner))
{
if (building->type != type) { return std::nullopt; }
anchorOut = building->anchor;
return CoincidingBuilding{building->id, building->rotation};
}
return std::nullopt;
}
} // namespace
BlueprintGhostResolved resolveBlueprintGhost(const FactoryState& state, const GameConfig& config,
BuildingType type, QPoint anchor, Rotation rotation, std::optional<QPoint> hoverTile)
{
// The single-building gesture first, because it answers without looking at the
// ghost's own position at all: whatever same-type building the cursor is on takes the
// settings, at any facing, and the ghost snaps onto it (REQ-UI-BLUEPRINT-TRANSFER).
if (hoverTile.has_value() && isConfigurableBuildingType(type))
{
QPoint hoveredAnchor;
const std::optional<CoincidingBuilding> hovered =
findSameTypeBuildingAt(state, type, *hoverTile, hoveredAnchor);
if (hovered.has_value())
{
return BlueprintGhostResolved{BlueprintGhostAction::Transfer, hovered->id,
hoveredAnchor, hovered->rotation};
}
}
// Terrain and world bounds next: nothing rescues a ghost hanging off the asteroid
// (REQ-BLD-PLACE-VALID condition (a)).
if (!isPlacementValid(state, config, type, anchor, rotation))
{
return BlueprintGhostResolved{BlueprintGhostAction::Invalid, std::nullopt,
anchor, rotation};
}
const std::optional<CoincidingBuilding> coinciding =
findCoincidingSameTypeBuilding(state, config, type, anchor, rotation);
if (coinciding.has_value())
{
// The building the blueprint wants is already there, facing the same way. It
// takes the blueprint's settings if it has any to take (REQ-UI-BLUEPRINT-TRANSFER)
// and is otherwise left exactly as it is (REQ-UI-BLUEPRINT-OVERLAP). Tunnels are
// not excluded from the latter: nothing is rotated, so the reason for their
// REQ-BLD-ROTATE-IN-PLACE exception does not arise.
if (coinciding->rotation == rotation)
{
return BlueprintGhostResolved{isConfigurableBuildingType(type)
? BlueprintGhostAction::Transfer
: BlueprintGhostAction::CompatibleOverlap,
coinciding->id, anchor, rotation};
}
// Facing the other way, and placement may not re-orient it.
return BlueprintGhostResolved{BlueprintGhostAction::Invalid, std::nullopt,
anchor, rotation};
}
// No coincidence: any occupancy at all is an ordinary overlap
// (REQ-BLD-PLACE-VALID condition (b)).
const BuildingDef* def = config.buildings.findBuildingDef(type);
if (!def)
{
return BlueprintGhostResolved{BlueprintGhostAction::Invalid, std::nullopt,
anchor, rotation};
}
const ParsedSurfaceMask parsed = parseSurfaceMask(def->surfaceMask, rotation);
for (const QPoint& relativeCell : parsed.bodyCells)
{
if (isTileOccupied(state, anchor + relativeCell))
{
return BlueprintGhostResolved{BlueprintGhostAction::Invalid, std::nullopt,
anchor, rotation};
}
}
return BlueprintGhostResolved{BlueprintGhostAction::PlaceNew, std::nullopt,
anchor, rotation};
}
bool canPlaceBuilding(const FactoryState& state, const GameConfig& config, bool canPlaceBuilding(const FactoryState& state, const GameConfig& config,
BuildingType type, QPoint anchor, Rotation rotation) BuildingType type, QPoint anchor, Rotation rotation)
{ {

View File

@@ -30,9 +30,27 @@ bool bodyCellsWithinWorldBounds(const FactoryState& state, const GameConfig& con
bool isPlacementValid(const FactoryState& state, const GameConfig& config, bool isPlacementValid(const FactoryState& state, const GameConfig& config,
BuildingType type, QPoint anchor, Rotation rotation); BuildingType type, QPoint anchor, Rotation rotation);
// An existing building or site whose footprint a ghost exactly covers.
struct CoincidingBuilding
{
BuildingId id;
Rotation rotation;
};
// The building or site whose footprint a ghost of the given type/anchor/rotation
// exactly covers: same type, same body cells, a single owner. Operational buildings
// and construction sites alike. Rotation is not part of the test -- the target's own
// facing is reported so each caller can apply its own rule to it.
std::optional<CoincidingBuilding> findCoincidingSameTypeBuilding(const FactoryState& state,
const GameConfig& config,
BuildingType type,
QPoint anchor,
Rotation rot);
// The building or site that a ghost of the given type/anchor/rotation would // The building or site that a ghost of the given type/anchor/rotation would
// rotate in place rather than replace: same type, same body cells, one owner // rotate in place rather than replace: same type, same body cells, one owner
// (REQ-BLD-ROTATE-IN-PLACE). Tunnels never qualify. // (REQ-BLD-ROTATE-IN-PLACE). Tunnels never qualify. Builder mode only; blueprint
// placement mode never rotates anything -- see resolveBlueprintGhost.
std::optional<BuildingId> findRotateInPlaceTarget(const FactoryState& state, std::optional<BuildingId> findRotateInPlaceTarget(const FactoryState& state,
const GameConfig& config, const GameConfig& config,
BuildingType type, QPoint anchor, BuildingType type, QPoint anchor,
@@ -46,6 +64,48 @@ std::optional<BuildingId> findRotateInPlaceTarget(const FactoryState& state,
bool canPlaceBuilding(const FactoryState& state, const GameConfig& config, bool canPlaceBuilding(const FactoryState& state, const GameConfig& config,
BuildingType type, QPoint anchor, Rotation rotation); BuildingType type, QPoint anchor, Rotation rotation);
// What one ghost of a blueprint would do at its resolved tile.
enum class BlueprintGhostAction
{
PlaceNew, // free, valid cells: a new construction site, charged for
CompatibleOverlap, // the same building is already there: left untouched, free
// (REQ-UI-BLUEPRINT-OVERLAP)
Transfer, // hand this blueprint's settings to the building already there,
// free (REQ-UI-BLUEPRINT-TRANSFER)
Invalid // terrain, bounds, or an overlap that is neither of the above
};
struct BlueprintGhostResolved
{
BlueprintGhostAction action;
std::optional<BuildingId> targetId; // set for CompatibleOverlap and Transfer
// Where the ghost belongs on screen. The queried anchor and rotation, except at a
// hovered transfer target, where the ghost snaps onto the target so it shows what the
// click will act on (REQ-UI-BLUEPRINT-TRANSFER).
QPoint ghostAnchor;
Rotation ghostRotation;
};
// Classifies one ghost of a blueprint against the current factory state
// (REQ-UI-BLUEPRINT-OVERLAP, REQ-UI-BLUEPRINT-TRANSFER).
//
// `hoverTile` is set only for a blueprint holding exactly one building, and is then the
// tile under the cursor. That gesture is a copying tool rather than a layout, so it finds
// its transfer target by hit-testing the cursor instead of by footprint coincidence --
// without which a Shipyard could never be targeted at a different facing, its 4x2
// footprint covering entirely different tiles once rotated. Pass nullopt for a
// constellation, whose ghosts are judged purely by where the blueprint puts them. The
// size is read from the blueprint as stored, before locked types are dropped, so the
// gesture does not change behavior as the player unlocks things.
//
// Shared by the ghost coloring and the click path so a preview cannot disagree with what
// the click then does -- the same reason resolveBeltDragPath is shared.
BlueprintGhostResolved resolveBlueprintGhost(const FactoryState& state,
const GameConfig& config,
BuildingType type, QPoint anchor,
Rotation rotation,
std::optional<QPoint> hoverTile);
// What a belt drag would do to one tile of its path (REQ-BLD-BELT-DRAG). // What a belt drag would do to one tile of its path (REQ-BLD-BELT-DRAG).
enum class BeltTileAction enum class BeltTileAction
{ {

View File

@@ -45,9 +45,17 @@ bool recipeInputsAvailable(const Building& b, const RecipeDef& recipe)
} }
std::map<std::string, int> std::map<std::string, int>
computeShipyardRequiredMaterials(const GameConfig& config, const Building& b) computeShipyardRequiredMaterials(const GameConfig& config, const Building& b)
{
return computeShipyardRequiredMaterials(config, b.recipeId, b.shipLayout);
}
std::map<std::string, int>
computeShipyardRequiredMaterials(const GameConfig& config,
const std::string& recipeId,
const std::optional<ShipLayoutConfig>& shipLayout)
{ {
std::map<std::string, int> requiredMaterials; std::map<std::string, int> requiredMaterials;
const ShipDef* shipDef = config.ships.findShipDef(b.recipeId); const ShipDef* shipDef = config.ships.findShipDef(recipeId);
if (!shipDef) if (!shipDef)
{ {
return requiredMaterials; return requiredMaterials;
@@ -56,9 +64,9 @@ computeShipyardRequiredMaterials(const GameConfig& config, const Building& b)
{ {
requiredMaterials[ing.item] += ing.amount; requiredMaterials[ing.item] += ing.amount;
} }
if (b.shipLayout.has_value()) if (shipLayout.has_value())
{ {
for (const PlacedModule& pm : b.shipLayout->placedModules) for (const PlacedModule& pm : shipLayout->placedModules)
{ {
const ModuleDef* modDef = config.modules.findModuleDef(pm.moduleId); const ModuleDef* modDef = config.modules.findModuleDef(pm.moduleId);
if (!modDef) if (!modDef)

View File

@@ -38,6 +38,12 @@ bool recipeInputsAvailable(const Building& b, const RecipeDef& recipe);
std::map<std::string, int> computeShipyardRequiredMaterials(const GameConfig& config, std::map<std::string, int> computeShipyardRequiredMaterials(const GameConfig& config,
const Building& b); const Building& b);
// The same sum over a stored configuration rather than an operational building, so a
// construction site's schematic can be costed before it is built (REQ-BLD-SITE-CONFIG).
std::map<std::string, int> computeShipyardRequiredMaterials(
const GameConfig& config, const std::string& recipeId,
const std::optional<ShipLayoutConfig>& shipLayout);
// True when a production cycle could start right now, ignoring output-buffer space. // True when a production cycle could start right now, ignoring output-buffer space.
bool hasInputsToStart(const GameConfig& config, const Building& b); bool hasInputsToStart(const GameConfig& config, const Building& b);

View File

@@ -15,8 +15,23 @@ struct PlacedModule
Rotation rotation; Rotation rotation;
}; };
inline bool operator==(const PlacedModule& a, const PlacedModule& b)
{
return a.moduleId == b.moduleId && a.position == b.position && a.rotation == b.rotation;
}
// The complete module configuration for a shipyard's current ship (REQ-MOD-CONFIG). // The complete module configuration for a shipyard's current ship (REQ-MOD-CONFIG).
struct ShipLayoutConfig struct ShipLayoutConfig
{ {
std::vector<PlacedModule> placedModules; std::vector<PlacedModule> placedModules;
}; };
// Deliberately order-sensitive: two layouts holding the same modules in a different
// vector order compare unequal. This only decides whether applying a layout is a no-op
// (REQ-MAT-INPUT-BUFFER), so the conservative answer is the safe one -- reporting a
// change that is not one costs a buffer reset, reporting no change when there is one
// would leave the shipyard stale.
inline bool operator==(const ShipLayoutConfig& a, const ShipLayoutConfig& b)
{
return a.placedModules == b.placedModules;
}

View File

@@ -16,10 +16,10 @@
#include "SimulationTestAccess.h" #include "SimulationTestAccess.h"
#include "TestConfig.h" #include "TestConfig.h"
// readBuildingConfig underpins the copy-settings gesture (REQ-BLD-COPY-CONFIG): // readBuildingConfig underpins blueprint capture (REQ-UI-BLUEPRINT-STORAGE): it
// it extracts a building's recipe / schematic / layout / splitter filters so they // extracts a building's recipe / schematic / layout / splitter filters so they can be
// can be stamped onto a same-type building. It reads operational buildings and // stored in the blueprint and reapplied on placement. It reads operational buildings
// construction sites alike. // and construction sites alike.
namespace namespace
{ {
@@ -60,7 +60,7 @@ const ShipDef* findAvailableSchematic(const GameConfig& cfg)
} }
} // namespace } // namespace
TEST_CASE("readBuildingConfig returns a miner's selected recipe", "[copyconfig]") TEST_CASE("readBuildingConfig returns a miner's selected recipe", "[blueprint]")
{ {
const GameConfig cfg = loadTestConfig(); const GameConfig cfg = loadTestConfig();
Simulation sim(loadTestConfig(), 7); Simulation sim(loadTestConfig(), 7);
@@ -78,7 +78,7 @@ TEST_CASE("readBuildingConfig returns a miner's selected recipe", "[copyconfig]"
} }
TEST_CASE("readBuildingConfig leaves recipe unset when nothing is selected", TEST_CASE("readBuildingConfig leaves recipe unset when nothing is selected",
"[copyconfig]") "[blueprint]")
{ {
const GameConfig cfg = loadTestConfig(); const GameConfig cfg = loadTestConfig();
Simulation sim(loadTestConfig(), 7); Simulation sim(loadTestConfig(), 7);
@@ -93,7 +93,7 @@ TEST_CASE("readBuildingConfig leaves recipe unset when nothing is selected",
} }
TEST_CASE("readBuildingConfig returns a shipyard's schematic and layout", TEST_CASE("readBuildingConfig returns a shipyard's schematic and layout",
"[copyconfig]") "[blueprint]")
{ {
const GameConfig cfg = loadTestConfig(); const GameConfig cfg = loadTestConfig();
Simulation sim(loadTestConfig(), 7); Simulation sim(loadTestConfig(), 7);
@@ -103,17 +103,28 @@ TEST_CASE("readBuildingConfig returns a shipyard's schematic and layout",
const BuildingId id = placeOperational(sim, cfg, BuildingType::Shipyard, QPoint(0, 0)); const BuildingId id = placeOperational(sim, cfg, BuildingType::Shipyard, QPoint(0, 0));
SimulationTestAccess::buildings(sim).setRecipe(SimulationTestAccess::state(sim), id, schematic->id); SimulationTestAccess::buildings(sim).setRecipe(SimulationTestAccess::state(sim), id, schematic->id);
SimulationTestAccess::buildings(sim).setShipLayout(SimulationTestAccess::state(sim), id, ShipLayoutConfig{});
// A real layout, not an empty one: applying an empty layout to a shipyard that has
// none is a no-op (REQ-MAT-INPUT-BUFFER), so it would leave nothing to read back.
ShipLayoutConfig layout;
PlacedModule placed;
placed.moduleId = "armor_plate";
placed.position = QPoint(0, 0);
placed.rotation = Rotation::East;
layout.placedModules.push_back(placed);
SimulationTestAccess::buildings(sim).setShipLayout(SimulationTestAccess::state(sim), id, layout);
const std::optional<BuildingConfig> config = readBuildingConfig(sim, id); const std::optional<BuildingConfig> config = readBuildingConfig(sim, id);
REQUIRE(config.has_value()); REQUIRE(config.has_value());
CHECK(config->type == BuildingType::Shipyard); CHECK(config->type == BuildingType::Shipyard);
REQUIRE(config->recipeId.has_value()); REQUIRE(config->recipeId.has_value());
CHECK(*config->recipeId == schematic->id); CHECK(*config->recipeId == schematic->id);
CHECK(config->shipLayout.has_value()); REQUIRE(config->shipLayout.has_value());
REQUIRE(config->shipLayout->placedModules.size() == 1);
CHECK(config->shipLayout->placedModules[0].moduleId == "armor_plate");
} }
TEST_CASE("readBuildingConfig reads a queued construction site", "[copyconfig]") TEST_CASE("readBuildingConfig reads a queued construction site", "[blueprint]")
{ {
const GameConfig cfg = loadTestConfig(); const GameConfig cfg = loadTestConfig();
Simulation sim(loadTestConfig(), 7); Simulation sim(loadTestConfig(), 7);
@@ -134,7 +145,7 @@ TEST_CASE("readBuildingConfig reads a queued construction site", "[copyconfig]")
CHECK(*config->recipeId == "mine_iron_ore"); CHECK(*config->recipeId == "mine_iron_ore");
} }
TEST_CASE("readBuildingConfig returns nullopt for an unknown id", "[copyconfig]") TEST_CASE("readBuildingConfig returns nullopt for an unknown id", "[blueprint]")
{ {
Simulation sim(loadTestConfig(), 7); Simulation sim(loadTestConfig(), 7);
CHECK_FALSE(readBuildingConfig(sim, kInvalidBuildingId).has_value()); CHECK_FALSE(readBuildingConfig(sim, kInvalidBuildingId).has_value());

View File

@@ -1039,6 +1039,292 @@ TEST_CASE("BuildingSystem: findRotateInPlaceTarget works for a symmetric multi-t
REQUIRE(*result == id); REQUIRE(*result == id);
} }
// ---------------------------------------------------------------------------
// resolveBlueprintGhost
// ---------------------------------------------------------------------------
// What a blueprint ghost does where it meets an existing building
// (REQ-UI-BLUEPRINT-OVERLAP, REQ-UI-BLUEPRINT-TRANSFER). Blueprint placement never
// rotates anything, so a coinciding building must either take the blueprint's settings
// or already match it exactly.
namespace
{
// A single-building blueprint, whose cursor sits on the ghost's own anchor unless a test
// says otherwise. That gesture hit-tests the cursor for its transfer target.
BlueprintGhostResolved resolveOne(const PlacementFixture& f, BuildingType type,
QPoint anchor, Rotation rotation)
{
return resolveBlueprintGhost(f.state, f.cfg, type, anchor, rotation, anchor);
}
BlueprintGhostResolved resolveOneHovering(const PlacementFixture& f, BuildingType type,
QPoint anchor, Rotation rotation, QPoint cursorTile)
{
return resolveBlueprintGhost(f.state, f.cfg, type, anchor, rotation, cursorTile);
}
// One ghost of a constellation: no cursor hit-test, judged purely on where it sits.
BlueprintGhostResolved resolveInConstellation(const PlacementFixture& f, BuildingType type,
QPoint anchor, Rotation rotation)
{
return resolveBlueprintGhost(f.state, f.cfg, type, anchor, rotation, std::nullopt);
}
} // namespace
TEST_CASE("isConfigurableBuildingType: only types with player-facing settings",
"[blueprint]")
{
// The gate on whether a single-building blueprint transfers anything at all.
CHECK(isConfigurableBuildingType(BuildingType::Miner));
CHECK(isConfigurableBuildingType(BuildingType::Assembler));
CHECK(isConfigurableBuildingType(BuildingType::Shipyard));
CHECK(isConfigurableBuildingType(BuildingType::Splitter));
// Smelter and Reprocessing Plant run implicit recipes (REQ-BLD-SMELTER,
// REQ-BLD-REPROCESSING) and the rest have no settings whatsoever.
CHECK_FALSE(isConfigurableBuildingType(BuildingType::Smelter));
CHECK_FALSE(isConfigurableBuildingType(BuildingType::ReprocessingPlant));
CHECK_FALSE(isConfigurableBuildingType(BuildingType::SalvageBay));
CHECK_FALSE(isConfigurableBuildingType(BuildingType::Belt));
CHECK_FALSE(isConfigurableBuildingType(BuildingType::TunnelEntry));
CHECK_FALSE(isConfigurableBuildingType(BuildingType::TunnelExit));
CHECK_FALSE(isConfigurableBuildingType(BuildingType::Hq));
}
TEST_CASE("resolveBlueprintGhost: free valid cells place a new building", "[blueprint]")
{
PlacementFixture f;
// Anchored on the asteroid (x < 0): a miner is all-asteroid cells. BuildingSystem's
// place() skips the terrain rules, but resolveBlueprintGhost applies them.
const BlueprintGhostResolved resolved =
resolveOne(f, BuildingType::Miner, QPoint(-2, 0), Rotation::East);
CHECK(resolved.action == BlueprintGhostAction::PlaceNew);
CHECK_FALSE(resolved.targetId.has_value());
}
TEST_CASE("resolveBlueprintGhost: terrain-invalid positions are invalid", "[blueprint]")
{
PlacementFixture f;
// A miner is all-asteroid (A) cells, so it cannot sit out in space (x >= 0).
CHECK(resolveOne(f, BuildingType::Miner, QPoint(5, 0), Rotation::East).action
== BlueprintGhostAction::Invalid);
}
TEST_CASE("resolveBlueprintGhost: overlapping a different building type is invalid",
"[blueprint]")
{
PlacementFixture f;
f.bs.place(f.state, BuildingType::Belt, QPoint(-1, 0), Rotation::East, 0);
CHECK(resolveOne(f, BuildingType::Splitter, QPoint(-1, 0), Rotation::East).action
== BlueprintGhostAction::Invalid);
}
TEST_CASE("resolveBlueprintGhost: a partial overlap of the same type is invalid",
"[blueprint]")
{
PlacementFixture f;
// Smelter at (-3,0) covers (-3,0),(-2,0),(-3,1),(-2,1); a ghost at (-2,0) covers only
// two of those, so it coincides with nothing and is an ordinary occupied overlap.
// Both footprints stay on the asteroid, so terrain is not what fails here.
f.bs.place(f.state, BuildingType::Smelter, QPoint(-3, 0), Rotation::East, 0);
CHECK(resolveOne(f, BuildingType::Smelter, QPoint(-2, 0), Rotation::East).action
== BlueprintGhostAction::Invalid);
}
TEST_CASE("resolveBlueprintGhost: a single configurable building transfers its settings",
"[blueprint]")
{
PlacementFixture f;
const BuildingId id =
f.bs.place(f.state, BuildingType::Miner, QPoint(-2, 0), Rotation::East, 0).value();
const BlueprintGhostResolved resolved =
resolveOne(f, BuildingType::Miner, QPoint(-2, 0), Rotation::East);
REQUIRE(resolved.action == BlueprintGhostAction::Transfer);
REQUIRE(resolved.targetId.has_value());
CHECK(*resolved.targetId == id);
}
TEST_CASE("resolveBlueprintGhost: a transfer ignores the target's rotation", "[blueprint]")
{
// A transfer never rotates anything, so which way the target faces cannot matter
// (REQ-UI-BLUEPRINT-TRANSFER). The ghost snaps to the target's facing rather than
// keeping the blueprint's.
PlacementFixture f;
const BuildingId id =
f.bs.place(f.state, BuildingType::Splitter, QPoint(-1, 0), Rotation::East, 0).value();
const BlueprintGhostResolved resolved =
resolveOne(f, BuildingType::Splitter, QPoint(-1, 0), Rotation::North);
REQUIRE(resolved.action == BlueprintGhostAction::Transfer);
REQUIRE(resolved.targetId.has_value());
CHECK(*resolved.targetId == id);
CHECK(resolved.ghostRotation == Rotation::East);
}
TEST_CASE("resolveBlueprintGhost: a single-building blueprint transfers from anywhere on the target",
"[blueprint]")
{
// The point of hit-testing the cursor instead of comparing footprints. Coincidence
// needs the ghost's anchor to land on the target's own anchor, so with a 2x2 body
// three of its four tiles missed and read as an ordinary overlap. Hovering any body
// tile now targets it, and the ghost snaps onto the building
// (REQ-UI-BLUEPRINT-TRANSFER).
PlacementFixture f;
// Assembler body covers (-3,0),(-2,0),(-3,1),(-2,1); its anchor is (-3,0).
const BuildingId id =
f.bs.place(f.state, BuildingType::Assembler, QPoint(-3, 0), Rotation::East, 0).value();
const QPoint offAnchorTile(-2, 1);
const BlueprintGhostResolved resolved =
resolveOneHovering(f, BuildingType::Assembler, offAnchorTile, Rotation::East,
offAnchorTile);
REQUIRE(resolved.action == BlueprintGhostAction::Transfer);
CHECK(*resolved.targetId == id);
CHECK(resolved.ghostAnchor == QPoint(-3, 0));
// The same misaligned ghost inside a constellation still just overlaps invalidly:
// a layout is placed where the blueprint puts it, and nothing snaps.
CHECK(resolveInConstellation(f, BuildingType::Assembler, offAnchorTile, Rotation::East).action
== BlueprintGhostAction::Invalid);
}
TEST_CASE("resolveBlueprintGhost: hovering a different building type does not transfer",
"[blueprint]")
{
PlacementFixture f;
f.bs.place(f.state, BuildingType::Smelter, QPoint(-3, 0), Rotation::East, 0);
// A miner blueprint over a smelter: the cursor hit-test only matches its own type.
CHECK(resolveOne(f, BuildingType::Miner, QPoint(-3, 0), Rotation::East).action
== BlueprintGhostAction::Invalid);
}
TEST_CASE("resolveBlueprintGhost: a construction site is a transfer target too",
"[blueprint]")
{
PlacementFixture f;
// Not ticked to completion, so it is still queued (REQ-BLD-SITE-CONFIG).
const BuildingId id =
f.bs.place(f.state, BuildingType::Assembler, QPoint(-3, 0), Rotation::East, 0).value();
REQUIRE_FALSE(getAllSites(f.state).empty());
const BlueprintGhostResolved resolved =
resolveOne(f, BuildingType::Assembler, QPoint(-3, 0), Rotation::East);
REQUIRE(resolved.action == BlueprintGhostAction::Transfer);
CHECK(*resolved.targetId == id);
}
TEST_CASE("resolveBlueprintGhost: a single building with no settings overlaps instead",
"[blueprint]")
{
// A belt carries nothing to transfer, so the same footprint is a compatible overlap
// when the facings match -- and invalid when they do not, since nothing here may
// re-orient it (REQ-UI-BLUEPRINT-OVERLAP).
PlacementFixture f;
const BuildingId id =
f.bs.place(f.state, BuildingType::Belt, QPoint(-1, 0), Rotation::East, 0).value();
const BlueprintGhostResolved matching =
resolveOne(f, BuildingType::Belt, QPoint(-1, 0), Rotation::East);
REQUIRE(matching.action == BlueprintGhostAction::CompatibleOverlap);
CHECK(*matching.targetId == id);
CHECK(resolveOne(f, BuildingType::Belt, QPoint(-1, 0), Rotation::North).action
== BlueprintGhostAction::Invalid);
}
TEST_CASE("resolveBlueprintGhost: a constellation transfers onto a matching building",
"[blueprint]")
{
// Blueprint size does not gate the transfer itself: a configurable building already
// standing where the blueprint wants it, facing the same way, takes its settings
// whatever else the blueprint holds (REQ-UI-BLUEPRINT-TRANSFER).
PlacementFixture f;
const BuildingId id =
f.bs.place(f.state, BuildingType::Miner, QPoint(-2, 0), Rotation::East, 0).value();
const BlueprintGhostResolved resolved =
resolveInConstellation(f, BuildingType::Miner, QPoint(-2, 0), Rotation::East);
REQUIRE(resolved.action == BlueprintGhostAction::Transfer);
CHECK(*resolved.targetId == id);
}
TEST_CASE("resolveBlueprintGhost: a constellation still requires a matching rotation",
"[blueprint]")
{
// Only the single-building gesture is forgiving about facing. A constellation's
// ghosts stay where the blueprint puts them, and one that cannot be re-oriented to
// match blocks the whole placement (REQ-UI-BLUEPRINT-OVERLAP).
PlacementFixture f;
f.bs.place(f.state, BuildingType::Splitter, QPoint(-1, 0), Rotation::East, 0);
CHECK(resolveInConstellation(f, BuildingType::Splitter, QPoint(-1, 0), Rotation::North).action
== BlueprintGhostAction::Invalid);
}
TEST_CASE("resolveBlueprintGhost: a constellation mixes transfers and plain overlaps",
"[blueprint]")
{
// One drop can reconfigure some of the buildings already there while leaving others
// alone: the split is by whether the type has settings at all, not by blueprint size
// (REQ-UI-BLUEPRINT-OVERLAP).
PlacementFixture f;
const BuildingId minerId =
f.bs.place(f.state, BuildingType::Miner, QPoint(-2, 0), Rotation::East, 0).value();
const BuildingId smelterId =
f.bs.place(f.state, BuildingType::Smelter, QPoint(-5, 0), Rotation::East, 0).value();
const BlueprintGhostResolved miner =
resolveInConstellation(f, BuildingType::Miner, QPoint(-2, 0), Rotation::East);
REQUIRE(miner.action == BlueprintGhostAction::Transfer);
CHECK(*miner.targetId == minerId);
// A smelter runs an implicit recipe (REQ-BLD-SMELTER), so there is nothing to hand
// over and it is simply left as it is.
const BlueprintGhostResolved smelter =
resolveInConstellation(f, BuildingType::Smelter, QPoint(-5, 0), Rotation::East);
REQUIRE(smelter.action == BlueprintGhostAction::CompatibleOverlap);
CHECK(*smelter.targetId == smelterId);
}
TEST_CASE("resolveBlueprintGhost: an identical tunnel is a compatible overlap", "[blueprint]")
{
// findRotateInPlaceTarget refuses tunnels because re-orienting one is unsupported.
// Nothing is re-oriented here, so that reason does not apply and the tunnel the
// blueprint wants -- already there, same facing -- is simply left alone.
PlacementFixture f;
const BuildingId id =
f.bs.place(f.state, BuildingType::TunnelEntry, QPoint(-1, 0), Rotation::East, 0).value();
f.bs.place(f.state, BuildingType::TunnelExit, QPoint(-2, 0), Rotation::East, 0);
REQUIRE_FALSE(
findRotateInPlaceTarget(f.state, f.cfg, BuildingType::TunnelEntry, QPoint(-1, 0), Rotation::East)
.has_value());
const BlueprintGhostResolved resolved =
resolveInConstellation(f, BuildingType::TunnelEntry, QPoint(-1, 0), Rotation::East);
REQUIRE(resolved.action == BlueprintGhostAction::CompatibleOverlap);
CHECK(*resolved.targetId == id);
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// rotateInPlace // rotateInPlace
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------

View File

@@ -14,8 +14,10 @@ add_files(
TunnelCompletionTest.cpp TunnelCompletionTest.cpp
WorldCoordinatesTest.cpp WorldCoordinatesTest.cpp
WorldCameraTest.cpp WorldCameraTest.cpp
FloatingPanelPlacementTest.cpp
SelectionControllerTest.cpp SelectionControllerTest.cpp
BuildModeControllerTest.cpp BuildModeControllerTest.cpp
ControlActionTest.cpp
BuildingTest.cpp BuildingTest.cpp
BuildingConfigTest.cpp BuildingConfigTest.cpp
ShipTest.cpp ShipTest.cpp

View File

@@ -0,0 +1,328 @@
#include "catch.hpp"
#include <algorithm>
#include <vector>
#include "BuildModeController.h"
#include "BuildingType.h"
#include "ControlAction.h"
// REQ-UI-CONTROLS-ACCURACY. The panel and the input handling read one table, and these
// tests are what makes that pay: the round-trip case below fails the moment a row is
// shown whose binding resolves elsewhere, which is the drift the whole design exists to
// prevent. Everything here works on action ids -- the display strings live in the ui
// target and are not what can silently go wrong.
namespace
{
ControlContext generalContext()
{
return ControlContext();
}
ControlContext selectionContext(bool placeable = true)
{
ControlContext context;
context.selection = ControlSelection::Buildings;
context.selectionCount = 3;
context.placeableBuildingSelected = placeable;
return context;
}
ControlContext builderContext(BuildingType type)
{
ControlContext context;
context.mode = BuildMode::Builder;
context.builderType = type;
return context;
}
ControlContext blueprintContext(bool transfer = false)
{
ControlContext context;
context.mode = BuildMode::Blueprint;
context.hoveredGhostIsTransfer = transfer;
return context;
}
ControlContext deconstructContext()
{
ControlContext context;
context.mode = BuildMode::Deconstruct;
return context;
}
// A spread wide enough that every availability rule and every binding condition is
// exercised by the whole-table properties below.
std::vector<ControlContext> allContexts()
{
ControlContext beltDragging = builderContext(BuildingType::Belt);
beltDragging.draggingBelt = true;
ControlContext generalWithBlueprint = generalContext();
generalWithBlueprint.temporaryBlueprintExists = true;
ControlContext fieldSelection = selectionContext(false);
fieldSelection.selection = ControlSelection::FieldObjects;
return {generalContext(),
generalWithBlueprint,
selectionContext(),
fieldSelection,
builderContext(BuildingType::Belt),
builderContext(BuildingType::Assembler),
beltDragging,
blueprintContext(false),
blueprintContext(true),
deconstructContext()};
}
std::vector<ControlAction> shownActions(const ControlContext& context)
{
std::vector<ControlAction> actions = getContextActions(context);
const std::vector<ControlAction> always = getAlwaysAvailableActions(context);
actions.insert(actions.end(), always.begin(), always.end());
return actions;
}
bool contains(const std::vector<ControlAction>& actions, ControlAction action)
{
return std::find(actions.begin(), actions.end(), action) != actions.end();
}
} // namespace
TEST_CASE("ControlAction: every shown row is available", "[controls]")
{
for (const ControlContext& context : allContexts())
{
for (ControlAction action : shownActions(context))
{
REQUIRE(isControlActionAvailable(action, context));
}
}
}
TEST_CASE("ControlAction: no row is shown twice", "[controls]")
{
for (const ControlContext& context : allContexts())
{
std::vector<ControlAction> actions = shownActions(context);
std::vector<ControlAction> unique = actions;
std::sort(unique.begin(), unique.end());
unique.erase(std::unique(unique.begin(), unique.end()), unique.end());
REQUIRE(unique.size() == actions.size());
}
}
// The core anti-drift property: a row's badges are rendered from its bindings, so every
// binding a row advertises must actually trigger that row's action in that same context.
TEST_CASE("ControlAction: every advertised binding resolves back to its own action",
"[controls]")
{
for (const ControlContext& context : allContexts())
{
for (ControlAction action : shownActions(context))
{
const std::vector<ControlBinding> bindings =
getControlActionBindings(action, context);
REQUIRE_FALSE(bindings.empty());
for (const ControlBinding& binding : bindings)
{
if (binding.isMouse)
{
REQUIRE(resolveMouseAction(binding.mouse, context) == action);
}
else
{
REQUIRE(resolveKeyAction(binding.key, binding.modifiers, context)
== action);
}
}
}
}
}
// The other direction: an input that resolves to something must resolve to an action
// that is actually available there, so no input can trigger a no-op. This is weaker
// than "must be a shown row" on purpose -- a context may omit an available binding
// (Ctrl+click in the General context), which REQ-UI-CONTROLS-ACCURACY permits; what it
// may never do is act on an unavailable one.
TEST_CASE("ControlAction: every resolvable input is available", "[controls]")
{
const std::vector<MouseBinding> mouseBindings = {
MouseBinding::LeftClick, MouseBinding::LeftDrag, MouseBinding::CtrlLeftClick,
MouseBinding::CtrlLeftDrag, MouseBinding::RightClick};
for (const ControlContext& context : allContexts())
{
for (MouseBinding binding : mouseBindings)
{
const ControlAction action = resolveMouseAction(binding, context);
if (action != ControlAction::None)
{
REQUIRE(isControlActionAvailable(action, context));
}
}
const std::vector<int> keys = {Qt::Key_A, Qt::Key_D, Qt::Key_W, Qt::Key_S,
Qt::Key_Space, Qt::Key_C, Qt::Key_V, Qt::Key_R,
Qt::Key_Q, Qt::Key_Escape};
for (int key : keys)
{
for (Qt::KeyboardModifiers modifiers :
{Qt::KeyboardModifiers(Qt::NoModifier),
Qt::KeyboardModifiers(Qt::ShiftModifier),
Qt::KeyboardModifiers(Qt::ControlModifier)})
{
const ControlAction action = resolveKeyAction(key, modifiers, context);
if (action != ControlAction::None)
{
REQUIRE(isControlActionAvailable(action, context));
}
}
}
}
}
TEST_CASE("ControlAction: contexts are named by mode and selection", "[controls]")
{
REQUIRE(getControlContextKind(generalContext()) == ControlContextKind::General);
REQUIRE(getControlContextKind(selectionContext()) == ControlContextKind::Selection);
REQUIRE(getControlContextKind(builderContext(BuildingType::Belt))
== ControlContextKind::Build);
REQUIRE(getControlContextKind(blueprintContext()) == ControlContextKind::Blueprint);
REQUIRE(getControlContextKind(deconstructContext())
== ControlContextKind::Deconstruct);
}
TEST_CASE("ControlAction: Q enters deconstruct mode, or leaves the active one",
"[controls]")
{
REQUIRE(resolveKeyAction(Qt::Key_Q, Qt::NoModifier, generalContext())
== ControlAction::EnterDeconstruct);
REQUIRE(resolveKeyAction(Qt::Key_Q, Qt::NoModifier, selectionContext())
== ControlAction::EnterDeconstruct);
REQUIRE(resolveKeyAction(Qt::Key_Q, Qt::NoModifier, builderContext(BuildingType::Belt))
== ControlAction::ExitMode);
REQUIRE(resolveKeyAction(Qt::Key_Q, Qt::NoModifier, blueprintContext())
== ControlAction::ExitMode);
REQUIRE(resolveKeyAction(Qt::Key_Q, Qt::NoModifier, deconstructContext())
== ControlAction::ExitMode);
}
TEST_CASE("ControlAction: Ctrl distinguishes the chords, other modifiers do not",
"[controls]")
{
const ControlContext context = selectionContext();
REQUIRE(resolveKeyAction(Qt::Key_C, Qt::NoModifier, context)
== ControlAction::CopyTemporary);
REQUIRE(resolveKeyAction(Qt::Key_C, Qt::ControlModifier, context)
== ControlAction::CreateBlueprint);
REQUIRE(resolveKeyAction(Qt::Key_V, Qt::ControlModifier, context)
== ControlAction::OpenBlueprints);
// Shift+A must still pan, as it always has -- matching modifiers exactly instead of
// testing Ctrl alone would silently swallow the press.
REQUIRE(resolveKeyAction(Qt::Key_A, Qt::ShiftModifier, context) == ControlAction::Move);
REQUIRE(resolveKeyAction(Qt::Key_R, Qt::ShiftModifier, blueprintContext())
== ControlAction::Rotate);
}
TEST_CASE("ControlAction: a transfer target turns the click into Apply settings",
"[controls]")
{
const ControlContext plain = blueprintContext(false);
const ControlContext transfer = blueprintContext(true);
REQUIRE(resolveMouseAction(MouseBinding::LeftClick, plain) == ControlAction::Place);
REQUIRE(resolveMouseAction(MouseBinding::LeftClick, transfer)
== ControlAction::ApplySettings);
REQUIRE(contains(getContextActions(plain), ControlAction::Place));
REQUIRE_FALSE(contains(getContextActions(plain), ControlAction::ApplySettings));
REQUIRE(contains(getContextActions(transfer), ControlAction::ApplySettings));
REQUIRE_FALSE(contains(getContextActions(transfer), ControlAction::Place));
}
TEST_CASE("ControlAction: a belt drag takes the right mouse button from ExitMode",
"[controls]")
{
ControlContext dragging = builderContext(BuildingType::Belt);
dragging.draggingBelt = true;
const ControlContext idle = builderContext(BuildingType::Belt);
REQUIRE(resolveMouseAction(MouseBinding::RightClick, idle) == ControlAction::ExitMode);
REQUIRE(resolveMouseAction(MouseBinding::RightClick, dragging)
== ControlAction::CancelBeltLine);
// Q still leaves the mode outright while the drag runs, so ExitMode stays shown --
// with its right-click badge dropped, since the button now means something else.
REQUIRE(resolveKeyAction(Qt::Key_Q, Qt::NoModifier, dragging) == ControlAction::ExitMode);
const std::vector<ControlBinding> idleBindings =
getControlActionBindings(ControlAction::ExitMode, idle);
const std::vector<ControlBinding> dragBindings =
getControlActionBindings(ControlAction::ExitMode, dragging);
REQUIRE(idleBindings.size() == 2);
REQUIRE(dragBindings.size() == 1);
REQUIRE_FALSE(dragBindings.front().isMouse);
}
TEST_CASE("ControlAction: dragging a line is offered for belts only", "[controls]")
{
REQUIRE(resolveMouseAction(MouseBinding::LeftDrag, builderContext(BuildingType::Belt))
== ControlAction::PlaceBeltLine);
REQUIRE(resolveMouseAction(MouseBinding::LeftDrag,
builderContext(BuildingType::Assembler))
== ControlAction::None);
REQUIRE(resolveMouseAction(MouseBinding::LeftDrag, blueprintContext())
== ControlAction::None);
}
TEST_CASE("ControlAction: blueprint keys are offered only where they do something",
"[controls]")
{
// V does nothing until C has captured something (REQ-UI-BLUEPRINT-TEMP).
ControlContext withBlueprint = generalContext();
withBlueprint.temporaryBlueprintExists = true;
REQUIRE_FALSE(contains(shownActions(generalContext()), ControlAction::PasteTemporary));
REQUIRE(contains(shownActions(withBlueprint), ControlAction::PasteTemporary));
REQUIRE(resolveKeyAction(Qt::Key_V, Qt::NoModifier, generalContext())
== ControlAction::None);
// C and Ctrl+C need a selection holding something placeable (REQ-UI-HOTKEYS).
ControlContext fieldSelection = selectionContext(false);
fieldSelection.selection = ControlSelection::FieldObjects;
REQUIRE(contains(getContextActions(selectionContext()), ControlAction::CopyTemporary));
REQUIRE_FALSE(contains(getContextActions(fieldSelection), ControlAction::CopyTemporary));
REQUIRE(resolveKeyAction(Qt::Key_C, Qt::NoModifier, fieldSelection)
== ControlAction::None);
// Ctrl+V opens the dialog whatever is going on (REQ-UI-HOTKEYS).
for (const ControlContext& context : allContexts())
{
REQUIRE(resolveKeyAction(Qt::Key_V, Qt::ControlModifier, context)
== ControlAction::OpenBlueprints);
}
}
TEST_CASE("ControlAction: selection rows appear only once something is selected",
"[controls]")
{
const std::vector<ControlAction> general = getContextActions(generalContext());
const std::vector<ControlAction> selection = getContextActions(selectionContext());
REQUIRE(contains(general, ControlAction::Select));
REQUIRE(contains(general, ControlAction::EnterDeconstruct));
REQUIRE_FALSE(contains(general, ControlAction::AddToSelection));
REQUIRE_FALSE(contains(general, ControlAction::CreateBlueprint));
REQUIRE(contains(selection, ControlAction::AddToSelection));
REQUIRE(contains(selection, ControlAction::AddAreaToSelection));
REQUIRE(contains(selection, ControlAction::CreateBlueprint));
REQUIRE(contains(selection, ControlAction::EnterDeconstruct));
}

View File

@@ -0,0 +1,156 @@
#include "catch.hpp"
#include <vector>
#include <QRect>
#include "FloatingPanelPlacement.h"
// The band every case below places into: 1000x600, so a bottom edge of 599.
static QRect makeBand()
{
return QRect(0, 0, 1000, 600);
}
static const int kMarginPx = 8;
TEST_CASE("With nothing in the way a widget may use the whole band", "[layout]")
{
// REQ-UI-SELECTION-PANEL: the band's own bottom is the limit when no other floating
// widget has been placed yet.
REQUIRE(getAvailableBottomPx(makeBand(), {}, 0, 999, kMarginPx) == 599);
}
TEST_CASE("A widget in the same column pushes the bottom above it", "[layout]")
{
// The build button bar sitting at the bottom center leaves the space above it, less
// the margin kept between the two (REQ-UI-BUILD-BAR).
const std::vector<QRect> occupied = { QRect(400, 520, 200, 72) };
REQUIRE(getAvailableBottomPx(makeBand(), occupied, 350, 650, kMarginPx) == 511);
}
TEST_CASE("A widget beside the column does not shorten it", "[layout]")
{
// The controls panel in the bottom-left corner is not in the way of a panel standing
// at the right edge, however tall it is (REQ-UI-CONTROLS-PANEL).
const std::vector<QRect> occupied = { QRect(0, 100, 200, 499) };
REQUIRE(getAvailableBottomPx(makeBand(), occupied, 700, 999, kMarginPx) == 599);
// Touching columns do count as meeting: the panel starts exactly where the widget
// ends, which is an overlap of one pixel.
REQUIRE(getAvailableBottomPx(makeBand(), occupied, 199, 999, kMarginPx) == 91);
}
TEST_CASE("The topmost widget in the column decides", "[layout]")
{
// Several widgets meet the column: the one that reaches highest is the binding one,
// whatever order they are given in.
const std::vector<QRect> occupied = { QRect(400, 520, 200, 72),
QRect(0, 300, 500, 299),
QRect(900, 560, 100, 40) };
REQUIRE(getAvailableBottomPx(makeBand(), occupied, 450, 550, kMarginPx) == 291);
}
TEST_CASE("An empty rectangle occupies nothing", "[layout]")
{
// A floating widget that is hidden contributes a null rect rather than being left
// out of the pass.
const std::vector<QRect> occupied = { QRect(), QRect(400, 520, 200, 0) };
REQUIRE(getAvailableBottomPx(makeBand(), occupied, 0, 999, kMarginPx) == 599);
}
TEST_CASE("A widget filling the column leaves nothing", "[layout]")
{
// The caller is expected to notice that the space left is not positive rather than
// being handed a floor of its own.
const std::vector<QRect> occupied = { QRect(0, 0, 1000, 600) };
REQUIRE(getAvailableBottomPx(makeBand(), occupied, 0, 999, kMarginPx) == -9);
}
// ---------------------------------------------------------------------------
// Which side of the selection the panel takes
// ---------------------------------------------------------------------------
TEST_CASE("The panel stands to the right of the selection where it fits", "[layout]")
{
// REQ-UI-SELECTION-PANEL: right of the anchor is the first choice.
REQUIRE(chooseSide(makeBand(), QRect(100, 100, 60, 60), 300, kMarginPx)
== PanelSide::Right);
}
TEST_CASE("The panel goes left when the right cannot hold it", "[layout]")
{
// A selection near the right edge leaves 100 px there, not enough for a 300 px
// panel, and the left is wide open.
REQUIRE(chooseSide(makeBand(), QRect(880, 100, 20, 60), 300, kMarginPx)
== PanelSide::Left);
}
TEST_CASE("Fitting on neither side, the panel takes the roomier one", "[layout]")
{
// A bounding box spanning most of the view: 192 px free on the left, 92 on the
// right, and a 300 px panel fits in neither. It covers as little as it can.
REQUIRE(chooseSide(makeBand(), QRect(200, 100, 700, 200), 300, kMarginPx)
== PanelSide::Left);
REQUIRE(chooseSide(makeBand(), QRect(100, 100, 700, 200), 300, kMarginPx)
== PanelSide::Right);
}
// ---------------------------------------------------------------------------
// Where it then stands
// ---------------------------------------------------------------------------
TEST_CASE("The panel sits beside the anchor with its top edges aligned", "[layout]")
{
// REQ-UI-SELECTION-PANEL: separated by the margin, growing away from the selection,
// top edge on the anchor's top edge.
const QRect placed = placeBesideAnchor(makeBand(), QRect(100, 120, 60, 60),
PanelSide::Right, QSize(300, 200), {},
kMarginPx);
REQUIRE(placed == QRect(168, 120, 300, 200));
const QRect placedLeft = placeBesideAnchor(makeBand(), QRect(500, 120, 60, 60),
PanelSide::Left, QSize(300, 200), {},
kMarginPx);
REQUIRE(placedLeft == QRect(192, 120, 300, 200));
}
TEST_CASE("A panel that would hang below the view is lifted", "[layout]")
{
// Top-aligning with a selection low in the view would put the panel's bottom past
// the band, so it rises until it fits rather than overrunning it.
const QRect placed = placeBesideAnchor(makeBand(), QRect(100, 500, 60, 60),
PanelSide::Right, QSize(300, 200), {},
kMarginPx);
REQUIRE(placed == QRect(168, 400, 300, 200));
}
TEST_CASE("A panel standing over another widget rises above it", "[layout]")
{
// The controls panel in the bottom-left is in the way of a panel placed to the left
// of a selection: it clears the top of it by the margin (REQ-UI-CONTROLS-PANEL).
const std::vector<QRect> occupied = { QRect(0, 300, 260, 300) };
const QRect placed = placeBesideAnchor(makeBand(), QRect(500, 250, 60, 60),
PanelSide::Left, QSize(300, 200), occupied,
kMarginPx);
REQUIRE(placed == QRect(192, 92, 300, 200));
}
TEST_CASE("A panel taller than the space left is capped", "[layout]")
{
// Capping is the caller's cue to scroll: it asked for 700 and got what there was.
const QRect placed = placeBesideAnchor(makeBand(), QRect(100, 100, 60, 60),
PanelSide::Right, QSize(300, 700), {},
kMarginPx);
REQUIRE(placed == QRect(168, 0, 300, 600));
}
TEST_CASE("A panel that fits on neither side is pushed inside the view", "[layout]")
{
// The one case where it covers part of the selection (REQ-UI-SELECTION-PANEL): it
// stands as far from the anchor as the band allows, not off the edge of it.
const QRect placed = placeBesideAnchor(makeBand(), QRect(100, 100, 700, 200),
PanelSide::Right, QSize(300, 200), {},
kMarginPx);
REQUIRE(placed == QRect(700, 100, 300, 200));
}

View File

@@ -262,6 +262,123 @@ TEST_CASE("Shipyard: setShipLayout cancels in-progress production",
CHECK_FALSE(b2->production.has_value()); CHECK_FALSE(b2->production.has_value());
} }
// Applying a configuration a building already has is a no-op (REQ-MAT-INPUT-BUFFER).
// setRecipe has always worked this way; setShipLayout did not, and wiped the shipyard
// on every re-apply. That matters now that a blueprint configuration transfer
// (REQ-UI-BLUEPRINT-TRANSFER) can be clicked repeatedly onto matching shipyards.
TEST_CASE("Shipyard: re-applying the same layout keeps production and buffers",
"[modules][shipyard]")
{
Simulation sim(loadTestConfig(), 42);
const ShipDef* def = findSchematic(sim.getConfig(), "interceptor");
REQUIRE(def != nullptr);
const BuildingDef* yardDef = findShipyardDef(sim.getConfig());
REQUIRE(yardDef != nullptr);
const BuildingId yardId = placeShipyard(sim, *yardDef);
SimulationTestAccess::buildings(sim).setRecipe(SimulationTestAccess::state(sim), yardId, "interceptor");
ShipLayoutConfig layout;
PlacedModule pm;
pm.moduleId = "armor_plate";
pm.position = QPoint(0, 0);
pm.rotation = Rotation::East;
layout.placedModules.push_back(pm);
SimulationTestAccess::buildings(sim).setShipLayout(SimulationTestAccess::state(sim), yardId, layout);
fillMaterials(sim, yardId, *def, layout);
sim.tick();
const Building* before = findBuilding(sim.getFactoryState(), yardId);
REQUIRE(before != nullptr);
REQUIRE(before->production.has_value());
const Tick completesAt = before->production->completesAt;
// A separately built but equal layout: equality is by value, not by identity.
ShipLayoutConfig sameLayout;
sameLayout.placedModules.push_back(pm);
SimulationTestAccess::buildings(sim).setShipLayout(SimulationTestAccess::state(sim), yardId, sameLayout);
const Building* after = findBuilding(sim.getFactoryState(), yardId);
REQUIRE(after != nullptr);
REQUIRE(after->production.has_value());
CHECK(after->production->completesAt == completesAt);
CHECK(after->inputBuffer.caps.at(ItemType{"iron_ingot"}) == 10);
}
TEST_CASE("Shipyard: an empty layout on an unconfigured shipyard changes nothing",
"[modules][shipyard]")
{
// An unset layout and an empty one are the same state everywhere that matters, so
// clearing an already-unconfigured shipyard must not cancel its cycle. This is the
// case a transfer from a layout-less source shipyard produces.
Simulation sim(loadTestConfig(), 42);
const ShipDef* def = findSchematic(sim.getConfig(), "interceptor");
REQUIRE(def != nullptr);
const BuildingDef* yardDef = findShipyardDef(sim.getConfig());
REQUIRE(yardDef != nullptr);
const BuildingId yardId = placeShipyard(sim, *yardDef);
SimulationTestAccess::buildings(sim).setRecipe(SimulationTestAccess::state(sim), yardId, "interceptor");
ShipLayoutConfig emptyLayout;
fillMaterials(sim, yardId, *def, emptyLayout);
sim.tick();
const Building* before = findBuilding(sim.getFactoryState(), yardId);
REQUIRE(before != nullptr);
REQUIRE(before->production.has_value());
REQUIRE_FALSE(before->shipLayout.has_value());
SimulationTestAccess::buildings(sim).setShipLayout(SimulationTestAccess::state(sim), yardId, emptyLayout);
const Building* after = findBuilding(sim.getFactoryState(), yardId);
REQUIRE(after != nullptr);
CHECK(after->production.has_value());
CHECK_FALSE(after->shipLayout.has_value());
}
TEST_CASE("Shipyard: the same modules in a different order count as a change",
"[modules][shipyard]")
{
// Layout equality is deliberately order-sensitive (see ShipLayout.h): the safe
// answer when in doubt is "changed", which costs a buffer reset rather than
// leaving a shipyard building the wrong ship.
Simulation sim(loadTestConfig(), 42);
const ShipDef* def = findSchematic(sim.getConfig(), "interceptor");
REQUIRE(def != nullptr);
const BuildingDef* yardDef = findShipyardDef(sim.getConfig());
REQUIRE(yardDef != nullptr);
const BuildingId yardId = placeShipyard(sim, *yardDef);
SimulationTestAccess::buildings(sim).setRecipe(SimulationTestAccess::state(sim), yardId, "interceptor");
PlacedModule armor;
armor.moduleId = "armor_plate";
armor.position = QPoint(0, 0);
armor.rotation = Rotation::East;
PlacedModule sensor;
sensor.moduleId = "sensor_booster";
sensor.position = QPoint(1, 0);
sensor.rotation = Rotation::East;
ShipLayoutConfig layout;
layout.placedModules.push_back(armor);
layout.placedModules.push_back(sensor);
SimulationTestAccess::buildings(sim).setShipLayout(SimulationTestAccess::state(sim), yardId, layout);
fillMaterials(sim, yardId, *def, layout);
sim.tick();
REQUIRE(findBuilding(sim.getFactoryState(), yardId)->production.has_value());
ShipLayoutConfig reordered;
reordered.placedModules.push_back(sensor);
reordered.placedModules.push_back(armor);
SimulationTestAccess::buildings(sim).setShipLayout(SimulationTestAccess::state(sim), yardId, reordered);
CHECK_FALSE(findBuilding(sim.getFactoryState(), yardId)->production.has_value());
}
TEST_CASE("Shipyard: builds a bare hull when no layout is configured", TEST_CASE("Shipyard: builds a bare hull when no layout is configured",
"[modules][shipyard]") "[modules][shipyard]")
{ {

View File

@@ -39,6 +39,11 @@ bool BlueprintLibrary::getCanCaptureSelection() const
return selectionHasPlaceableBuilding(*m_sim, m_selectedBuildingIds); return selectionHasPlaceableBuilding(*m_sim, m_selectedBuildingIds);
} }
bool BlueprintLibrary::getHasTemporaryBlueprint() const
{
return m_temporaryBlueprint.has_value();
}
void BlueprintLibrary::saveSelectionAs(const QString& name) void BlueprintLibrary::saveSelectionAs(const QString& name)
{ {
Blueprint blueprint = createBlueprintFromSelection(); Blueprint blueprint = createBlueprintFromSelection();
@@ -116,22 +121,48 @@ void BlueprintLibrary::handleEvent(std::shared_ptr<const SelectionChangedEvent>
void BlueprintLibrary::handleEvent(std::shared_ptr<const BlueprintModeExitedEvent> /*event*/) void BlueprintLibrary::handleEvent(std::shared_ptr<const BlueprintModeExitedEvent> /*event*/)
{ {
// Only the saved-blueprint index is cleared. A temporary blueprint deliberately
// survives its placement mode so V can re-enter it (REQ-UI-BLUEPRINT-TEMP).
m_activeIndex = std::nullopt; m_activeIndex = std::nullopt;
} }
void BlueprintLibrary::handleEvent( void BlueprintLibrary::handleEvent(
std::shared_ptr<const TemporaryBlueprintRequestedEvent> /*event*/) std::shared_ptr<const TemporaryBlueprintCaptureRequestedEvent> /*event*/)
{ {
// Temporary blueprint (REQ-UI-BLUEPRINT-TEMP): build from the current selection and // C (REQ-UI-BLUEPRINT-TEMP): capture the current selection and enter placement mode
// enter placement mode without adding it to the list or persisting it. If nothing // for it, without naming it, listing it, or persisting it. If nothing player-placeable
// player-placeable is selected, do nothing. // is selected, do nothing at all -- in particular, keep the previous temporary
// blueprint, which V can still place.
Blueprint blueprint = createBlueprintFromSelection(); Blueprint blueprint = createBlueprintFromSelection();
if (blueprint.buildings.empty()) { return; } if (blueprint.buildings.empty()) { return; }
m_temporaryBlueprint = std::move(blueprint);
// No saved blueprint is active while a temporary one is being placed. // No saved blueprint is active while a temporary one is being placed.
m_activeIndex = std::nullopt; m_activeIndex = std::nullopt;
EventManager::getInstance()->sendEventImmediately( EventManager::getInstance()->sendEventImmediately(
std::make_shared<BlueprintPlacementRequestedEvent>(std::move(blueprint))); std::make_shared<BlueprintPlacementRequestedEvent>(*m_temporaryBlueprint));
}
void BlueprintLibrary::handleEvent(
std::shared_ptr<const TemporaryBlueprintPlaceRequestedEvent> /*event*/)
{
// V (REQ-UI-BLUEPRINT-TEMP): re-enter placement mode for the temporary blueprint,
// capturing nothing. With none captured, nothing happens -- no mode is entered and
// whichever mode is active is left alone. Affordability is not checked here, matching
// C; cost is enforced at placement (REQ-UI-BLUEPRINT-PLACE). The blueprint is copied,
// not moved: it stays available for the next V.
if (!m_temporaryBlueprint.has_value()) { return; }
m_activeIndex = std::nullopt;
EventManager::getInstance()->sendEventImmediately(
std::make_shared<BlueprintPlacementRequestedEvent>(*m_temporaryBlueprint));
}
void BlueprintLibrary::handleEvent(std::shared_ptr<const GameResetEvent> /*event*/)
{
// A restart begins a new run, and the temporary blueprint belongs to the old one
// (REQ-UI-BLUEPRINT-TEMP). The saved blueprints are not run state and stay.
m_temporaryBlueprint = std::nullopt;
} }
Blueprint BlueprintLibrary::createBlueprintFromSelection() const Blueprint BlueprintLibrary::createBlueprintFromSelection() const

View File

@@ -10,8 +10,10 @@
#include "BuildingId.h" #include "BuildingId.h"
#include "EventHandler.h" #include "EventHandler.h"
#include "GameConfig.h" #include "GameConfig.h"
#include "GameResetEvent.h"
#include "SelectionChangedEvent.h" #include "SelectionChangedEvent.h"
#include "TemporaryBlueprintRequestedEvent.h" #include "TemporaryBlueprintCaptureRequestedEvent.h"
#include "TemporaryBlueprintPlaceRequestedEvent.h"
class Simulation; class Simulation;
class QWidget; class QWidget;
@@ -24,9 +26,12 @@ class QWidget;
// (REQ-UI-BLUEPRINT-DIALOG), and the modal dialogs that present them must be driven from // (REQ-UI-BLUEPRINT-DIALOG), and the modal dialogs that present them must be driven from
// MainWindow, the only widget that can pause the game (ModalPauseScope) and raise the dim // MainWindow, the only widget that can pause the game (ModalPauseScope) and raise the dim
// overlay. This class is the model those dialogs read and mutate. // overlay. This class is the model those dialogs read and mutate.
class BlueprintLibrary : public CombinedEventHandler<SelectionChangedEvent, class BlueprintLibrary
: public CombinedEventHandler<SelectionChangedEvent,
BlueprintModeExitedEvent, BlueprintModeExitedEvent,
TemporaryBlueprintRequestedEvent> TemporaryBlueprintCaptureRequestedEvent,
TemporaryBlueprintPlaceRequestedEvent,
GameResetEvent>
{ {
public: public:
// dialogParent parents the load-failure message box (REQ-UI-BLUEPRINT-LOAD) and is // dialogParent parents the load-failure message box (REQ-UI-BLUEPRINT-LOAD) and is
@@ -39,6 +44,11 @@ public:
// (REQ-UI-BLUEPRINT-CREATE). // (REQ-UI-BLUEPRINT-CREATE).
bool getCanCaptureSelection() const; bool getCanCaptureSelection() const;
// True once C has captured something -- the condition under which V does anything
// (REQ-UI-BLUEPRINT-TEMP), and so the condition under which the controls panel
// offers it (REQ-UI-CONTROLS-ACCURACY).
bool getHasTemporaryBlueprint() const;
// Captures the current selection under the given name and appends it to the list. // Captures the current selection under the given name and appends it to the list.
// Silently does nothing when nothing player-placeable is selected. // Silently does nothing when nothing player-placeable is selected.
void saveSelectionAs(const QString& name); void saveSelectionAs(const QString& name);
@@ -67,7 +77,11 @@ public:
private: private:
void handleEvent(std::shared_ptr<const SelectionChangedEvent> event) override; void handleEvent(std::shared_ptr<const SelectionChangedEvent> event) override;
void handleEvent(std::shared_ptr<const BlueprintModeExitedEvent> event) override; void handleEvent(std::shared_ptr<const BlueprintModeExitedEvent> event) override;
void handleEvent(std::shared_ptr<const TemporaryBlueprintRequestedEvent> event) override; void handleEvent(
std::shared_ptr<const TemporaryBlueprintCaptureRequestedEvent> event) override;
void handleEvent(
std::shared_ptr<const TemporaryBlueprintPlaceRequestedEvent> event) override;
void handleEvent(std::shared_ptr<const GameResetEvent> event) override;
Blueprint createBlueprintFromSelection() const; Blueprint createBlueprintFromSelection() const;
void loadFromDisk(); void loadFromDisk();
@@ -83,4 +97,10 @@ private:
// Index of the blueprint currently in placement mode, so deleting it can exit that // Index of the blueprint currently in placement mode, so deleting it can exit that
// mode (REQ-UI-BLUEPRINT-DELETE). nullopt = no saved blueprint is being placed. // mode (REQ-UI-BLUEPRINT-DELETE). nullopt = no saved blueprint is being placed.
std::optional<int> m_activeIndex; std::optional<int> m_activeIndex;
// The one unnamed blueprint captured with C and re-placed with V
// (REQ-UI-BLUEPRINT-TEMP). Deliberately kept out of m_blueprints: it is never named,
// never listed in the selection dialog, and never written to blueprints.toml. It
// outlives its placement mode, so V can re-enter it. nullopt = none captured since
// startup or the last restart.
std::optional<Blueprint> m_temporaryBlueprint;
}; };

View File

@@ -158,7 +158,7 @@ BlueprintSelectionDialog::BlueprintSelectionDialog(BlueprintLibrary* library,
// Frameless: the dialog draws its own header row, so an OS title bar would only // Frameless: the dialog draws its own header row, so an OS title bar would only
// repeat it (REQ-UI-BLUEPRINT-DIALOG). Square corners rather than rounded ones -- // repeat it (REQ-UI-BLUEPRINT-DIALOG). Square corners rather than rounded ones --
// rounding a top-level window needs a translucent background, which is unreliable // rounding a top-level window needs a translucent background, which is unreliable
// on Windows. The border matches the build bar and the side panel. // on Windows. The border matches the build bar and the selection panel.
setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
setAttribute(Qt::WA_StyledBackground, true); setAttribute(Qt::WA_StyledBackground, true);
setStyleSheet(QStringLiteral( setStyleSheet(QStringLiteral(

View File

@@ -2,9 +2,7 @@
#include <string> #include <string>
#include <QByteArray>
#include <QColor> #include <QColor>
#include <QFile>
#include <QFont> #include <QFont>
#include <QFontMetrics> #include <QFontMetrics>
#include <QGuiApplication> #include <QGuiApplication>
@@ -15,18 +13,18 @@
#include <QPixmap> #include <QPixmap>
#include <QPushButton> #include <QPushButton>
#include <QRect> #include <QRect>
#include <QRegularExpression>
#include <QSignalMapper> #include <QSignalMapper>
#include <QSize> #include <QSize>
#include <QString> #include <QString>
#include <QSvgRenderer>
#include "BuildingIconCache.h"
#include "BuildingType.h" #include "BuildingType.h"
#include "BuildingTypeSelectedEvent.h" #include "BuildingTypeSelectedEvent.h"
#include "DeconstructModeToggleRequestedEvent.h" #include "DeconstructModeToggleRequestedEvent.h"
#include "DisplayName.h" #include "DisplayName.h"
#include "EventManager.h" #include "EventManager.h"
#include "ExitBuilderModeRequestedEvent.h" #include "ExitBuilderModeRequestedEvent.h"
#include "FloatingLayoutInvalidatedEvent.h"
#include "IconCaption.h" #include "IconCaption.h"
#include "InputMapper.h" #include "InputMapper.h"
#include "ItemIconCache.h" #include "ItemIconCache.h"
@@ -54,45 +52,15 @@ namespace
// Gap between the chip icon and the cost line on a button face. // Gap between the chip icon and the cost line on a button face.
const int kFaceGapPx = 2; const int kFaceGapPx = 2;
// Rasterizes a chip SVG straight at its on-screen size times the device pixel // Normal and grey-background chip pixmaps for one icon name. Empty pixmaps if the
// ratio, so it stays crisp without a downscale step. // file cannot be read; the caller then falls back to a name caption
QPixmap renderChip(const QByteArray& svg)
{
const qreal dpr = qApp ? qApp->devicePixelRatio() : 1.0;
QSvgRenderer renderer(svg);
QPixmap pixmap(static_cast<int>(kIconSize.width() * dpr),
static_cast<int>(kIconSize.height() * dpr));
pixmap.setDevicePixelRatio(dpr);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
renderer.render(&painter);
return pixmap;
}
// Normal and grey-background chip pixmaps for a "<id>.svg" file. Empty pixmaps if
// the file cannot be read; the caller then falls back to a name caption
// (REQ-UI-BUILD-ICON). // (REQ-UI-BUILD-ICON).
struct ChipPixmaps { QPixmap normal; QPixmap grey; }; struct ChipPixmaps { QPixmap normal; QPixmap grey; };
ChipPixmaps loadChipPixmaps(const QString& path) ChipPixmaps loadChipPixmaps(BuildingIconCache& icons, const std::string& iconName)
{ {
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) { return {}; }
const QByteArray svg = file.readAll();
ChipPixmaps result; ChipPixmaps result;
result.normal = renderChip(svg); result.normal = icons.getChip(iconName, kIconSize.width());
result.grey = icons.getGreyChip(iconName, kIconSize.width());
// Recolor only the chip background: the first "#rrggbb" fill in the file is the
// rounded background rect; the white glyph uses fill="none" and is left alone.
QString greyed = QString::fromUtf8(svg);
static const QRegularExpression fillPattern(QStringLiteral("fill=\"#[0-9a-fA-F]{6}\""));
const QRegularExpressionMatch match = fillPattern.match(greyed);
if (match.hasMatch())
{
greyed.replace(match.capturedStart(), match.capturedLength(),
QStringLiteral("fill=\"#5f636e\""));
}
result.grey = renderChip(greyed.toUtf8());
return result; return result;
} }
@@ -181,18 +149,18 @@ namespace
BuildButtonBar::BuildButtonBar(Simulation* sim, const GameConfig* config, BuildButtonBar::BuildButtonBar(Simulation* sim, const GameConfig* config,
const std::string& iconDir, BuildingIconCache* buildingIcons,
ItemIconCache* itemIcons, QWidget* parent) ItemIconCache* itemIcons, QWidget* parent)
: QWidget(parent) : QWidget(parent)
, m_sim(sim) , m_sim(sim)
, m_config(config) , m_config(config)
, m_iconDir(iconDir) , m_buildingIcons(buildingIcons)
, m_itemIcons(itemIcons) , m_itemIcons(itemIcons)
{ {
// The bar floats over the rendered world rather than sitting in a panel, so it // The bar floats over the rendered world rather than sitting in a panel, so it
// brings its own opaque background to stay legible over any world content // brings its own opaque background to stay legible over any world content
// (REQ-UI-BUILD-BAR). Palette colors keep it consistent with the buttons it holds // (REQ-UI-BUILD-BAR). Palette colors keep it consistent with the buttons it holds
// and with the side panels; this is widget chrome, not world rendering, so it is // and with the selection panel; this is widget chrome, not world rendering, so it is
// deliberately not a visuals.toml color. // deliberately not a visuals.toml color.
setAttribute(Qt::WA_StyledBackground, true); setAttribute(Qt::WA_StyledBackground, true);
setStyleSheet(QStringLiteral( setStyleSheet(QStringLiteral(
@@ -231,13 +199,12 @@ BuildButtonBar::BuildButtonBar(Simulation* sim, const GameConfig* config,
const QString name = (def.type == BuildingType::TunnelEntry) const QString name = (def.type == BuildingType::TunnelEntry)
? tr("Tunnel") ? tr("Tunnel")
: QString::fromStdString(toDisplayName(def.id)); : QString::fromStdString(toDisplayName(def.id));
// Icon file name matches the building id (REQ-UI-BUILD-ICON); Tunnel Entry's // Icon file name matches the building id (REQ-UI-BUILD-ICON); Tunnel Entry's
// "tunnel_entry.svg" serves the shared Tunnel button. // "tunnel_entry.svg" serves the shared Tunnel button.
const QString iconPath = QString::fromStdString(m_iconDir) + "/"
+ QString::fromStdString(def.id) + ".svg";
const ButtonFace face = buildButtonFace( const ButtonFace face = buildButtonFace(
loadChipPixmaps(iconPath), InputMapper::getBuildHotkeyLabel(def.type), name, loadChipPixmaps(*m_buildingIcons, def.id),
InputMapper::getBuildHotkeyLabel(def.type), name,
QString::number(def.cost), blockIcon, font(), palette()); QString::number(def.cost), blockIcon, font(), palette());
QPushButton* btn = new QPushButton(this); QPushButton* btn = new QPushButton(this);
@@ -268,7 +235,7 @@ BuildButtonBar::BuildButtonBar(Simulation* sim, const GameConfig* config,
// Having no cost, it shows its name where the building buttons show theirs // Having no cost, it shows its name where the building buttons show theirs
// (REQ-UI-DECONSTRUCT-BUTTON), and its Q toggle as the badge (REQ-UI-HOTKEYS). // (REQ-UI-DECONSTRUCT-BUTTON), and its Q toggle as the badge (REQ-UI-HOTKEYS).
const ButtonFace deconstructFace = buildButtonFace( const ButtonFace deconstructFace = buildButtonFace(
loadChipPixmaps(QString::fromStdString(m_iconDir) + "/deconstruct.svg"), loadChipPixmaps(*m_buildingIcons, "deconstruct"),
QStringLiteral("Q"), tr("Deconstruct"), tr("Deconstruct"), QPixmap(), QStringLiteral("Q"), tr("Deconstruct"), tr("Deconstruct"), QPixmap(),
font(), palette()); font(), palette());
@@ -304,10 +271,25 @@ BuildButtonBar::~BuildButtonBar()
unregisterForEvents(); unregisterForEvents();
} }
void BuildButtonBar::anchorTo(const QRect& worldViewRect) void BuildButtonBar::placeIn(const QRect& viewRect,
const std::vector<QRect>& /*occupiedRects*/)
{ {
m_viewRect = worldViewRect; if (viewRect.isNull())
recenter(); {
return;
}
// The layout drops hidden buttons from its size hint, but only once it has been
// re-run: an unlock changes which buttons are shown, and Qt would not get around to
// it before the bar is measured here.
layout()->activate();
const QSize barSize = sizeHint();
// Centered, except that a bar wider than the view stays flush with its left edge
// rather than hanging off both sides.
const int x = qMax(viewRect.left(),
viewRect.left() + (viewRect.width() - barSize.width()) / 2);
const int y = viewRect.bottom() - kBottomMarginPx - barSize.height() + 1;
setGeometry(QRect(QPoint(x, y), barSize));
} }
void BuildButtonBar::clearActiveButton() void BuildButtonBar::clearActiveButton()
@@ -357,29 +339,11 @@ void BuildButtonBar::updateVisibility()
{ {
m_buttons[i]->setVisible(m_sim->isBuildingUnlocked(m_types[i])); m_buttons[i]->setVisible(m_sim->isBuildingUnlocked(m_types[i]));
} }
// A hidden button leaves the row, so the bar has to take up its new width and // A hidden button leaves the row, so the bar takes up a new width and has to be
// re-center on it (REQ-UI-BUILD-BAR). // re-centered on it -- and the widgets that keep clear of the bar have to be placed
recenter(); // against that new rect too, so the whole pass is re-run (REQ-UI-BUILD-BAR).
} EventManager::getInstance()->sendEventImmediately(
std::make_shared<FloatingLayoutInvalidatedEvent>());
void BuildButtonBar::recenter()
{
if (m_viewRect.isNull())
{
return;
}
// The layout drops hidden buttons from its size hint, but only once it has been
// re-run: updateVisibility() calls this straight after setVisible(), before Qt
// would get around to it on its own.
layout()->activate();
const QSize barSize = sizeHint();
// Centered, except that a bar wider than the view stays flush with its left edge
// rather than hanging off both sides.
const int x = qMax(m_viewRect.left(),
m_viewRect.left() + (m_viewRect.width() - barSize.width()) / 2);
const int y = m_viewRect.bottom() - kBottomMarginPx - barSize.height() + 1;
setGeometry(QRect(QPoint(x, y), barSize));
} }
void BuildButtonBar::onBuildButton(int index) void BuildButtonBar::onBuildButton(int index)

View File

@@ -15,18 +15,22 @@
#include "BuildingType.h" #include "BuildingType.h"
#include "DeconstructModeChangedEvent.h" #include "DeconstructModeChangedEvent.h"
#include "EventHandler.h" #include "EventHandler.h"
#include "FloatingPanel.h"
#include "GameConfig.h" #include "GameConfig.h"
#include "UnlockedBuildingsChangedEvent.h" #include "UnlockedBuildingsChangedEvent.h"
class QPushButton; class QPushButton;
class Simulation; class Simulation;
class BuildingIconCache;
class ItemIconCache; class ItemIconCache;
// The build menu: one horizontal row of build buttons floating over the game world // The build menu: one horizontal row of build buttons floating over the game world
// view (REQ-UI-BUILD-BAR). The bar is sized to its buttons; its owner hands it the // view (REQ-UI-BUILD-BAR). The bar is sized to its buttons and centers itself along the
// world view's rect through anchorTo() and it centers itself along that rect's // bottom edge of the rect its owner places it in. It is placed first of the floating
// bottom edge. // widgets and so takes the space it wants outright: nothing ever moves it aside, and the
// widgets placed after it keep out of its way instead.
class BuildButtonBar : public QWidget, class BuildButtonBar : public QWidget,
public FloatingPanel,
public CombinedEventHandler<BuilderModeExitedEvent, public CombinedEventHandler<BuilderModeExitedEvent,
DeconstructModeChangedEvent, DeconstructModeChangedEvent,
BuildHotkeyPressedEvent, BuildHotkeyPressedEvent,
@@ -36,20 +40,19 @@ class BuildButtonBar : public QWidget,
Q_OBJECT Q_OBJECT
public: public:
// iconDir is the directory holding the per-building "<id>.svg" chip icons // buildingIcons supplies each button's chip icon (REQ-UI-BUILD-ICON) and itemIcons
// (REQ-UI-BUILD-ICON), read from disk at runtime like the config files. // the building_block icon shown in each button's cost (REQ-UI-BUILD-COST). Both are
// itemIcons is the window-wide per-item icon cache and supplies the // window-wide caches; neither is owned, and both must outlive this widget.
// building_block icon shown in each button's cost (REQ-UI-BUILD-COST). Not
// owned; must outlive this widget.
BuildButtonBar(Simulation* sim, const GameConfig* config, BuildButtonBar(Simulation* sim, const GameConfig* config,
const std::string& iconDir, ItemIconCache* itemIcons, BuildingIconCache* buildingIcons, ItemIconCache* itemIcons,
QWidget* parent = nullptr); QWidget* parent = nullptr);
~BuildButtonBar() override; ~BuildButtonBar() override;
// Centers the bar along the bottom edge of the game world view's rect, given in // Centers the bar along the bottom edge of the game world view's rect, given in the
// the bar's parent coordinates (REQ-UI-BUILD-BAR). The rect is remembered, so a // bar's parent coordinates (REQ-UI-BUILD-BAR). Nothing is occupied yet when the bar
// re-center later driven by an unlock needs no second call from the owner. // is placed, so it ignores what it is handed there.
void anchorTo(const QRect& worldViewRect); void placeIn(const QRect& viewRect,
const std::vector<QRect>& occupiedRects) override;
void clearActiveButton(); void clearActiveButton();
@@ -63,11 +66,6 @@ private:
// unlock state (REQ-LOCK-BUILDING); a locked building type's button is hidden. // unlock state (REQ-LOCK-BUILDING); a locked building type's button is hidden.
void updateVisibility(); void updateVisibility();
// Shrinks the bar to its currently shown buttons and re-centers it in the
// anchored rect (REQ-UI-BUILD-BAR). Does nothing until anchorTo() supplied that
// rect, so the construction-time call is harmless.
void recenter();
void handleEvent(std::shared_ptr<const BuilderModeExitedEvent> event) override; void handleEvent(std::shared_ptr<const BuilderModeExitedEvent> event) override;
void handleEvent(std::shared_ptr<const DeconstructModeChangedEvent> event) override; void handleEvent(std::shared_ptr<const DeconstructModeChangedEvent> event) override;
void handleEvent(std::shared_ptr<const BuildHotkeyPressedEvent> event) override; void handleEvent(std::shared_ptr<const BuildHotkeyPressedEvent> event) override;
@@ -80,12 +78,11 @@ private slots:
private: private:
Simulation* m_sim; Simulation* m_sim;
const GameConfig* m_config; const GameConfig* m_config;
std::string m_iconDir; BuildingIconCache* m_buildingIcons; // Not owned; lives in MainWindow.
ItemIconCache* m_itemIcons; // Not owned; lives in MainWindow. ItemIconCache* m_itemIcons; // Not owned; lives in MainWindow.
std::vector<BuildingType> m_types; std::vector<BuildingType> m_types;
std::vector<QPushButton*> m_buttons; std::vector<QPushButton*> m_buttons;
std::map<BuildingType, int> m_costs; std::map<BuildingType, int> m_costs;
std::optional<std::size_t> m_activeIndex; std::optional<std::size_t> m_activeIndex;
QPushButton* m_deconstructButton; QPushButton* m_deconstructButton;
QRect m_viewRect;
}; };

View File

@@ -0,0 +1,120 @@
#include "BuildingIconCache.h"
#include <QFile>
#include <QGuiApplication>
#include <QPainter>
#include <QRegularExpression>
#include <QSvgRenderer>
namespace
{
// Chip background color for a build button the player cannot afford
// (REQ-UI-BUILD-DISABLED). Part of the icon rather than of any widget's palette, so it
// lives with the recoloring step.
const char* const kGreyFill = "fill=\"#5f636e\"";
} // namespace
BuildingIconCache::BuildingIconCache(const QString& iconDir)
: m_iconDir(iconDir)
{
}
const QByteArray& BuildingIconCache::getSvg(const std::string& iconName)
{
const std::map<std::string, QByteArray>::const_iterator cached =
m_svgByName.find(iconName);
if (cached != m_svgByName.end())
{
return cached->second;
}
// An absent or unreadable file caches an empty byte array so it is not retried;
// a missing icon is not an error (REQ-UI-BUILD-ICON).
QByteArray svg;
QFile file(m_iconDir + "/" + QString::fromStdString(iconName) + ".svg");
if (file.open(QIODevice::ReadOnly))
{
svg = file.readAll();
}
return m_svgByName.emplace(iconName, std::move(svg)).first->second;
}
const QByteArray& BuildingIconCache::getGreySvg(const std::string& iconName)
{
const std::map<std::string, QByteArray>::const_iterator cached =
m_greySvgByName.find(iconName);
if (cached != m_greySvgByName.end())
{
return cached->second;
}
// Recolor only the chip background: the first "#rrggbb" fill in the file is the
// rounded background rect; the white glyph uses fill="none" and is left alone.
const QByteArray& svg = getSvg(iconName);
QByteArray greyed = svg;
if (!svg.isEmpty())
{
QString text = QString::fromUtf8(svg);
static const QRegularExpression fillPattern(
QStringLiteral("fill=\"#[0-9a-fA-F]{6}\""));
const QRegularExpressionMatch match = fillPattern.match(text);
if (match.hasMatch())
{
text.replace(match.capturedStart(), match.capturedLength(),
QLatin1String(kGreyFill));
}
greyed = text.toUtf8();
}
return m_greySvgByName.emplace(iconName, std::move(greyed)).first->second;
}
bool BuildingIconCache::hasIcon(const std::string& iconName)
{
return !getSvg(iconName).isEmpty();
}
QPixmap BuildingIconCache::getChip(const std::string& iconName, int sizePx)
{
return getPixmap(iconName, getSvg(iconName), sizePx);
}
QPixmap BuildingIconCache::getGreyChip(const std::string& iconName, int sizePx)
{
return getPixmap("grey:" + iconName, getGreySvg(iconName), sizePx);
}
QPixmap BuildingIconCache::getPixmap(const std::string& cacheKey,
const QByteArray& svg, int sizePx)
{
if (sizePx <= 0)
{
return QPixmap();
}
const std::pair<std::string, int> key(cacheKey, sizePx);
const std::map<std::pair<std::string, int>, QPixmap>::const_iterator cached =
m_pixmapCache.find(key);
if (cached != m_pixmapCache.end())
{
return cached->second;
}
QPixmap pixmap;
if (!svg.isEmpty())
{
// Rasterized straight at its on-screen size times the device pixel ratio, so it
// stays crisp without a downscale step.
const qreal dpr = qApp ? qApp->devicePixelRatio() : 1.0;
QSvgRenderer renderer(svg);
pixmap = QPixmap(static_cast<int>(sizePx * dpr), static_cast<int>(sizePx * dpr));
pixmap.setDevicePixelRatio(dpr);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
renderer.render(&painter);
}
return m_pixmapCache.emplace(key, std::move(pixmap)).first->second;
}

View File

@@ -0,0 +1,55 @@
#pragma once
#include <map>
#include <string>
#include <utility>
#include <QByteArray>
#include <QPixmap>
#include <QString>
// Rasterizes and caches the per-building chip SVGs (REQ-UI-BUILD-ICON). A chip is a
// rounded colored background bearing a white line glyph, loaded from a directory with
// one file per building named after the building's id (e.g. "belt.svg"). Shared by the
// build button bar and the selection panel's card header (REQ-UI-SELECTION-CARD) so the
// rasterization is not duplicated.
//
// A missing icon file is not an error: hasIcon() returns false for it and the caller
// falls back (a name caption on a build button, a bare title in the panel header).
class BuildingIconCache
{
public:
// iconDir is the directory holding the "<id>.svg" chip files (typically
// "<configDir>/../icons/buildings").
explicit BuildingIconCache(const QString& iconDir);
// True if a chip SVG file exists for the given icon name. Loads the file's bytes on
// first query and remembers the result (including absence) so repeated calls are
// cheap. The name is a building id for the building buttons, but need not be one --
// the Deconstruct button's "deconstruct" chip goes through the same path.
bool hasIcon(const std::string& iconName);
// The chip rasterized to a transparent sizePx*sizePx pixmap at the device pixel
// ratio, cached per (name, size). Returns a null pixmap when the file is missing.
QPixmap getChip(const std::string& iconName, int sizePx);
// As getChip(), but with the chip background recolored grey and the glyph left
// alone, for a build button the player cannot currently afford
// (REQ-UI-BUILD-DISABLED).
QPixmap getGreyChip(const std::string& iconName, int sizePx);
private:
// Raw SVG bytes for an icon name, loading and caching them on first access. An
// absent file caches an empty QByteArray so it is not retried.
const QByteArray& getSvg(const std::string& iconName);
// The same SVG with its background fill replaced by grey, cached alongside.
const QByteArray& getGreySvg(const std::string& iconName);
// Shared rasterize-and-cache step. cacheKey distinguishes the normal and grey
// variants of one icon name within the single pixmap cache.
QPixmap getPixmap(const std::string& cacheKey, const QByteArray& svg, int sizePx);
QString m_iconDir;
std::map<std::string, QByteArray> m_svgByName;
std::map<std::string, QByteArray> m_greySvgByName;
std::map<std::pair<std::string, int>, QPixmap> m_pixmapCache;
};

View File

@@ -1,3 +1,5 @@
add_subdirectory(selection)
SET(HDRS SET(HDRS
${HDRS} ${HDRS}
${CMAKE_CURRENT_SOURCE_DIR}/VisualsConfig.h ${CMAKE_CURRENT_SOURCE_DIR}/VisualsConfig.h
@@ -10,9 +12,12 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/WorldPrimitives.h ${CMAKE_CURRENT_SOURCE_DIR}/WorldPrimitives.h
${CMAKE_CURRENT_SOURCE_DIR}/WorldRenderer.h ${CMAKE_CURRENT_SOURCE_DIR}/WorldRenderer.h
${CMAKE_CURRENT_SOURCE_DIR}/HeaderBar.h ${CMAKE_CURRENT_SOURCE_DIR}/HeaderBar.h
${CMAKE_CURRENT_SOURCE_DIR}/FloatingPanel.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildButtonBar.h ${CMAKE_CURRENT_SOURCE_DIR}/BuildButtonBar.h
${CMAKE_CURRENT_SOURCE_DIR}/SelectedBuildingPanel.h ${CMAKE_CURRENT_SOURCE_DIR}/SelectionPanel.h
${CMAKE_CURRENT_SOURCE_DIR}/FieldSelectionPanel.h ${CMAKE_CURRENT_SOURCE_DIR}/SelectionBounds.h
${CMAKE_CURRENT_SOURCE_DIR}/ControlsPanel.h
${CMAKE_CURRENT_SOURCE_DIR}/ControlActionText.h
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintLibrary.h ${CMAKE_CURRENT_SOURCE_DIR}/BlueprintLibrary.h
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintSelectionDialog.h ${CMAKE_CURRENT_SOURCE_DIR}/BlueprintSelectionDialog.h
${CMAKE_CURRENT_SOURCE_DIR}/ShipLayoutDialog.h ${CMAKE_CURRENT_SOURCE_DIR}/ShipLayoutDialog.h
@@ -22,10 +27,16 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionDialog.h ${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionDialog.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeTooltip.h ${CMAKE_CURRENT_SOURCE_DIR}/RecipeTooltip.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemIconCache.h ${CMAKE_CURRENT_SOURCE_DIR}/ItemIconCache.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildingIconCache.h
${CMAKE_CURRENT_SOURCE_DIR}/IconCaption.h ${CMAKE_CURRENT_SOURCE_DIR}/IconCaption.h
PARENT_SCOPE PARENT_SCOPE
) )
set(UI_INCLUDE_PATH
${UI_INCLUDE_PATH}
PARENT_SCOPE
)
SET(SRCS SET(SRCS
${SRCS} ${SRCS}
${CMAKE_CURRENT_SOURCE_DIR}/VisualsLoader.cpp ${CMAKE_CURRENT_SOURCE_DIR}/VisualsLoader.cpp
@@ -37,8 +48,10 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/WorldRenderer.cpp ${CMAKE_CURRENT_SOURCE_DIR}/WorldRenderer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/HeaderBar.cpp ${CMAKE_CURRENT_SOURCE_DIR}/HeaderBar.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BuildButtonBar.cpp ${CMAKE_CURRENT_SOURCE_DIR}/BuildButtonBar.cpp
${CMAKE_CURRENT_SOURCE_DIR}/SelectedBuildingPanel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/SelectionPanel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/FieldSelectionPanel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/SelectionBounds.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ControlsPanel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ControlActionText.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintLibrary.cpp ${CMAKE_CURRENT_SOURCE_DIR}/BlueprintLibrary.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintSelectionDialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/BlueprintSelectionDialog.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ShipLayoutDialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/ShipLayoutDialog.cpp
@@ -48,6 +61,7 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionDialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionDialog.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeTooltip.cpp ${CMAKE_CURRENT_SOURCE_DIR}/RecipeTooltip.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemIconCache.cpp ${CMAKE_CURRENT_SOURCE_DIR}/ItemIconCache.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BuildingIconCache.cpp
${CMAKE_CURRENT_SOURCE_DIR}/IconCaption.cpp ${CMAKE_CURRENT_SOURCE_DIR}/IconCaption.cpp
PARENT_SCOPE PARENT_SCOPE
) )

View File

@@ -0,0 +1,92 @@
#include "ControlActionText.h"
#include <QCoreApplication>
#include <QKeySequence>
namespace
{
// tr() for a file of free functions. Q_DECLARE_TR_FUNCTIONS expands with access
// specifiers, so it needs a class rather than a namespace; this struct exists only to
// carry it and give the strings a single lupdate context.
struct Strings
{
Q_DECLARE_TR_FUNCTIONS(ControlActionText)
};
QString getMouseBadge(MouseBinding binding)
{
switch (binding)
{
case MouseBinding::LeftClick: return Strings::tr("LMB");
case MouseBinding::LeftDrag: return Strings::tr("LMB drag");
case MouseBinding::CtrlLeftClick: return Strings::tr("Ctrl+LMB");
case MouseBinding::CtrlLeftDrag: return Strings::tr("Ctrl+LMB drag");
case MouseBinding::RightClick: return Strings::tr("RMB");
}
return QString();
}
} // namespace
QString getControlBindingBadge(const ControlBinding& binding)
{
if (binding.isMouse) { return getMouseBadge(binding.mouse); }
// QKeySequence spells the modifiers and the key together and localizes them, which
// is what makes this stay correct once keys are rebindable: the chip is generated
// from the binding rather than typed next to it.
return QKeySequence(binding.key | static_cast<int>(binding.modifiers))
.toString(QKeySequence::NativeText);
}
QString getControlActionLabel(ControlAction action, const ControlContext& context)
{
switch (action)
{
case ControlAction::None: return QString();
case ControlAction::Move: return Strings::tr("Move");
case ControlAction::GameSpeed: return Strings::tr("Game speed");
case ControlAction::TogglePause: return Strings::tr("Toggle pause");
case ControlAction::PasteTemporary: return Strings::tr("Paste last");
case ControlAction::OpenBlueprints: return Strings::tr("Blueprints");
case ControlAction::OpenMenu: return Strings::tr("Menu");
// A click on empty space clears and a click on an object replaces; naming only the
// first would be a half-truth once something is selected.
case ControlAction::Select:
return context.selection == ControlSelection::None
? Strings::tr("Select")
: Strings::tr("Select / clear selection");
case ControlAction::SelectArea: return Strings::tr("Select area");
case ControlAction::AddToSelection: return Strings::tr("Add / remove from selection");
case ControlAction::AddAreaToSelection: return Strings::tr("Add area to selection");
case ControlAction::EnterDeconstruct: return Strings::tr("Deconstruct mode");
case ControlAction::CopyTemporary: return Strings::tr("Copy to temporary blueprint");
case ControlAction::CreateBlueprint: return Strings::tr("Create blueprint");
case ControlAction::Place: return Strings::tr("Place");
case ControlAction::ApplySettings: return Strings::tr("Apply settings");
case ControlAction::PlaceBeltLine: return Strings::tr("Place belt line");
case ControlAction::Rotate: return Strings::tr("Rotate");
case ControlAction::CancelBeltLine: return Strings::tr("Cancel belt line");
case ControlAction::ExitMode:
return context.mode == BuildMode::Deconstruct
? Strings::tr("Exit deconstruct mode")
: Strings::tr("Exit placement");
case ControlAction::ToggleDeconstruct: return Strings::tr("Toggle deconstruct");
case ControlAction::DeconstructArea: return Strings::tr("Deconstruct area");
}
return QString();
}
QString getControlContextName(ControlContextKind kind)
{
switch (kind)
{
case ControlContextKind::General: return Strings::tr("GENERAL");
case ControlContextKind::Selection: return Strings::tr("SELECTION");
case ControlContextKind::Build: return Strings::tr("BUILD MODE");
case ControlContextKind::Blueprint: return Strings::tr("BLUEPRINT MODE");
case ControlContextKind::Deconstruct: return Strings::tr("DECONSTRUCT MODE");
}
return QString();
}

View File

@@ -0,0 +1,26 @@
#pragma once
#include <QString>
#include "ControlAction.h"
// What the player is shown for the actions and bindings declared in ControlAction.h
// (REQ-UI-CONTROLS-CONTENT). Kept out of lib/core deliberately: that file decides what
// is available and what triggers it, this one decides what it is called, and only this
// half is presentation.
//
// A badge is rendered from the binding it belongs to rather than written beside it, so
// what the panel shows on a chip is what the resolver actually matches. When bindings
// become player-configurable, this is the only place that has to learn to spell a
// rebound key.
// The chip text for one binding: "Ctrl+V", "LMB drag", "RMB".
QString getControlBindingBadge(const ControlBinding& binding);
// What the action is called in this context. A few actions are named for their
// situation rather than their implementation -- one exit action reads "Exit placement"
// in a placement mode and "Exit deconstruct mode" in deconstruct mode.
QString getControlActionLabel(ControlAction action, const ControlContext& context);
// The heading, in the upper case the card shows it in (REQ-UI-CONTROLS-CARD).
QString getControlContextName(ControlContextKind kind);

340
src/ui/ControlsPanel.cpp Normal file
View File

@@ -0,0 +1,340 @@
#include "ControlsPanel.h"
#include <QFont>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QScrollArea>
#include <QScrollBar>
#include <QTimer>
#include <QVBoxLayout>
#include "ControlActionText.h"
#include "EventManager.h"
#include "FloatingLayoutInvalidatedEvent.h"
#include "FloatingPanelPlacement.h"
#include "GameWorldView.h"
#include "selection/SelectionNames.h"
namespace
{
const int kMarginPx = 8; // between the view's edge and the panel
const int kCardMarginPx = 8; // inside the panel, around its content
const int kHeadingGapPx = 4; // between the heading and the rows
const int kRefreshMs = 50; // see the class comment on why this polls
// The panel's border, from the stylesheet below. Spelled out because the stylesheet box
// is what sets it and asking the style for it before the first show is unreliable.
const int kBorderPx = 1;
// Separates the heading's name from its detail, e.g. "BUILD MODE * Assembler".
const QChar kHeadingSeparator(0x00B7); // U+00B7 MIDDLE DOT
// The upper-case heading and caption are tracked out a little so they read as labels
// rather than as words. Set on the font because Qt's stylesheets have no letter-spacing
// property -- writing one there is silently ignored apart from a warning per widget.
QFont makeSpacedFont(QFont font, bool bold, int pointSizeDelta)
{
font.setBold(bold);
if (pointSizeDelta != 0 && font.pointSize() > 0)
{
font.setPointSize(qMax(1, font.pointSize() + pointSizeDelta));
}
font.setLetterSpacing(QFont::AbsoluteSpacing, 1.0);
return font;
}
// One row: the chips for the bindings, then what the action is called. Built as a plain
// widget rather than a class of its own -- it holds no state and answers no questions.
QWidget* makeRow(ControlAction action, const ControlContext& context, QWidget* parent)
{
QWidget* row = new QWidget(parent);
QHBoxLayout* layout = new QHBoxLayout(row);
layout->setContentsMargins(0, 2, 0, 2);
layout->setSpacing(4);
// Every badge is rendered from the binding the resolver matches, so a chip cannot
// claim a key that does nothing (REQ-UI-CONTROLS-ACCURACY). The chips of the row
// that leaves the mode are the ones marked, not its label (REQ-UI-CONTROLS-CARD).
const bool exitsMode = (action == ControlAction::ExitMode);
const std::vector<ControlBinding> bindings = getControlActionBindings(action, context);
for (const ControlBinding& binding : bindings)
{
QLabel* badge = new QLabel(getControlBindingBadge(binding), row);
badge->setObjectName(exitsMode ? QStringLiteral("controlBadgeExit")
: QStringLiteral("controlBadge"));
layout->addWidget(badge);
}
QLabel* label = new QLabel(getControlActionLabel(action, context), row);
label->setObjectName(QStringLiteral("controlLabel"));
layout->addSpacing(4);
layout->addWidget(label);
layout->addStretch(1);
return row;
}
// Adds a freshly built widget to the rows and shows it.
//
// The show is what makes it count. A widget created under an already-visible parent
// starts hidden, and a layout treats a hidden item as empty -- it contributes nothing
// to the size hint until something shows it, which otherwise does not happen until the
// event loop next runs, long after the panel has measured itself.
void addAndShow(QVBoxLayout* layout, QWidget* widget)
{
layout->addWidget(widget);
widget->show();
}
} // namespace
ControlsPanel::ControlsPanel(const GameWorldView* view, QWidget* parent)
: QWidget(parent)
, m_view(view)
{
// Floats over the rendered world, so it brings its own background to stay legible
// over any world content (REQ-UI-CONTROLS-PANEL). Palette colors match the build
// button bar's and the selection panel's chrome; like them this is widget chrome
// rather than world rendering, so it is deliberately not a visuals.toml color. The
// class scoped selector keeps the border on the panel rather than cascading onto
// its children.
setAttribute(Qt::WA_StyledBackground, true);
// Letter spacing is deliberately absent here: Qt's stylesheet syntax has no such
// property and warns on every widget it is applied to. The heading and the caption
// set it on their QFont instead.
setStyleSheet(QStringLiteral(
"ControlsPanel { background-color: palette(window);"
" border: 1px solid palette(mid); border-radius: 4px; }"
"QLabel#controlHeading { color: palette(text); }"
"QLabel#controlBadge { border: 1px solid palette(mid); border-radius: 3px;"
" padding: 1px 5px; font-family: monospace; color: palette(text); }"
"QLabel#controlLabel { color: palette(text); }"
// The row that leaves the mode is marked on its chips rather than its label
// (REQ-UI-CONTROLS-CARD): the label keeps the ordinary text color, so the row
// stays legible whatever the palette, and only the chips carry the warning.
//
// A literal red because there is no palette role for "destructive" -- the
// nearest, bright-text, is white by design, being meant for text over dark
// highlights, and was unreadable on this panel's chrome. This value reads on a
// light and a dark background alike. It is widget chrome, so like the rest of
// this stylesheet it is deliberately not a visuals.toml color.
"QLabel#controlBadgeExit { border: 1px solid #c0392b; border-radius: 3px;"
" padding: 1px 5px; font-family: monospace; color: #c0392b; }"
"QLabel#controlCaption { color: palette(mid); }"));
QVBoxLayout* outerLayout = new QVBoxLayout(this);
outerLayout->setContentsMargins(kCardMarginPx, kCardMarginPx,
kCardMarginPx, kCardMarginPx);
outerLayout->setSpacing(kHeadingGapPx);
m_heading = new QLabel(this);
m_heading->setObjectName(QStringLiteral("controlHeading"));
m_heading->setCursor(Qt::PointingHandCursor);
m_heading->setFont(makeSpacedFont(font(), /*bold*/ true, /*pointSizeDelta*/ 0));
outerLayout->addWidget(m_heading);
// Rows taller than the space available scroll rather than being cut off
// (REQ-UI-CONTROLS-PANEL). The viewport is transparent so the panel's own rounded
// chrome shows through, and horizontal scrolling is off because the width always
// follows the content.
m_rows = new QWidget(this);
m_rowsLayout = new QVBoxLayout(m_rows);
m_rowsLayout->setContentsMargins(0, 0, 0, 0);
m_rowsLayout->setSpacing(0);
m_rows->setAutoFillBackground(false);
m_scrollArea = new QScrollArea(this);
m_scrollArea->setFrameShape(QFrame::NoFrame);
m_scrollArea->setWidgetResizable(true);
m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
m_scrollArea->viewport()->setAutoFillBackground(false);
m_scrollArea->setWidget(m_rows);
outerLayout->addWidget(m_scrollArea);
// Polling rather than subscribing; see the class comment.
m_refreshTimer = new QTimer(this);
connect(m_refreshTimer, &QTimer::timeout, this, &ControlsPanel::refresh);
m_refreshTimer->start(kRefreshMs);
refresh();
}
void ControlsPanel::invalidateLayout()
{
EventManager::getInstance()->sendEventImmediately(
std::make_shared<FloatingLayoutInvalidatedEvent>());
}
void ControlsPanel::mousePressEvent(QMouseEvent* event)
{
// Only the heading toggles; a click anywhere else is swallowed so it never reaches
// the world beneath (REQ-UI-CONTROLS-PANEL).
if (m_heading->geometry().contains(event->pos()))
{
m_collapsed = !m_collapsed;
m_scrollArea->setVisible(!m_collapsed);
invalidateLayout();
}
event->accept();
}
void ControlsPanel::refresh()
{
if (!m_view) { return; }
const ControlContext context = m_view->getControlContext();
const QString heading = getHeadingText(context);
const std::vector<ControlAction> contextActions = getContextActions(context);
const std::vector<ControlAction> alwaysActions = getAlwaysAvailableActions(context);
if (heading == m_shownHeading && contextActions == m_shownContextActions
&& alwaysActions == m_shownAlwaysActions)
{
return;
}
m_shownHeading = heading;
m_shownContextActions = contextActions;
m_shownAlwaysActions = alwaysActions;
rebuild(context);
}
void ControlsPanel::rebuild(const ControlContext& context)
{
m_heading->setText(m_shownHeading);
// Rows are rebuilt wholesale rather than reconciled: a context change replaces
// nearly all of them, and the panel redraws only when something actually changed.
while (QLayoutItem* item = m_rowsLayout->takeAt(0))
{
delete item->widget();
delete item;
}
for (ControlAction action : m_shownContextActions)
{
addAndShow(m_rowsLayout, makeRow(action, context, m_rows));
}
// The always-available block sits under a divider in every context, the General one
// included, so the card is read the same way wherever the player is
// (REQ-UI-CONTROLS-CARD).
if (!m_shownAlwaysActions.empty())
{
QFrame* divider = new QFrame(m_rows);
divider->setFrameShape(QFrame::HLine);
divider->setFrameShadow(QFrame::Plain);
m_rowsLayout->addSpacing(6);
addAndShow(m_rowsLayout, divider);
QLabel* caption = new QLabel(tr("ALWAYS AVAILABLE"), m_rows);
caption->setObjectName(QStringLiteral("controlCaption"));
caption->setFont(makeSpacedFont(font(), /*bold*/ false, /*pointSizeDelta*/ -1));
addAndShow(m_rowsLayout, caption);
}
for (ControlAction action : m_shownAlwaysActions)
{
addAndShow(m_rowsLayout, makeRow(action, context, m_rows));
}
m_scrollArea->setVisible(!m_collapsed);
invalidateLayout();
}
QString ControlsPanel::getHeadingText(const ControlContext& context) const
{
const ControlContextKind kind = getControlContextKind(context);
const QString name = getControlContextName(kind);
QString detail;
switch (kind)
{
case ControlContextKind::Build:
detail = getBuildingTypeName(context.builderType);
break;
case ControlContextKind::Blueprint:
{
// The temporary blueprint is never named (REQ-UI-BLUEPRINT-TEMP), so it is
// labelled by what it is rather than left blank.
const QString blueprintName = m_view->getActiveBlueprintName();
detail = blueprintName.isEmpty() ? tr("Temporary") : blueprintName;
break;
}
case ControlContextKind::Selection:
detail = context.selection == ControlSelection::Buildings
? tr("%n building(s)", "", context.selectionCount)
: tr("%n object(s)", "", context.selectionCount);
break;
case ControlContextKind::General:
case ControlContextKind::Deconstruct:
break;
}
if (detail.isEmpty()) { return name; }
return name + QStringLiteral(" ") + kHeadingSeparator + QStringLiteral(" ") + detail;
}
void ControlsPanel::placeIn(const QRect& viewRect, const std::vector<QRect>& occupiedRects)
{
if (viewRect.isNull()) { return; }
// Rows are torn down and rebuilt wholesale, and a widget added to a layout is only
// shown once that layout runs -- without this the new rows count for nothing and
// the card is measured for the context before it. The polish belongs to the same
// step: a freshly created label reports an unstyled size hint until the stylesheet
// has reached it, and the badge chips carry border and padding that change it.
m_rows->ensurePolished();
m_rowsLayout->invalidate();
m_rowsLayout->activate();
const QRect band = viewRect.adjusted(kMarginPx, kMarginPx, -kMarginPx, -kMarginPx);
if (band.width() <= 0 || band.height() <= 0) { return; }
// Measured from the heading and the rows directly rather than from the panel's own
// layout: the rows now sit in a scroll area, whose size hint describes a viewport
// and says nothing about how tall its contents are. Deliberately not activating the
// panel's own layout either -- that lays its children out inside the geometry left
// over from the previous context, which is the wrong frame of reference for
// choosing the new one. setGeometry below re-runs it.
const int chromePx = 2 * (kCardMarginPx + kBorderPx);
const QSize headingHint = m_heading->sizeHint();
const QSize rowsHint = m_rows->sizeHint();
int contentWidthPx = headingHint.width();
int contentHeightPx = headingHint.height();
if (!m_collapsed)
{
contentWidthPx = qMax(contentWidthPx, rowsHint.width());
contentHeightPx += kHeadingGapPx + rowsHint.height();
}
const int wantedHeightPx = contentHeightPx + chromePx;
// The bottom-left corner of the view, growing upward as rows are added
// (REQ-UI-CONTROLS-PANEL).
int widthPx = qMin(contentWidthPx + chromePx, band.width());
// The build button bar is centered and sized to its buttons, so it usually leaves
// this corner free and the panel can share the bottom edge with it. Only where the
// two would actually meet does the panel rise, clearing the bar's top by the same
// margin it keeps from the view's edges (REQ-UI-BUILD-BAR). The bar is the only
// widget placed before this one, so it is the only rect that can be in the way.
const int bottomPx = getAvailableBottomPx(band, occupiedRects, band.left(),
band.left() + widthPx - 1, kMarginPx);
int heightPx = qMin(wantedHeightPx, qMax(0, bottomPx - band.top() + 1));
int topPx = bottomPx - heightPx + 1;
// Whatever the rows lost to either cap, they scroll for. The scrollbar needs its
// own width, or it would appear over the labels.
if (heightPx < wantedHeightPx)
{
widthPx = qMin(widthPx + m_scrollArea->verticalScrollBar()->sizeHint().width(),
band.width());
}
setGeometry(band.left(), topPx, widthPx, heightPx);
}

87
src/ui/ControlsPanel.h Normal file
View File

@@ -0,0 +1,87 @@
#pragma once
#include <vector>
#include <QRect>
#include <QString>
#include <QWidget>
#include "ControlAction.h"
#include "FloatingPanel.h"
class GameWorldView;
class QLabel;
class QScrollArea;
class QTimer;
class QVBoxLayout;
// Shows the controls available in the player's current situation
// (REQ-UI-CONTROLS-PANEL). The panel decides nothing: which rows apply is
// ControlAction.h's answer, the same one the key handling and the world view's mouse
// dispatch act on, so what is shown and what happens cannot part company
// (REQ-UI-CONTROLS-ACCURACY).
//
// It floats over the game world at the left edge, bottom-aligned within the band its
// owner hands it, and collapses to its heading when the heading is clicked.
//
// Refreshed on a timer rather than by subscribing to events: two of the things that
// change a row -- a belt drag starting, the ghost moving over a transfer target --
// happen on mouse movement and publish nothing, and they still have to be reflected
// while the game is paused, so there is no tick to hang it on either. The rebuild is
// skipped unless the resolved content actually differs, which is a vector of enums to
// compare.
class ControlsPanel : public QWidget, public FloatingPanel
{
Q_OBJECT
public:
// Neither pointer is owned; both must outlive this widget. The view is the source
// of the control context, being the widget that owns the build mode and the
// selection.
ControlsPanel(const GameWorldView* view, QWidget* parent = nullptr);
// Places the panel in the bottom-left corner of the game world view. It shares the
// bottom edge with the build button bar rather than clearing its strip, the bar
// being centered and sized to its buttons and so usually leaving the left free; it
// rises above the bar only when the two would otherwise overlap
// (REQ-UI-CONTROLS-PANEL, REQ-UI-BUILD-BAR). The bar is the only thing placed before
// it, so it is the only rect it ever has to rise above.
void placeIn(const QRect& viewRect,
const std::vector<QRect>& occupiedRects) override;
protected:
// Clicking the heading collapses and expands the panel (REQ-UI-CONTROLS-PANEL).
void mousePressEvent(QMouseEvent* event) override;
private:
// Re-resolves the context and rebuilds only if the rows or the heading changed.
void refresh();
// Replaces the rows with those of the current context.
void rebuild(const ControlContext& context);
// The heading's "<name> * <detail>" text for the context, detail omitted when the
// context has none.
QString getHeadingText(const ControlContext& context) const;
// Asks for the placement pass to be re-run, the panel's own size having changed.
void invalidateLayout();
const GameWorldView* m_view;
QLabel* m_heading;
// Scrolls the rows once they outgrow the space the panel has (REQ-UI-CONTROLS-PANEL).
// The heading is deliberately outside it, so it stays put and stays clickable.
QScrollArea* m_scrollArea;
QWidget* m_rows;
QVBoxLayout* m_rowsLayout;
QTimer* m_refreshTimer;
// What is currently drawn, so a refresh that resolves to the same thing does
// nothing. The always-available block is kept separately because the divider
// between the two is part of what is drawn.
QString m_shownHeading;
std::vector<ControlAction> m_shownContextActions;
std::vector<ControlAction> m_shownAlwaysActions;
// Survives context changes and simulation restarts; presentation only, never a
// command (REQ-UI-CONTROLS-PANEL).
bool m_collapsed = false;
};

View File

@@ -1,403 +0,0 @@
#include "FieldSelectionPanel.h"
#include <algorithm>
#include <map>
#include <string>
#include <QFont>
#include <QLabel>
#include <QStringList>
#include <QVBoxLayout>
#include "DebrisSystem.h"
#include "DisplayName.h"
#include "EntityAdmin.h"
#include "FactionComponent.h"
#include "GameConfig.h"
#include "HealthComponent.h"
#include "ModuleOwnerComponent.h"
#include "SelectedBehaviorComponent.h"
#include "ShipIdentityComponent.h"
#include "ShipStatsCalculator.h"
#include "ShipStatsPanel.h"
#include "Simulation.h"
#include "StationBodyComponent.h"
#include "ThreatCostCalculator.h"
#include "WeaponComponent.h"
FieldSelectionPanel::FieldSelectionPanel(Simulation* sim,
const GameConfig* config,
QWidget* parent)
: QWidget(parent)
, m_sim(sim)
, m_config(config)
{
// Zero margins and the same spacing as the enclosing SelectedBuildingPanel layout, so
// nesting the field widgets in this panel leaves their geometry unchanged.
m_layout = new QVBoxLayout(this);
m_layout->setContentsMargins(0, 0, 0, 0);
m_layout->setSpacing(4);
m_layout->setAlignment(Qt::AlignTop);
m_entityTitleLabel = new QLabel(this);
QFont titleFont = m_entityTitleLabel->font();
titleFont.setBold(true);
m_entityTitleLabel->setFont(titleFont);
m_layout->addWidget(m_entityTitleLabel);
m_entityTitleLabel->hide();
m_entityStatsPanel = new ShipStatsPanel(config, this);
m_layout->addWidget(m_entityStatsPanel);
m_entityStatsPanel->hide();
m_stationStatsLabel = new QLabel(this);
m_stationStatsLabel->setWordWrap(true);
m_layout->addWidget(m_stationStatsLabel);
m_stationStatsLabel->hide();
m_entitySummaryLabel = new QLabel(this);
m_entitySummaryLabel->setWordWrap(true);
m_layout->addWidget(m_entitySummaryLabel);
m_entitySummaryLabel->hide();
m_scrapLabel = new QLabel(this);
m_layout->addWidget(m_scrapLabel);
m_scrapLabel->hide();
hide();
registerForEvents();
}
FieldSelectionPanel::~FieldSelectionPanel()
{
unregisterForEvents();
}
void FieldSelectionPanel::setSelectedEntities(const std::vector<entt::entity>& entities)
{
m_selectedEntities = entities;
rebuild();
}
void FieldSelectionPanel::setSelectedDebris(const std::vector<entt::entity>& debris)
{
m_selectedDebris = debris;
rebuild();
}
void FieldSelectionPanel::clearSelection()
{
m_selectedEntities.clear();
m_selectedDebris.clear();
rebuild();
}
bool FieldSelectionPanel::hasSelection() const
{
return !m_selectedEntities.empty() || !m_selectedDebris.empty();
}
void FieldSelectionPanel::hideAllWidgets()
{
m_entityTitleLabel->hide();
m_entityStatsPanel->hide();
m_stationStatsLabel->hide();
m_entitySummaryLabel->hide();
m_scrapLabel->hide();
}
void FieldSelectionPanel::rebuild()
{
if (!hasSelection())
{
// Nothing in the field category: take no space, leaving the panel to whatever
// the building category shows (REQ-UI-SELECTION-CATEGORIES).
hideAllWidgets();
hide();
return;
}
show();
EntityAdmin& admin = m_sim->getAdmin();
// A full single-object stats panel is shown only for a lone field object: one actor
// with no debris, or one piece of debris with no actors. As soon as the selection holds
// more than one object (multiple actors, multiple debris, or actors plus debris), the
// panel switches to the compact count summary (REQ-UI-FIELD-MULTI-SELECTION).
if (m_selectedEntities.size() == 1 && m_selectedDebris.empty())
{
m_entitySummaryLabel->hide();
m_scrapLabel->hide();
const entt::entity entity = m_selectedEntities.front();
if (admin.isValid(entity) && admin.hasAll<ShipIdentityComponent>(entity))
{
buildEntityShip(entity);
}
else if (admin.isValid(entity) && admin.hasAll<StationBodyComponent>(entity))
{
buildEntityStation(entity);
}
else
{
m_entityTitleLabel->hide();
m_entityStatsPanel->hide();
m_stationStatsLabel->hide();
}
return;
}
if (m_selectedEntities.empty() && m_selectedDebris.size() == 1)
{
// Single piece of debris: a "Debris" heading plus a "Scrap" stat row, styled like
// the ship/station stats panels (REQ-UI-DEBRIS-PANEL).
m_entitySummaryLabel->hide();
m_entityStatsPanel->hide();
m_stationStatsLabel->hide();
buildDebrisSingle();
return;
}
// More than one field object: a compact count summary. buildEntitySummary() appends the
// "Debris x N" and "Scrap x N" lines when debris is part of the selection.
m_entityTitleLabel->hide();
m_entityStatsPanel->hide();
m_stationStatsLabel->hide();
m_scrapLabel->hide();
buildEntitySummary();
}
void FieldSelectionPanel::refreshDisplay()
{
if (!hasSelection()) { return; }
// Keep the live values current: the single-actor stats panel, the single-debris stats
// panel (whose Scrap row shrinks as it is collected), or the count summary (whose Scrap
// line shrinks likewise) — matching the layout chosen by rebuild()
// (REQ-UI-SHIP-STATS-PANEL, REQ-UI-DEBRIS-PANEL).
if (m_selectedEntities.size() == 1 && m_selectedDebris.empty())
{
refreshEntityStats();
}
else if (m_selectedEntities.empty() && m_selectedDebris.size() == 1)
{
buildDebrisSingle();
}
else
{
buildEntitySummary();
}
}
void FieldSelectionPanel::buildDebrisSingle()
{
// "Debris" heading + a single "Scrap" stat row for the piece's remaining amount,
// mirroring the single-actor stats panels (REQ-UI-DEBRIS-PANEL).
m_entityTitleLabel->setText(tr("Debris"));
m_entityTitleLabel->show();
m_scrapLabel->setText(tr("Scrap: %1").arg(selectedDebrisScrapTotal()));
m_scrapLabel->show();
}
void FieldSelectionPanel::buildEntitySummary()
{
EntityAdmin& admin = m_sim->getAdmin();
// Group actors by faction + kind + ship schematic, preserving first-seen order
// (REQ-UI-FIELD-MULTI-SELECTION).
std::vector<QString> keys;
std::map<QString, int> counts;
std::map<QString, QString> labels;
for (entt::entity entity : m_selectedEntities)
{
if (!admin.isValid(entity)) { continue; }
const bool isEnemy = admin.hasAll<FactionComponent>(entity)
&& admin.get<FactionComponent>(entity).isEnemy;
QString key;
QString label;
if (admin.hasAll<ShipIdentityComponent>(entity))
{
const std::string& id = admin.get<ShipIdentityComponent>(entity).schematicId;
const QString name = QString::fromStdString(toDisplayName(id));
key = (isEnemy ? QStringLiteral("ship:enemy:") : QStringLiteral("ship:player:"))
+ QString::fromStdString(id);
label = isEnemy ? tr("Enemy %1").arg(name) : name;
}
else if (admin.hasAll<StationBodyComponent>(entity))
{
key = isEnemy ? QStringLiteral("station:enemy") : QStringLiteral("station:player");
label = isEnemy ? tr("Enemy Defence Station") : tr("Player Defence Station");
}
else
{
continue;
}
if (counts.find(key) == counts.end())
{
keys.push_back(key);
labels[key] = label;
}
counts[key] += 1;
}
// One "<type> x <count>" line per group (matching the recipe tooltip and the building
// multi-selection). No total-count header, consistent with the building panel. When
// debris is part of the selection, a "Debris x <count>" line followed by a
// "Scrap x <total>" line are appended into the same label so the line spacing is
// uniform (REQ-UI-FIELD-MULTI-SELECTION, REQ-UI-DEBRIS-PANEL).
QStringList lines;
for (const QString& key : keys)
{
lines << tr("%1 x %2").arg(labels[key]).arg(counts[key]);
}
if (!m_selectedDebris.empty())
{
lines << tr("Debris x %1").arg(static_cast<int>(m_selectedDebris.size()));
lines << scrapTotalText();
}
m_entitySummaryLabel->setText(lines.join('\n'));
m_entitySummaryLabel->show();
}
void FieldSelectionPanel::buildEntityShip(entt::entity entity)
{
EntityAdmin& admin = m_sim->getAdmin();
const ShipIdentityComponent& identity = admin.get<ShipIdentityComponent>(entity);
const HealthComponent& health = admin.get<HealthComponent>(entity);
m_entityTitleLabel->setText(tr("Ship: %1")
.arg(QString::fromStdString(identity.schematicId)));
m_entityTitleLabel->show();
const ShipStats stats = buildShipStatsFromEntity(admin, entity);
m_entityStatsPanel->refreshFromLive(stats, health.hp);
m_entityStatsPanel->setBehavior(
admin.get<SelectedBehaviorComponent>(entity).winner);
m_entityStatsPanel->setDebugDrawEnabled(m_debugDraw);
const ShipDef* schematicDef =
m_config->ships.findShipDef(identity.schematicId);
if (schematicDef)
{
const double threat = calculateShipThreatCost(
m_config->threatCosts, *m_config, schematicDef->id,
schematicDef->defaultModules);
m_entityStatsPanel->setThreatCost(threat);
}
m_entityStatsPanel->show();
m_stationStatsLabel->hide();
}
void FieldSelectionPanel::buildEntityStation(entt::entity entity)
{
EntityAdmin& admin = m_sim->getAdmin();
const HealthComponent& health = admin.get<HealthComponent>(entity);
const bool isEnemy = admin.hasAll<FactionComponent>(entity)
&& admin.get<FactionComponent>(entity).isEnemy;
m_entityTitleLabel->setText(isEnemy
? tr("Enemy Defence Station")
: tr("Player Defence Station"));
m_entityTitleLabel->show();
float totalDps = 0.0f;
float maxRange = 0.0f;
bool hasWeapons = false;
admin.forEach<ModuleOwnerComponent, WeaponComponent>(
[&](entt::entity /*child*/, const ModuleOwnerComponent& owner, const WeaponComponent& w)
{
if (owner.owner != entity) { return; }
hasWeapons = true;
totalDps += w.damage * w.fireRateHz;
if (w.range_tiles > maxRange) { maxRange = w.range_tiles; }
});
QString statsText = tr("HP: %1 / %2")
.arg(static_cast<int>(health.hp + 0.5f))
.arg(static_cast<int>(health.maxHp + 0.5f));
if (hasWeapons)
{
statsText += tr("\nDPS: %1").arg(QString::number(static_cast<double>(totalDps), 'f', 1));
statsText += tr("\nRange: %1 tiles").arg(QString::number(static_cast<double>(maxRange), 'f', 1));
}
m_stationStatsLabel->setText(statsText);
m_stationStatsLabel->show();
m_entityStatsPanel->hide();
}
void FieldSelectionPanel::refreshEntityStats()
{
// Only the single-actor stats panel needs a live refresh; the multi-actor summary is
// static counts, and GameWorldView prunes dead/despawned actors and re-emits the
// selection (REQ-UI-ENTITY-CLICK-SELECT), so the panel does not mutate it here.
if (m_selectedEntities.size() != 1) { return; }
EntityAdmin& admin = m_sim->getAdmin();
const entt::entity entity = m_selectedEntities.front();
if (!admin.isValid(entity) || !admin.hasAll<HealthComponent>(entity)) { return; }
const HealthComponent& health = admin.get<HealthComponent>(entity);
if (health.hp <= 0.0f) { return; }
if (admin.hasAll<ShipIdentityComponent>(entity))
{
const ShipStats stats = buildShipStatsFromEntity(admin, entity);
m_entityStatsPanel->refreshFromLive(stats, health.hp);
m_entityStatsPanel->setBehavior(
admin.get<SelectedBehaviorComponent>(entity).winner);
}
else if (admin.hasAll<StationBodyComponent>(entity))
{
buildEntityStation(entity);
}
}
int FieldSelectionPanel::selectedDebrisScrapTotal() const
{
// Sum the remaining scrap across the still-living selected debris (REQ-UI-DEBRIS-PANEL).
int total = 0;
for (const DebrisInfo& info : getAllDebrisInfo(m_sim->getAdmin()))
{
if (std::find(m_selectedDebris.begin(), m_selectedDebris.end(), info.entity)
!= m_selectedDebris.end())
{
total += info.amount;
}
}
return total;
}
QString FieldSelectionPanel::scrapTotalText() const
{
return tr("Scrap x %1").arg(selectedDebrisScrapTotal());
}
void FieldSelectionPanel::handleEvent(std::shared_ptr<const TickAdvancedEvent> /*event*/)
{
refreshDisplay();
}
void FieldSelectionPanel::handleEvent(
std::shared_ptr<const PlayerCommandsAppliedEvent> /*event*/)
{
// Player commands are applied by a queued drain, not synchronously. When the game is
// paused no tick advances, so TickAdvancedEvent never fires; refresh here too.
refreshDisplay();
}
void FieldSelectionPanel::handleEvent(std::shared_ptr<const DebugDrawToggledEvent> event)
{
m_debugDraw = event->active;
m_entityStatsPanel->setDebugDrawEnabled(event->active);
}

View File

@@ -1,91 +0,0 @@
#pragma once
#include <vector>
#include <QString>
#include <QWidget>
#include "entt/entity/entity.hpp"
#include "DebugDrawToggledEvent.h"
#include "EventHandler.h"
#include "PlayerCommandsAppliedEvent.h"
#include "TickAdvancedEvent.h"
struct GameConfig;
class Simulation;
class ShipStatsPanel;
class QLabel;
class QVBoxLayout;
// Renders the "field" selection category — ships, defence stations and debris — as either
// a single-object stats panel (ship, station, or debris) or a compact multi-object count
// summary (REQ-UI-SELECTION-CATEGORIES, REQ-UI-FIELD-MULTI-SELECTION, REQ-UI-DEBRIS-PANEL).
//
// The panel owns its own selection state and its own widgets, and nothing else. Which of
// the two selection categories owns the side panel is arbitrated by the parent
// SelectedBuildingPanel: it feeds this panel through setSelectedEntities() /
// setSelectedDebris() / clearSelection() and asks it via hasSelection(). This panel hides
// itself whenever its selection is empty, so an inactive field category takes no space.
class FieldSelectionPanel : public QWidget,
public CombinedEventHandler<TickAdvancedEvent,
PlayerCommandsAppliedEvent,
DebugDrawToggledEvent>
{
Q_OBJECT
public:
FieldSelectionPanel(Simulation* sim, const GameConfig* config,
QWidget* parent = nullptr);
~FieldSelectionPanel() override;
// Replaces the selected actors (ships and defence stations); debris is left alone,
// the two coexist within the field category (REQ-UI-SELECTION-CATEGORIES).
void setSelectedEntities(const std::vector<entt::entity>& entities);
// Replaces the selected debris; the selected actors are left alone.
void setSelectedDebris(const std::vector<entt::entity>& debris);
// Drops the whole field selection — used when the building category takes over.
void clearSelection();
// True while the field category has anything selected, i.e. while this panel owns
// the side panel's content.
bool hasSelection() const;
private:
void handleEvent(std::shared_ptr<const TickAdvancedEvent> event) override;
void handleEvent(std::shared_ptr<const PlayerCommandsAppliedEvent> event) override;
void handleEvent(std::shared_ptr<const DebugDrawToggledEvent> event) override;
// Picks the layout for the current selection and shows/hides this panel accordingly.
void rebuild();
// Keeps the live values of the layout chosen by rebuild() current.
void refreshDisplay();
void buildEntityShip(entt::entity entity);
void buildEntityStation(entt::entity entity);
void buildEntitySummary();
void buildDebrisSingle();
void refreshEntityStats();
void hideAllWidgets();
// Summed remaining scrap across the selected debris (REQ-UI-DEBRIS-PANEL).
int selectedDebrisScrapTotal() const;
// "Scrap x N" line for the multi-object summary (REQ-UI-FIELD-MULTI-SELECTION).
QString scrapTotalText() const;
Simulation* m_sim;
const GameConfig* m_config;
bool m_debugDraw = false;
// The selected ships/defence stations. Shares the "field" selection category with
// debris (m_selectedDebris): both can be non-empty at once (REQ-UI-SELECTION-CATEGORIES).
std::vector<entt::entity> m_selectedEntities;
std::vector<entt::entity> m_selectedDebris;
QVBoxLayout* m_layout;
QLabel* m_entityTitleLabel;
ShipStatsPanel* m_entityStatsPanel;
QLabel* m_stationStatsLabel;
QLabel* m_entitySummaryLabel;
// Shows the debris "Scrap" stat row (single selection) — the scrap total for the
// multi-object summary lives in m_entitySummaryLabel instead.
QLabel* m_scrapLabel;
};

27
src/ui/FloatingPanel.h Normal file
View File

@@ -0,0 +1,27 @@
#pragma once
#include <vector>
#include <QRect>
// A widget floating over the game world view (REQ-UI-WORLD-SIZE). MainWindow places all
// of them in one ordered pass -- build button bar, then controls panel, then selection
// panel -- and each places itself into the space the earlier ones have not taken. The
// order is the priority the requirements state: the bar never moves for anyone
// (REQ-UI-BUILD-BAR), the controls panel steps around the bar (REQ-UI-CONTROLS-PANEL),
// and keeping clear of both is the selection panel's job (REQ-UI-SELECTION-PANEL).
//
// A widget never re-places itself, because what it may take depends on the widgets placed
// before it. It instead publishes FloatingLayoutInvalidatedEvent whenever its content or
// its visibility changed, and the owner re-runs the whole pass.
class FloatingPanel
{
public:
virtual ~FloatingPanel() = default;
// Sets this widget's own geometry within viewRect, keeping clear of occupiedRects --
// the geometry of every floating widget already placed in this pass, in the same
// coordinates. A widget with nothing to show hides itself and takes no space.
virtual void placeIn(const QRect& viewRect,
const std::vector<QRect>& occupiedRects) = 0;
};

View File

@@ -1,6 +1,7 @@
#include "GameWorldView.h" #include "GameWorldView.h"
#include "PlacementRules.h" #include "PlacementRules.h"
#include "FactoryQueries.h" #include "FactoryQueries.h"
#include "BlueprintLibrary.h"
#include <algorithm> #include <algorithm>
#include <cctype> #include <cctype>
@@ -46,6 +47,8 @@
#include "ItemIconCache.h" #include "ItemIconCache.h"
#include "PositionComponent.h" #include "PositionComponent.h"
#include "DebrisSystem.h" #include "DebrisSystem.h"
#include "SelectionAnchorChangedEvent.h"
#include "SelectionBounds.h"
#include "SelectionChangedEvent.h" #include "SelectionChangedEvent.h"
#include "ShipIdentityComponent.h" #include "ShipIdentityComponent.h"
#include "ShipSystem.h" #include "ShipSystem.h"
@@ -58,7 +61,7 @@
#include "EscapeMenuRequestedEvent.h" #include "EscapeMenuRequestedEvent.h"
#include "TracePrintRequestedEvent.h" #include "TracePrintRequestedEvent.h"
#include "BuildHotkeyPressedEvent.h" #include "BuildHotkeyPressedEvent.h"
#include "TemporaryBlueprintRequestedEvent.h" #include "GameResetEvent.h"
#include "BossWaveUpdatedEvent.h" #include "BossWaveUpdatedEvent.h"
#include "BuilderModeExitedEvent.h" #include "BuilderModeExitedEvent.h"
#include "BlueprintModeExitedEvent.h" #include "BlueprintModeExitedEvent.h"
@@ -73,6 +76,23 @@
namespace namespace
{ {
// The action a left-button gesture triggers, with the Ctrl variant falling back to the
// plain one wherever nothing is bound to it. That fallback is what keeps Ctrl+click
// placing a building in builder mode and Ctrl+drag deconstructing an area: the modifier
// only means something where an action claims it (REQ-UI-CONTROLS-CONTENT).
ControlAction resolveLeftGesture(bool controlHeld, bool isDrag,
const ControlContext& context)
{
if (controlHeld)
{
const ControlAction action = resolveMouseAction(
isDrag ? MouseBinding::CtrlLeftDrag : MouseBinding::CtrlLeftClick, context);
if (action != ControlAction::None) { return action; }
}
return resolveMouseAction(isDrag ? MouseBinding::LeftDrag : MouseBinding::LeftClick,
context);
}
// Keep only the filter entries whose item type is currently unlocked // Keep only the filter entries whose item type is currently unlocked
// (REQ-LOCK-UI-BLUEPRINT). An empty result means "accept all". // (REQ-LOCK-UI-BLUEPRINT). An empty result means "accept all".
std::vector<ItemType> filterUnlockedItems(const std::vector<ItemType>& filter, std::vector<ItemType> filterUnlockedItems(const std::vector<ItemType>& filter,
@@ -269,20 +289,6 @@ void GameWorldView::onFrame()
pruneDespawnedDebris(); pruneDespawnedDebris();
pruneDespawnedActors(); pruneDespawnedActors();
// Expire copy/paste flashes. Lifetime is wall-clock (the frame delta), so the
// flash plays for a fixed real duration regardless of game speed, including
// while the game is paused (REQ-BLD-COPY-CONFIG-FEEDBACK).
if (!m_copyConfigFlashes.empty())
{
std::vector<CopyConfigFlash> live;
for (CopyConfigFlash flash : m_copyConfigFlashes)
{
flash.remainingMs -= elapsed;
if (flash.remainingMs > 0) { live.push_back(flash); }
}
m_copyConfigFlashes = std::move(live);
}
// Apply held scroll // Apply held scroll
{ {
const bool viewMoved = const bool viewMoved =
@@ -414,9 +420,8 @@ void GameWorldView::paintGL()
WorldRenderFrame GameWorldView::makeRenderFrame() const WorldRenderFrame GameWorldView::makeRenderFrame() const
{ {
return WorldRenderFrame{m_selection, m_buildMode, m_activeBeams, m_copiedConfig, return WorldRenderFrame{m_selection, m_buildMode, m_activeBeams, m_boxSelecting,
m_copyConfigFlashes, m_boxSelecting, m_boxStartTile, m_boxStartTile, m_boxCurrentTile, m_debugDraw};
m_boxCurrentTile, m_debugDraw};
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -578,16 +583,21 @@ void GameWorldView::placeBlueprintAtTile(QPoint center)
// Locked building types are excluded from this placement entirely // Locked building types are excluded from this placement entirely
// (REQ-LOCK-BUILDING, REQ-LOCK-UI-BLUEPRINT): not validity-checked here. // (REQ-LOCK-BUILDING, REQ-LOCK-UI-BLUEPRINT): not validity-checked here.
if (!m_sim->isBuildingUnlocked(bb.type)) { continue; } if (!m_sim->isBuildingUnlocked(bb.type)) { continue; }
if (!canPlaceBuildingHere(bb.type, center + bb.offset, bb.rotation)) { return; } if (resolveBlueprintGhostHere(bb, center).action == BlueprintGhostAction::Invalid)
{
return;
}
} }
// Cost only applies to buildings that are genuinely new (not rotate-in-place), // Only genuinely new buildings are charged for: a compatible overlap places nothing
// and excludes locked building types (REQ-LOCK-UI-BLUEPRINT). // (REQ-UI-BLUEPRINT-OVERLAP) and a transfer changes settings only
// (REQ-UI-BLUEPRINT-TRANSFER). Locked building types are excluded from the total
// as well (REQ-LOCK-UI-BLUEPRINT).
int totalCost = 0; int totalCost = 0;
for (const BlueprintBuilding& bb : bp.buildings) for (const BlueprintBuilding& bb : bp.buildings)
{ {
if (!m_sim->isBuildingUnlocked(bb.type)) { continue; } if (!m_sim->isBuildingUnlocked(bb.type)) { continue; }
if (findRotateInPlaceTarget(m_sim->getFactoryState(), m_sim->getConfig(), bb.type, center + bb.offset, bb.rotation).has_value()) if (resolveBlueprintGhostHere(bb, center).action != BlueprintGhostAction::PlaceNew)
{ {
continue; continue;
} }
@@ -600,15 +610,15 @@ void GameWorldView::placeBlueprintAtTile(QPoint center)
{ {
if (!m_sim->isBuildingUnlocked(bb.type)) { continue; } if (!m_sim->isBuildingUnlocked(bb.type)) { continue; }
const QPoint anchor = center + bb.offset; const QPoint anchor = center + bb.offset;
const std::optional<BuildingId> rotateTarget = const BlueprintGhostResolved resolved = resolveBlueprintGhostHere(bb, center);
findRotateInPlaceTarget(m_sim->getFactoryState(), m_sim->getConfig(), bb.type, anchor, bb.rotation);
if (rotateTarget.has_value()) // The building the blueprint wants is already there, facing the same way: leave
// it exactly as it is (REQ-UI-BLUEPRINT-OVERLAP).
if (resolved.action == BlueprintGhostAction::CompatibleOverlap) { continue; }
if (resolved.action == BlueprintGhostAction::Transfer)
{ {
std::shared_ptr<RotateInPlaceCommand> rotateCommand = transferConfigTo(*resolved.targetId, bb);
std::make_shared<RotateInPlaceCommand>();
rotateCommand->id = *rotateTarget;
rotateCommand->newRotation = bb.rotation;
enqueueCommand(rotateCommand);
continue; continue;
} }
@@ -621,26 +631,7 @@ void GameWorldView::placeBlueprintAtTile(QPoint center)
command->anchor = anchor; command->anchor = anchor;
command->rotation = bb.rotation; command->rotation = bb.rotation;
if (!bb.recipeId.empty()) command->recipeId = unlockedRecipeId(bb);
{
if (bb.type == BuildingType::Shipyard)
{
if (m_sim->isSchematicUnlocked(bb.recipeId))
{
command->recipeId = bb.recipeId;
}
}
else
{
const bool needsUnlockCheck = bb.type == BuildingType::Miner
|| bb.type == BuildingType::Assembler;
if (!needsUnlockCheck || m_sim->isRecipeUnlocked(bb.recipeId))
{
command->recipeId = bb.recipeId;
}
}
}
command->shipLayout = bb.shipLayout; command->shipLayout = bb.shipLayout;
if (bb.type == BuildingType::Splitter if (bb.type == BuildingType::Splitter
@@ -658,6 +649,97 @@ void GameWorldView::placeBlueprintAtTile(QPoint center)
} }
} }
BlueprintGhostResolved GameWorldView::resolveBlueprintGhostHere(const BlueprintBuilding& building,
QPoint center) const
{
// A single-building blueprint hit-tests the cursor for its transfer target; a
// constellation does not (REQ-UI-BLUEPRINT-TRANSFER). `center` is the cursor tile.
// The size is read from the blueprint as stored, before locked types are dropped, so
// the gesture behaves the same however much the player has unlocked.
const std::optional<QPoint> hoverTile =
m_buildMode.getBlueprint().buildings.size() == 1 ? std::make_optional(center)
: std::nullopt;
return resolveBlueprintGhost(m_sim->getFactoryState(), m_sim->getConfig(),
building.type, center + building.offset, building.rotation,
hoverTile);
}
std::string GameWorldView::unlockedRecipeId(const BlueprintBuilding& building) const
{
// A stored recipe or schematic is applied only while it is unlocked; a locked one
// yields no id at all rather than a stale one (REQ-LOCK-UI-BLUEPRINT). Shared by
// placement and configuration transfer so the two cannot gate differently.
if (building.recipeId.empty()) { return std::string(); }
if (building.type == BuildingType::Shipyard)
{
return m_sim->isSchematicUnlocked(building.recipeId) ? building.recipeId
: std::string();
}
const bool needsUnlockCheck = building.type == BuildingType::Miner
|| building.type == BuildingType::Assembler;
if (!needsUnlockCheck || m_sim->isRecipeUnlocked(building.recipeId))
{
return building.recipeId;
}
return std::string();
}
void GameWorldView::transferConfigTo(BuildingId id, const BlueprintBuilding& source)
{
// Hands the blueprint's settings to a building that is already there, changing
// nothing else -- no construction site, no cost, no rotation
// (REQ-UI-BLUEPRINT-TRANSFER). Every field is sent unconditionally, so a field the
// blueprint has nothing stored for clears the target's rather than leaving it: the
// target ends up identical to the source. Setting a value the building already holds
// is a no-op in the simulation (REQ-MAT-INPUT-BUFFER), which is what keeps clicking
// an already-matching building free of buffer and production-progress loss.
if (source.type == BuildingType::Splitter)
{
// Operational splitters are configured by tile, sites by BuildingId (mirrors
// SelectionPanel::onSplitterFilterChanged). Locked item types are dropped
// per REQ-LOCK-UI-BLUEPRINT.
const std::vector<ItemType> filterA = filterUnlockedItems(source.splitterFilterA, *m_sim);
const std::vector<ItemType> filterB = filterUnlockedItems(source.splitterFilterB, *m_sim);
if (const Building* building = findBuilding(m_sim->getFactoryState(), id))
{
std::shared_ptr<SetSplitterFiltersCommand> command =
std::make_shared<SetSplitterFiltersCommand>();
command->tile = building->anchor;
command->filterA = filterA;
command->filterB = filterB;
enqueueCommand(command);
}
else
{
std::shared_ptr<SetSiteSplitterFiltersCommand> command =
std::make_shared<SetSiteSplitterFiltersCommand>();
command->id = id;
command->filterA = filterA;
command->filterB = filterB;
enqueueCommand(command);
}
return;
}
std::shared_ptr<SetRecipeCommand> recipeCommand = std::make_shared<SetRecipeCommand>();
recipeCommand->id = id;
recipeCommand->recipeId = unlockedRecipeId(source);
enqueueCommand(recipeCommand);
// After the schematic, never before: a genuine schematic change resets the layout,
// and both commands drain in order at the next tick boundary.
if (source.type == BuildingType::Shipyard)
{
std::shared_ptr<SetShipLayoutCommand> layoutCommand =
std::make_shared<SetShipLayoutCommand>();
layoutCommand->id = id;
layoutCommand->layout = source.shipLayout.value_or(ShipLayoutConfig{});
enqueueCommand(layoutCommand);
}
}
void GameWorldView::updateTunnelGhost() void GameWorldView::updateTunnelGhost()
{ {
// The connection preview and entry/exit switch only apply at a valid placement // The connection preview and entry/exit switch only apply at a valid placement
@@ -1013,7 +1095,7 @@ void GameWorldView::keyPressEvent(QKeyEvent* event)
// Keys are turned into actions and published by the input mapper // Keys are turned into actions and published by the input mapper
// (REQ-UI-HOTKEYS); this widget reacts to those as an ordinary subscriber, so // (REQ-UI-HOTKEYS); this widget reacts to those as an ordinary subscriber, so
// nothing is handled here directly. // nothing is handled here directly.
if (m_inputMapper.handleKeyPress(event)) { return; } if (m_inputMapper.handleKeyPress(event, getControlContext())) { return; }
QOpenGLWidget::keyPressEvent(event); QOpenGLWidget::keyPressEvent(event);
} }
@@ -1025,11 +1107,7 @@ void GameWorldView::keyReleaseEvent(QKeyEvent* event)
QOpenGLWidget::keyReleaseEvent(event); QOpenGLWidget::keyReleaseEvent(event);
return; return;
} }
if (m_inputMapper.handleKeyRelease(event)) { return; } if (m_inputMapper.handleKeyRelease(event, getControlContext())) { return; }
// Releasing Shift discards the copied building settings (REQ-BLD-COPY-CONFIG).
// Stays here rather than moving to the input mapper: Shift is the modifier of a
// mouse gesture, not a keyboard action of its own.
if (event->key() == Qt::Key_Shift) { m_copiedConfig.reset(); }
QOpenGLWidget::keyReleaseEvent(event); QOpenGLWidget::keyReleaseEvent(event);
} }
@@ -1043,45 +1121,93 @@ void GameWorldView::focusOutEvent(QFocusEvent* event)
QOpenGLWidget::focusOutEvent(event); QOpenGLWidget::focusOutEvent(event);
} }
void GameWorldView::setBlueprintLibrary(const BlueprintLibrary* library)
{
m_blueprintLibrary = library;
}
ControlContext GameWorldView::getControlContext() const
{
ControlContext context;
context.mode = m_buildMode.getMode();
context.draggingBelt = m_buildMode.isDraggingBelt();
context.hoveredGhostIsTransfer = m_buildMode.isHoveredGhostTransfer();
if (m_buildMode.isBuilderMode()) { context.builderType = m_buildMode.getBuilderType(); }
// Buildings win over field objects, so the two are never both non-empty
// (REQ-UI-SELECTION-CATEGORIES).
const std::vector<BuildingId>& buildings = m_selection.getSelectedBuildings();
const std::vector<entt::entity>& actors = m_selection.getSelectedActors();
const std::vector<entt::entity>& debris = m_selection.getSelectedDebris();
if (!buildings.empty())
{
context.selection = ControlSelection::Buildings;
context.selectionCount = static_cast<int>(buildings.size());
}
else if (!actors.empty() || !debris.empty())
{
context.selection = ControlSelection::FieldObjects;
context.selectionCount = static_cast<int>(actors.size() + debris.size());
}
if (m_blueprintLibrary)
{
context.placeableBuildingSelected = m_blueprintLibrary->getCanCaptureSelection();
context.temporaryBlueprintExists = m_blueprintLibrary->getHasTemporaryBlueprint();
}
return context;
}
QString GameWorldView::getActiveBlueprintName() const
{
if (!m_buildMode.isBlueprintMode()) { return QString(); }
return m_buildMode.getBlueprint().name;
}
void GameWorldView::mousePressEvent(QMouseEvent* event) void GameWorldView::mousePressEvent(QMouseEvent* event)
{ {
const WorldCoordinates coordinates = getCoordinates(); const WorldCoordinates coordinates = getCoordinates();
const ControlContext context = getControlContext();
if (event->button() != Qt::LeftButton) if (event->button() != Qt::LeftButton)
{ {
if (event->button() == Qt::RightButton) if (event->button() == Qt::RightButton)
{ {
if (m_buildMode.isBuilderMode() && m_buildMode.isDraggingBelt()) switch (resolveMouseAction(MouseBinding::RightClick, context))
{ {
// Cancel the in-progress belt drag without placing anything; case ControlAction::CancelBeltLine:
// stay in belt builder mode (REQ-BLD-BELT-DRAG). // Drop the in-progress path without placing anything; belt builder
// mode stays active (REQ-BLD-BELT-DRAG).
m_buildMode.cancelBeltDrag(); m_buildMode.cancelBeltDrag();
} break;
else if (m_buildMode.getMode() != BuildMode::None) case ControlAction::ExitMode:
{
m_buildMode.exitCurrentMode(); m_buildMode.exitCurrentMode();
} break;
else if (event->modifiers() & Qt::ShiftModifier) default:
{ break;
// Shift + right-click copies a building's settings, but only in the
// default selection mode (REQ-BLD-COPY-CONFIG).
const QPoint tile = coordinates.widgetToTile(event->pos());
std::optional<BuildingId> id = buildingAtTile(tile);
if (!id.has_value()) { id = siteAtTile(tile); }
if (id.has_value()) { copyConfigFrom(*id); }
} }
} }
return; return;
} }
const QPoint tile = coordinates.widgetToTile(event->pos()); const QPoint tile = coordinates.widgetToTile(event->pos());
const bool controlHeld = (event->modifiers() & Qt::ControlModifier) != 0;
if (m_buildMode.isBuilderMode()) // A press begins the click gesture; whether it turns out to be a drag is settled on
// release, where the drag binding is resolved instead.
switch (resolveLeftGesture(controlHeld, /*isDrag*/ false, context))
{ {
if (m_buildMode.getBuilderType() == BuildingType::Belt) case ControlAction::Place:
case ControlAction::ApplySettings:
if (m_buildMode.isBlueprintMode())
{ {
// Deferred placement: start the drag and show the path ghost; nothing placeBlueprintAtTile(tile);
// is placed until release (REQ-BLD-BELT-DRAG). }
else if (m_buildMode.getBuilderType() == BuildingType::Belt)
{
// Belts place by dragging, so the press only anchors the path and shows its
// ghost; nothing is placed until release, and a plain click is the one-tile
// case (REQ-BLD-BELT-DRAG).
m_buildMode.beginBeltDrag(tile); m_buildMode.beginBeltDrag(tile);
m_cursorWorldPos = coordinates.widgetToWorld(event->pos()); m_cursorWorldPos = coordinates.widgetToWorld(event->pos());
recomputeBeltDragPath(tile); recomputeBeltDragPath(tile);
@@ -1090,41 +1216,22 @@ void GameWorldView::mousePressEvent(QMouseEvent* event)
{ {
placeAtTile(tile); placeAtTile(tile);
} }
} break;
else if (m_buildMode.isBlueprintMode())
{ case ControlAction::ToggleDeconstruct:
placeBlueprintAtTile(tile);
}
else if (m_buildMode.isDeconstructMode())
{
// Start a deconstruct box drag; a plain click resolves as a 1x1 box on // Start a deconstruct box drag; a plain click resolves as a 1x1 box on
// release (REQ-BLD-DECONSTRUCT-CLICK, REQ-BLD-DECONSTRUCT-BOX). // release (REQ-BLD-DECONSTRUCT-CLICK, REQ-BLD-DECONSTRUCT-BOX).
m_boxSelecting = true; m_boxSelecting = true;
m_boxStartTile = tile; m_boxStartTile = tile;
m_boxCurrentTile = tile; m_boxCurrentTile = tile;
} break;
else
{
// Shift + left-click applies the copied settings to a same-type building
// (REQ-BLD-COPY-CONFIG). Consumes the click so it does not change the
// selection. Only active in the default selection mode.
if ((event->modifiers() & Qt::ShiftModifier) && m_copiedConfig.has_value())
{
std::optional<BuildingId> id = buildingAtTile(tile);
if (!id.has_value()) { id = siteAtTile(tile); }
if (id.has_value())
{
pasteConfigTo(*id);
return;
}
}
const bool ctrl = (event->modifiers() & Qt::ControlModifier) != 0;
case ControlAction::Select:
case ControlAction::AddToSelection:
// Only a click that hit nothing starts a box drag. Starting one on a hit // Only a click that hit nothing starts a box drag. Starting one on a hit
// would re-resolve the same object as a 1x1 box on release and undo the // would re-resolve the same object as a 1x1 box on release and undo the
// click: a Ctrl+click would toggle the building off, then straight back on. // click: a Ctrl+click would toggle the building off, then straight back on.
if (!selectAtPoint(tile, coordinates.widgetToWorld(event->pos()), ctrl)) if (!selectAtPoint(tile, coordinates.widgetToWorld(event->pos()), controlHeld))
{ {
// selectAtPoint has already cleared the selection unless Ctrl is // selectAtPoint has already cleared the selection unless Ctrl is
// preserving it for an additive drag. // preserving it for an additive drag.
@@ -1132,6 +1239,10 @@ void GameWorldView::mousePressEvent(QMouseEvent* event)
m_boxStartTile = tile; m_boxStartTile = tile;
m_boxCurrentTile = tile; m_boxCurrentTile = tile;
} }
break;
default:
break;
} }
} }
@@ -1146,6 +1257,7 @@ bool GameWorldView::selectAtPoint(QPoint tile, QVector2D worldPos, bool additive
if (!buildingHit.has_value()) { buildingHit = siteAtTile(tile); } if (!buildingHit.has_value()) { buildingHit = siteAtTile(tile); }
if (buildingHit.has_value()) if (buildingHit.has_value())
{ {
publishSelectionAnchor(mode, {*buildingHit}, {}, {});
m_selection.selectBuildings({*buildingHit}, mode); m_selection.selectBuildings({*buildingHit}, mode);
return true; return true;
} }
@@ -1153,6 +1265,7 @@ bool GameWorldView::selectAtPoint(QPoint tile, QVector2D worldPos, bool additive
const entt::entity actorHit = entityAtWorldPos(m_sim->getAdmin(), worldPos); const entt::entity actorHit = entityAtWorldPos(m_sim->getAdmin(), worldPos);
if (actorHit != entt::null) if (actorHit != entt::null)
{ {
publishSelectionAnchor(mode, {}, {actorHit}, {});
m_selection.selectFieldObjects({actorHit}, {}, mode); m_selection.selectFieldObjects({actorHit}, {}, mode);
return true; return true;
} }
@@ -1160,6 +1273,7 @@ bool GameWorldView::selectAtPoint(QPoint tile, QVector2D worldPos, bool additive
const entt::entity debrisHit = debrisAtWorldPos(m_sim->getAdmin(), worldPos); const entt::entity debrisHit = debrisAtWorldPos(m_sim->getAdmin(), worldPos);
if (debrisHit != entt::null) if (debrisHit != entt::null)
{ {
publishSelectionAnchor(mode, {}, {}, {debrisHit});
m_selection.selectFieldObjects({}, {debrisHit}, mode); m_selection.selectFieldObjects({}, {debrisHit}, mode);
return true; return true;
} }
@@ -1180,6 +1294,7 @@ void GameWorldView::selectInBox(bool additive)
buildingsInBox(m_sim->getFactoryState(), m_boxStartTile, m_boxCurrentTile); buildingsInBox(m_sim->getFactoryState(), m_boxStartTile, m_boxCurrentTile);
if (!boxIds.empty()) if (!boxIds.empty())
{ {
publishSelectionAnchor(mode, boxIds, {}, {});
m_selection.selectBuildings(boxIds, mode); m_selection.selectBuildings(boxIds, mode);
return; return;
} }
@@ -1190,6 +1305,7 @@ void GameWorldView::selectInBox(bool additive)
debrisInBox(m_sim->getAdmin(), m_boxStartTile, m_boxCurrentTile); debrisInBox(m_sim->getAdmin(), m_boxStartTile, m_boxCurrentTile);
if (!boxActors.empty() || !boxDebris.empty()) if (!boxActors.empty() || !boxDebris.empty())
{ {
publishSelectionAnchor(mode, {}, boxActors, boxDebris);
m_selection.selectFieldObjects(boxActors, boxDebris, mode); m_selection.selectFieldObjects(boxActors, boxDebris, mode);
return; return;
} }
@@ -1198,6 +1314,35 @@ void GameWorldView::selectInBox(bool additive)
if (!additive) { m_selection.clearAll(); } if (!additive) { m_selection.clearAll(); }
} }
void GameWorldView::publishSelectionAnchor(SelectionMode mode,
const std::vector<BuildingId>& buildings,
const std::vector<entt::entity>& actors,
const std::vector<entt::entity>& debris)
{
// An additive gesture onto something already selected is growing that selection, not
// starting one, and the panel stays where it was put (REQ-UI-SELECTION-PANEL).
const bool startsSelection =
(mode == SelectionMode::Replace) || (m_selection.getSelectedBuildings().empty()
&& m_selection.getSelectedActors().empty()
&& m_selection.getSelectedDebris().empty());
if (!startsSelection)
{
return;
}
// Screen space, frozen here: the panel is placed against where the selection is at
// this moment and stays there, however far the view scrolls or the objects move
// afterwards.
const QRect anchorRect = getSelectionWidgetRect(*m_sim, getCoordinates(),
buildings, actors, debris);
if (anchorRect.isNull())
{
return;
}
EventManager::getInstance()->sendEventImmediately(
std::make_shared<SelectionAnchorChangedEvent>(anchorRect));
}
void GameWorldView::mouseMoveEvent(QMouseEvent* event) void GameWorldView::mouseMoveEvent(QMouseEvent* event)
{ {
const WorldCoordinates coordinates = getCoordinates(); const WorldCoordinates coordinates = getCoordinates();
@@ -1228,6 +1373,21 @@ void GameWorldView::mouseMoveEvent(QMouseEvent* event)
else if (m_buildMode.isBlueprintMode()) else if (m_buildMode.isBlueprintMode())
{ {
m_buildMode.setBlueprintGhostTile(tile); m_buildMode.setBlueprintGhostTile(tile);
// Resolved here, once, through the same classifier the click and the ghost's
// colour use, and stored on the mode: the controls panel says "Apply settings"
// exactly when clicking would transfer (REQ-UI-BLUEPRINT-TRANSFER). Only a
// single-building blueprint hit-tests the cursor, so only it can be a hovered
// transfer target.
const std::vector<BlueprintBuilding>& buildings =
m_buildMode.getBlueprint().buildings;
bool transfer = false;
if (buildings.size() == 1)
{
transfer = resolveBlueprintGhostHere(buildings.front(), tile).action
== BlueprintGhostAction::Transfer;
}
m_buildMode.setHoveredGhostTransfer(transfer);
} }
else if (m_buildMode.isDeconstructMode()) else if (m_buildMode.isDeconstructMode())
{ {
@@ -1259,7 +1419,11 @@ void GameWorldView::mouseReleaseEvent(QMouseEvent* event)
const std::vector<BuildingId> boxIds = const std::vector<BuildingId> boxIds =
buildingsInBox(m_sim->getFactoryState(), m_boxStartTile, m_boxCurrentTile); buildingsInBox(m_sim->getFactoryState(), m_boxStartTile, m_boxCurrentTile);
if (m_buildMode.isDeconstructMode()) const bool controlHeld = (event->modifiers() & Qt::ControlModifier) != 0;
const ControlAction dragAction =
resolveLeftGesture(controlHeld, /*isDrag*/ true, getControlContext());
if (dragAction == ControlAction::DeconstructArea)
{ {
const FactoryState& factory = m_sim->getFactoryState(); const FactoryState& factory = m_sim->getFactoryState();
@@ -1321,7 +1485,9 @@ void GameWorldView::mouseReleaseEvent(QMouseEvent* event)
return; return;
} }
selectInBox((event->modifiers() & Qt::ControlModifier) != 0); // A Ctrl box adds and never deselects, where a plain one replaces
// (REQ-UI-MULTI-SELECT).
selectInBox(dragAction == ControlAction::AddAreaToSelection);
} }
} }
@@ -1375,85 +1541,6 @@ void GameWorldView::rotateGhost(bool clockwise)
} }
} }
void GameWorldView::copyConfigFrom(BuildingId id)
{
const std::optional<BuildingConfig> config = readBuildingConfig(*m_sim, id);
if (!config.has_value()) { return; }
// Only cache when there is something to copy: a selected recipe / schematic
// (Miner, Assembler, Shipyard) or any Splitter (empty filters = accept-all).
// Building types with no settings (Smelter, Reprocessing Plant, Salvage Bay,
// belts / tunnels, HQ) leave any existing cache untouched (REQ-BLD-COPY-CONFIG).
if (!config->recipeId.has_value() && !config->isSplitter) { return; }
m_copiedConfig = config;
m_copyConfigFlashes.push_back({ id, kCopyFlashDurationMs });
}
void GameWorldView::pasteConfigTo(BuildingId id)
{
if (!m_copiedConfig.has_value()) { return; }
const std::optional<BuildingConfig> target = readBuildingConfig(*m_sim, id);
if (!target.has_value() || target->type != m_copiedConfig->type) { return; }
// The paste applies below; flash the target to confirm (REQ-BLD-COPY-CONFIG-FEEDBACK).
m_copyConfigFlashes.push_back({ id, kCopyFlashDurationMs });
const BuildingConfig& source = *m_copiedConfig;
// The cached settings were valid on a same-type source building, so they are
// valid and available on the target: unlock state is global, so a selected
// recipe / schematic (REQ-LOCK-UI-RECIPE, REQ-LOCK-UI-SCHEMATIC) and splitter
// filter item types (REQ-LOCK-UI-SPLITTER) remain unlocked. Applying reuses the
// same configuration commands as the selected building panel, inheriting their
// buffer-clearing and mid-cycle-cancel semantics (REQ-MAT-INPUT-BUFFER,
// REQ-MAT-OUTPUT-BUFFER, REQ-BLD-SHIPYARD).
if (source.isSplitter)
{
// Operational splitters are configured by tile; sites by BuildingId
// (mirrors SelectedBuildingPanel::onSplitterFilterChanged).
if (const Building* building = findBuilding(m_sim->getFactoryState(), id))
{
std::shared_ptr<SetSplitterFiltersCommand> command =
std::make_shared<SetSplitterFiltersCommand>();
command->tile = building->anchor;
command->filterA = source.splitterFilterA;
command->filterB = source.splitterFilterB;
enqueueCommand(command);
}
else
{
std::shared_ptr<SetSiteSplitterFiltersCommand> command =
std::make_shared<SetSiteSplitterFiltersCommand>();
command->id = id;
command->filterA = source.splitterFilterA;
command->filterB = source.splitterFilterB;
enqueueCommand(command);
}
return;
}
if (source.recipeId.has_value())
{
std::shared_ptr<SetRecipeCommand> command = std::make_shared<SetRecipeCommand>();
command->id = id;
command->recipeId = *source.recipeId;
enqueueCommand(command);
}
// For a shipyard the schematic (above) must be applied before its module
// layout, so both commands drain in order at the next tick boundary.
if (source.type == BuildingType::Shipyard && source.shipLayout.has_value())
{
std::shared_ptr<SetShipLayoutCommand> command =
std::make_shared<SetShipLayoutCommand>();
command->id = id;
command->layout = *source.shipLayout;
enqueueCommand(command);
}
}
double GameWorldView::getGameSpeed() const double GameWorldView::getGameSpeed() const
{ {
return m_gameSpeedMultiplier; return m_gameSpeedMultiplier;
@@ -1484,8 +1571,6 @@ void GameWorldView::resetForNewGame()
m_activeBeams.clear(); m_activeBeams.clear();
m_schematicChoiceShown = false; m_schematicChoiceShown = false;
m_selection.clearAll(); m_selection.clearAll();
m_copiedConfig = std::nullopt;
m_copyConfigFlashes.clear();
m_boxSelecting = false; m_boxSelecting = false;
m_camera.reset(); m_camera.reset();
// Drops any key still held across the restart, which also republishes the pan // Drops any key still held across the restart, which also republishes the pan
@@ -1502,6 +1587,10 @@ void GameWorldView::resetForNewGame()
m_lastArtifactCount = -1; m_lastArtifactCount = -1;
EventManager::getInstance()->sendEventImmediately( EventManager::getInstance()->sendEventImmediately(
std::make_shared<SelectionChangedEvent>(std::vector<BuildingId>{})); std::make_shared<SelectionChangedEvent>(std::vector<BuildingId>{}));
// The one place a restart actually lands (the menu, game over and win dialogs only
// enqueue the command), so it is where presentation state belonging to the finished
// run is dropped -- e.g. the temporary blueprint (REQ-UI-BLUEPRINT-TEMP).
EventManager::getInstance()->sendEventImmediately(std::make_shared<GameResetEvent>());
setGameSpeed(1.0); setGameSpeed(1.0);
// Rebase the wall-clock time source so a fresh run starts from a clean time // Rebase the wall-clock time source so a fresh run starts from a clean time
// base. Without this, wall time accumulated while a modal (Game Over, Win, or // base. Without this, wall time accumulated while a modal (Game Over, Win, or
@@ -1624,7 +1713,7 @@ void GameWorldView::handleEvent(std::shared_ptr<const DebugDrawToggleRequestedEv
void GameWorldView::handleEvent(std::shared_ptr<const CommandRequestedEvent> event) void GameWorldView::handleEvent(std::shared_ptr<const CommandRequestedEvent> event)
{ {
// Other widgets (MainWindow, SelectedBuildingPanel) request commands via this // Other widgets (MainWindow, SelectionPanel) request commands via this
// event; GameWorldView owns the CommandManager and enqueues them. // event; GameWorldView owns the CommandManager and enqueues them.
if (event->command && event->command->kind == CommandKind::Reset) if (event->command && event->command->kind == CommandKind::Reset)
{ {

View File

@@ -20,7 +20,6 @@
#include "Blueprint.h" #include "Blueprint.h"
#include "BuildModeController.h" #include "BuildModeController.h"
#include "BuildingConfig.h"
#include "BlueprintModeExitedEvent.h" #include "BlueprintModeExitedEvent.h"
#include "BlueprintPlacementRequestedEvent.h" #include "BlueprintPlacementRequestedEvent.h"
#include "BuilderModeExitedEvent.h" #include "BuilderModeExitedEvent.h"
@@ -65,6 +64,7 @@
struct Command; struct Command;
struct ParsedReplay; struct ParsedReplay;
class BlueprintLibrary;
class ItemIconCache; class ItemIconCache;
class ReplayPlayer; class ReplayPlayer;
class Simulation; class Simulation;
@@ -103,6 +103,21 @@ public:
void setGameSpeed(double multiplier); void setGameSpeed(double multiplier);
void resetForNewGame(); void resetForNewGame();
// The blueprint library is constructed after this widget, so it arrives by setter.
// Not owned; supplies the two facts about blueprints that the control context needs
// (REQ-UI-CONTROLS-CONTENT).
void setBlueprintLibrary(const BlueprintLibrary* library);
// The player's current situation, as the one snapshot every reader of the control
// table works from: this widget's own mouse dispatch, the input mapper, and the
// controls panel (REQ-UI-CONTROLS-CONTENT). Built here because this widget owns the
// build mode and the selection.
ControlContext getControlContext() const;
// Name of the blueprint being placed, for the controls panel's heading. Empty while
// no blueprint is active and for the unnamed temporary one (REQ-UI-BLUEPRINT-TEMP).
QString getActiveBlueprintName() const;
protected: protected:
void initializeGL() override; void initializeGL() override;
void paintGL() override; void paintGL() override;
@@ -188,6 +203,16 @@ private:
std::optional<BuildingId> siteAtTile(QPoint tile) const; std::optional<BuildingId> siteAtTile(QPoint tile) const;
void placeBlueprintAtTile(QPoint center); void placeBlueprintAtTile(QPoint center);
// resolveBlueprintGhost (PlacementRules) for one building of the blueprint currently
// in placement mode, anchored at the cursor tile `center`.
BlueprintGhostResolved resolveBlueprintGhostHere(const BlueprintBuilding& building,
QPoint center) const;
// The blueprint's stored recipe or schematic id, or empty when it stores none or the
// stored one is currently locked (REQ-LOCK-UI-BLUEPRINT).
std::string unlockedRecipeId(const BlueprintBuilding& building) const;
// Applies a single-building blueprint's settings to the building it is hovering,
// instead of placing anything (REQ-UI-BLUEPRINT-TRANSFER).
void transferConfigTo(BuildingId id, const BlueprintBuilding& source);
// Drops despawned or fully-collected debris from the selection // Drops despawned or fully-collected debris from the selection
// (REQ-UI-DEBRIS-CLICK-SELECT). Called each frame from onFrame(). // (REQ-UI-DEBRIS-CLICK-SELECT). Called each frame from onFrame().
@@ -201,6 +226,15 @@ private:
// which is the only case that goes on to start a box drag. // which is the only case that goes on to start a box drag.
bool selectAtPoint(QPoint tile, QVector2D worldPos, bool additive); bool selectAtPoint(QPoint tile, QVector2D worldPos, bool additive);
void selectInBox(bool additive); void selectInBox(bool additive);
// Publishes where on the screen the selection about to be made sits, so the
// selection panel can be placed beside it (REQ-UI-SELECTION-PANEL). Called with
// what is about to be selected, immediately before selecting it, and publishes
// nothing unless that selection is starting rather than growing.
void publishSelectionAnchor(
SelectionMode mode,
const std::vector<BuildingId>& buildings,
const std::vector<entt::entity>& actors,
const std::vector<entt::entity>& debris);
void stepSpeed(int delta); void stepSpeed(int delta);
void placeAtTile(QPoint tile); void placeAtTile(QPoint tile);
@@ -217,12 +251,6 @@ private:
// Enqueues placements and rotate-in-place commands for the resolved path. // Enqueues placements and rotate-in-place commands for the resolved path.
void applyBeltDragPath(); void applyBeltDragPath();
// Copy-settings gesture (REQ-BLD-COPY-CONFIG): Shift+right-click copies a
// building's configuration into m_copiedConfig; Shift+left-click applies it to
// another building of the same type via the existing configuration commands.
void copyConfigFrom(BuildingId id);
void pasteConfigTo(BuildingId id);
// Turns the ghost and refreshes everything that depends on its facing: placement // Turns the ghost and refreshes everything that depends on its facing: placement
// validity, the tunnel completion match, and an in-progress belt drag's path. // validity, the tunnel completion match, and an in-progress belt drag's path.
// The mode transitions themselves live on m_buildMode. // The mode transitions themselves live on m_buildMode.
@@ -271,23 +299,14 @@ private:
// and to resolve the tunnel ghost sub-tile (REQ-BLD-TUNNEL-MODE). // and to resolve the tunnel ghost sub-tile (REQ-BLD-TUNNEL-MODE).
QVector2D m_cursorWorldPos; QVector2D m_cursorWorldPos;
// Temporary cache for the copy-settings gesture (REQ-BLD-COPY-CONFIG); held
// only while Shift is down and cleared on Shift release.
std::optional<BuildingConfig> m_copiedConfig;
// Brief outline flash shown on a building when settings are copied from it or
// pasted onto it (REQ-BLD-COPY-CONFIG-FEEDBACK). remainingMs counts down in
// wall-clock time so the flash plays at a fixed length regardless of game speed
// (and while paused).
std::vector<CopyConfigFlash> m_copyConfigFlashes;
static constexpr qint64 kCopyFlashDurationMs = 300;
bool m_debugDraw; bool m_debugDraw;
// Owns the selection across all three categories and the rules for moving // Owns the selection across all three categories and the rules for moving
// between them (REQ-UI-SELECTION-CATEGORIES), including publishing the change // between them (REQ-UI-SELECTION-CATEGORIES), including publishing the change
// events. This widget only resolves what was hit. // events. This widget only resolves what was hit.
SelectionController m_selection; SelectionController m_selection;
// Not owned; set after construction, so null until MainWindow has built it.
const BlueprintLibrary* m_blueprintLibrary = nullptr;
bool m_boxSelecting; bool m_boxSelecting;
QPoint m_boxStartTile; QPoint m_boxStartTile;
QPoint m_boxCurrentTile; QPoint m_boxCurrentTile;

View File

@@ -9,6 +9,7 @@
#include "BlueprintSelectionRequestedEvent.h" #include "BlueprintSelectionRequestedEvent.h"
#include "BuildHotkeyPressedEvent.h" #include "BuildHotkeyPressedEvent.h"
#include "BuildingType.h" #include "BuildingType.h"
#include "ControlAction.h"
#include "DebugDrawToggleRequestedEvent.h" #include "DebugDrawToggleRequestedEvent.h"
#include "EscapeMenuRequestedEvent.h" #include "EscapeMenuRequestedEvent.h"
#include "EventManager.h" #include "EventManager.h"
@@ -17,7 +18,8 @@
#include "PanDirectionChangedEvent.h" #include "PanDirectionChangedEvent.h"
#include "PauseToggleRequestedEvent.h" #include "PauseToggleRequestedEvent.h"
#include "SpeedStepRequestedEvent.h" #include "SpeedStepRequestedEvent.h"
#include "TemporaryBlueprintRequestedEvent.h" #include "TemporaryBlueprintCaptureRequestedEvent.h"
#include "TemporaryBlueprintPlaceRequestedEvent.h"
#include "TracePrintRequestedEvent.h" #include "TracePrintRequestedEvent.h"
namespace namespace
@@ -76,7 +78,7 @@ QString InputMapper::getBuildHotkeyLabel(BuildingType type)
return QString(); return QString();
} }
bool InputMapper::handleKeyPress(QKeyEvent* event) bool InputMapper::handleKeyPress(QKeyEvent* event, const ControlContext& context)
{ {
// Auto-repeat says nothing new about which keys are down, and a held action is // Auto-repeat says nothing new about which keys are down, and a held action is
// already held. // already held.
@@ -85,6 +87,9 @@ bool InputMapper::handleKeyPress(QKeyEvent* event)
// Number-key build-mode hotkeys (REQ-UI-HOTKEYS). nativeVirtualKey gives the // Number-key build-mode hotkeys (REQ-UI-HOTKEYS). nativeVirtualKey gives the
// physical digit independent of keyboard layout and Shift (with Shift held, key() // physical digit independent of keyboard layout and Shift (with Shift held, key()
// for the number row can arrive as Key_Exclam etc.). VK_1..VK_9 = 0x31..0x39. // for the number row can arrive as Key_Exclam etc.). VK_1..VK_9 = 0x31..0x39.
// Not part of the ControlAction table: these are advertised on the build buttons
// rather than in the controls panel, and getBuildHotkeyLabel already reads the
// same binding table this does (REQ-UI-CONTROLS-ACCURACY).
const quint32 virtualKey = event->nativeVirtualKey(); const quint32 virtualKey = event->nativeVirtualKey();
if (virtualKey >= 0x31 && virtualKey <= 0x39) if (virtualKey >= 0x31 && virtualKey <= 0x39)
{ {
@@ -99,100 +104,102 @@ bool InputMapper::handleKeyPress(QKeyEvent* event)
} }
} }
// Blueprint chords (REQ-UI-HOTKEYS). Checked ahead of the plain-key switch below, // Development controls, deliberately outside the table so they are never offered
// which binds bare A/D/W/S/R/Q/T and must not fire on a Ctrl chord. Both requests // to the player (REQ-UI-CONTROLS-ACCURACY).
// are decided by MainWindow, the only widget that can pause the game and dim the
// window for a modal.
if ((event->modifiers() & Qt::ControlModifier) != 0)
{
switch (event->key()) switch (event->key())
{ {
case Qt::Key_C:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<BlueprintSaveRequestedEvent>());
return true;
case Qt::Key_V:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<BlueprintSelectionRequestedEvent>());
return true;
default:
break;
}
}
switch (event->key())
{
case Qt::Key_A:
m_panLeftHeld = true;
updatePanDirection();
return true;
case Qt::Key_D:
m_panRightHeld = true;
updatePanDirection();
return true;
case Qt::Key_Space:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<PauseToggleRequestedEvent>());
return true;
case Qt::Key_W:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<SpeedStepRequestedEvent>(+1));
return true;
case Qt::Key_S:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<SpeedStepRequestedEvent>(-1));
return true;
case Qt::Key_R:
// Shift reverses the rotation direction (REQ-BLD-ROTATE).
EventManager::getInstance()->sendEventImmediately(
std::make_shared<GhostRotationRequestedEvent>(
(event->modifiers() & Qt::ShiftModifier) != 0));
return true;
case Qt::Key_Q:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<ModeCancelRequestedEvent>());
return true;
case Qt::Key_T:
// Request a temporary blueprint from the current selection (REQ-UI-BLUEPRINT-TEMP).
// The BlueprintLibrary owns the selection and blueprint-capture logic; it decides
// whether anything placeable is selected and drives placement mode from there.
EventManager::getInstance()->sendEventImmediately(
std::make_shared<TemporaryBlueprintRequestedEvent>());
return true;
case Qt::Key_F3: case Qt::Key_F3:
EventManager::getInstance()->sendEventImmediately( EventManager::getInstance()->sendEventImmediately(
std::make_shared<DebugDrawToggleRequestedEvent>()); std::make_shared<DebugDrawToggleRequestedEvent>());
return true; return true;
case Qt::Key_Escape:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<EscapeMenuRequestedEvent>());
return true;
case Qt::Key_F4: case Qt::Key_F4:
EventManager::getInstance()->addEvent( EventManager::getInstance()->addEvent(
std::make_shared<TracePrintRequestedEvent>()); std::make_shared<TracePrintRequestedEvent>());
return true; return true;
default: default:
break;
}
// Everything else: the key names an action, the action names an event. Which key
// is bound to what, and whether it does anything in this situation, are both the
// table's business -- this switch only knows what each action means
// (REQ-UI-HOTKEYS, REQ-UI-CONTROLS-ACCURACY).
switch (resolveKeyAction(event->key(), event->modifiers(), context))
{
case ControlAction::Move:
// A parameter of the action rather than an action of its own: the table binds
// both keys to Move and the direction is read off the key here, as the rotation
// direction and the build hotkey's digit are.
if (event->key() == Qt::Key_A) { m_panLeftHeld = true; }
else { m_panRightHeld = true; }
updatePanDirection();
return true;
case ControlAction::GameSpeed:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<SpeedStepRequestedEvent>(event->key() == Qt::Key_W ? +1 : -1));
return true;
case ControlAction::TogglePause:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<PauseToggleRequestedEvent>());
return true;
case ControlAction::Rotate:
// Shift reverses the rotation direction (REQ-BLD-ROTATE).
EventManager::getInstance()->sendEventImmediately(
std::make_shared<GhostRotationRequestedEvent>(
(event->modifiers() & Qt::ShiftModifier) != 0));
return true;
case ControlAction::EnterDeconstruct:
case ControlAction::ExitMode:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<ModeCancelRequestedEvent>());
return true;
case ControlAction::CopyTemporary:
// The BlueprintLibrary owns the selection and blueprint-capture logic; it drives
// placement mode from there (REQ-UI-BLUEPRINT-TEMP).
EventManager::getInstance()->sendEventImmediately(
std::make_shared<TemporaryBlueprintCaptureRequestedEvent>());
return true;
case ControlAction::PasteTemporary:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<TemporaryBlueprintPlaceRequestedEvent>());
return true;
case ControlAction::CreateBlueprint:
// Decided by MainWindow, the only widget that can pause the game and dim the
// window for a modal.
EventManager::getInstance()->sendEventImmediately(
std::make_shared<BlueprintSaveRequestedEvent>());
return true;
case ControlAction::OpenBlueprints:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<BlueprintSelectionRequestedEvent>());
return true;
case ControlAction::OpenMenu:
EventManager::getInstance()->sendEventImmediately(
std::make_shared<EscapeMenuRequestedEvent>());
return true;
default:
// Either nothing is bound to the key here, or what is bound is a mouse gesture
// the view handles. Unconsumed, so ordinary Qt shortcuts keep working.
return false; return false;
} }
} }
bool InputMapper::handleKeyRelease(QKeyEvent* event) bool InputMapper::handleKeyRelease(QKeyEvent* event, const ControlContext& context)
{ {
if (event->isAutoRepeat()) { return false; } if (event->isAutoRepeat()) { return false; }
switch (event->key()) // Only held actions have a release worth acting on. Resolved through the table
// rather than matched against A and D directly, so the keys stay rebindable in one
// place rather than two.
if (resolveKeyAction(event->key(), event->modifiers(), context) != ControlAction::Move)
{ {
case Qt::Key_A:
m_panLeftHeld = false;
updatePanDirection();
return true;
case Qt::Key_D:
m_panRightHeld = false;
updatePanDirection();
return true;
default:
return false; return false;
} }
if (event->key() == Qt::Key_A) { m_panLeftHeld = false; }
else { m_panRightHeld = false; }
updatePanDirection();
return true;
} }
void InputMapper::releaseAll() void InputMapper::releaseAll()

View File

@@ -3,14 +3,19 @@
#include <QString> #include <QString>
#include "BuildingType.h" #include "BuildingType.h"
#include "ControlAction.h"
#include "WorldCamera.h" #include "WorldCamera.h"
class QKeyEvent; class QKeyEvent;
// Turns raw key events into the game's semantic actions and publishes them // Turns raw key events into the game's semantic actions and publishes them
// (REQ-UI-HOTKEYS). Widgets react to the action, never to the key, so the two can // (REQ-UI-HOTKEYS). Widgets react to the action, never to the key, so the two can
// be rebound independently later; the bindings themselves are still hard-coded // be rebound independently later.
// here for now. //
// Which key means what is not decided here: the caller hands in a ControlContext and
// ControlAction.h resolves the press against it, so this file only knows what each
// action means once resolved. That is what keeps the controls panel and the key
// handling from drifting apart -- both read the one table (REQ-UI-CONTROLS-ACCURACY).
// //
// Two output shapes, chosen by the nature of the action rather than by taste: // Two output shapes, chosen by the nature of the action rather than by taste:
// //
@@ -34,9 +39,10 @@ public:
static QString getBuildHotkeyLabel(BuildingType type); static QString getBuildHotkeyLabel(BuildingType type);
// Both return true when the key was consumed; the caller passes anything else // Both return true when the key was consumed; the caller passes anything else
// on to its base class so unrelated shortcuts keep working. // on to its base class so unrelated shortcuts keep working. `context` is the
bool handleKeyPress(QKeyEvent* event); // player's current situation, which decides what a key does (REQ-UI-CONTROLS-CONTENT).
bool handleKeyRelease(QKeyEvent* event); bool handleKeyPress(QKeyEvent* event, const ControlContext& context);
bool handleKeyRelease(QKeyEvent* event, const ControlContext& context);
// Drops all held-key state, publishing the resulting change. Call when the // Drops all held-key state, publishing the resulting change. Call when the
// receiving widget can no longer expect key-up events. // receiving widget can no longer expect key-up events.

View File

@@ -28,9 +28,11 @@
#include "RecipeSelectionDialog.h" #include "RecipeSelectionDialog.h"
#include "SchematicChoiceDialog.h" #include "SchematicChoiceDialog.h"
#include "HeaderBar.h" #include "HeaderBar.h"
#include "SelectedBuildingPanel.h" #include "SelectionPanel.h"
#include "ControlsPanel.h"
#include "ShipLayoutBlueprintSerializer.h" #include "ShipLayoutBlueprintSerializer.h"
#include "ShipLayoutDialog.h" #include "ShipLayoutDialog.h"
#include "BuildingIconCache.h"
#include "ItemIconCache.h" #include "ItemIconCache.h"
#include "ModalPauseScope.h" #include "ModalPauseScope.h"
#include "Simulation.h" #include "Simulation.h"
@@ -48,55 +50,52 @@ MainWindow::MainWindow(Simulation* sim, const std::string& configDir,
setWindowTitle(tr("Dota Factory")); setWindowTitle(tr("Dota Factory"));
resize(1280, 768); resize(1280, 768);
// Item icons live alongside the config (a sibling of the config dir), read from // Item and building icons live alongside the config (siblings of the config dir),
// disk at runtime like the building icons and visuals.toml (REQ-UI-ITEM-ICON). // read from disk at runtime the same way visuals.toml is (REQ-UI-ITEM-ICON,
const std::string itemsIconDir = QDir::cleanPath( // REQ-UI-BUILD-ICON).
QString::fromStdString(m_configDir) + "/../icons/items").toStdString(); const QString configDirPath = QString::fromStdString(m_configDir);
m_itemIcons = std::make_unique<ItemIconCache>( m_itemIcons = std::make_unique<ItemIconCache>(
QString::fromStdString(itemsIconDir)); QDir::cleanPath(configDirPath + "/../icons/items"));
m_buildingIcons = std::make_unique<BuildingIconCache>(
QDir::cleanPath(configDirPath + "/../icons/buildings"));
m_headerBar = new HeaderBar(sim, &sim->getConfig(), m_itemIcons.get(), this); m_headerBar = new HeaderBar(sim, &sim->getConfig(), m_itemIcons.get(), this);
m_gameWorldView = new GameWorldView(sim, &sim->getConfig(), &m_visuals, m_configDir, m_gameWorldView = new GameWorldView(sim, &sim->getConfig(), &m_visuals, m_configDir,
m_itemIcons.get(), m_replay.get(), this); m_itemIcons.get(), m_replay.get(), this);
// Building icons live alongside the config (a sibling of the config dir), read // Floats over the game world at its bottom center, sized to its buttons
// from disk at runtime the same way visuals.toml is.
const std::string iconDir = QDir::cleanPath(
QString::fromStdString(m_configDir) + "/../icons/buildings").toStdString();
// Floats over the game world rather than living in the side panel column
// (REQ-UI-BUILD-BAR). Creation order is the stacking order for siblings, so // (REQ-UI-BUILD-BAR). Creation order is the stacking order for siblings, so
// building it after the world view puts it above the world and its vignettes, // building it after the world view puts it above the world and its vignettes,
// and before the dim overlay keeps modals dimming it too (REQ-UI-MODAL-DIM). // and before the dim overlay keeps modals dimming it too (REQ-UI-MODAL-DIM).
// Its geometry comes from layoutPanels(). // Its geometry comes from layoutPanels().
m_buildButtonBar = new BuildButtonBar(sim, &sim->getConfig(), iconDir, m_buildButtonBar = new BuildButtonBar(sim, &sim->getConfig(),
m_itemIcons.get(), this); m_buildingIcons.get(), m_itemIcons.get(),
this);
// The blueprints have no widget of their own: they are saved with Ctrl+C and picked // The blueprints have no widget of their own: they are saved with Ctrl+C and picked
// from a modal dialog (REQ-UI-BLUEPRINT-DIALOG), both driven from this window // from a modal dialog (REQ-UI-BLUEPRINT-DIALOG), both driven from this window
// because only it can pause the game and raise the dim overlay. Built after the // because only it can pause the game and raise the dim overlay. Built after the
// world view because loading blueprints.toml may put a message box on screen. // world view because loading blueprints.toml may put a message box on screen.
m_blueprintLibrary = std::make_unique<BlueprintLibrary>(sim, &sim->getConfig(), this); m_blueprintLibrary = std::make_unique<BlueprintLibrary>(sim, &sim->getConfig(), this);
// Two facts about blueprints decide what the world view offers the player
// (REQ-UI-CONTROLS-CONTENT); the library is built after the view, so it is handed
// over here rather than passed to the constructor.
m_gameWorldView->setBlueprintLibrary(m_blueprintLibrary.get());
m_sidePanel = new QWidget(this); // Floats over the game world at its right edge rather than occupying a column of
QVBoxLayout* sideLayout = new QVBoxLayout(m_sidePanel); // its own, and hides itself while nothing is selected (REQ-UI-SELECTION-PANEL). Like
sideLayout->setContentsMargins(1, 1, 1, 1); // the build button bar it is a sibling of the world view built after it, which is
sideLayout->setSpacing(1); // what puts it above the world and its vignettes and below the dim overlay. It
// brings its own chrome; its geometry comes from layoutPanels().
m_selectionPanel = new SelectionPanel(sim, &sim->getConfig(), &m_visuals,
m_itemIcons.get(), m_buildingIcons.get(),
this);
// The selected building panel is the column's only panel and fills its height // Floats at the world view's opposite edge from the selection panel and reads the
// (REQ-UI-PANEL-COLUMN). // world view for the player's current situation (REQ-UI-CONTROLS-PANEL). Built
m_selectedBuildingPanel = new SelectedBuildingPanel(sim, &sim->getConfig(), m_sidePanel); // after the view for the same stacking reason as the panels above it.
sideLayout->addWidget(m_selectedBuildingPanel, 1); m_controlsPanel = new ControlsPanel(m_gameWorldView, this);
// Draw a thin border around the side panel section. The class scoped selector keeps
// the border on the panel itself rather than cascading onto its child widgets;
// WA_StyledBackground lets the plain QWidget subclass honor the stylesheet box
// (border/background).
m_selectedBuildingPanel->setAttribute(Qt::WA_StyledBackground, true);
m_sidePanel->setStyleSheet(QStringLiteral(
"SelectedBuildingPanel { border: 1px solid palette(mid); }"));
// Created last so it stacks above the other children; covers the whole window and // Created last so it stacks above the other children; covers the whole window and
// dims the game behind modal dialogs/menus (REQ-UI-MODAL-DIM). // dims the game behind modal dialogs/menus (REQ-UI-MODAL-DIM).
@@ -166,16 +165,57 @@ void MainWindow::layoutPanels()
const int totalH = height(); const int totalH = height();
const int headerH = m_headerBar->sizeHint().height(); const int headerH = m_headerBar->sizeHint().height();
if (headerH <= 0) { return; } if (headerH <= 0) { return; }
const int mainW = totalW * 75 / 100;
const int sideW = totalW - mainW;
m_headerBar->setGeometry(0, 0, mainW, headerH); // Header bar and game world view span the full window width; the two floating
m_gameWorldView->setGeometry(0, headerH, mainW, totalH - headerH); // widgets below are the only things over the world (REQ-UI-HEADER,
m_sidePanel->setGeometry(mainW, 0, sideW, totalH); // REQ-UI-WORLD-SIZE).
// Sizes itself to its buttons and centers along the bottom of the world view const QRect worldRect(0, headerH, totalW, totalH - headerH);
// (REQ-UI-BUILD-BAR). m_headerBar->setGeometry(0, 0, totalW, headerH);
m_buildButtonBar->anchorTo(QRect(0, headerH, mainW, totalH - headerH)); m_gameWorldView->setGeometry(worldRect);
m_dimOverlay->setGeometry(0, 0, totalW, totalH); m_dimOverlay->setGeometry(0, 0, totalW, totalH);
// The floating widgets are placed in one ordered pass, each into the space the
// earlier ones have not taken (FloatingPanel.h). The order is the priority the
// requirements state: the build button bar takes what it wants and never moves for
// anyone (REQ-UI-BUILD-BAR), the controls panel steps around the bar
// (REQ-UI-CONTROLS-PANEL), and the selection panel keeps clear of both
// (REQ-UI-SELECTION-PANEL). A widget with nothing to show hides itself in placeIn()
// and takes no space.
//
// Re-entry is refused rather than queued: setGeometry() on a widget in the pass can
// reach code that asks for another pass, and the one already running is about to
// produce the same answer.
if (m_layingOut)
{
return;
}
m_layingOut = true;
const std::vector<QWidget*> floatingWidgets = {
m_buildButtonBar, m_controlsPanel, m_selectionPanel };
const std::vector<FloatingPanel*> floatingPanels = {
m_buildButtonBar, m_controlsPanel, m_selectionPanel };
std::vector<QRect> occupiedRects;
for (std::size_t i = 0; i < floatingPanels.size(); ++i)
{
floatingPanels[i]->placeIn(worldRect, occupiedRects);
if (floatingWidgets[i]->isVisible())
{
occupiedRects.push_back(floatingWidgets[i]->geometry());
}
}
m_layingOut = false;
}
void MainWindow::handleEvent(
std::shared_ptr<const FloatingLayoutInvalidatedEvent> /*event*/)
{
// One of the floating widgets changed size or visibility. What each of them may take
// depends on the ones placed before it, so the answer is the whole pass rather than
// that one widget re-placing itself.
layoutPanels();
} }
void MainWindow::handleEvent(std::shared_ptr<const SchematicChoicesAvailableEvent> event) void MainWindow::handleEvent(std::shared_ptr<const SchematicChoicesAvailableEvent> event)

View File

@@ -12,6 +12,7 @@
#include "BuildingId.h" #include "BuildingId.h"
#include "EscapeMenuRequestedEvent.h" #include "EscapeMenuRequestedEvent.h"
#include "EventHandler.h" #include "EventHandler.h"
#include "FloatingLayoutInvalidatedEvent.h"
#include "GameConfig.h" #include "GameConfig.h"
#include "GameOverEvent.h" #include "GameOverEvent.h"
#include "LayoutDialogRequestedEvent.h" #include "LayoutDialogRequestedEvent.h"
@@ -28,9 +29,11 @@ struct ParsedReplay;
class Simulation; class Simulation;
class GameWorldView; class GameWorldView;
class HeaderBar; class HeaderBar;
class SelectedBuildingPanel; class SelectionPanel;
class ControlsPanel;
class BuildButtonBar; class BuildButtonBar;
class BlueprintLibrary; class BlueprintLibrary;
class BuildingIconCache;
class ItemIconCache; class ItemIconCache;
class QCloseEvent; class QCloseEvent;
class QResizeEvent; class QResizeEvent;
@@ -43,7 +46,8 @@ class MainWindow : public QWidget,
LayoutDialogRequestedEvent, LayoutDialogRequestedEvent,
RecipeSelectionRequestedEvent, RecipeSelectionRequestedEvent,
BlueprintSaveRequestedEvent, BlueprintSaveRequestedEvent,
BlueprintSelectionRequestedEvent> BlueprintSelectionRequestedEvent,
FloatingLayoutInvalidatedEvent>
{ {
Q_OBJECT Q_OBJECT
@@ -65,6 +69,7 @@ private:
void handleEvent(std::shared_ptr<const RecipeSelectionRequestedEvent> event) override; void handleEvent(std::shared_ptr<const RecipeSelectionRequestedEvent> event) override;
void handleEvent(std::shared_ptr<const BlueprintSaveRequestedEvent> event) override; void handleEvent(std::shared_ptr<const BlueprintSaveRequestedEvent> event) override;
void handleEvent(std::shared_ptr<const BlueprintSelectionRequestedEvent> event) override; void handleEvent(std::shared_ptr<const BlueprintSelectionRequestedEvent> event) override;
void handleEvent(std::shared_ptr<const FloatingLayoutInvalidatedEvent> event) override;
// Reloads the game config and visuals.toml from disk (REQ-CFG-RELOAD), shared // Reloads the game config and visuals.toml from disk (REQ-CFG-RELOAD), shared
// by every restart path. On success the reloaded visuals are applied to this // by every restart path. On success the reloaded visuals are applied to this
@@ -83,6 +88,8 @@ private:
// both callers already hold theirs, which is what keeps the dim continuous when a // both callers already hold theirs, which is what keeps the dim continuous when a
// confirmed save hands straight over to this dialog (REQ-UI-MODAL-DIM). // confirmed save hands straight over to this dialog (REQ-UI-MODAL-DIM).
void showBlueprintSelectionDialog(); void showBlueprintSelectionDialog();
// Places the widgets floating over the game world view, in one ordered pass
// (FloatingPanel.h). Runs on a resize and on every FloatingLayoutInvalidatedEvent.
void layoutPanels(); void layoutPanels();
private: private:
@@ -92,16 +99,23 @@ private:
// One per-item icon cache for the whole window (REQ-UI-ITEM-ICON): the header, // One per-item icon cache for the whole window (REQ-UI-ITEM-ICON): the header,
// build bar, world view, and recipe dialog all rasterize the same SVGs. // build bar, world view, and recipe dialog all rasterize the same SVGs.
std::unique_ptr<ItemIconCache> m_itemIcons; std::unique_ptr<ItemIconCache> m_itemIcons;
// Likewise one per-building chip cache (REQ-UI-BUILD-ICON), shared by the build bar
// and the selection panel's card headers (REQ-UI-SELECTION-CARD).
std::unique_ptr<BuildingIconCache> m_buildingIcons;
GameWorldView* m_gameWorldView; GameWorldView* m_gameWorldView;
HeaderBar* m_headerBar; HeaderBar* m_headerBar;
SelectedBuildingPanel* m_selectedBuildingPanel; SelectionPanel* m_selectionPanel;
ControlsPanel* m_controlsPanel;
BuildButtonBar* m_buildButtonBar; BuildButtonBar* m_buildButtonBar;
// The saved blueprints themselves; they have no widget of their own any more and // The saved blueprints themselves; they have no widget of their own any more and
// are reached through the two modal dialogs (REQ-UI-BLUEPRINT-DIALOG). // are reached through the two modal dialogs (REQ-UI-BLUEPRINT-DIALOG).
std::unique_ptr<BlueprintLibrary> m_blueprintLibrary; std::unique_ptr<BlueprintLibrary> m_blueprintLibrary;
QWidget* m_sidePanel;
ModalDimOverlay* m_dimOverlay = nullptr; ModalDimOverlay* m_dimOverlay = nullptr;
std::vector<ShipLayoutBlueprint> m_layoutBlueprints; std::vector<ShipLayoutBlueprint> m_layoutBlueprints;
std::shared_ptr<ParsedReplay> m_replay; // non-null => view-only playback std::shared_ptr<ParsedReplay> m_replay; // non-null => view-only playback
// Set while the placement pass runs, so a widget placed in it cannot start a second
// pass from inside the first.
bool m_layingOut = false;
}; };

View File

@@ -1,858 +0,0 @@
#include "SelectedBuildingPanel.h"
#include "FactoryQueries.h"
#include <algorithm>
#include <cctype>
#include <map>
#include <set>
#include <string>
#include <QLabel>
#include <QListWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include "BeltSystem.h"
#include "Command.h"
#include "CommandRequestedEvent.h"
#include "EntitySelectionChangedEvent.h"
#include "EventManager.h"
#include "FieldSelectionPanel.h"
#include "TickAdvancedEvent.h"
#include "Building.h"
#include "BuildingSystem.h"
#include "BuildingType.h"
#include "ItemType.h"
#include "LayoutDialogRequestedEvent.h"
#include "ModulesConfig.h"
#include "PlayerCommandsAppliedEvent.h"
#include "RecipeSelectionDialog.h"
#include "RecipeSelectionRequestedEvent.h"
#include "Rotation.h"
#include "ShipLayoutPreview.h"
#include "Simulation.h"
namespace
{
QString buildingTypeName(BuildingType type)
{
if (type == BuildingType::Hq)
{
return QObject::tr("Player HQ");
}
const std::string id = buildingTypeId(type);
QString result;
bool nextUpper = true;
for (char c : id)
{
if (c == '_')
{
result += ' ';
nextUpper = true;
}
else if (nextUpper)
{
result += static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
nextUpper = false;
}
else
{
result += c;
}
}
return result;
}
bool isProductionBuilding(BuildingType type)
{
return type == BuildingType::Miner
|| type == BuildingType::Smelter
|| type == BuildingType::Assembler
|| type == BuildingType::ReprocessingPlant
|| type == BuildingType::Shipyard;
}
// Buildings that expose a player recipe/schematic selection control
// (REQ-UI-SELECT-BUTTON): Miner ore type, Assembler recipe, Shipyard schematic.
// The Smelter and Reprocessing Plant auto-process and offer no selection
// (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING).
bool hasRecipeSelection(BuildingType type)
{
return type == BuildingType::Miner
|| type == BuildingType::Assembler
|| type == BuildingType::Shipyard;
}
QString rotationLabel(Rotation r)
{
switch (r)
{
case Rotation::North: return QObject::tr("North (↑)");
case Rotation::East: return QObject::tr("East (→)");
case Rotation::South: return QObject::tr("South (↓)");
case Rotation::West: return QObject::tr("West (←)");
}
return "";
}
} // namespace
SelectedBuildingPanel::SelectedBuildingPanel(Simulation* sim,
const GameConfig* config,
QWidget* parent)
: QWidget(parent)
, m_sim(sim)
, m_config(config)
, m_splitterTile(0, 0)
{
m_layout = new QVBoxLayout(this);
m_layout->setContentsMargins(8, 8, 8, 8);
m_layout->setSpacing(4);
m_layout->setAlignment(Qt::AlignTop);
m_titleLabel = new QLabel(this);
m_recipeSelectButton = new QPushButton(this);
m_clearBeltBtn = new QPushButton(tr("Clear Items"), this);
m_filterALabel = new QLabel(this);
m_filterAList = new QListWidget(this);
m_filterBLabel = new QLabel(this);
m_filterBList = new QListWidget(this);
m_layoutPreview = new ShipLayoutPreview(this);
m_configureLayoutBtn = new QPushButton(tr("Configure Layout"), this);
m_buffersLabel = new QLabel(this);
m_buffersLabel->setWordWrap(true);
m_filterAList->setMaximumHeight(100);
m_filterBList->setMaximumHeight(100);
m_layout->addWidget(m_titleLabel);
m_layout->addWidget(m_recipeSelectButton);
m_layout->addWidget(m_layoutPreview);
m_layout->addWidget(m_configureLayoutBtn);
m_layout->addWidget(m_clearBeltBtn);
m_layout->addWidget(m_filterALabel);
m_layout->addWidget(m_filterAList);
m_layout->addWidget(m_filterBLabel);
m_layout->addWidget(m_filterBList);
m_layout->addWidget(m_buffersLabel);
connect(m_recipeSelectButton, &QPushButton::clicked,
this, &SelectedBuildingPanel::onSelectRecipeClicked);
connect(m_clearBeltBtn, &QPushButton::clicked,
this, &SelectedBuildingPanel::onClearBelt);
connect(m_configureLayoutBtn, &QPushButton::clicked, this, [this]() {
if (m_singleBuildingId.has_value())
{
EventManager::getInstance()->sendEventImmediately(
std::make_shared<LayoutDialogRequestedEvent>(*m_singleBuildingId));
}
});
connect(m_filterAList, &QListWidget::itemChanged,
this, &SelectedBuildingPanel::onSplitterFilterChanged);
connect(m_filterBList, &QListWidget::itemChanged,
this, &SelectedBuildingPanel::onSplitterFilterChanged);
// The field selection renders below the building content and hides itself while
// nothing field-side is selected, so it costs no space then.
m_fieldSelectionPanel = new FieldSelectionPanel(sim, config, this);
m_layout->addWidget(m_fieldSelectionPanel);
buildEmpty();
registerForEvents();
}
SelectedBuildingPanel::~SelectedBuildingPanel()
{
unregisterForEvents();
}
void SelectedBuildingPanel::onSelectionChanged(const std::vector<BuildingId>& ids)
{
m_selectedBuildingIds = ids;
if (!ids.empty())
{
// A building selection is exclusive: it supersedes any field selection —
// actors and scrap (REQ-UI-SELECTION-CATEGORIES).
m_fieldSelectionPanel->clearSelection();
}
rebuild();
}
void SelectedBuildingPanel::yieldToFieldSelection()
{
// The mirror image of onSelectionChanged(): a field selection — actors, debris, or
// both — supersedes any building selection (REQ-UI-SELECTION-CATEGORIES). An empty
// field selection changes nothing here: the building content, if any, keeps the panel.
if (!m_fieldSelectionPanel->hasSelection()) { return; }
m_selectedBuildingIds.clear();
buildEmpty();
}
void SelectedBuildingPanel::rebuild()
{
if (m_selectedBuildingIds.empty())
{
buildEmpty();
}
else if (m_selectedBuildingIds.size() == 1)
{
buildSingle(m_selectedBuildingIds[0]);
}
else
{
buildMulti(m_selectedBuildingIds);
}
}
void SelectedBuildingPanel::hideAllWidgets()
{
m_titleLabel->hide();
m_recipeSelectButton->hide();
m_layoutPreview->hide();
m_configureLayoutBtn->hide();
m_clearBeltBtn->hide();
m_filterALabel->hide();
m_filterAList->hide();
m_filterBLabel->hide();
m_filterBList->hide();
m_buffersLabel->hide();
}
void SelectedBuildingPanel::buildEmpty()
{
// Shows nothing for the building category — either because nothing is selected or
// because the field category has taken the panel over.
m_singleBuildingId = std::nullopt;
hideAllWidgets();
}
void SelectedBuildingPanel::buildSingle(BuildingId id)
{
m_singleBuildingId = id;
hideAllWidgets();
const Building* b = findBuilding(m_sim->getFactoryState(), id);
const ConstructionSite* s = b ? nullptr : findSite(m_sim->getFactoryState(), id);
if (!b && !s)
{
buildEmpty();
return;
}
m_singleIsSite = (s != nullptr);
// A construction site exposes the same configuration as the operational
// building it will become (REQ-BLD-SITE-CONFIG). The only difference is
// that its buffer/production rows are replaced by a construction-progress
// line, since a site has no buffers and runs no production cycle.
const BuildingType type = b ? b->type : s->type;
const std::string& recipeId = b ? b->recipeId : s->recipeId;
const std::optional<ShipLayoutConfig>& shipLayout =
b ? b->shipLayout : s->shipLayout;
const QPoint anchor = b ? b->anchor : s->anchor;
m_titleLabel->setText(m_singleIsSite
? tr("(Building) %1").arg(buildingTypeName(type))
: buildingTypeName(type));
m_titleLabel->show();
m_buffersLabel->show();
if (hasRecipeSelection(type))
{
const std::vector<RecipeSelectionOption> options =
buildRecipeSelectionOptions(type, *m_sim, *m_config);
const RecipeSelectionOption* current = nullptr;
for (const RecipeSelectionOption& option : options)
{
if (option.id == recipeId)
{
current = &option;
break;
}
}
if (current && !current->id.empty())
{
m_recipeSelectButton->setText(current->caption);
m_recipeSelectButton->setToolTip(current->tooltip);
}
else
{
const QString placeholder = (type == BuildingType::Shipyard)
? tr("Select schematic")
: tr("Select recipe");
m_recipeSelectButton->setText(placeholder);
m_recipeSelectButton->setToolTip(QString());
}
m_recipeSelectButton->show();
updateShipyardLayoutWidgets(type, recipeId, shipLayout);
}
else
{
m_recipeSelectButton->hide();
updateShipyardLayoutWidgets(type, recipeId, shipLayout);
}
// Belt "Clear" removes items from a live belt tile; a construction site has
// none and is not registered with BeltSystem yet, so hide it for sites.
if (isBeltSubsystemType(type) && !m_singleIsSite)
{
m_clearBeltBtn->show();
}
else
{
m_clearBeltBtn->hide();
}
if (type == BuildingType::Splitter)
{
std::optional<BeltSystem::SplitterInfo> info;
if (m_singleIsSite)
{
info = getSiteSplitterInfo(m_sim->getFactoryState(), m_sim->getConfig(), id);
}
else
{
m_splitterTile = anchor;
info = m_sim->getBelts().getSplitterInfo(m_splitterTile);
}
buildSplitterFilters(info);
}
else
{
m_filterALabel->hide();
m_filterAList->hide();
m_filterBLabel->hide();
m_filterBList->hide();
}
if (m_singleIsSite)
{
refreshSiteProgress(s);
}
else
{
refreshBuffers(b);
}
}
void SelectedBuildingPanel::refreshSiteProgress(const ConstructionSite* s)
{
QString progress;
if (s->completesAt == 0)
{
progress = tr("Queued");
}
else
{
const BuildingDef* def = nullptr;
for (const BuildingDef& d : m_config->buildings.buildings)
{
if (d.type == s->type) { def = &d; break; }
}
if (def && def->constructionTimeSeconds > 0)
{
const Tick duration = secondsToTicks(def->constructionTimeSeconds);
const Tick elapsed = m_sim->getCurrentTick() - (s->completesAt - duration);
const int pct = static_cast<int>(
std::max(Tick(0), std::min(duration, elapsed)) * 100 / duration);
progress = tr("%1% complete").arg(pct);
}
else
{
progress = tr("Building...");
}
}
m_buffersLabel->setText(progress);
}
void SelectedBuildingPanel::refreshBuffers(const Building* b)
{
const RecipeDef* recipe = findRecipe(b);
const ShipDef* shipDef = (b->type == BuildingType::Shipyard)
? findShipDef(b->recipeId)
: nullptr;
// Auto-recipe buildings (Smelter, Reprocessing Plant) have no selected
// recipe; while a cycle runs, resolve the recipe actually in production so
// the cycle time and progress can be shown (REQ-UI-PRODUCTION-PROGRESS).
if (!recipe && isAutoRecipeBuildingType(b->type) && b->production.has_value())
{
recipe = m_config->recipes.findRecipeDef(b->production->recipeId, b->type);
}
QString bufText;
if (!b->inputBuffer.counts.empty())
{
bufText += tr("Input: ");
for (const std::pair<const ItemType, int>& entry : b->inputBuffer.counts)
{
int perCycle = 0;
if (recipe)
{
for (const RecipeIngredient& ing : recipe->inputs)
{
if (ing.item == entry.first.id) { perCycle = ing.amount; break; }
}
}
else if (shipDef)
{
for (const RecipeIngredient& mat : shipDef->schematic.materials)
{
if (mat.item == entry.first.id) { perCycle = mat.amount; break; }
}
if (b->shipLayout.has_value())
{
for (const PlacedModule& pm : b->shipLayout->placedModules)
{
const ModuleDef* modDef =
m_config->modules.findModuleDef(pm.moduleId);
if (!modDef) { continue; }
for (const RecipeIngredient& ing : modDef->materials)
{
if (ing.item == entry.first.id)
{
perCycle += ing.amount;
}
}
}
}
}
bufText += QString::fromStdString(entry.first.id)
+ ": " + QString::number(entry.second);
if (perCycle > 0)
{
bufText += "/" + QString::number(perCycle);
}
bufText += " ";
}
bufText += "\n";
}
// Count output-side items: buffered plus still-emerging on the output belts.
// An emerging item still belongs to the output buffer (REQ-MAT-OUTPUT-EMERGE),
// so it must be included here or it would vanish from the panel while animating.
std::map<std::string, int> outCounts;
for (const Item& item : b->outputBuffer.items)
{
outCounts[item.type.id]++;
}
for (const std::vector<BeltItemSlot>& lane : b->emergingItems)
{
for (const BeltItemSlot& slot : lane)
{
outCounts[slot.item.type.id]++;
}
}
if (recipe && !recipe->outputs.empty())
{
bufText += tr("Output: ");
for (const RecipeOutput& out : recipe->outputs)
{
const std::map<std::string, int>::const_iterator it =
outCounts.find(out.item);
const int count = (it != outCounts.end()) ? it->second : 0;
bufText += QString::fromStdString(out.item)
+ ": " + QString::number(count)
+ "/" + QString::number(out.amount) + " ";
}
}
else if (!outCounts.empty())
{
bufText += tr("Output: ");
for (const std::pair<const std::string, int>& entry : outCounts)
{
bufText += QString::fromStdString(entry.first)
+ ": " + QString::number(entry.second) + " ";
}
}
if (isProductionBuilding(b->type)
&& (recipe || shipDef || isAutoRecipeBuildingType(b->type)))
{
if (recipe || shipDef)
{
double durationSeconds = recipe
? recipe->durationSeconds
: shipDef->schematic.productionTimeSeconds;
if (shipDef && b->shipLayout.has_value())
{
for (const PlacedModule& pm : b->shipLayout->placedModules)
{
const ModuleDef* modDef =
m_config->modules.findModuleDef(pm.moduleId);
if (modDef)
{
durationSeconds += modDef->productionTimeSeconds;
}
}
}
bufText += tr("Cycle: %1 s\n").arg(durationSeconds, 0, 'f', 1);
if (b->production.has_value())
{
const Tick cycleTicks = secondsToTicks(durationSeconds);
const Tick completesAt = b->production->completesAt;
const Tick currentTick = m_sim->getCurrentTick();
const Tick elapsed = currentTick - (completesAt - cycleTicks);
const int pct = static_cast<int>(
std::max(Tick(0), std::min(cycleTicks, elapsed)) * 100 / cycleTicks);
bufText += tr("Progress: %1%\n").arg(pct);
}
else
{
bufText += tr("Progress: idle\n");
}
}
else
{
// Auto-recipe building with no active cycle: no single recipe to
// show a cycle time for.
bufText += tr("Progress: idle\n");
}
}
m_buffersLabel->setText(bufText);
// The recipe/schematic is applied via a queued command that only drains on a
// later frame, so the per-tick refresh must own the shipyard preview and the
// Configure Layout button's visibility; otherwise they stay hidden until the
// building is re-selected (which re-runs buildSingle).
updateShipyardLayoutWidgets(b->type, b->recipeId, b->shipLayout);
}
void SelectedBuildingPanel::updateShipyardLayoutWidgets(
BuildingType type,
const std::string& recipeId,
const std::optional<ShipLayoutConfig>& shipLayout)
{
// The preview and Configure button are shipyard-only controls; hide them
// entirely for other building types.
if (type != BuildingType::Shipyard)
{
m_layoutPreview->hide();
m_configureLayoutBtn->hide();
return;
}
const ShipDef* shipDef = findShipDef(recipeId);
const bool hasSchematic = shipDef && !shipDef->layout.empty();
// Always show the preview and Configure button for a shipyard; they are only
// enabled once a schematic is selected (REQ-MOD-UI-PREVIEW).
if (hasSchematic)
{
ShipLayoutConfig layout;
if (shipLayout.has_value())
{
layout = *shipLayout;
}
m_layoutPreview->setShipAndLayout(
shipDef->layout, layout, &m_config->modules);
}
else
{
m_layoutPreview->showPlaceholder();
}
m_layoutPreview->setEnabled(hasSchematic);
m_configureLayoutBtn->setEnabled(hasSchematic);
m_layoutPreview->show();
m_configureLayoutBtn->show();
}
const RecipeDef* SelectedBuildingPanel::findRecipe(const Building* b) const
{
if (b->recipeId.empty()) { return nullptr; }
return m_config->recipes.findRecipeDef(b->recipeId, b->type);
}
const ShipDef* SelectedBuildingPanel::findShipDef(const std::string& id) const
{
if (id.empty()) { return nullptr; }
return m_config->ships.findShipDef(id);
}
void SelectedBuildingPanel::handleEvent(std::shared_ptr<const TickAdvancedEvent> /*event*/)
{
refreshSelectionDisplay(RefreshReason::PeriodicTick);
}
void SelectedBuildingPanel::handleEvent(
std::shared_ptr<const PlayerCommandsAppliedEvent> /*event*/)
{
// Player commands (e.g. choosing a shipyard schematic) are applied by a
// queued drain, not synchronously. When the game is paused no tick advances,
// so TickAdvancedEvent never fires; refresh here too, otherwise the panel
// would not reflect the change until the next tick or a re-selection.
refreshSelectionDisplay(RefreshReason::CommandApplied);
}
void SelectedBuildingPanel::refreshSelectionDisplay(RefreshReason reason)
{
// Only a single selected building has live content to refresh. While the field
// category owns the panel there is none: yieldToFieldSelection() has cleared it, so
// this returns immediately and the field panel refreshes itself off the same events.
if (!m_singleBuildingId.has_value()) { return; }
const Building* b = findBuilding(m_sim->getFactoryState(), *m_singleBuildingId);
if (b)
{
if (m_titleLabel->text().startsWith(tr("(Building) ")))
{
rebuild();
}
else
{
refreshBuffers(b);
}
return;
}
const ConstructionSite* s = findSite(m_sim->getFactoryState(), *m_singleBuildingId);
if (s)
{
// A periodic tick only advances construction progress, so update just the
// progress label. Rebuilding every tick would hide/re-show all widgets and
// cancel any in-progress click on the recipe button. An applied command
// may have changed the site's recipe/layout, so rebuild in that case.
if (reason == RefreshReason::CommandApplied)
{
rebuild();
}
else
{
refreshSiteProgress(s);
}
return;
}
buildEmpty();
}
void SelectedBuildingPanel::buildMulti(const std::vector<BuildingId>& ids)
{
m_singleBuildingId = std::nullopt;
m_recipeSelectButton->hide();
m_clearBeltBtn->hide();
m_filterALabel->hide();
m_filterAList->hide();
m_filterBLabel->hide();
m_filterBList->hide();
m_buffersLabel->hide();
std::map<BuildingType, int> counts;
for (BuildingId id : ids)
{
const Building* b = findBuilding(m_sim->getFactoryState(), id);
if (b)
{
counts[b->type]++;
continue;
}
const ConstructionSite* s = findSite(m_sim->getFactoryState(), id);
if (s)
{
counts[s->type]++;
}
}
bool hasBelt = false;
int totalCost = 0;
QString text;
for (const std::pair<const BuildingType, int>& entry : counts)
{
text += buildingTypeName(entry.first) + " x "
+ QString::number(entry.second) + "\n";
if (isBeltSubsystemType(entry.first))
{
hasBelt = true;
}
// Total placement cost counts only player-placeable buildings; the HQ
// and defence stations are excluded (REQ-UI-MULTI-SELECTION).
const BuildingDef* def = m_config->buildings.findBuildingDef(entry.first);
if (def && def->playerPlaceable)
{
totalCost += def->cost * entry.second;
}
}
text += tr("Total: %1 Building Blocks").arg(totalCost);
m_titleLabel->setText(text.trimmed());
m_titleLabel->show();
if (hasBelt)
{
m_clearBeltBtn->show();
}
}
void SelectedBuildingPanel::onSelectRecipeClicked()
{
if (!m_singleBuildingId.has_value())
{
return;
}
// The emit is synchronous: MainWindow pauses the game, runs the modal
// selection dialog, and restores the speed before this returns. The chosen
// recipe/schematic is only *enqueued* as a command, though, and drains on a
// later frame -- so this rebuild() still sees the old recipe. The per-tick
// refreshBuffers() path picks up the new schematic (and shows the layout
// preview + Configure Layout button) once the command has been applied.
EventManager::getInstance()->sendEventImmediately(
std::make_shared<RecipeSelectionRequestedEvent>(*m_singleBuildingId));
rebuild();
}
void SelectedBuildingPanel::buildSplitterFilters(
const std::optional<BeltSystem::SplitterInfo>& info)
{
if (!info.has_value())
{
m_filterALabel->hide();
m_filterAList->hide();
m_filterBLabel->hide();
m_filterBList->hide();
return;
}
const std::vector<std::string> items = getAllItemIds();
auto populateList = [&](QListWidget* list, QLabel* label,
const QString& dirLabel,
const std::vector<ItemType>& filter)
{
label->setText(tr("%1 filter (empty = all):").arg(dirLabel));
list->blockSignals(true);
list->clear();
for (const std::string& itemId : items)
{
if (!m_sim->isItemUnlocked(itemId)) { continue; }
QListWidgetItem* row = new QListWidgetItem(
QString::fromStdString(itemId), list);
const bool checked = filter.empty()
? false
: std::find(filter.begin(), filter.end(),
ItemType{itemId}) != filter.end();
row->setCheckState(checked ? Qt::Checked : Qt::Unchecked);
row->setFlags(row->flags() | Qt::ItemIsUserCheckable);
}
list->blockSignals(false);
label->show();
list->show();
};
populateList(m_filterAList, m_filterALabel,
rotationLabel(info->outputA), info->filterA);
populateList(m_filterBList, m_filterBLabel,
rotationLabel(info->outputB), info->filterB);
}
void SelectedBuildingPanel::onSplitterFilterChanged()
{
if (!m_singleBuildingId.has_value())
{
return;
}
auto collectFilter = [](QListWidget* list) -> std::vector<ItemType>
{
std::vector<ItemType> filter;
for (int i = 0; i < list->count(); ++i)
{
const QListWidgetItem* row = list->item(i);
if (row->checkState() == Qt::Checked)
{
filter.push_back(ItemType{row->text().toStdString()});
}
}
return filter;
};
if (m_singleIsSite)
{
std::shared_ptr<SetSiteSplitterFiltersCommand> command =
std::make_shared<SetSiteSplitterFiltersCommand>();
command->id = *m_singleBuildingId;
command->filterA = collectFilter(m_filterAList);
command->filterB = collectFilter(m_filterBList);
EventManager::getInstance()->sendEventImmediately(
std::make_shared<CommandRequestedEvent>(command));
}
else
{
std::shared_ptr<SetSplitterFiltersCommand> command =
std::make_shared<SetSplitterFiltersCommand>();
command->tile = m_splitterTile;
command->filterA = collectFilter(m_filterAList);
command->filterB = collectFilter(m_filterBList);
EventManager::getInstance()->sendEventImmediately(
std::make_shared<CommandRequestedEvent>(command));
}
}
std::vector<std::string> SelectedBuildingPanel::getAllItemIds() const
{
std::set<std::string> seen;
for (const RecipeDef& recipe : m_config->recipes.recipes)
{
for (const RecipeIngredient& ing : recipe.inputs)
{
seen.insert(ing.item);
}
for (const RecipeOutput& out : recipe.outputs)
{
seen.insert(out.item);
}
}
return std::vector<std::string>(seen.begin(), seen.end());
}
void SelectedBuildingPanel::onClearBelt()
{
std::vector<QPoint> tiles;
for (BuildingId id : m_selectedBuildingIds)
{
const Building* b = findBuilding(m_sim->getFactoryState(), id);
if (b && isBeltSubsystemType(b->type))
{
for (const QPoint& cell : b->bodyCells)
{
tiles.push_back(cell);
}
}
}
if (!tiles.empty())
{
std::shared_ptr<ClearBeltTilesCommand> command =
std::make_shared<ClearBeltTilesCommand>();
command->tiles = std::move(tiles);
EventManager::getInstance()->sendEventImmediately(
std::make_shared<CommandRequestedEvent>(command));
}
}
void SelectedBuildingPanel::handleEvent(std::shared_ptr<const EntitySelectionChangedEvent> event)
{
m_fieldSelectionPanel->setSelectedEntities(event->entities);
yieldToFieldSelection();
}
void SelectedBuildingPanel::handleEvent(std::shared_ptr<const SelectionChangedEvent> event)
{
onSelectionChanged(event->ids);
}
void SelectedBuildingPanel::handleEvent(
std::shared_ptr<const DebrisSelectionChangedEvent> event)
{
// Debris is a field object: it supersedes any building selection but coexists
// with actors (REQ-UI-SELECTION-CATEGORIES).
m_fieldSelectionPanel->setSelectedDebris(event->debris);
yieldToFieldSelection();
}

View File

@@ -1,122 +0,0 @@
#pragma once
#include <optional>
#include <string>
#include <vector>
#include <QPoint>
#include <QWidget>
#include "BeltSystem.h"
#include "Building.h"
#include "BuildingId.h"
#include "EntitySelectionChangedEvent.h"
#include "EventHandler.h"
#include "GameConfig.h"
#include "PlayerCommandsAppliedEvent.h"
#include "RecipesConfig.h"
#include "DebrisSelectionChangedEvent.h"
#include "SelectionChangedEvent.h"
#include "ShipLayout.h"
#include "ShipsConfig.h"
#include "Tick.h"
#include "TickAdvancedEvent.h"
class Simulation;
class FieldSelectionPanel;
class ShipLayoutPreview;
class QLabel;
class QListWidget;
class QPushButton;
class QVBoxLayout;
// Shows the current selection. The building category (buildings and construction sites)
// is rendered by this panel itself; the field category (ships, defence stations, debris)
// is rendered by the embedded FieldSelectionPanel.
//
// The two categories are mutually exclusive (REQ-UI-SELECTION-CATEGORIES) and this panel
// is the sole arbiter of which one owns the content: it listens to all three selection
// events, forwards the field ones to the child panel, and drops the losing category's
// content. Neither panel touches the other's widgets.
class SelectedBuildingPanel : public QWidget,
public CombinedEventHandler<TickAdvancedEvent,
PlayerCommandsAppliedEvent,
EntitySelectionChangedEvent,
SelectionChangedEvent,
DebrisSelectionChangedEvent>
{
Q_OBJECT
public:
SelectedBuildingPanel(Simulation* sim, const GameConfig* config,
QWidget* parent = nullptr);
~SelectedBuildingPanel() override;
private:
void handleEvent(std::shared_ptr<const TickAdvancedEvent> event) override;
void handleEvent(std::shared_ptr<const PlayerCommandsAppliedEvent> event) override;
void handleEvent(std::shared_ptr<const EntitySelectionChangedEvent> event) override;
void handleEvent(std::shared_ptr<const SelectionChangedEvent> event) override;
void handleEvent(std::shared_ptr<const DebrisSelectionChangedEvent> event) override;
private slots:
void onSelectRecipeClicked();
void onClearBelt();
void onSplitterFilterChanged();
private:
// Why the selection display is being refreshed. A periodic tick only needs a
// lightweight content update (e.g. a construction site's progress label),
// whereas an applied player command may have changed the configuration and
// needs a full structural rebuild.
enum class RefreshReason
{
PeriodicTick,
CommandApplied
};
void onSelectionChanged(const std::vector<BuildingId>& ids);
// Gives the panel to the field category once it has anything selected.
void yieldToFieldSelection();
void refreshSelectionDisplay(RefreshReason reason);
void rebuild();
void hideAllWidgets();
void buildEmpty();
void buildSingle(BuildingId id);
void buildMulti(const std::vector<BuildingId>& ids);
void refreshBuffers(const Building* b);
void refreshSiteProgress(const ConstructionSite* s);
void updateShipyardLayoutWidgets(BuildingType type,
const std::string& recipeId,
const std::optional<ShipLayoutConfig>& shipLayout);
void buildSplitterFilters(const std::optional<BeltSystem::SplitterInfo>& info);
const RecipeDef* findRecipe(const Building* b) const;
const ShipDef* findShipDef(const std::string& id) const;
std::vector<std::string> getAllItemIds() const;
Simulation* m_sim;
const GameConfig* m_config;
std::vector<BuildingId> m_selectedBuildingIds;
QVBoxLayout* m_layout;
QLabel* m_titleLabel;
QPushButton* m_recipeSelectButton;
QPushButton* m_clearBeltBtn;
QLabel* m_filterALabel;
QListWidget* m_filterAList;
QLabel* m_filterBLabel;
QListWidget* m_filterBList;
QLabel* m_buffersLabel;
ShipLayoutPreview* m_layoutPreview;
QPushButton* m_configureLayoutBtn;
std::optional<BuildingId> m_singleBuildingId;
bool m_singleIsSite = false; // selected single entity is a construction site
QPoint m_splitterTile;
std::string m_currentRecipeId;
// Renders the field selection (actors + debris) below the building content
// (REQ-UI-FIELD-MULTI-SELECTION). Hides itself while nothing field-side is selected.
FieldSelectionPanel* m_fieldSelectionPanel;
};

115
src/ui/SelectionBounds.cpp Normal file
View File

@@ -0,0 +1,115 @@
#include "SelectionBounds.h"
#include "Building.h"
#include "DebrisComponent.h"
#include "EntityAdmin.h"
#include "FactoryQueries.h"
#include "PositionComponent.h"
#include "Simulation.h"
#include "StationBodyComponent.h"
#include "WorldCoordinates.h"
#include "WorldPrimitives.h"
namespace
{
// The widget rectangle of a footprint anchored at a tile, both kinds of body being
// described the same way.
QRectF getFootprintWidgetRect(const WorldCoordinates& coordinates, QPoint anchor,
QSize footprint)
{
const QPointF topLeft = coordinates.tileToWidget(anchor);
return QRectF(topLeft.x(), topLeft.y(),
footprint.width() * static_cast<qreal>(coordinates.getTilePx()),
footprint.height() * static_cast<qreal>(coordinates.getTilePx()));
}
} // namespace
std::optional<QRectF> getBuildingWidgetRect(const FactoryState& state,
const WorldCoordinates& coordinates,
BuildingId id)
{
if (const Building* building = findBuilding(state, id))
{
return getFootprintWidgetRect(coordinates, building->anchor, building->footprint);
}
if (const ConstructionSite* site = findSite(state, id))
{
return getFootprintWidgetRect(coordinates, site->anchor, site->footprint);
}
return std::nullopt;
}
std::optional<QRectF> getActorWidgetRect(const EntityAdmin& admin,
const WorldCoordinates& coordinates,
entt::entity actor)
{
if (!admin.isValid(actor))
{
return std::nullopt;
}
if (admin.hasAll<StationBodyComponent>(actor))
{
const StationBodyComponent& body = admin.get<StationBodyComponent>(actor);
return getFootprintWidgetRect(coordinates, body.anchor, body.footprint);
}
if (admin.hasAll<PositionComponent>(actor))
{
// A ship is a triangle about its center; the square its longest extent fits in
// is what the panel is placed beside.
const QPointF center =
coordinates.worldToWidget(admin.get<PositionComponent>(actor).value);
const qreal extent = static_cast<qreal>(getShipForwardExtentPx(coordinates));
return QRectF(center.x() - extent, center.y() - extent,
2.0 * extent, 2.0 * extent);
}
return std::nullopt;
}
std::optional<QRectF> getDebrisWidgetRect(const EntityAdmin& admin,
const WorldCoordinates& coordinates,
entt::entity debris)
{
if (!admin.isValid(debris) || !admin.hasAll<PositionComponent, DebrisComponent>(debris))
{
return std::nullopt;
}
const QPointF center =
coordinates.worldToWidget(admin.get<PositionComponent>(debris).value);
const qreal radius = static_cast<qreal>(getDebrisRadiusPx(coordinates));
return QRectF(center.x() - radius, center.y() - radius, 2.0 * radius, 2.0 * radius);
}
QRect getSelectionWidgetRect(const Simulation& sim, const WorldCoordinates& coordinates,
const std::vector<BuildingId>& buildings,
const std::vector<entt::entity>& actors,
const std::vector<entt::entity>& debris)
{
QRectF bounds;
// A null rect unites to nothing of its own, so the first object found sets the box
// and every later one grows it.
auto add = [&bounds](const std::optional<QRectF>& rect)
{
if (rect.has_value())
{
bounds = bounds.isNull() ? *rect : bounds.united(*rect);
}
};
for (BuildingId id : buildings)
{
add(getBuildingWidgetRect(sim.getFactoryState(), coordinates, id));
}
for (entt::entity actor : actors)
{
add(getActorWidgetRect(sim.getAdmin(), coordinates, actor));
}
for (entt::entity piece : debris)
{
add(getDebrisWidgetRect(sim.getAdmin(), coordinates, piece));
}
return bounds.isNull() ? QRect() : bounds.toAlignedRect();
}

48
src/ui/SelectionBounds.h Normal file
View File

@@ -0,0 +1,48 @@
#pragma once
#include <optional>
#include <vector>
#include <QRect>
#include "entt/entity/entity.hpp"
#include "BuildingId.h"
class EntityAdmin;
class Simulation;
class WorldCoordinates;
struct FactoryState;
// Where selectable objects are on the screen. The world renderer draws every selection
// outline from these rectangles, and the selection panel is placed beside the one that
// covers the whole selection (REQ-UI-SELECTION-PANEL).
//
// All of them are in the game world view's own widget coordinates, and all of them are
// only true for the WorldCoordinates they were asked for: the transform is a value built
// per frame or per event, so a rectangle does not survive a scroll or a resize.
// The footprint of a building or of a construction site (REQ-UI-SELECTION-CARD). Null
// when the id names neither, which is what a deconstruction under the caller looks like.
std::optional<QRectF> getBuildingWidgetRect(const FactoryState& state,
const WorldCoordinates& coordinates,
BuildingId id);
// The body of a ship or of a defence station (REQ-UI-ENTITY-CLICK-SELECT): a station's
// footprint, or the square the ship's triangle is drawn in.
std::optional<QRectF> getActorWidgetRect(const EntityAdmin& admin,
const WorldCoordinates& coordinates,
entt::entity actor);
// The circle a piece of debris is drawn as (REQ-UI-DEBRIS-CLICK-SELECT).
std::optional<QRectF> getDebrisWidgetRect(const EntityAdmin& admin,
const WorldCoordinates& coordinates,
entt::entity debris);
// The rectangle covering a whole selection -- one object, or the bounding box of all of
// them (REQ-UI-SELECTION-PANEL). Objects that no longer resolve are skipped; the result
// is null when none of them does.
QRect getSelectionWidgetRect(const Simulation& sim, const WorldCoordinates& coordinates,
const std::vector<BuildingId>& buildings,
const std::vector<entt::entity>& actors,
const std::vector<entt::entity>& debris);

369
src/ui/SelectionPanel.cpp Normal file
View File

@@ -0,0 +1,369 @@
#include "SelectionPanel.h"
#include <QLayout>
#include <QList>
#include <QScrollArea>
#include <QScrollBar>
#include <QVBoxLayout>
#include "BuildingIconCache.h"
#include "EventManager.h"
#include "FloatingLayoutInvalidatedEvent.h"
#include "FloatingPanelPlacement.h"
#include "ItemIconCache.h"
#include "Simulation.h"
#include "VisualsConfig.h"
#include "selection/SelectionContent.h"
namespace
{
// Distance kept between the panel and the edges of the game world view, and between it
// and the widgets it steps around (REQ-UI-SELECTION-PANEL).
const int kMarginPx = 8;
// Upper bound on the card width. The panel is content-sized, but several of the cards'
// widgets have no natural width of their own -- the word-wrapped summary labels grow
// without limit, and a QListWidget asks for 256 px whatever it holds -- so the width is
// capped and the labels wrap at the cap. 320 px is the width the former side panel
// column had at the default window size.
const int kMaxContentWidthPx = 320;
// Padding between the panel's border and the card inside it.
const int kCardMarginPx = 8;
} // namespace
SelectionPanel::SelectionPanel(Simulation* sim, const GameConfig* config,
const VisualsConfig* visuals, ItemIconCache* itemIcons,
BuildingIconCache* buildingIcons, QWidget* parent)
: QWidget(parent)
{
m_context.sim = sim;
m_context.config = config;
m_context.visuals = visuals;
m_context.itemIcons = itemIcons;
m_context.buildingIcons = buildingIcons;
m_context.debugDrawEnabled = &m_debugDrawEnabled;
// The panel floats over the rendered world rather than sitting in a column, so it
// brings its own opaque background to stay legible over any world content
// (REQ-UI-SELECTION-PANEL). Palette colors match the build button bar's chrome; like
// it, this is widget chrome rather than world rendering, so it is deliberately not a
// visuals.toml color. The class scoped selector keeps the border on the panel itself
// rather than cascading onto its child widgets.
setAttribute(Qt::WA_StyledBackground, true);
setStyleSheet(QStringLiteral(
"SelectionPanel { background-color: palette(window);"
" border: 1px solid palette(mid); border-radius: 4px; }"));
// A card taller than the band scrolls rather than overrunning it
// (REQ-UI-SELECTION-PANEL). The viewport is transparent so the panel's own rounded
// chrome shows through, and horizontal scrolling is off because the width always
// follows the content.
m_body = new QWidget(this);
m_scrollArea = new QScrollArea(this);
m_scrollArea->setFrameShape(QFrame::NoFrame);
m_scrollArea->setWidgetResizable(true);
m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// The panel works out for itself whether the card fits the band, and sizes itself to
// leave room for the bar when it does not (REQ-UI-SELECTION-PANEL), so refit() sets
// this policy rather than leaving the scroll area to decide. Asked to decide, it
// shows a bar the moment the card is momentarily larger than the viewport -- which
// happens while the card is being measured -- and does not take it back when the
// range turns out to be empty.
m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_scrollArea->viewport()->setAutoFillBackground(false);
m_body->setAutoFillBackground(false);
m_scrollArea->setWidget(m_body);
QVBoxLayout* outerLayout = new QVBoxLayout(this);
outerLayout->setContentsMargins(0, 0, 0, 0);
outerLayout->setSpacing(0);
outerLayout->addWidget(m_scrollArea);
m_bodyLayout = new QVBoxLayout(m_body);
m_bodyLayout->setContentsMargins(kCardMarginPx, kCardMarginPx,
kCardMarginPx, kCardMarginPx);
m_bodyLayout->setSpacing(0);
m_bodyLayout->setAlignment(Qt::AlignTop);
hide();
registerForEvents();
}
SelectionPanel::~SelectionPanel()
{
unregisterForEvents();
}
void SelectionPanel::invalidateLayout()
{
EventManager::getInstance()->sendEventImmediately(
std::make_shared<FloatingLayoutInvalidatedEvent>());
}
void SelectionPanel::handleEvent(std::shared_ptr<const SelectionChangedEvent> event)
{
m_request.buildings = event->ids;
if (!m_request.buildings.empty())
{
// A building selection is exclusive: it supersedes any field selection -- actors
// and scrap alike (REQ-UI-SELECTION-CATEGORIES).
m_request.actors.clear();
m_request.debris.clear();
}
rebuildContent();
}
void SelectionPanel::handleEvent(
std::shared_ptr<const SelectionAnchorChangedEvent> event)
{
// A new selection is starting. Both the anchor and the side are settled against it
// and then left alone for as long as it lasts (REQ-UI-SELECTION-PANEL); the side is
// only reset here, being resolved on the next placement once the card's width is
// known. The rect arrives in the world view's coordinates and is translated when the
// panel is placed, the two widgets being siblings in the same parent.
m_anchorRect = event->rectPx;
m_side.reset();
}
void SelectionPanel::handleEvent(
std::shared_ptr<const EntitySelectionChangedEvent> event)
{
m_request.actors = event->entities;
if (!m_request.actors.empty() || !m_request.debris.empty())
{
m_request.buildings.clear();
}
rebuildContent();
}
void SelectionPanel::handleEvent(
std::shared_ptr<const DebrisSelectionChangedEvent> event)
{
// Debris is a field object: it supersedes any building selection but coexists with
// actors (REQ-UI-SELECTION-CATEGORIES).
m_request.debris = event->debris;
if (!m_request.actors.empty() || !m_request.debris.empty())
{
m_request.buildings.clear();
}
rebuildContent();
}
void SelectionPanel::handleEvent(std::shared_ptr<const TickAdvancedEvent> /*event*/)
{
refreshContent();
}
void SelectionPanel::handleEvent(
std::shared_ptr<const PlayerCommandsAppliedEvent> /*event*/)
{
// Player commands (choosing a shipyard schematic, say) are applied by a queued
// drain, not synchronously. When the game is paused no tick advances, so
// TickAdvancedEvent never fires; refreshing here too is what makes the change show
// up without waiting for a tick or a re-selection.
refreshContent();
}
void SelectionPanel::handleEvent(std::shared_ptr<const DebugDrawToggledEvent> event)
{
m_debugDrawEnabled = event->active;
}
void SelectionPanel::refreshContent()
{
if (!m_content)
{
return;
}
// A card never changes its own shape, so when the selection now calls for a
// different one it is replaced rather than refreshed. Only a single selected
// building can reach that state without the selection itself changing -- its
// construction site finishes, or it is deconstructed under the panel. Everything
// else is re-published as a selection change, so re-deriving the key here would walk
// a large multi-selection every tick to learn nothing.
if (m_request.buildings.size() == 1
&& chooseContent(m_request, *m_context.sim) != m_contentKey)
{
rebuildContent();
return;
}
m_content->refresh();
invalidateLayout();
}
void SelectionPanel::rebuildContent()
{
if (m_content)
{
// Retired rather than deleted: a rebuild can be reached from inside one of the
// card's own click handlers -- the recipe control opens a modal dialog and the
// choice comes back as a command -- and control has to be able to return into
// the widget that is going away.
m_content->hide();
m_content->deleteLater();
m_content = nullptr;
}
m_contentKey = chooseContent(m_request, *m_context.sim);
m_content = createContent(m_contentKey, m_request, m_context, m_body);
if (m_content)
{
m_bodyLayout->addWidget(m_content);
// The show is what makes the card count. A widget created under an
// already-visible parent starts hidden, and a layout treats a hidden item as
// empty -- it adds nothing to the size hint until something shows it, which
// otherwise does not happen until the event loop next runs, long after refit()
// has measured the panel. The panel then fits itself to an empty body and
// collapses to its scroll bar.
m_content->show();
m_content->refresh();
}
invalidateLayout();
}
void SelectionPanel::placeIn(const QRect& viewRect, const std::vector<QRect>& occupiedRects)
{
// Nothing selected in either category means no panel at all rather than an empty one
// (REQ-UI-EMPTY-SELECTION), leaving the whole game world view visible.
setVisible(m_content != nullptr);
if (m_content == nullptr || viewRect.isNull())
{
return;
}
const QRect band = viewRect.adjusted(kMarginPx, kMarginPx, -kMarginPx, -kMarginPx);
// The anchor is published in the world view's coordinates and this panel is placed in
// its parent's; the two widgets are siblings, so the view's own origin is the whole
// difference. Without an anchor the panel falls back to the top-right corner, by
// standing beside a point just outside that corner -- in practice unreachable, every
// non-empty selection following a click or a drag that publishes one.
const QRect anchorRect =
m_anchorRect.isNull() ? QRect(band.right() + kMarginPx + 1, band.top(), 1, 1)
: m_anchorRect.translated(viewRect.topLeft());
// The panel's border is drawn around the scroll area rather than around the card, so
// it is added to whatever the card asks for. Spelled out here instead of read back
// from contentsMargins() because the stylesheet box is what sets it, and asking the
// style for it before the first show is unreliable.
const int borderPx = 1;
const int maxWidthPx = qMin(kMaxContentWidthPx, band.width() - 2 * borderPx);
if (maxWidthPx <= 0 || band.height() <= 2 * borderPx)
{
return;
}
// What the card asks for at a given width. The width has to be applied before
// asking, because a card's height depends on the room it is given -- and so, once
// laid out, does the width it reports. Measuring at whatever width the panel
// happens to have carries the previous card's shape into this one.
//
// Each measurement re-runs the card's layouts -- every one of them, not just the
// body's own. Changing a label's text posts a LayoutRequest to the widget holding it
// and that event is only delivered when the event loop next runs, so a layout nested
// inside the card still reports the width of the text before the change: measuring
// here and re-measuring on the following refresh then gives two different answers,
// and the panel visibly resizes a frame after its content changed. Re-activating
// them all is what a delivered LayoutRequest would have done.
//
// Cards are built and discarded whole, so this is also what discards the previous
// card's cached hints, and what accounts for the parts a card hides and shows as it
// refreshes. The polish belongs to the same step: a freshly created chip reports an
// unstyled hint until the stylesheet has reached it, and the chips carry border and
// padding that change their size.
auto measureAt = [this](int widthPx) -> QSize
{
m_body->resize(widthPx, m_body->height());
m_body->ensurePolished();
// Deepest first, so no layout is re-activated from children that are themselves
// still stale. findChildren walks parents before children, hence the reverse.
const QList<QLayout*> nested = m_body->findChildren<QLayout*>();
for (QList<QLayout*>::const_reverse_iterator it = nested.rbegin();
it != nested.rend(); ++it)
{
(*it)->invalidate();
(*it)->activate();
}
m_body->layout()->invalidate();
m_body->layout()->activate();
return m_body->sizeHint();
};
// Run twice. Parts of a card report an unstyled size until the style has actually
// reached them, which for a freshly built card happens during the first round of
// measuring; the second round then measures a card that is fully laid out and
// settles on the answer. Without it a card can end up a few pixels short of what it
// turns out to need, and the difference shows as a scroll bar over a card that
// looks like it fits.
for (int pass = 0; pass < 2; ++pass)
{
// First at the cap, the most room the card can ever get, to learn how wide it
// wants to be; then at that width for the height that follows from it.
int contentWidthPx = qMin(measureAt(maxWidthPx).width(), maxWidthPx);
// Which side of the selection the panel takes is settled on the first placement
// after a new anchor and kept for as long as that selection lasts, so a card that
// grows or shrinks never flips the panel across the object it describes
// (REQ-UI-SELECTION-PANEL). This is the first point at which its width is known.
if (!m_side.has_value())
{
m_side = chooseSide(band, anchorRect, contentWidthPx + 2 * borderPx,
kMarginPx);
}
// How much height there is depends on where the panel ends up standing: of the
// widgets placed before it, only those whose rectangles meet its own column are
// in its way. That column follows from the width just measured, so this cannot be
// settled before it -- and where the scroll bar below widens the panel, the second
// pass settles it again against the wider column. Asking for the whole band's
// height is what makes the answer the most the panel could have there.
const int maxHeightPx =
placeBesideAnchor(band, anchorRect, *m_side,
QSize(contentWidthPx + 2 * borderPx, band.height()),
occupiedRects, kMarginPx).height() - 2 * borderPx;
if (maxHeightPx <= 0)
{
return;
}
int contentHeightPx = measureAt(contentWidthPx).height();
// A card taller than the space left is capped there and scrolls
// (REQ-UI-SELECTION-PANEL). The bar is laid out beside the card, so the panel
// widens by its width to leave the card the width its height was measured for --
// and where the cap does not allow that, the card is measured again at what is
// left over.
const bool scrolls = (contentHeightPx > maxHeightPx);
int viewportWidthPx = contentWidthPx;
if (scrolls)
{
const int scrollBarWidthPx =
m_scrollArea->verticalScrollBar()->sizeHint().width();
contentWidthPx = qMin(contentWidthPx + scrollBarWidthPx, maxWidthPx);
contentHeightPx = maxHeightPx;
viewportWidthPx = contentWidthPx - scrollBarWidthPx;
measureAt(viewportWidthPx);
}
m_scrollArea->setVerticalScrollBarPolicy(
scrolls ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAlwaysOff);
// Left at the size the scroll area is about to give it, so the card is not
// briefly wider than its viewport.
m_body->resize(viewportWidthPx, m_body->sizeHint().height());
const int panelWidthPx = contentWidthPx + 2 * borderPx;
const int panelHeightPx = contentHeightPx + 2 * borderPx;
setGeometry(placeBesideAnchor(band, anchorRect, *m_side,
QSize(panelWidthPx, panelHeightPx),
occupiedRects, kMarginPx));
}
}

110
src/ui/SelectionPanel.h Normal file
View File

@@ -0,0 +1,110 @@
#pragma once
#include <QRect>
#include <QWidget>
#include <optional>
#include <vector>
#include "DebrisSelectionChangedEvent.h"
#include "DebugDrawToggledEvent.h"
#include "EntitySelectionChangedEvent.h"
#include "EventHandler.h"
#include "FloatingPanel.h"
#include "FloatingPanelPlacement.h"
#include "PlayerCommandsAppliedEvent.h"
#include "SelectionAnchorChangedEvent.h"
#include "SelectionChangedEvent.h"
#include "TickAdvancedEvent.h"
#include "selection/SelectionContentFactory.h"
#include "selection/SelectionContext.h"
struct GameConfig;
struct VisualsConfig;
class BuildingIconCache;
class ItemIconCache;
class SelectionContent;
class Simulation;
class QScrollArea;
class QVBoxLayout;
// Shows the current selection. The panel itself renders nothing: it arbitrates between
// the two selection categories (REQ-UI-SELECTION-CATEGORIES), picks the card that fits
// what is selected (REQ-UI-SELECTION-CONTENT), and hosts exactly one of them at a time.
// What each card looks like lives in src/ui/selection/.
//
// The panel floats over the game world view rather than occupying a column of its own
// (REQ-UI-SELECTION-PANEL): it sizes itself to its card, places itself in what the build
// button bar and the controls panel have left free, and hides itself entirely while
// nothing is selected (REQ-UI-EMPTY-SELECTION).
class SelectionPanel : public QWidget,
public FloatingPanel,
public CombinedEventHandler<TickAdvancedEvent,
PlayerCommandsAppliedEvent,
EntitySelectionChangedEvent,
SelectionChangedEvent,
SelectionAnchorChangedEvent,
DebrisSelectionChangedEvent,
DebugDrawToggledEvent>
{
Q_OBJECT
public:
// visuals, itemIcons and buildingIcons are window-wide rendering resources the cards
// draw from; none is owned and all must outlive this widget.
SelectionPanel(Simulation* sim, const GameConfig* config,
const VisualsConfig* visuals, ItemIconCache* itemIcons,
BuildingIconCache* buildingIcons, QWidget* parent = nullptr);
~SelectionPanel() override;
// Sizes the panel to its card and places it beside the selection it describes, in
// what the widgets placed before it have left free. Keeping clear of them is entirely
// this panel's job; neither of them ever moves for it (REQ-UI-SELECTION-PANEL,
// REQ-UI-BUILD-BAR, REQ-UI-CONTROLS-PANEL).
void placeIn(const QRect& viewRect,
const std::vector<QRect>& occupiedRects) override;
private:
void handleEvent(std::shared_ptr<const SelectionChangedEvent> event) override;
void handleEvent(std::shared_ptr<const SelectionAnchorChangedEvent> event) override;
void handleEvent(std::shared_ptr<const EntitySelectionChangedEvent> event) override;
void handleEvent(std::shared_ptr<const DebrisSelectionChangedEvent> event) override;
void handleEvent(std::shared_ptr<const TickAdvancedEvent> event) override;
void handleEvent(std::shared_ptr<const PlayerCommandsAppliedEvent> event) override;
void handleEvent(std::shared_ptr<const DebugDrawToggledEvent> event) override;
// Re-reads the live values of the card on screen. When the selection now calls for a
// different card -- a construction site finishing is the case that matters -- it
// rebuilds instead, because a card never changes its own shape.
void refreshContent();
// Replaces the card with the one the current selection calls for.
void rebuildContent();
// Asks for the placement pass to be re-run, the card having changed size or the
// panel having gained or lost its reason to be shown at all.
void invalidateLayout();
SelectionContext m_context;
// Read through m_context by the cards that need it, so a toggle reaches the card on
// screen without it having to subscribe to the event itself.
bool m_debugDrawEnabled = false;
SelectionRequest m_request;
ContentKey m_contentKey;
SelectionContent* m_content = nullptr;
// Where the current selection was on the screen when it started, in the game world
// view's coordinates, and which side of it the panel took. Both are frozen for as
// long as the selection lasts: the anchor because the panel does not chase a
// scrolling view or a moving ship, the side because a card that grows must not flip
// the panel across the object (REQ-UI-SELECTION-PANEL). The side is resolved on the
// first placement after a new anchor, being the first point at which the panel's
// width is known.
QRect m_anchorRect;
std::optional<PanelSide> m_side;
// Scrolls the card once it outgrows the space the panel has (REQ-UI-SELECTION-PANEL).
// The card is a child of m_body, not of the panel itself.
QScrollArea* m_scrollArea;
QWidget* m_body;
QVBoxLayout* m_bodyLayout;
};

View File

@@ -1,11 +1,14 @@
#include "ShipStatsPanel.h" #include "ShipStatsPanel.h"
#include <QLabel>
#include <QString> #include <QString>
#include <QVBoxLayout> #include <QVBoxLayout>
#include "BarRow.h"
#include "GameConfig.h" #include "GameConfig.h"
#include "SectionBox.h"
#include "SelectionNames.h"
#include "ShipStatsCalculator.h" #include "ShipStatsCalculator.h"
#include "StatRow.h"
#include "ThreatCostCalculator.h" #include "ThreatCostCalculator.h"
namespace namespace
@@ -16,20 +19,6 @@ QString fmt(float value)
return QString::number(static_cast<double>(value), 'f', 1); return QString::number(static_cast<double>(value), 'f', 1);
} }
QLabel* makeSectionHeader(const QString& text, QWidget* parent)
{
QLabel* label = new QLabel(text, parent);
QFont f = label->font();
f.setBold(true);
label->setFont(f);
return label;
}
QLabel* makeStatLabel(QWidget* parent)
{
return new QLabel(parent);
}
} // namespace } // namespace
@@ -38,215 +27,150 @@ ShipStatsPanel::ShipStatsPanel(const GameConfig* config, QWidget* parent)
, m_config(config) , m_config(config)
{ {
QVBoxLayout* layout = new QVBoxLayout(this); QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(4, 4, 4, 4); layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(2); layout->setSpacing(2);
layout->setAlignment(Qt::AlignTop); layout->setAlignment(Qt::AlignTop);
// Hull stats always visible. // Hull stats -- always visible, except cargo capacity, which only a ship that can
m_hpLabel = makeStatLabel(this); // carry anything shows (REQ-MOD-UI-STATS-PANEL).
m_speedLabel = makeStatLabel(this); m_hpBar = new BarRow(tr("HP"), this);
m_sensorRangeLabel = makeStatLabel(this); m_speedRow = new StatRow(tr("Max speed"), this);
m_mainAccelLabel = makeStatLabel(this); m_sensorRangeRow = new StatRow(tr("Sensor range"), this);
m_maneuveringAccelLabel = makeStatLabel(this); m_mainAccelRow = new StatRow(tr("Main accel"), this);
m_angularAccelLabel = makeStatLabel(this); m_maneuveringAccelRow = new StatRow(tr("Maneuvering accel"), this);
m_maxRotSpeedLabel = makeStatLabel(this); m_angularAccelRow = new StatRow(tr("Angular accel"), this);
m_cargoCapacityLabel = makeStatLabel(this); m_maxRotSpeedRow = new StatRow(tr("Max rotation"), this);
m_cargoCapacityLabel->setVisible(false); m_cargoCapacityRow = new StatRow(tr("Cargo capacity"), this);
m_cargoCapacityRow->hide();
layout->addWidget(m_hpLabel); layout->addWidget(m_hpBar);
layout->addWidget(m_speedLabel); layout->addWidget(m_speedRow);
layout->addWidget(m_sensorRangeLabel); layout->addWidget(m_sensorRangeRow);
layout->addWidget(m_mainAccelLabel); layout->addWidget(m_mainAccelRow);
layout->addWidget(m_maneuveringAccelLabel); layout->addWidget(m_maneuveringAccelRow);
layout->addWidget(m_angularAccelLabel); layout->addWidget(m_angularAccelRow);
layout->addWidget(m_maxRotSpeedLabel); layout->addWidget(m_maxRotSpeedRow);
layout->addWidget(m_cargoCapacityLabel); layout->addWidget(m_cargoCapacityRow);
// Weapon capability section. // One section per capability module type, each shown only while at least one such
m_weaponSection = new QWidget(this); // module is installed (REQ-MOD-UI-STATS-PANEL).
{ m_weaponSection = new SectionBox(tr("Weapons"), this);
QVBoxLayout* sl = new QVBoxLayout(m_weaponSection); m_weaponDpsRow = new StatRow(tr("DPS"), m_weaponSection);
sl->setContentsMargins(0, 4, 0, 0); m_weaponRangeRow = new StatRow(tr("Range"), m_weaponSection);
sl->setSpacing(2); m_weaponSection->getContentLayout()->addWidget(m_weaponDpsRow);
sl->addWidget(makeSectionHeader(tr("Weapons"), m_weaponSection)); m_weaponSection->getContentLayout()->addWidget(m_weaponRangeRow);
m_weaponDpsLabel = makeStatLabel(m_weaponSection); m_weaponSection->hide();
m_weaponRangeLabel = makeStatLabel(m_weaponSection);
sl->addWidget(m_weaponDpsLabel);
sl->addWidget(m_weaponRangeLabel);
}
m_weaponSection->setVisible(false);
layout->addWidget(m_weaponSection); layout->addWidget(m_weaponSection);
// Salvage capability section. m_salvageSection = new SectionBox(tr("Salvage"), this);
m_salvageSection = new QWidget(this); m_salvageRateRow = new StatRow(tr("Collection rate"), m_salvageSection);
{ m_salvageRangeRow = new StatRow(tr("Range"), m_salvageSection);
QVBoxLayout* sl = new QVBoxLayout(m_salvageSection); m_salvageSection->getContentLayout()->addWidget(m_salvageRateRow);
sl->setContentsMargins(0, 4, 0, 0); m_salvageSection->getContentLayout()->addWidget(m_salvageRangeRow);
sl->setSpacing(2); m_salvageSection->hide();
sl->addWidget(makeSectionHeader(tr("Salvage"), m_salvageSection));
m_salvageRateLabel = makeStatLabel(m_salvageSection);
m_salvageRangeLabel = makeStatLabel(m_salvageSection);
sl->addWidget(m_salvageRateLabel);
sl->addWidget(m_salvageRangeLabel);
}
m_salvageSection->setVisible(false);
layout->addWidget(m_salvageSection); layout->addWidget(m_salvageSection);
// Repair capability section. m_repairSection = new SectionBox(tr("Repair"), this);
m_repairSection = new QWidget(this); m_repairRateRow = new StatRow(tr("Repair rate"), m_repairSection);
{ m_repairRangeRow = new StatRow(tr("Range"), m_repairSection);
QVBoxLayout* sl = new QVBoxLayout(m_repairSection); m_repairSection->getContentLayout()->addWidget(m_repairRateRow);
sl->setContentsMargins(0, 4, 0, 0); m_repairSection->getContentLayout()->addWidget(m_repairRangeRow);
sl->setSpacing(2); m_repairSection->hide();
sl->addWidget(makeSectionHeader(tr("Repair"), m_repairSection));
m_repairRateLabel = makeStatLabel(m_repairSection);
m_repairRangeLabel = makeStatLabel(m_repairSection);
sl->addWidget(m_repairRateLabel);
sl->addWidget(m_repairRangeLabel);
}
m_repairSection->setVisible(false);
layout->addWidget(m_repairSection); layout->addWidget(m_repairSection);
// Current behavior — live entities only; hidden in the static design // Live entities only; the design preview has no behavior to show
// preview (REQ-UI-SHIP-BEHAVIOR). // (REQ-UI-SHIP-BEHAVIOR).
m_behaviorLabel = makeSectionHeader(QString(), this); m_behaviorRow = new StatRow(tr("Behavior"), this);
m_behaviorLabel->setVisible(false); m_behaviorRow->hide();
layout->addWidget(m_behaviorLabel); layout->addWidget(m_behaviorRow);
// Threat cost — debug-only, initially hidden. // Threat cost -- shown only while debug draw is active (REQ-UI-SHIP-STATS-PANEL).
m_threatCostLabel = makeStatLabel(this); m_threatCostRow = new StatRow(tr("Threat cost"), this);
m_threatCostLabel->setVisible(false); m_threatCostRow->hide();
layout->addWidget(m_threatCostLabel); layout->addWidget(m_threatCostRow);
}
layout->addStretch(); void ShipStatsPanel::setBehavior(BehaviorKind kind)
{
const QString label = getBehaviorLabel(kind);
m_behaviorRow->setValue(label);
m_behaviorRow->setVisible(!label.isEmpty());
} }
void ShipStatsPanel::refresh(const std::string& shipId, void ShipStatsPanel::refresh(const std::string& shipId,
const std::vector<PlacedModule>& modules) const std::vector<PlacedModule>& modules)
{ {
const ShipStats stats = calculateShipStats(*m_config, shipId, modules); const ShipStats stats = calculateShipStats(*m_config, shipId, modules);
const QString hpText = tr("HP: %1").arg(static_cast<int>(stats.hp + 0.5f)); applyStats(stats, 1.0, QString::number(static_cast<int>(stats.hp + 0.5f)));
applyStats(stats, hpText);
const double threat = calculateShipThreatCost(m_config->threatCosts, *m_config, setThreatCost(calculateShipThreatCost(m_config->threatCosts, *m_config,
shipId, modules); shipId, modules));
setThreatCost(threat);
// The static design preview has no live behavior to show.
m_behaviorLabel->setVisible(false);
} }
void ShipStatsPanel::refreshFromLive(const ShipStats& stats, float currentHp) void ShipStatsPanel::refreshFromLive(const ShipStats& stats, float currentHp)
{ {
const QString hpText = tr("HP: %1 / %2") const double fraction = (stats.hp > 0.0f)
? static_cast<double>(currentHp) / stats.hp
: 0.0;
applyStats(stats, fraction, tr("%1 / %2")
.arg(static_cast<int>(currentHp + 0.5f)) .arg(static_cast<int>(currentHp + 0.5f))
.arg(static_cast<int>(stats.hp + 0.5f)); .arg(static_cast<int>(stats.hp + 0.5f)));
applyStats(stats, hpText);
} }
void ShipStatsPanel::applyStats(const ShipStats& stats, const QString& hpText) void ShipStatsPanel::applyStats(const ShipStats& stats, double hpFraction,
const QString& hpText)
{ {
m_hpLabel->setText(hpText); m_hpBar->setValue(hpFraction, hpText);
m_speedLabel->setText( m_speedRow->setValue(tr("%1 tiles/s").arg(fmt(stats.maxSpeed_tps)));
tr("Max Speed: %1 tiles/s").arg(fmt(stats.maxSpeed_tps))); m_sensorRangeRow->setValue(tr("%1 tiles").arg(fmt(stats.sensorRange_tiles)));
m_sensorRangeLabel->setText( m_mainAccelRow->setValue(
tr("Sensor Range: %1 tiles").arg(fmt(stats.sensorRange_tiles))); tr("%1 tiles/s\xc2\xb2").arg(fmt(stats.mainAcceleration_tpss)));
m_mainAccelLabel->setText( m_maneuveringAccelRow->setValue(
tr("Main Accel: %1 tiles/s\xc2\xb2").arg(fmt(stats.mainAcceleration_tpss))); tr("%1 tiles/s\xc2\xb2").arg(fmt(stats.maneuveringAcceleration_tpss)));
m_maneuveringAccelLabel->setText( m_angularAccelRow->setValue(
tr("Maneuvering Accel: %1 tiles/s\xc2\xb2").arg(fmt(stats.maneuveringAcceleration_tpss))); tr("%1 rad/s\xc2\xb2").arg(fmt(stats.angularAcceleration_radpss)));
m_angularAccelLabel->setText( m_maxRotSpeedRow->setValue(tr("%1 rad/s").arg(fmt(stats.maxRotationSpeed_radps)));
tr("Angular Accel: %1 rad/s\xc2\xb2").arg(fmt(stats.angularAcceleration_radpss)));
m_maxRotSpeedLabel->setText(
tr("Max Rotation: %1 rad/s").arg(fmt(stats.maxRotationSpeed_radps)));
// Cargo capacity is shown only when the ship can actually hold cargo // Cargo capacity is shown only when the ship can actually hold cargo
// (REQ-MOD-UI-STATS-PANEL). // (REQ-MOD-UI-STATS-PANEL).
m_cargoCapacityRow->setVisible(stats.cargoCapacity > 0);
if (stats.cargoCapacity > 0) if (stats.cargoCapacity > 0)
{ {
m_cargoCapacityLabel->setText( m_cargoCapacityRow->setValue(QString::number(stats.cargoCapacity));
tr("Cargo Capacity: %1").arg(stats.cargoCapacity));
m_cargoCapacityLabel->setVisible(true);
}
else
{
m_cargoCapacityLabel->setVisible(false);
} }
m_weaponSection->setVisible(stats.weapons.has_value());
if (stats.weapons.has_value()) if (stats.weapons.has_value())
{ {
m_weaponDpsLabel->setText( m_weaponDpsRow->setValue(fmt(stats.weapons->combinedDps));
tr("DPS: %1").arg(fmt(stats.weapons->combinedDps))); m_weaponRangeRow->setValue(tr("%1 tiles").arg(fmt(stats.weapons->maxRange_tiles)));
m_weaponRangeLabel->setText(
tr("Range: %1 tiles").arg(fmt(stats.weapons->maxRange_tiles)));
m_weaponSection->setVisible(true);
}
else
{
m_weaponSection->setVisible(false);
} }
m_salvageSection->setVisible(stats.salvage.has_value());
if (stats.salvage.has_value()) if (stats.salvage.has_value())
{ {
m_salvageRateLabel->setText( m_salvageRateRow->setValue(
tr("Collection Rate: %1/s").arg(fmt(stats.salvage->combinedCollectionRate))); tr("%1 /s").arg(fmt(stats.salvage->combinedCollectionRate)));
m_salvageRangeLabel->setText( m_salvageRangeRow->setValue(tr("%1 tiles").arg(fmt(stats.salvage->maxRange_tiles)));
tr("Range: %1 tiles").arg(fmt(stats.salvage->maxRange_tiles)));
m_salvageSection->setVisible(true);
}
else
{
m_salvageSection->setVisible(false);
} }
m_repairSection->setVisible(stats.repair.has_value());
if (stats.repair.has_value()) if (stats.repair.has_value())
{ {
m_repairRateLabel->setText( m_repairRateRow->setValue(
tr("Repair Rate: %1 HP/s").arg(fmt(stats.repair->combinedRepairRate_hps))); tr("%1 HP/s").arg(fmt(stats.repair->combinedRepairRate_hps)));
m_repairRangeLabel->setText( m_repairRangeRow->setValue(tr("%1 tiles").arg(fmt(stats.repair->maxRange_tiles)));
tr("Range: %1 tiles").arg(fmt(stats.repair->maxRange_tiles)));
m_repairSection->setVisible(true);
} }
else
{
m_repairSection->setVisible(false);
}
}
void ShipStatsPanel::setBehavior(BehaviorKind kind)
{
QString label;
switch (kind)
{
case BehaviorKind::Retreat: label = tr("Retreating"); break;
case BehaviorKind::Attack: label = tr("Engaging"); break;
case BehaviorKind::SalvageScrap:
case BehaviorKind::DeliverScrap: label = tr("Salvaging"); break;
case BehaviorKind::Repair: label = tr("Repairing"); break;
case BehaviorKind::Rally: label = tr("Rallying"); break;
case BehaviorKind::Standby: label = tr("Standby"); break;
case BehaviorKind::Advance: label = tr("Advancing"); break;
case BehaviorKind::None: break;
}
if (label.isEmpty())
{
m_behaviorLabel->setVisible(false);
return;
}
m_behaviorLabel->setText(tr("Behavior: %1").arg(label));
m_behaviorLabel->setVisible(true);
} }
void ShipStatsPanel::setThreatCost(double cost) void ShipStatsPanel::setThreatCost(double cost)
{ {
m_threatCostLabel->setText(tr("Threat Cost: %1").arg(cost, 0, 'f', 1)); m_threatCostRow->setValue(QString::number(cost, 'f', 1));
m_threatCostLabel->setVisible(m_debugDraw); m_threatCostRow->setVisible(m_debugDraw);
} }
void ShipStatsPanel::setDebugDrawEnabled(bool enabled) void ShipStatsPanel::setDebugDrawEnabled(bool enabled)
{ {
m_debugDraw = enabled; m_debugDraw = enabled;
m_threatCostLabel->setVisible(m_debugDraw); m_threatCostRow->setVisible(m_debugDraw);
} }

View File

@@ -1,18 +1,28 @@
#pragma once #pragma once
#include <map>
#include <string> #include <string>
#include <vector> #include <vector>
#include <QWidget> #include <QWidget>
#include "BehaviorKind.h"
#include "ShipLayout.h" #include "ShipLayout.h"
#include "ShipStatsCalculator.h" #include "ShipStatsCalculator.h"
struct GameConfig; #include "BehaviorKind.h"
class QLabel;
struct GameConfig;
class BarRow;
class SectionBox;
class StatRow;
// The hull stats and capability module summaries of one ship, as a bar for HP and a
// label/value row for everything else. Shared by the live selection card
// (REQ-UI-SHIP-STATS-PANEL), the layout configuration dialog's design preview
// (REQ-MOD-UI-STATS-PANEL) and the balancing tool, so all three read alike.
//
// The behavior row is for consumers with no header to put it in. The selection card
// shows the behavior in its header instead (REQ-UI-SHIP-BEHAVIOR) and leaves the row
// unset; the design preview has no live ship to have a behavior at all.
class ShipStatsPanel : public QWidget class ShipStatsPanel : public QWidget
{ {
Q_OBJECT Q_OBJECT
@@ -20,44 +30,47 @@ class ShipStatsPanel : public QWidget
public: public:
explicit ShipStatsPanel(const GameConfig* config, QWidget* parent = nullptr); explicit ShipStatsPanel(const GameConfig* config, QWidget* parent = nullptr);
// Stats of a design rather than of a live ship: the HP bar reads full, because the
// number shown is the maximum the design would have.
void refresh(const std::string& shipId, void refresh(const std::string& shipId,
const std::vector<PlacedModule>& modules); const std::vector<PlacedModule>& modules);
void refreshFromLive(const ShipStats& stats, float currentHp); void refreshFromLive(const ShipStats& stats, float currentHp);
// Displays the ship's current top-priority behavior (REQ-UI-SHIP-BEHAVIOR). // Shows the ship's top-priority behavior as a row of its own. Never called by the
// selection card, which has a header slot for it.
void setBehavior(BehaviorKind kind); void setBehavior(BehaviorKind kind);
void setThreatCost(double cost); void setThreatCost(double cost);
void setDebugDrawEnabled(bool enabled); void setDebugDrawEnabled(bool enabled);
private: private:
void applyStats(const ShipStats& stats, const QString& hpText); void applyStats(const ShipStats& stats, double hpFraction, const QString& hpText);
const GameConfig* m_config; const GameConfig* m_config;
bool m_debugDraw = false; bool m_debugDraw = false;
QLabel* m_behaviorLabel; BarRow* m_hpBar;
QLabel* m_hpLabel; StatRow* m_speedRow;
QLabel* m_speedLabel; StatRow* m_sensorRangeRow;
QLabel* m_sensorRangeLabel; StatRow* m_mainAccelRow;
QLabel* m_mainAccelLabel; StatRow* m_maneuveringAccelRow;
QLabel* m_maneuveringAccelLabel; StatRow* m_angularAccelRow;
QLabel* m_angularAccelLabel; StatRow* m_maxRotSpeedRow;
QLabel* m_maxRotSpeedLabel; StatRow* m_cargoCapacityRow;
QLabel* m_cargoCapacityLabel;
QWidget* m_weaponSection; SectionBox* m_weaponSection;
QLabel* m_weaponDpsLabel; StatRow* m_weaponDpsRow;
QLabel* m_weaponRangeLabel; StatRow* m_weaponRangeRow;
QWidget* m_salvageSection; SectionBox* m_salvageSection;
QLabel* m_salvageRateLabel; StatRow* m_salvageRateRow;
QLabel* m_salvageRangeLabel; StatRow* m_salvageRangeRow;
QWidget* m_repairSection; SectionBox* m_repairSection;
QLabel* m_repairRateLabel; StatRow* m_repairRateRow;
QLabel* m_repairRangeLabel; StatRow* m_repairRangeRow;
QLabel* m_threatCostLabel; StatRow* m_behaviorRow;
StatRow* m_threatCostRow;
}; };

View File

@@ -48,7 +48,7 @@ struct OverlayVisuals
QColor selectionRect; QColor selectionRect;
QColor tileHighlight; QColor tileHighlight;
QColor selectedOutline; QColor selectedOutline;
QColor copyConfig; QColor configTransfer; // blueprint ghost over a transfer target (REQ-UI-BLUEPRINT-TRANSFER)
QColor lockedAsteroid; QColor lockedAsteroid;
QColor modalDim; QColor modalDim;
QColor tunnelPreview; // tunnel connection preview highlight (REQ-BLD-TUNNEL-MODE) QColor tunnelPreview; // tunnel connection preview highlight (REQ-BLD-TUNNEL-MODE)

View File

@@ -224,7 +224,7 @@ VisualsConfig VisualsLoader::load(const std::string& path)
cfg.overlays.selectionRect = parseColor(requireString(ov, "selection_rect", "overlays"), "overlays.selection_rect"); cfg.overlays.selectionRect = parseColor(requireString(ov, "selection_rect", "overlays"), "overlays.selection_rect");
cfg.overlays.tileHighlight = parseColor(requireString(ov, "tile_highlight", "overlays"), "overlays.tile_highlight"); cfg.overlays.tileHighlight = parseColor(requireString(ov, "tile_highlight", "overlays"), "overlays.tile_highlight");
cfg.overlays.selectedOutline = parseColor(requireString(ov, "selected_outline", "overlays"), "overlays.selected_outline"); cfg.overlays.selectedOutline = parseColor(requireString(ov, "selected_outline", "overlays"), "overlays.selected_outline");
cfg.overlays.copyConfig = parseColor(requireString(ov, "copy_config", "overlays"), "overlays.copy_config"); cfg.overlays.configTransfer = parseColor(requireString(ov, "config_transfer", "overlays"), "overlays.config_transfer");
cfg.overlays.lockedAsteroid = parseColor(requireString(ov, "locked_asteroid", "overlays"), "overlays.locked_asteroid"); cfg.overlays.lockedAsteroid = parseColor(requireString(ov, "locked_asteroid", "overlays"), "overlays.locked_asteroid");
cfg.overlays.modalDim = parseColor(requireString(ov, "modal_dim", "overlays"), "overlays.modal_dim"); cfg.overlays.modalDim = parseColor(requireString(ov, "modal_dim", "overlays"), "overlays.modal_dim");
cfg.overlays.tunnelPreview = parseColor(requireString(ov, "tunnel_preview", "overlays"), "overlays.tunnel_preview"); cfg.overlays.tunnelPreview = parseColor(requireString(ov, "tunnel_preview", "overlays"), "overlays.tunnel_preview");

View File

@@ -35,6 +35,7 @@
#include "ProductionRules.h" #include "ProductionRules.h"
#include "RepairBehavior.h" #include "RepairBehavior.h"
#include "SalvageScrapBehavior.h" #include "SalvageScrapBehavior.h"
#include "SelectionBounds.h"
#include "SensorRangeComponent.h" #include "SensorRangeComponent.h"
#include "ShipIdentityComponent.h" #include "ShipIdentityComponent.h"
#include "Simulation.h" #include "Simulation.h"
@@ -108,7 +109,7 @@ QColor statusLightFill(ProductionStatus status, const StatusLightVisuals& sl)
} // namespace } // namespace
WorldRenderer::WorldRenderer(Simulation& sim, const VisualsConfig& visuals, WorldRenderer::WorldRenderer(const Simulation& sim, const VisualsConfig& visuals,
ItemIconCache* itemIcons, const std::string& configDir) ItemIconCache* itemIcons, const std::string& configDir)
: m_sim(sim) : m_sim(sim)
, m_visuals(visuals) , m_visuals(visuals)
@@ -129,7 +130,6 @@ void WorldRenderer::render(QPainter& painter, const WorldCoordinates& coordinate
// into the port and stay visible while crossing directly between two touching // into the port and stay visible while crossing directly between two touching
// buildings (REQ-MAT-OUTPUT-EMERGE, REQ-MAT-INPUT-INTAKE, REQ-MAT-DIRECT-COUPLE). // buildings (REQ-MAT-OUTPUT-EMERGE, REQ-MAT-INPUT-INTAKE, REQ-MAT-DIRECT-COUPLE).
drawPortItems(painter, coordinates, frame); drawPortItems(painter, coordinates, frame);
drawCopyConfigFeedback(painter, coordinates, frame);
drawStations(painter, coordinates, frame); drawStations(painter, coordinates, frame);
drawBeltItems(painter, coordinates, frame); drawBeltItems(painter, coordinates, frame);
drawDebris(painter, coordinates, frame); drawDebris(painter, coordinates, frame);
@@ -452,30 +452,6 @@ void WorldRenderer::drawBuildings(QPainter& painter, const WorldCoordinates& coo
drawSelectionHighlights(painter, coordinates, frame); drawSelectionHighlights(painter, coordinates, frame);
} }
std::optional<QRectF> WorldRenderer::footprintWidgetRect(
const WorldCoordinates& coordinates, BuildingId id) const
{
std::optional<QPoint> anchor;
std::optional<QSize> footprint;
if (const Building* b = findBuilding(m_sim.getFactoryState(), id))
{
anchor = b->anchor;
footprint = b->footprint;
}
else if (const ConstructionSite* s = findSite(m_sim.getFactoryState(), id))
{
anchor = s->anchor;
footprint = s->footprint;
}
if (!anchor.has_value() || !footprint.has_value()) { return std::nullopt; }
const QPointF tl = coordinates.tileToWidget(*anchor);
return QRectF(tl.x(), tl.y(),
footprint->width() * static_cast<qreal>(coordinates.getTilePx()),
footprint->height() * static_cast<qreal>(coordinates.getTilePx()));
}
void WorldRenderer::drawSelectionHighlights(QPainter& painter, const WorldCoordinates& coordinates, void WorldRenderer::drawSelectionHighlights(QPainter& painter, const WorldCoordinates& coordinates,
const WorldRenderFrame& frame) const WorldRenderFrame& frame)
{ {
@@ -484,7 +460,8 @@ void WorldRenderer::drawSelectionHighlights(QPainter& painter, const WorldCoordi
for (BuildingId selId : frame.selection.getSelectedBuildings()) for (BuildingId selId : frame.selection.getSelectedBuildings())
{ {
const std::optional<QRectF> rect = footprintWidgetRect(coordinates, selId); const std::optional<QRectF> rect =
getBuildingWidgetRect(m_sim.getFactoryState(), coordinates, selId);
if (!rect.has_value()) { continue; } if (!rect.has_value()) { continue; }
// Outline sits 1px outside the footprint (into adjacent tiles). // Outline sits 1px outside the footprint (into adjacent tiles).
painter.drawRect(rect->adjusted(-1, -1, 1, 1)); painter.drawRect(rect->adjusted(-1, -1, 1, 1));
@@ -505,44 +482,6 @@ void WorldRenderer::drawSelectionHighlights(QPainter& painter, const WorldCoordi
} }
} }
void WorldRenderer::drawCopyConfigFeedback(QPainter& painter, const WorldCoordinates& coordinates,
const WorldRenderFrame& frame)
{
const QColor color = m_visuals.overlays.copyConfig;
// Eligible-target tint: while a configuration is cached, every same-type
// building and site (the source included) is a valid paste target and is
// washed in the copy-settings color (REQ-BLD-COPY-CONFIG-FEEDBACK).
if (frame.copiedConfig.has_value())
{
painter.setPen(Qt::NoPen);
painter.setBrush(color);
const BuildingType type = frame.copiedConfig->type;
for (const Building& b : getAllBuildings(m_sim.getFactoryState()))
{
if (b.type != type) { continue; }
const std::optional<QRectF> rect = footprintWidgetRect(coordinates, b.id);
if (rect.has_value()) { painter.drawRect(*rect); }
}
for (const ConstructionSite& s : getAllSites(m_sim.getFactoryState()))
{
if (s.type != type) { continue; }
const std::optional<QRectF> rect = footprintWidgetRect(coordinates, s.id);
if (rect.has_value()) { painter.drawRect(*rect); }
}
}
// Copy / paste flashes: a brief outline in the same color, drawn like the
// selection outline (REQ-BLD-COPY-CONFIG-FEEDBACK).
painter.setPen(QPen(color, 2));
painter.setBrush(Qt::NoBrush);
for (const CopyConfigFlash& flash : frame.copyConfigFlashes)
{
const std::optional<QRectF> rect = footprintWidgetRect(coordinates, flash.id);
if (rect.has_value()) { painter.drawRect(rect->adjusted(-1, -1, 1, 1)); }
}
}
void WorldRenderer::drawPortItems(QPainter& painter, const WorldCoordinates& coordinates, void WorldRenderer::drawPortItems(QPainter& painter, const WorldCoordinates& coordinates,
const WorldRenderFrame& /*frame*/) const WorldRenderFrame& /*frame*/)
{ {
@@ -967,7 +906,8 @@ void WorldRenderer::drawOverlays(QPainter& painter, const WorldCoordinates& coor
const BeltPathTile& entry = frame.buildMode.getBeltDragPath()[index]; const BeltPathTile& entry = frame.buildMode.getBeltDragPath()[index];
drawBuildingGhost(painter, coordinates, BuildingType::Belt, drawBuildingGhost(painter, coordinates, BuildingType::Belt,
entry.tile, entry.rotation, entry.tile, entry.rotation,
/*valid*/ item.action != BeltTileAction::Invalid, item.action != BeltTileAction::Invalid
? GhostTint::Normal : GhostTint::Invalid,
/*showPortTargetGlyphs*/ true); /*showPortTargetGlyphs*/ true);
} }
} }
@@ -999,7 +939,8 @@ void WorldRenderer::drawOverlays(QPainter& painter, const WorldCoordinates& coor
drawBuildingGhost(painter, coordinates, drawBuildingGhost(painter, coordinates,
frame.buildMode.getEffectiveBuilderType(), frame.buildMode.getEffectiveBuilderType(),
ghostTile, frame.buildMode.getGhostRotation(), ghostTile, frame.buildMode.getGhostRotation(),
frame.buildMode.isGhostValid(), frame.buildMode.isGhostValid()
? GhostTint::Normal : GhostTint::Invalid,
/*showPortTargetGlyphs*/ true); /*showPortTargetGlyphs*/ true);
} }
} }
@@ -1007,15 +948,39 @@ void WorldRenderer::drawOverlays(QPainter& painter, const WorldCoordinates& coor
// Blueprint placement ghost // Blueprint placement ghost
if (frame.buildMode.isBlueprintMode()) if (frame.buildMode.isBlueprintMode())
{ {
// A single-building blueprint hit-tests the cursor for its transfer target; a
// constellation does not (REQ-UI-BLUEPRINT-TRANSFER). The stored building count,
// not the count after locked types are dropped, so the rule does not shift as the
// player unlocks things.
const QPoint cursorTile = frame.buildMode.getBlueprintGhostTile();
const std::optional<QPoint> hoverTile =
frame.buildMode.getBlueprint().buildings.size() == 1
? std::make_optional(cursorTile) : std::nullopt;
for (const BlueprintBuilding& bb : frame.buildMode.getBlueprint().buildings) for (const BlueprintBuilding& bb : frame.buildMode.getBlueprint().buildings)
{ {
// Locked building types are omitted from the blueprint (REQ-LOCK-BUILDING, // Locked building types are omitted from the blueprint (REQ-LOCK-BUILDING,
// REQ-LOCK-UI-BLUEPRINT), so they are not ghosted either. // REQ-LOCK-UI-BLUEPRINT), so they are not ghosted either.
if (!m_sim.isBuildingUnlocked(bb.type)) { continue; } if (!m_sim.isBuildingUnlocked(bb.type)) { continue; }
const QPoint anchor = frame.buildMode.getBlueprintGhostTile() + bb.offset; // The same classifier the click path uses, so the color always predicts what
const bool valid = canPlaceBuilding(m_sim.getFactoryState(), m_sim.getConfig(), bb.type, anchor, bb.rotation); // clicking would do (REQ-UI-BLUEPRINT-OVERLAP, REQ-UI-BLUEPRINT-TRANSFER). A
drawBuildingGhost(painter, coordinates, bb.type, anchor, bb.rotation, // compatible overlap is an ordinary valid ghost. The resolved anchor and
valid, /*showPortTargetGlyphs*/ false); // rotation are drawn rather than the blueprint's own, so a hovered transfer
// target shows the ghost snapped onto it.
const BlueprintGhostResolved resolved = resolveBlueprintGhost(
m_sim.getFactoryState(), m_sim.getConfig(), bb.type, cursorTile + bb.offset,
bb.rotation, hoverTile);
GhostTint tint = GhostTint::Normal;
if (resolved.action == BlueprintGhostAction::Transfer)
{
tint = GhostTint::Transfer;
}
else if (resolved.action == BlueprintGhostAction::Invalid)
{
tint = GhostTint::Invalid;
}
drawBuildingGhost(painter, coordinates, bb.type, resolved.ghostAnchor,
resolved.ghostRotation, tint,
/*showPortTargetGlyphs*/ false);
} }
} }
@@ -1087,7 +1052,7 @@ void WorldRenderer::drawBuildingGhost(QPainter& painter,
const WorldCoordinates& coordinates, const WorldCoordinates& coordinates,
BuildingType type, BuildingType type,
QPoint anchorTile, Rotation rotation, QPoint anchorTile, Rotation rotation,
bool valid, bool showPortTargetGlyphs) GhostTint tint, bool showPortTargetGlyphs)
{ {
const BuildingDef* def = m_sim.getConfig().buildings.findBuildingDef(type); const BuildingDef* def = m_sim.getConfig().buildings.findBuildingDef(type);
if (!def) { return; } if (!def) { return; }
@@ -1097,15 +1062,18 @@ void WorldRenderer::drawBuildingGhost(QPainter& painter,
if (it == m_visuals.buildings.end()) { return; } if (it == m_visuals.buildings.end()) { return; }
const BuildingVisuals& bv = it->second; const BuildingVisuals& bv = it->second;
// Valid ghosts show the building type's own colors; invalid ghosts override // Normal ghosts show the building type's own colors; the other two tints override
// with the distinct invalid color (REQ-BLD-GHOST, REQ-BLD-PLACE-VALID). The // them with a single flat color -- invalid (REQ-BLD-GHOST, REQ-BLD-PLACE-VALID) or
// invalid color's RGB is taken at full opacity so it does not double-dim // configuration transfer (REQ-UI-BLUEPRINT-TRANSFER). An override's RGB is taken at
// against the setOpacity below (the configured color carries its own alpha). // full opacity so it does not double-dim against the setOpacity below (the
const QColor invalidColor(m_visuals.overlays.ghostInvalid.red(), // configured color carries its own alpha).
m_visuals.overlays.ghostInvalid.green(), const QColor& configured = tint == GhostTint::Transfer
m_visuals.overlays.ghostInvalid.blue()); ? m_visuals.overlays.configTransfer
const QColor fillColor = valid ? bv.fill : invalidColor; : m_visuals.overlays.ghostInvalid;
const QColor lineColor = valid ? bv.outline : invalidColor; const QColor overrideColor(configured.red(), configured.green(), configured.blue());
const bool useOwnColors = tint == GhostTint::Normal;
const QColor fillColor = useOwnColors ? bv.fill : overrideColor;
const QColor lineColor = useOwnColors ? bv.outline : overrideColor;
const ParsedSurfaceMask parsed = parseSurfaceMask(def->surfaceMask, rotation); const ParsedSurfaceMask parsed = parseSurfaceMask(def->surfaceMask, rotation);
if (parsed.bodyCells.empty()) { return; } if (parsed.bodyCells.empty()) { return; }

View File

@@ -14,7 +14,6 @@
#include "BeamFiredEvent.h" #include "BeamFiredEvent.h"
#include "BuildModeController.h" #include "BuildModeController.h"
#include "BuildingConfig.h"
#include "BuildingId.h" #include "BuildingId.h"
#include "BuildingType.h" #include "BuildingType.h"
#include "Rotation.h" #include "Rotation.h"
@@ -36,14 +35,14 @@ struct ActiveBeam
QVector2D targetOffset; QVector2D targetOffset;
}; };
// Brief outline flash shown on a building when settings are copied from it or // How a placement ghost is colored. Normal shows the building type's own colors
// pasted onto it (REQ-BLD-COPY-CONFIG-FEEDBACK). remainingMs counts down in // (REQ-BLD-GHOST); the other two override them (REQ-BLD-PLACE-VALID,
// wall-clock time so the flash plays at a fixed length regardless of game speed // REQ-UI-BLUEPRINT-TRANSFER).
// (and while paused). enum class GhostTint
struct CopyConfigFlash
{ {
BuildingId id; Normal,
qint64 remainingMs; Invalid,
Transfer
}; };
// Everything the renderer draws that the simulation does not know about: what the // Everything the renderer draws that the simulation does not know about: what the
@@ -55,8 +54,6 @@ struct WorldRenderFrame
const SelectionController& selection; const SelectionController& selection;
const BuildModeController& buildMode; const BuildModeController& buildMode;
const std::vector<ActiveBeam>& beams; const std::vector<ActiveBeam>& beams;
const std::optional<BuildingConfig>& copiedConfig;
const std::vector<CopyConfigFlash>& copyConfigFlashes;
bool isBoxSelecting; bool isBoxSelecting;
QPoint boxStartTile; QPoint boxStartTile;
QPoint boxCurrentTile; QPoint boxCurrentTile;
@@ -80,7 +77,7 @@ public:
// `itemIcons` is the window-wide per-item icon cache (REQ-UI-ITEM-ICON); not // `itemIcons` is the window-wide per-item icon cache (REQ-UI-ITEM-ICON); not
// owned, must outlive this renderer. `configDir` is used once, to load the // owned, must outlive this renderer. `configDir` is used once, to load the
// per-building world icons. // per-building world icons.
WorldRenderer(Simulation& sim, const VisualsConfig& visuals, WorldRenderer(const Simulation& sim, const VisualsConfig& visuals,
ItemIconCache* itemIcons, const std::string& configDir); ItemIconCache* itemIcons, const std::string& configDir);
~WorldRenderer(); ~WorldRenderer();
@@ -94,8 +91,6 @@ private:
const WorldRenderFrame& frame); const WorldRenderFrame& frame);
void drawSelectionHighlights(QPainter& painter, const WorldCoordinates& coordinates, void drawSelectionHighlights(QPainter& painter, const WorldCoordinates& coordinates,
const WorldRenderFrame& frame); const WorldRenderFrame& frame);
void drawCopyConfigFeedback(QPainter& painter, const WorldCoordinates& coordinates,
const WorldRenderFrame& frame);
void drawPortItems(QPainter& painter, const WorldCoordinates& coordinates, void drawPortItems(QPainter& painter, const WorldCoordinates& coordinates,
const WorldRenderFrame& frame); const WorldRenderFrame& frame);
void drawStations(QPainter& painter, const WorldCoordinates& coordinates, void drawStations(QPainter& painter, const WorldCoordinates& coordinates,
@@ -128,7 +123,7 @@ private:
bool centered); bool centered);
void drawBuildingGhost(QPainter& painter, const WorldCoordinates& coordinates, void drawBuildingGhost(QPainter& painter, const WorldCoordinates& coordinates,
BuildingType type, QPoint anchorTile, Rotation rotation, BuildingType type, QPoint anchorTile, Rotation rotation,
bool valid, bool showPortTargetGlyphs); GhostTint tint, bool showPortTargetGlyphs);
// Loads the per-building world icons (REQ-UI-WORLD-ICON) from // Loads the per-building world icons (REQ-UI-WORLD-ICON) from
// <configDir>/../icons/buildings once at construction. Only the building // <configDir>/../icons/buildings once at construction. Only the building
@@ -144,17 +139,10 @@ private:
BuildingType type, const QRectF& box, BuildingType type, const QRectF& box,
const QColor& fill) const; const QColor& fill) const;
// Widget-space rectangle covering a building or construction site's footprint,
// or nullopt if the id resolves to neither. Shared by the selection highlight
// and the copy-settings feedback (REQ-BLD-COPY-CONFIG-FEEDBACK).
std::optional<QRectF> footprintWidgetRect(const WorldCoordinates& coordinates,
BuildingId id) const;
std::optional<QVector2D> entityPosition(entt::entity entity) const; std::optional<QVector2D> entityPosition(entt::entity entity) const;
// Non-const only because EntityAdmin's component accessors are; the renderer // The renderer reads the simulation and never writes it.
// reads the simulation and never writes it. const Simulation& m_sim;
Simulation& m_sim;
const VisualsConfig& m_visuals; const VisualsConfig& m_visuals;
// Per-item icon cache (REQ-UI-ITEM-ICON), shared window-wide and owned by // Per-item icon cache (REQ-UI-ITEM-ICON), shared window-wide and owned by

View File

@@ -0,0 +1,75 @@
#include "AutoProductionContent.h"
#include "Building.h"
#include "BuildingTarget.h"
#include "GameConfig.h"
#include "ProductionRules.h"
AutoProductionContent::AutoProductionContent(const SelectionContext& context,
const SelectionRequest& request,
QWidget* parent)
: BufferedBuildingContent(context, request.buildings.front(), parent)
{
}
BufferedBuildingContent::CycleInfo AutoProductionContent::getCycleInfo(
const BuildingTarget& target) const
{
CycleInfo info;
// An auto-recipe building always runs an implicit recipe (REQ-BLD-SMELTER,
// REQ-BLD-REPROCESSING), so its production section is always shown -- but only a
// running cycle names a recipe, so while it is idle there is no cycle to describe.
info.runsProduction = true;
if (target.building)
{
// What the building handles at all, so its buffers are not blank whenever it
// happens to be between cycles (REQ-UI-SINGLE-SELECTION). This is the same union
// of every recipe of its type that the simulation sized the buffers over, and
// the locked ones among them are dropped when the card lists them.
for (const RecipeDef* recipe :
gatherCandidateRecipes(*getContext().config, *target.building))
{
for (const RecipeIngredient& ingredient : recipe->inputs)
{
info.handledInputs.push_back(ingredient.item);
}
for (const RecipeOutput& output : recipe->outputs)
{
info.handledOutputs.push_back(output.item);
}
}
}
// Which recipe describes the cycle: the one running, or -- between cycles -- the one
// that ran last. Dropping it while idle would take the summary row and the chips'
// per-cycle amounts away and bring them back with every cycle, resizing the card in
// step with the building's status (REQ-UI-RECIPE-SUMMARY). Only a building that has
// never run has nothing to describe.
if (target.building && target.building->production.has_value())
{
m_lastRecipeId = target.building->production->recipeId;
}
if (!target.building || m_lastRecipeId.empty())
{
return info;
}
const RecipeDef* recipe =
getContext().config->recipes.findRecipeDef(m_lastRecipeId, target.type);
if (!recipe)
{
return info;
}
for (const RecipeIngredient& ingredient : recipe->inputs)
{
info.perCycleInputs[ingredient.item] = ingredient.amount;
}
for (const RecipeOutput& output : recipe->outputs)
{
info.perCycleOutputs[output.item] = output.amount;
}
info.durationSeconds = recipe->durationSeconds;
return info;
}

View File

@@ -0,0 +1,29 @@
#pragma once
#include <string>
#include "BufferedBuildingContent.h"
#include "SelectionContentFactory.h"
// The card for a Smelter or a Reprocessing Plant (REQ-UI-SELECTION-CONTENT). Both
// auto-process whatever they receive and have no player-facing recipe selection
// (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING), so the card has no configuration group at
// all; its cycle is whichever recipe is in production, or the last one that was.
class AutoProductionContent : public BufferedBuildingContent
{
Q_OBJECT
public:
AutoProductionContent(const SelectionContext& context,
const SelectionRequest& request, QWidget* parent = nullptr);
protected:
CycleInfo getCycleInfo(const BuildingTarget& target) const override;
private:
// The recipe last seen in production, which keeps describing the cycle while the
// building sits between cycles (REQ-UI-RECIPE-SUMMARY). Mutable because it is a
// record of what getCycleInfo() has observed rather than state of its own: the card
// shows the same thing whether or not it has been asked before.
mutable std::string m_lastRecipeId;
};

123
src/ui/selection/BarRow.cpp Normal file
View File

@@ -0,0 +1,123 @@
#include "BarRow.h"
#include <algorithm>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QPaintEvent>
#include <QVBoxLayout>
namespace
{
// Height and corner radius of the fill bar, in device-independent pixels.
const int kBarHeightPx = 6;
const qreal kBarRadiusPx = 3.0;
// Opacity of the unfilled track, over the card's background.
const int kTrackAlpha = 60;
} // namespace
// The bar itself. Painted rather than assembled from a QProgressBar, because all it
// needs is a rounded track with a rounded fill and a style sheet cannot be relied on to
// leave a progress bar's groove and chunk alone across styles.
class BarRow::Bar : public QWidget
{
public:
explicit Bar(QWidget* parent)
: QWidget(parent)
, m_fraction(0.0)
{
setFixedHeight(kBarHeightPx);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
}
void setFraction(double fraction)
{
m_fraction = std::max(0.0, std::min(1.0, fraction));
update();
}
void setFillColor(const QColor& color)
{
m_fillColor = color;
update();
}
protected:
void paintEvent(QPaintEvent* /*event*/) override
{
// The active group is asked for by name rather than taken from the current one,
// which follows the window's focus: the inactive group's highlight is close
// enough to the card's background that the bar reads as gone whenever the game
// is tabbed away from or a modal dialog holds focus -- exactly when a player
// watching a build finish is most likely to be looking at it.
const QColor fill = m_fillColor.isValid()
? m_fillColor
: palette().color(QPalette::Active, QPalette::Highlight);
QColor track = fill;
track.setAlpha(kTrackAlpha);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(Qt::NoPen);
painter.setBrush(track);
painter.drawRoundedRect(rect(), kBarRadiusPx, kBarRadiusPx);
if (m_fraction > 0.0)
{
QRect filled = rect();
filled.setWidth(static_cast<int>(filled.width() * m_fraction));
painter.setBrush(fill);
painter.drawRoundedRect(filled, kBarRadiusPx, kBarRadiusPx);
}
}
private:
double m_fraction;
QColor m_fillColor;
};
BarRow::BarRow(const QString& caption, QWidget* parent)
: QWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(2);
QWidget* captionRow = new QWidget(this);
QHBoxLayout* captionLayout = new QHBoxLayout(captionRow);
captionLayout->setContentsMargins(0, 0, 0, 0);
captionLayout->setSpacing(8);
m_captionLabel = new QLabel(caption, captionRow);
m_captionLabel->setVisible(!caption.isEmpty());
m_valueLabel = new QLabel(captionRow);
m_valueLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
captionLayout->addWidget(m_captionLabel);
captionLayout->addStretch(1);
captionLayout->addWidget(m_valueLabel);
m_bar = new Bar(this);
layout->addWidget(captionRow);
layout->addWidget(m_bar);
}
void BarRow::setValue(double fraction, const QString& valueText)
{
m_bar->setFraction(fraction);
m_valueLabel->setText(valueText);
}
void BarRow::setFillColor(const QColor& color)
{
m_bar->setFillColor(color);
}

36
src/ui/selection/BarRow.h Normal file
View File

@@ -0,0 +1,36 @@
#pragma once
#include <QColor>
#include <QString>
#include <QWidget>
class QLabel;
// A caption with its value hard right and a horizontal fill bar beneath it. One part for
// the three things the panel shows as a proportion: a construction site's progress, a
// building's production cycle, and the HP of a ship, a station or the HQ
// (REQ-UI-PRODUCTION-PROGRESS, REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL,
// REQ-UI-HQ-PANEL).
//
// The caption may be left empty, for a bar whose meaning is already given by the section
// it sits in.
class BarRow : public QWidget
{
Q_OBJECT
public:
explicit BarRow(const QString& caption, QWidget* parent = nullptr);
// fraction is clamped to [0, 1]; valueText is shown beside the caption as-is, so a
// bar can read "72%" or "340 / 500" as its meaning requires.
void setValue(double fraction, const QString& valueText);
// Overrides the fill color, which defaults to the palette's highlight.
void setFillColor(const QColor& color);
private:
class Bar;
QLabel* m_captionLabel;
QLabel* m_valueLabel;
Bar* m_bar;
};

View File

@@ -0,0 +1,38 @@
#include "BeltContent.h"
#include <QVBoxLayout>
#include "BuildingTarget.h"
#include "ClearBeltControl.h"
#include "SelectionNames.h"
BeltContent::BeltContent(const SelectionContext& context,
const SelectionRequest& request, QWidget* parent)
// Only an operational tile aggregates, so a card showing several is never a site;
// a single selected tile still can be one.
: SelectionContent(context,
request.buildings.size() == 1
? asConstructionSite(context, request.buildings.front())
: std::nullopt,
parent)
, m_ids(request.buildings)
{
getRuntimeLayout()->addWidget(new ClearBeltControl(context, m_ids, this));
}
void BeltContent::refreshConfiguration()
{
const BuildingTarget target = resolveBuildingTarget(getContext(), m_ids.front());
if (!target.isValid())
{
return;
}
// An aggregated selection may mix belts with tunnel ends, so it is named after the
// first tile; the count says how many are held (REQ-UI-SELECTION-AGGREGATE).
setBuildingIdentity(target.type, getBuildingTypeName(target.type));
if (m_ids.size() > 1)
{
setCountSlot(static_cast<int>(m_ids.size()));
}
}

View File

@@ -0,0 +1,30 @@
#pragma once
#include <vector>
#include "BuildingId.h"
#include "SelectionContent.h"
#include "SelectionContentFactory.h"
// The card for a belt, a tunnel entry or a tunnel exit
// (REQ-UI-SELECTION-CONTENT). These carry no configuration and no buffers of their own;
// their card is the clear action alone (REQ-UI-BELT-CLEAR).
//
// Because that action already operates on the whole selection, several of them aggregate
// into this one card with the count in the header (REQ-UI-SELECTION-AGGREGATE) -- the
// splitter is not among them, as its output filters are per-object.
class BeltContent : public SelectionContent
{
Q_OBJECT
public:
BeltContent(const SelectionContext& context, const SelectionRequest& request,
QWidget* parent = nullptr);
protected:
void refreshConfiguration() override;
void refreshRuntime() override {}
private:
std::vector<BuildingId> m_ids;
};

View File

@@ -0,0 +1,209 @@
#include "BufferedBuildingContent.h"
#include <map>
#include <set>
#include <QVBoxLayout>
#include "Building.h"
#include "BuildingTarget.h"
#include "DisplayName.h"
#include "FactoryQueries.h"
#include "ProductionSection.h"
#include "RecipeSummaryRow.h"
#include "SectionBox.h"
#include "SelectionNames.h"
#include "Simulation.h"
namespace
{
std::vector<RecipeSummaryRow::Amount> toAmounts(const std::map<std::string, int>& map)
{
std::vector<RecipeSummaryRow::Amount> amounts;
amounts.reserve(map.size());
for (const std::pair<const std::string, int>& entry : map)
{
amounts.push_back(RecipeSummaryRow::Amount{ entry.first, entry.second });
}
return amounts;
}
// Every item one side of the card should list: what the buffer holds, what a cycle
// moves, and what the building handles at all. A building's buffers can carry items it
// is not currently making anything of, and an auto-recipe building between cycles names
// nothing at all, so the three sources are unioned rather than one being picked.
std::set<std::string> collectItemIds(const std::map<std::string, int>& buffered,
const std::map<std::string, int>& perCycle,
const std::vector<std::string>& handled)
{
std::set<std::string> itemIds;
for (const std::pair<const std::string, int>& entry : buffered)
{
itemIds.insert(entry.first);
}
for (const std::pair<const std::string, int>& entry : perCycle)
{
itemIds.insert(entry.first);
}
itemIds.insert(handled.begin(), handled.end());
return itemIds;
}
int lookUp(const std::map<std::string, int>& map, const std::string& key)
{
const std::map<std::string, int>::const_iterator it = map.find(key);
return (it != map.end()) ? it->second : 0;
}
} // namespace
BufferedBuildingContent::BufferedBuildingContent(const SelectionContext& context,
BuildingId id, QWidget* parent)
: SelectionContent(context, asConstructionSite(context, id), parent)
, m_id(id)
{
// The summary is configuration -- what the building will do -- so it sits with the
// selection control and is shown for a construction site too (REQ-UI-RECIPE-SUMMARY).
m_recipeSummary = new RecipeSummaryRow(context.itemIcons, this);
getConfigurationLayout()->addWidget(m_recipeSummary);
m_inputSection = new SectionBox(tr("Input buffers"), this);
m_inputChips = new ItemChipRow(context.itemIcons, m_inputSection);
m_inputSection->getContentLayout()->addWidget(m_inputChips);
m_production = new ProductionSection(this);
m_outputSection = new SectionBox(tr("Output buffer"), this);
m_outputChips = new ItemChipRow(context.itemIcons, m_outputSection);
m_outputSection->getContentLayout()->addWidget(m_outputChips);
// In the direction the materials flow: what goes in, what is being made of it, what
// has come out (REQ-UI-SINGLE-SELECTION, REQ-UI-PRODUCTION-PROGRESS).
getRuntimeLayout()->addWidget(m_inputSection);
getRuntimeLayout()->addWidget(m_production);
getRuntimeLayout()->addWidget(m_outputSection);
}
void BufferedBuildingContent::refreshConfiguration()
{
const BuildingTarget target = resolveBuildingTarget(getContext(), m_id);
if (!target.isValid())
{
// Gone under the card. SelectionPanel rebuilds on the same refresh; this only
// has to avoid reading it.
return;
}
setBuildingIdentity(target.type, getBuildingTypeName(target.type));
const CycleInfo cycle = getCycleInfo(target);
m_recipeSummary->setSummary(toAmounts(cycle.perCycleInputs),
toAmounts(cycle.perCycleOutputs),
cycle.durationSeconds);
refreshControls(target);
}
void BufferedBuildingContent::refreshRuntime()
{
const BuildingTarget target = resolveBuildingTarget(getContext(), m_id);
if (!target.building)
{
return;
}
setProductionStatusSlot(*target.building);
const CycleInfo cycle = getCycleInfo(target);
const std::vector<ItemChipRow::Entry> inputs =
buildInputEntries(*target.building, cycle);
const std::vector<ItemChipRow::Entry> outputs =
buildOutputEntries(*target.building, cycle);
m_inputChips->setEntries(inputs);
m_outputChips->setEntries(outputs);
m_inputSection->setVisible(!inputs.empty());
m_outputSection->setVisible(!outputs.empty());
m_production->setProduction(cycle.runsProduction, *target.building,
cycle.durationSeconds,
getContext().sim->getCurrentTick());
}
std::vector<ItemChipRow::Entry> BufferedBuildingContent::buildInputEntries(
const Building& building, const CycleInfo& cycle) const
{
std::map<std::string, int> buffered;
for (const std::pair<const ItemType, int>& entry : building.inputBuffer.counts)
{
buffered[entry.first.id] = entry.second;
}
std::vector<ItemChipRow::Entry> entries;
for (const std::string& itemId :
collectItemIds(buffered, cycle.perCycleInputs, cycle.handledInputs))
{
// An auto-recipe building's buffers are sized over every recipe of its type,
// including recipes still locked, so those entries are left out here
// (REQ-UI-SINGLE-SELECTION, REQ-LOCK-UI-RECIPE).
if (!getContext().sim->isItemUnlocked(itemId)) { continue; }
ItemChipRow::Entry chip;
chip.itemId = itemId;
chip.countText = QString::number(lookUp(buffered, itemId));
const int perCycle = lookUp(cycle.perCycleInputs, itemId);
if (perCycle > 0)
{
chip.subLine = tr("/ %1 per cycle").arg(perCycle);
}
else
{
chip.subLine = QString::fromStdString(toDisplayName(itemId));
}
entries.push_back(chip);
}
return entries;
}
std::vector<ItemChipRow::Entry> BufferedBuildingContent::buildOutputEntries(
const Building& building, const CycleInfo& cycle) const
{
// The buffered items plus those still emerging onto the output belts: an emerging
// item still belongs to the output buffer (REQ-MAT-OUTPUT-EMERGE), so leaving it out
// would make it vanish from the panel while it animates.
std::map<std::string, int> buffered;
for (const Item& item : building.outputBuffer.items)
{
buffered[item.type.id]++;
}
for (const std::vector<BeltItemSlot>& lane : building.emergingItems)
{
for (const BeltItemSlot& slot : lane)
{
buffered[slot.item.type.id]++;
}
}
std::vector<ItemChipRow::Entry> entries;
for (const std::string& itemId :
collectItemIds(buffered, cycle.perCycleOutputs, cycle.handledOutputs))
{
if (!getContext().sim->isItemUnlocked(itemId)) { continue; }
ItemChipRow::Entry chip;
chip.itemId = itemId;
// Counted against the buffer's capacity, which is what production stops at
// (REQ-MAT-OUTPUT-BUFFER).
chip.countText = building.outputBuffer.capacity > 0
? tr("%1 / %2").arg(lookUp(buffered, itemId))
.arg(building.outputBuffer.capacity)
: QString::number(lookUp(buffered, itemId));
chip.subLine = QString::fromStdString(toDisplayName(itemId));
entries.push_back(chip);
}
return entries;
}

View File

@@ -0,0 +1,86 @@
#pragma once
#include <map>
#include <string>
#include <vector>
#include "BuildingId.h"
#include "ItemChipRow.h"
#include "SelectionContent.h"
struct Building;
struct BuildingTarget;
class ProductionSection;
class RecipeSummaryRow;
class SectionBox;
// Shared body of the four cards that show one building with buffers -- the Miner and
// Assembler, the Smelter and Reprocessing Plant, the Shipyard, and the Salvage Bay
// (REQ-UI-SELECTION-CONTENT). All four show the same header status, recipe summary,
// buffer contents and production progress; they differ only in what one production cycle
// costs and how long it takes, which is what the subclass supplies.
//
// This is implementation sharing, not a catalog entry: every concrete subclass is one
// row of the content catalog.
class BufferedBuildingContent : public SelectionContent
{
Q_OBJECT
protected:
// What one production cycle of this building consumes, produces, and takes.
struct CycleInfo
{
std::map<std::string, int> perCycleInputs;
std::map<std::string, int> perCycleOutputs;
// Items the card lists whether or not they are currently in the buffers, for a
// building whose recipe is implicit and so has nothing to name while it sits
// between cycles (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING). They carry no
// per-cycle denominator, since no one recipe is in force.
std::vector<std::string> handledInputs;
std::vector<std::string> handledOutputs;
// False when the building produces nothing at all (the Salvage Bay,
// REQ-BLD-SALVAGE-BAY) or has no recipe or schematic selected yet: the
// production section is then not shown (REQ-UI-PRODUCTION-PROGRESS).
bool runsProduction = false;
// 0 only when no recipe describes the cycle at all -- an auto-recipe building
// that has yet to run one (REQ-UI-RECIPE-SUMMARY). The progress line reads
// "idle" whenever no cycle is actually running, whatever this says.
double durationSeconds = 0.0;
};
BufferedBuildingContent(const SelectionContext& context, BuildingId id,
QWidget* parent);
// Called with a construction site's stored configuration too, so the summary of what
// the building will produce is shown before it is built (REQ-BLD-SITE-CONFIG).
virtual CycleInfo getCycleInfo(const BuildingTarget& target) const = 0;
// The subclass's own configuration controls. The identity, the recipe summary, the
// buffers and the production progress are handled here.
virtual void refreshControls(const BuildingTarget& /*target*/) {}
BuildingId getBuildingId() const { return m_id; }
private:
void refreshConfiguration() override;
void refreshRuntime() override;
std::vector<ItemChipRow::Entry> buildInputEntries(const Building& building,
const CycleInfo& cycle) const;
std::vector<ItemChipRow::Entry> buildOutputEntries(const Building& building,
const CycleInfo& cycle) const;
BuildingId m_id;
RecipeSummaryRow* m_recipeSummary;
// Input buffers, production progress, output buffer -- in that order, so the card
// reads the way the materials flow (REQ-UI-SINGLE-SELECTION).
SectionBox* m_inputSection;
ItemChipRow* m_inputChips;
ProductionSection* m_production;
SectionBox* m_outputSection;
ItemChipRow* m_outputChips;
};

View File

@@ -0,0 +1,34 @@
#include "BuildingTarget.h"
#include "FactoryQueries.h"
#include "SelectionContext.h"
#include "Simulation.h"
BuildingTarget resolveBuildingTarget(const SelectionContext& context, BuildingId id)
{
BuildingTarget target;
target.building = findBuilding(context.sim->getFactoryState(), id);
target.site = target.building
? nullptr
: findSite(context.sim->getFactoryState(), id);
if (!target.isValid())
{
return target;
}
target.type = target.building ? target.building->type : target.site->type;
target.recipeId = target.building ? target.building->recipeId : target.site->recipeId;
target.shipLayout = target.building ? target.building->shipLayout : target.site->shipLayout;
target.anchor = target.building ? target.building->anchor : target.site->anchor;
return target;
}
std::optional<BuildingId> asConstructionSite(const SelectionContext& context,
BuildingId id)
{
if (findSite(context.sim->getFactoryState(), id) != nullptr)
{
return id;
}
return std::nullopt;
}

View File

@@ -0,0 +1,45 @@
#pragma once
#include <optional>
#include <string>
#include <QPoint>
#include "BuildingId.h"
#include "BuildingType.h"
#include "ShipLayout.h"
struct Building;
struct ConstructionSite;
struct SelectionContext;
// One selected building id resolved to whichever of the two things it names: an
// operational building or a construction site still queued or under construction. A
// site carries the same configuration as the building it will become
// (REQ-BLD-SITE-CONFIG), so the fields both have are read out here once instead of in
// every content that shows a single building.
struct BuildingTarget
{
const Building* building = nullptr; // null while it is still a site
const ConstructionSite* site = nullptr; // null once it is built
BuildingType type = BuildingType::Miner;
std::string recipeId;
std::optional<ShipLayoutConfig> shipLayout;
QPoint anchor;
// False when the id names neither -- the object went away under the panel (it was
// deconstructed, or its site finished and its id was reused).
bool isValid() const { return building != nullptr || site != nullptr; }
};
// Resolves the id against the current factory state. The returned pointers are only
// valid until the simulation next mutates, so this is called per refresh rather than
// cached.
BuildingTarget resolveBuildingTarget(const SelectionContext& context, BuildingId id);
// The id wrapped as a construction site id when it names one, nullopt when it names an
// operational building. Every content showing a single building hands this to
// SelectionContent so the base can apply the site rule (REQ-UI-SELECTION-CARD).
std::optional<BuildingId> asConstructionSite(const SelectionContext& context,
BuildingId id);

View File

@@ -0,0 +1,76 @@
SET(HDRS
${HDRS}
${CMAKE_CURRENT_SOURCE_DIR}/SelectionContext.h
${CMAKE_CURRENT_SOURCE_DIR}/SelectionContent.h
${CMAKE_CURRENT_SOURCE_DIR}/SelectionContentFactory.h
${CMAKE_CURRENT_SOURCE_DIR}/SelectionNames.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildingTarget.h
${CMAKE_CURRENT_SOURCE_DIR}/DebrisScrap.h
${CMAKE_CURRENT_SOURCE_DIR}/StatRow.h
${CMAKE_CURRENT_SOURCE_DIR}/BarRow.h
${CMAKE_CURRENT_SOURCE_DIR}/SectionBox.h
${CMAKE_CURRENT_SOURCE_DIR}/CountRow.h
${CMAKE_CURRENT_SOURCE_DIR}/StatusPill.h
${CMAKE_CURRENT_SOURCE_DIR}/EmptyNote.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemChip.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemChipRow.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSummaryRow.h
${CMAKE_CURRENT_SOURCE_DIR}/ProductionSection.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionControl.h
${CMAKE_CURRENT_SOURCE_DIR}/ClearBeltControl.h
${CMAKE_CURRENT_SOURCE_DIR}/BufferedBuildingContent.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeProductionContent.h
${CMAKE_CURRENT_SOURCE_DIR}/AutoProductionContent.h
${CMAKE_CURRENT_SOURCE_DIR}/ShipyardContent.h
${CMAKE_CURRENT_SOURCE_DIR}/StorageContent.h
${CMAKE_CURRENT_SOURCE_DIR}/HqContent.h
${CMAKE_CURRENT_SOURCE_DIR}/BeltContent.h
${CMAKE_CURRENT_SOURCE_DIR}/SplitterContent.h
${CMAKE_CURRENT_SOURCE_DIR}/MultiBuildingContent.h
${CMAKE_CURRENT_SOURCE_DIR}/ShipContent.h
${CMAKE_CURRENT_SOURCE_DIR}/StationContent.h
${CMAKE_CURRENT_SOURCE_DIR}/DebrisContent.h
${CMAKE_CURRENT_SOURCE_DIR}/FieldMultiContent.h
PARENT_SCOPE
)
SET(SRCS
${SRCS}
${CMAKE_CURRENT_SOURCE_DIR}/SelectionContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/SelectionContentFactory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/SelectionNames.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BuildingTarget.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DebrisScrap.cpp
${CMAKE_CURRENT_SOURCE_DIR}/StatRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BarRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/SectionBox.cpp
${CMAKE_CURRENT_SOURCE_DIR}/CountRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/StatusPill.cpp
${CMAKE_CURRENT_SOURCE_DIR}/EmptyNote.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemChip.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemChipRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSummaryRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ProductionSection.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionControl.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ClearBeltControl.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BufferedBuildingContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeProductionContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/AutoProductionContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ShipyardContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/StorageContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/HqContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BeltContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/SplitterContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/MultiBuildingContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ShipContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/StationContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DebrisContent.cpp
${CMAKE_CURRENT_SOURCE_DIR}/FieldMultiContent.cpp
PARENT_SCOPE
)
set(UI_INCLUDE_PATH
${UI_INCLUDE_PATH}
${CMAKE_CURRENT_SOURCE_DIR}
PARENT_SCOPE
)

View File

@@ -0,0 +1,54 @@
#include "ClearBeltControl.h"
#include <QPoint>
#include <QPushButton>
#include <QVBoxLayout>
#include "Building.h"
#include "Command.h"
#include "CommandRequestedEvent.h"
#include "EventManager.h"
#include "FactoryQueries.h"
#include "Simulation.h"
ClearBeltControl::ClearBeltControl(const SelectionContext& context,
const std::vector<BuildingId>& ids, QWidget* parent)
: QWidget(parent)
, m_context(context)
, m_ids(ids)
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
QPushButton* button = new QPushButton(tr("Clear stuck items"), this);
layout->addWidget(button);
connect(button, &QPushButton::clicked, this, [this]() { clearSelectedTiles(); });
}
void ClearBeltControl::clearSelectedTiles() const
{
std::vector<QPoint> tiles;
for (BuildingId id : m_ids)
{
const Building* building = findBuilding(m_context.sim->getFactoryState(), id);
if (building && isBeltSubsystemType(building->type))
{
for (const QPoint& cell : building->bodyCells)
{
tiles.push_back(cell);
}
}
}
if (tiles.empty())
{
return;
}
std::shared_ptr<ClearBeltTilesCommand> command =
std::make_shared<ClearBeltTilesCommand>();
command->tiles = std::move(tiles);
EventManager::getInstance()->sendEventImmediately(
std::make_shared<CommandRequestedEvent>(command));
}

View File

@@ -0,0 +1,31 @@
#pragma once
#include <vector>
#include <QWidget>
#include "BuildingId.h"
#include "SelectionContext.h"
// The "Clear stuck items" action of the card's runtime group (REQ-UI-BELT-CLEAR): it
// removes every item from the selected belt, splitter and tunnel tiles, which is how a
// stalled line is resolved.
//
// It acts on the whole selection rather than on one tile, which is why a selection of
// belts and tunnel ends aggregates into a single card instead of a count summary
// (REQ-UI-SELECTION-AGGREGATE), and why the count summary shows the action too when a
// belt is among the selected buildings.
class ClearBeltControl : public QWidget
{
Q_OBJECT
public:
ClearBeltControl(const SelectionContext& context,
const std::vector<BuildingId>& ids, QWidget* parent = nullptr);
private:
void clearSelectedTiles() const;
SelectionContext m_context;
std::vector<BuildingId> m_ids;
};

View File

@@ -0,0 +1,29 @@
#include "CountRow.h"
#include <QHBoxLayout>
#include <QLabel>
CountRow::CountRow(const QPixmap& symbol, const QString& name, int count,
QWidget* parent)
: QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(6);
m_symbolLabel = new QLabel(this);
m_symbolLabel->setPixmap(symbol);
m_symbolLabel->setVisible(!symbol.isNull());
m_nameLabel = new QLabel(name, this);
// The same "x<count>" notation the recipe tooltip and the header's aggregate count
// use (REQ-UI-MULTI-SELECTION).
m_countLabel = new QLabel(tr("x%1").arg(count), this);
m_countLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
layout->addWidget(m_symbolLabel);
layout->addWidget(m_nameLabel);
layout->addStretch(1);
layout->addWidget(m_countLabel);
}

View File

@@ -0,0 +1,25 @@
#pragma once
#include <QPixmap>
#include <QString>
#include <QWidget>
class QLabel;
// One "<symbol> <name> x<count>" line of a count summary. The same part serves the
// building summary and the field summary, which count different things the same way
// (REQ-UI-MULTI-SELECTION, REQ-UI-FIELD-MULTI-SELECTION).
class CountRow : public QWidget
{
Q_OBJECT
public:
// An empty symbol leaves the icon off, for the kinds of object that have none.
CountRow(const QPixmap& symbol, const QString& name, int count,
QWidget* parent = nullptr);
private:
QLabel* m_symbolLabel;
QLabel* m_nameLabel;
QLabel* m_countLabel;
};

View File

@@ -0,0 +1,32 @@
#include "DebrisContent.h"
#include <QVBoxLayout>
#include "DebrisScrap.h"
#include "Simulation.h"
#include "StatRow.h"
DebrisContent::DebrisContent(const SelectionContext& context,
const SelectionRequest& request, QWidget* parent)
: SelectionContent(context, std::nullopt, parent)
, m_debris(request.debris)
{
m_scrapRow = new StatRow(tr("Scrap remaining"), this);
m_scrapRow->setValueEmphasized(true);
getRuntimeLayout()->addWidget(m_scrapRow);
setIdentity(QPixmap(), tr("Debris"));
if (m_debris.size() > 1)
{
setCountSlot(static_cast<int>(m_debris.size()));
}
}
void DebrisContent::refreshRuntime()
{
// The value falls as the debris is collected and as pieces despawn
// (REQ-UI-DEBRIS-CLICK-SELECT), so it is re-summed rather than remembered. With
// several pieces selected it is their sum (REQ-UI-SELECTION-AGGREGATE).
m_scrapRow->setValue(QString::number(
sumDebrisScrap(getContext().sim->getAdmin(), m_debris)));
}

View File

@@ -0,0 +1,31 @@
#pragma once
#include <vector>
#include "entt/entity/entity.hpp"
#include "SelectionContent.h"
#include "SelectionContentFactory.h"
class StatRow;
// The card for selected debris (REQ-UI-DEBRIS-PANEL): the scrap still left in it.
//
// It is the field category's aggregating content (REQ-UI-SELECTION-AGGREGATE): several
// pieces of debris show this same card with the count in the header and their scrap
// summed, because that is the one value the card holds and it adds up.
class DebrisContent : public SelectionContent
{
Q_OBJECT
public:
DebrisContent(const SelectionContext& context, const SelectionRequest& request,
QWidget* parent = nullptr);
protected:
void refreshRuntime() override;
private:
std::vector<entt::entity> m_debris;
StatRow* m_scrapRow;
};

View File

@@ -0,0 +1,18 @@
#include "DebrisScrap.h"
#include <algorithm>
#include "DebrisSystem.h"
int sumDebrisScrap(const EntityAdmin& admin, const std::vector<entt::entity>& debris)
{
int total = 0;
for (const DebrisInfo& info : getAllDebrisInfo(admin))
{
if (std::find(debris.begin(), debris.end(), info.entity) != debris.end())
{
total += info.amount;
}
}
return total;
}

View File

@@ -0,0 +1,13 @@
#pragma once
#include <vector>
#include "entt/entity/entity.hpp"
class EntityAdmin;
// Remaining scrap summed over the given debris, skipping pieces that have already been
// collected or despawned (REQ-RES-DEBRIS-DROP). Shared by the debris card and the field
// count summary, which show the same total in two shapes (REQ-UI-DEBRIS-PANEL,
// REQ-UI-FIELD-MULTI-SELECTION).
int sumDebrisScrap(const EntityAdmin& admin, const std::vector<entt::entity>& debris);

View File

@@ -0,0 +1,19 @@
#include "EmptyNote.h"
#include <QFont>
#include <QPalette>
EmptyNote::EmptyNote(const QString& text, QWidget* parent)
: QLabel(text, parent)
{
setWordWrap(true);
QFont noteFont = font();
noteFont.setItalic(true);
setFont(noteFont);
QPalette notePalette = palette();
notePalette.setColor(QPalette::WindowText,
palette().color(QPalette::Disabled, QPalette::WindowText));
setPalette(notePalette);
}

View File

@@ -0,0 +1,15 @@
#pragma once
#include <QString>
#include <QLabel>
// A dimmed aside explaining why a part of the card is not there yet -- a construction
// site's "no buffers until built" (REQ-UI-SELECTION-CARD). Styled apart from the card's
// values so it reads as an explanation rather than as data.
class EmptyNote : public QLabel
{
Q_OBJECT
public:
explicit EmptyNote(const QString& text, QWidget* parent = nullptr);
};

View File

@@ -0,0 +1,105 @@
#include "FieldMultiContent.h"
#include <map>
#include <string>
#include <QVBoxLayout>
#include "CountRow.h"
#include "DebrisScrap.h"
#include "DisplayName.h"
#include "EntityAdmin.h"
#include "FactionComponent.h"
#include "ShipIdentityComponent.h"
#include "Simulation.h"
#include "StatRow.h"
#include "StationBodyComponent.h"
FieldMultiContent::FieldMultiContent(const SelectionContext& context,
const SelectionRequest& request, QWidget* parent)
: SelectionContent(context, std::nullopt, parent)
, m_debris(request.debris)
, m_scrapRow(nullptr)
{
setIdentity(QPixmap(), tr("Mixed selection"));
setCountSlot(static_cast<int>(request.actors.size() + request.debris.size()));
buildSummary(request.actors);
}
void FieldMultiContent::buildSummary(const std::vector<entt::entity>& actors)
{
EntityAdmin& admin = getContext().sim->getAdmin();
// Grouped by faction, kind and ship schematic, in the order the groups are first
// seen (REQ-UI-FIELD-MULTI-SELECTION).
std::vector<QString> keys;
std::map<QString, int> counts;
std::map<QString, QString> labels;
for (entt::entity actor : actors)
{
if (!admin.isValid(actor)) { continue; }
const bool isEnemy = admin.hasAll<FactionComponent>(actor)
&& admin.get<FactionComponent>(actor).isEnemy;
QString key;
QString label;
if (admin.hasAll<ShipIdentityComponent>(actor))
{
const std::string& id = admin.get<ShipIdentityComponent>(actor).schematicId;
const QString name = QString::fromStdString(toDisplayName(id));
key = (isEnemy ? QStringLiteral("ship:enemy:")
: QStringLiteral("ship:player:"))
+ QString::fromStdString(id);
label = isEnemy ? tr("Enemy %1").arg(name) : name;
}
else if (admin.hasAll<StationBodyComponent>(actor))
{
key = isEnemy ? QStringLiteral("station:enemy")
: QStringLiteral("station:player");
label = isEnemy ? tr("Enemy Defence Station") : tr("Player Defence Station");
}
else
{
continue;
}
if (counts.find(key) == counts.end())
{
keys.push_back(key);
labels[key] = label;
}
counts[key] += 1;
}
for (const QString& key : keys)
{
getRuntimeLayout()->addWidget(
new CountRow(QPixmap(), labels[key], counts[key], this));
}
if (!m_debris.empty())
{
getRuntimeLayout()->addWidget(new CountRow(
QPixmap(), tr("Debris"), static_cast<int>(m_debris.size()), this));
// Indented under the debris row, so the total reads as belonging to it
// (REQ-UI-DEBRIS-PANEL).
m_scrapRow = new StatRow(tr("holding"), this);
m_scrapRow->setIndented(true);
m_scrapRow->setValueEmphasized(true);
getRuntimeLayout()->addWidget(m_scrapRow);
}
}
void FieldMultiContent::refreshRuntime()
{
// The counts are fixed for a given selection -- an actor leaving it re-publishes the
// selection and rebuilds this card -- but the scrap falls as the debris is collected.
if (m_scrapRow)
{
m_scrapRow->setValue(tr("%1 scrap")
.arg(sumDebrisScrap(getContext().sim->getAdmin(), m_debris)));
}
}

View File

@@ -0,0 +1,33 @@
#pragma once
#include <vector>
#include "entt/entity/entity.hpp"
#include "SelectionContent.h"
#include "SelectionContentFactory.h"
class StatRow;
// The count summary for a field selection holding more than one object that does not
// aggregate (REQ-UI-FIELD-MULTI-SELECTION): several actors, or actors together with
// debris. A count per type, and the debris' summed scrap when debris is part of it.
class FieldMultiContent : public SelectionContent
{
Q_OBJECT
public:
FieldMultiContent(const SelectionContext& context, const SelectionRequest& request,
QWidget* parent = nullptr);
protected:
void refreshRuntime() override;
private:
void buildSummary(const std::vector<entt::entity>& actors);
std::vector<entt::entity> m_debris;
// Null unless debris is part of the selection; the only value here that changes
// while the selection stands.
StatRow* m_scrapRow;
};

View File

@@ -0,0 +1,61 @@
#include "HqContent.h"
#include <vector>
#include <QVBoxLayout>
#include "BarRow.h"
#include "EntityAdmin.h"
#include "HealthComponent.h"
#include "HqProxyComponent.h"
#include "IconCaption.h"
#include "ItemChipRow.h"
#include "SectionBox.h"
#include "SelectionNames.h"
#include "Simulation.h"
HqContent::HqContent(const SelectionContext& context, const SelectionRequest& request,
QWidget* parent)
// The HQ is placed before the game starts and can never be deconstructed
// (REQ-BLD-DECONSTRUCT), so it is never a construction site.
: SelectionContent(context, std::nullopt, parent)
{
m_hpBar = new BarRow(tr("HP"), this);
m_stockSection = new SectionBox(tr("Building blocks"), this);
m_stockChips = new ItemChipRow(context.itemIcons, m_stockSection);
m_stockSection->getContentLayout()->addWidget(m_stockChips);
// HP first, as on every card that has it (REQ-UI-SELECTION-CARD, REQ-UI-HQ-PANEL).
getRuntimeLayout()->addWidget(m_hpBar);
getRuntimeLayout()->addWidget(m_stockSection);
setBuildingIdentity(BuildingType::Hq, getBuildingTypeName(BuildingType::Hq));
}
void HqContent::refreshRuntime()
{
// Not a buffer: blocks delivered by belt go straight into the global stock
// (REQ-HQ-BELT-INPUT). Showing it here is what tells the player to route them here
// (REQ-UI-HQ-PANEL).
ItemChipRow::Entry stock;
stock.itemId = kBlockItemId;
stock.countText = QString::number(getContext().sim->getBuildingBlocksStock());
stock.subLine = tr("in stock");
m_stockChips->setEntries(std::vector<ItemChipRow::Entry>{ stock });
// The HQ's health lives on its proxy entity, not on the building
// (REQ-HQ-STATS, REQ-UI-HP-BARS).
EntityAdmin& admin = getContext().sim->getAdmin();
admin.forEach<HqProxyComponent, HealthComponent>(
[this](entt::entity /*entity*/, const HqProxyComponent& /*proxy*/,
const HealthComponent& health)
{
const double fraction = (health.maxHp > 0.0f)
? static_cast<double>(health.hp) / health.maxHp
: 0.0;
m_hpBar->setValue(fraction, tr("%1 / %2")
.arg(static_cast<int>(health.hp + 0.5f))
.arg(static_cast<int>(health.maxHp + 0.5f)));
});
}

View File

@@ -0,0 +1,32 @@
#pragma once
#include "SelectionContent.h"
#include "SelectionContentFactory.h"
class BarRow;
class ItemChipRow;
class SectionBox;
// The card for the HQ (REQ-UI-HQ-PANEL): the global building blocks stock and the HQ's
// HP. It has no configuration group and no status indicator.
//
// The stock is not a buffer: blocks delivered by belt go straight into the global stock
// (REQ-HQ-BELT-INPUT), which is exactly why the card shows it -- it is what tells the
// player to route blocks here. The HP comes from the HQ's proxy entity rather than from
// the building, since that is where its health lives.
class HqContent : public SelectionContent
{
Q_OBJECT
public:
HqContent(const SelectionContext& context, const SelectionRequest& request,
QWidget* parent = nullptr);
protected:
void refreshRuntime() override;
private:
SectionBox* m_stockSection;
ItemChipRow* m_stockChips;
BarRow* m_hpBar;
};

View File

@@ -0,0 +1,72 @@
#include "ItemChip.h"
#include <QFont>
#include <QHBoxLayout>
#include <QLabel>
#include <QPalette>
#include <QVBoxLayout>
namespace
{
// Point-size rise of the count and drop of the sub-line, relative to the card's text.
const int kCountSizeRisePt = 2;
const int kSubLineSizeDropPt = 1;
} // namespace
ItemChip::ItemChip(const QPixmap& icon, QWidget* parent)
: QWidget(parent)
{
// Its own boxed chrome, drawn with palette colors like the rest of the panel's
// furniture rather than from visuals.toml, which is for world rendering.
setAttribute(Qt::WA_StyledBackground, true);
setStyleSheet(QStringLiteral(
"ItemChip { border: 1px solid palette(mid); border-radius: 3px; }"));
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(4, 3, 4, 3);
layout->setSpacing(6);
m_iconLabel = new QLabel(this);
m_iconLabel->setPixmap(icon);
m_iconLabel->setVisible(!icon.isNull());
QWidget* text = new QWidget(this);
QVBoxLayout* textLayout = new QVBoxLayout(text);
textLayout->setContentsMargins(0, 0, 0, 0);
textLayout->setSpacing(0);
m_countLabel = new QLabel(text);
QFont countFont = m_countLabel->font();
countFont.setPointSize(countFont.pointSize() + kCountSizeRisePt);
m_countLabel->setFont(countFont);
m_subLineLabel = new QLabel(text);
QFont subLineFont = m_subLineLabel->font();
subLineFont.setPointSize(qMax(1, subLineFont.pointSize() - kSubLineSizeDropPt));
m_subLineLabel->setFont(subLineFont);
QPalette subLinePalette = m_subLineLabel->palette();
subLinePalette.setColor(QPalette::WindowText,
palette().color(QPalette::Disabled, QPalette::WindowText));
m_subLineLabel->setPalette(subLinePalette);
m_subLineLabel->hide();
textLayout->addWidget(m_countLabel);
textLayout->addWidget(m_subLineLabel);
layout->addWidget(m_iconLabel);
layout->addWidget(text);
}
void ItemChip::setCount(const QString& count)
{
m_countLabel->setText(count);
}
void ItemChip::setSubLine(const QString& subLine)
{
m_subLineLabel->setText(subLine);
m_subLineLabel->setVisible(!subLine.isEmpty());
}

View File

@@ -0,0 +1,28 @@
#pragma once
#include <QPixmap>
#include <QString>
#include <QWidget>
class QLabel;
// One buffered item: its icon, its count in a larger type, and a sub-line beneath the
// count (REQ-UI-SINGLE-SELECTION). Boxed so a row of them reads as separate quantities
// rather than as a run of text.
class ItemChip : public QWidget
{
Q_OBJECT
public:
// An empty icon leaves the icon off and the chip laid out around the text alone.
ItemChip(const QPixmap& icon, QWidget* parent = nullptr);
void setCount(const QString& count);
// Left empty for an item with nothing to say beneath its count.
void setSubLine(const QString& subLine);
private:
QLabel* m_iconLabel;
QLabel* m_countLabel;
QLabel* m_subLineLabel;
};

View File

@@ -0,0 +1,83 @@
#include "ItemChipRow.h"
#include <QGridLayout>
#include "ItemChip.h"
#include "ItemIconCache.h"
namespace
{
// Size the item icon is drawn at inside a chip, in device-independent pixels.
const int kChipIconSizePx = 18;
// Chips per row. Two fit the panel's capped width side by side; a third would force the
// counts to shrink.
const int kChipsPerRow = 2;
} // namespace
ItemChipRow::ItemChipRow(ItemIconCache* itemIcons, QWidget* parent)
: QWidget(parent)
, m_itemIcons(itemIcons)
{
m_layout = new QGridLayout(this);
m_layout->setContentsMargins(0, 0, 0, 0);
m_layout->setSpacing(4);
}
void ItemChipRow::setEntries(const std::vector<Entry>& entries)
{
std::vector<std::string> itemIds;
itemIds.reserve(entries.size());
for (const Entry& entry : entries)
{
itemIds.push_back(entry.itemId);
}
// Only the set of items changing is a structural change; the counts change every
// tick and must not cost a widget rebuild.
if (itemIds != m_itemIds)
{
m_itemIds = std::move(itemIds);
rebuildChips(entries);
}
for (std::size_t index = 0; index < entries.size(); ++index)
{
m_chips[index]->setCount(entries[index].countText);
m_chips[index]->setSubLine(entries[index].subLine);
}
setVisible(!entries.empty());
}
void ItemChipRow::rebuildChips(const std::vector<Entry>& entries)
{
for (ItemChip* chip : m_chips)
{
m_layout->removeWidget(chip);
chip->deleteLater();
}
m_chips.clear();
for (std::size_t index = 0; index < entries.size(); ++index)
{
const std::string& itemId = entries[index].itemId;
// A missing icon file is not an error (REQ-UI-ITEM-ICON): the chip is then laid
// out around its count alone.
const QPixmap icon = m_itemIcons->hasIcon(itemId)
? m_itemIcons->getPixmap(itemId, kChipIconSizePx)
: QPixmap();
ItemChip* chip = new ItemChip(icon, this);
m_layout->addWidget(chip, static_cast<int>(index) / kChipsPerRow,
static_cast<int>(index) % kChipsPerRow);
// Shown right away, because the panel measures itself as soon as this returns. A
// widget created under an already-visible parent starts hidden, and a layout
// treats a hidden item as empty, so an unshown chip would add nothing to the
// size hint and the panel would be fitted to a buffer section that looks empty.
chip->show();
m_chips.push_back(chip);
}
}

View File

@@ -0,0 +1,44 @@
#pragma once
#include <string>
#include <vector>
#include <QString>
#include <QWidget>
class ItemChip;
class ItemIconCache;
class QGridLayout;
// The buffered items of one building, each as a chip carrying the item's icon, its
// current count and a sub-line (REQ-UI-SINGLE-SELECTION): the per-cycle amount for an
// input, the item's name for an output.
//
// The chips are rebuilt only when the set of items changes, not when their counts do, so
// a refresh at tick rate updates numbers instead of churning widgets.
class ItemChipRow : public QWidget
{
Q_OBJECT
public:
struct Entry
{
std::string itemId;
QString countText;
QString subLine;
};
// itemIcons is the window-wide per-item icon cache (REQ-UI-ITEM-ICON); an item with
// no icon file simply shows no icon, which is not an error. Not owned.
explicit ItemChipRow(ItemIconCache* itemIcons, QWidget* parent = nullptr);
void setEntries(const std::vector<Entry>& entries);
private:
void rebuildChips(const std::vector<Entry>& entries);
ItemIconCache* m_itemIcons;
QGridLayout* m_layout;
std::vector<std::string> m_itemIds; // what the chips currently stand for
std::vector<ItemChip*> m_chips;
};

View File

@@ -0,0 +1,99 @@
#include "MultiBuildingContent.h"
#include <map>
#include <QVBoxLayout>
#include "Building.h"
#include "BuildingIconCache.h"
#include "ClearBeltControl.h"
#include "CountRow.h"
#include "FactoryQueries.h"
#include "GameConfig.h"
#include "SelectionNames.h"
#include "Simulation.h"
#include "StatRow.h"
namespace
{
// Size the type symbol is drawn at on a count row, matching the card header's chip.
const int kCountSymbolSizePx = 20;
} // namespace
MultiBuildingContent::MultiBuildingContent(const SelectionContext& context,
const SelectionRequest& request,
QWidget* parent)
: SelectionContent(context, std::nullopt, parent)
, m_ids(request.buildings)
{
// The header names the size of the selection instead of an object
// (REQ-UI-MULTI-SELECTION).
setIdentity(QPixmap(), tr("%1 buildings").arg(static_cast<int>(m_ids.size())));
buildSummary();
// A selection holding any belt-subsystem tile can still be cleared as a whole
// (REQ-UI-BELT-CLEAR), even though the mixture is what kept it from aggregating.
bool hasBeltTile = false;
for (BuildingId id : m_ids)
{
const Building* building = findBuilding(context.sim->getFactoryState(), id);
if (building && isBeltSubsystemType(building->type))
{
hasBeltTile = true;
break;
}
}
if (hasBeltTile)
{
getRuntimeLayout()->addWidget(new ClearBeltControl(context, m_ids, this));
}
}
void MultiBuildingContent::buildSummary()
{
std::map<BuildingType, int> counts;
for (BuildingId id : m_ids)
{
const Building* building =
findBuilding(getContext().sim->getFactoryState(), id);
if (building)
{
counts[building->type]++;
continue;
}
const ConstructionSite* site =
findSite(getContext().sim->getFactoryState(), id);
if (site)
{
counts[site->type]++;
}
}
int totalCost = 0;
for (const std::pair<const BuildingType, int>& entry : counts)
{
getRuntimeLayout()->addWidget(new CountRow(
getContext().buildingIcons->getChip(buildingTypeId(entry.first),
kCountSymbolSizePx),
getBuildingTypeName(entry.first), entry.second, this));
// Only player-placeable buildings count toward the total; the HQ and defence
// stations are excluded (REQ-UI-MULTI-SELECTION). A construction site counts at
// its type's full placement cost regardless of progress.
const BuildingDef* def =
getContext().config->buildings.findBuildingDef(entry.first);
if (def && def->playerPlaceable)
{
totalCost += def->cost * entry.second;
}
}
StatRow* totalRow = new StatRow(tr("Total cost"), this);
totalRow->setValue(QString::number(totalCost));
totalRow->setValueEmphasized(true);
getRuntimeLayout()->addWidget(totalRow);
}

Some files were not shown because too many files have changed in this diff Show More