diff --git a/.gitignore b/.gitignore
index d0544dc3..70961d6c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,3 +19,7 @@
# Local Maven repository (publishAllPublicationsToLocalRepository)
/mcmodsrepo/
/.eclipse/
+
+# Python asset-generator caches
+__pycache__/
+*.py[cod]
diff --git a/docs/gui-screens.md b/docs/gui-screens.md
index 3cc78838..f1b83142 100644
--- a/docs/gui-screens.md
+++ b/docs/gui-screens.md
@@ -1,5 +1,142 @@
# GUI screens
+## Working-area control and upgrades drawer
+
+` ` is a flat, client-local display
+toggle. Place it beside `` inside ``.
+The selected processor implements `machine.feature.WorkingArea.Provider` and
+returns its base area from `baseWorkingArea()`: inclusive block offsets `(minRight, minUp, minForward,
+maxRight, maxUp, maxForward)` relative to the controller's horizontal facing.
+For example, `new WorkingArea(-4, 0, 1, 4, 0, 9)` describes a 9×9 crop layer in
+front of the controller. Offsets are bounded to ±128. The server samples the
+world bounds; the button never changes processing or another player's view.
+Returning null clears that processor's enabled outline. The snapshot retains its
+machine and resolved processor identity, so other processors' outlines are unaffected.
+When an area becomes available again, the player can enable it again.
+
+Enabled outlines remain visible after closing the GUI. They clear on machine
+removal/unload, dimension change or disconnect. Each processor has an independent toggle, including multiple processors on one
+machine. At most 32 processor outlines are shown,
+within 128 blocks of the camera. An open screen refreshes its displayed bounds;
+this first API does not subscribe to range changes after the screen closes.
+The machine's `VisualizerStyle.Provider` supplies the outline and enabled-button
+color. XML machines configure it with ` `; work particles use a separate tracking-client feature
+and remain live without an open GUI. See [work and range visualizers](xml-machines.md#work-and-range-visualizers).
+
+`` is a registered, collapsible right-side drawer. It contains
+ordinary inventory elements and uses normal native slot synchronization, saved
+machine storage, shift-click validation and server-side drawer exclusion:
+
+```xml
+
+
+
+
+
+
+```
+
+Declare matching machine storage, for example
+` `
+inside ``. `automation="false"` removes the resource-group selector and
+side-configuration entry while retaining the named inventory and saved contents.
+`upgrade-slot` accepts one item from the required tag by default. Set `max-stack-size`
+(1-64) to opt into a larger stack, still bounded by storage and the item stack limit.
+Generated gearbox and capacitor sockets explicitly use eight; range sockets use one. Ordinary items and
+items outside that tag are refused. Keep its backing storage manual to prevent
+automation bypassing the menu's admission policy. Removing an item from the tag
+does not destroy existing contents or prevent extraction. MMDLib's gearbox item
+has a shared processor effect; mods may supply other upgrade effects. An empty
+tag is useful while those effects are not built.
+Only one upgrades drawer is allowed per screen.
+
+For two component sockets above a 3×3 grid, use ``. Inside a
+machine XML screen, its slots are generated from the machine's ``
+declaration and backing storage:
+
+```xml
+
+
+
+```
+
+Machines extending `mmdlib:base_powered_machine` inherit upgrade support and a
+components-only drawer automatically; no per-machine declaration is needed.
+Other machine bases can enable support with ` `. MMDLib
+allocates a manual gearbox socket when a processor exists and a manual
+capacitor socket when energy storage exists. Their independent inventories are
+`mmdlib_gearbox` and `mmdlib_capacitor`, each with one slot (index 0, limit 8).
+They use shared icons, tooltips and item tags and never expose automation.
+A machine with just one capability gets one centered component socket.
+Override `` to supply a drawer containing extra slots.
+An authored upgrade layout also suppresses the inherited default drawer, so
+existing custom layouts do not bind the same component slots twice. Generation
+examines the composed screen, including inherited layouts. Slots placed by upgrade
+layouts are omitted from the generated processing/resource body; other slots in
+the same inventory retain their local indexes and remain visible. An empty
+` ` leaves the sockets in the generated main body.
+
+The screen's `storage` names only the machine-owned extra upgrade inventory:
+up to nine manual slots displayed in three columns below the components. Declare
+its count and `item-tag` on storage. For range upgrades, ` ` binds the entire extra inventory without listing
+individual addresses. Omit the screen `storage` attribute for components only.
+Machines without either capability can still display their own extra slots.
+
+Generated component IDs are `gearbox` and `capacitor`; extra IDs are
+`_`. An explicit `id` on `` prefixes all
+of them with `_`. Composition uses ordinary boxes and scoped inventories,
+so component and extra slots retain their own filters and storage identities.
+The two-component/nine-extra layout remains 58×84 pixels, with an 8-pixel gap.
+
+Explicit `gearbox-slot` / `capacitor-slot` bindings remain supported for existing
+machines. `` is an empty, machine-aware shorthand that expands into
+ordinary boxes and inventories; it has no separate element class or fixed eleven-slot
+variant. For a custom or standalone screen, compose ``, ``,
+`` and `` directly. New machines should let MMDLib own
+component storage and declare only their extras.
+
+The drawer is first on the right, above side configuration and redstone, and
+uses `mmdlib:icon_upgrades` for its tab. Mods can replace the socket `icon`
+sprites normally or compose other inventories inside ``.
+Upgrade slots are neutral grey and opt out of resource-group highlights.
+Stored processors can read `machine.inventoryContents("upgrades")` to derive
+effects from the named inventory in local slot order. This server-side snapshot
+contains detached item copies; it does not expose a mutable inventory or depend
+on GUI classes. Unknown inventory names are rejected. Count occupied eligible
+slots when each installed item should contribute once, regardless of stack size.
+For shared range effects, declare `range-slots` in machine XML and implement
+`WorkingArea.Provider.baseWorkingArea()`. Its default `workingArea()` expands
+the base using the host's installed range count (supplied by `StoredProcessor`).
+The area button samples these bounds through normal menu synchronization;
+its client behavior refreshes an enabled outline as snapshots arrive, including
+while processing is paused. The consuming mod defines its base area; MMDLib
+supplies range growth and block traversal. See [shared upgrades](xml-machines.md#shared-range-upgrades-and-working-areas).
+Upgrades are permanent. MMDLib supplies range, gearbox and capacitor effects;
+mods can add other upgrade items and policies.
+
+The drawer's open state is per menu; closing it or opening another server-owned
+drawer on the right makes its slots inactive. Drawer preference restoration and
+action acknowledgment use the shared UI lifecycle.
+
+All built-in drawers use `SideDrawerLayout.topBody` for body placement:
+upgrades, side configuration, redstone, statistics, information, equipment and
+recipes. `Drawer.contentBounds` is the client convenience entry point; the
+equipment and recipe helpers delegate to the same common-side geometry. Their
+tab positions are independent: moving a tab down never moves its content body
+down. A body includes its active tab's height in the shared rail, subject to the
+viewport limit. Panel/screen height limits and the recipe drawer's narrow-screen
+fallback are explicit policies of that shared geometry; content size and paging
+remain feature-owned.
+
+Upgrades places native slot children through an element layout contribution
+using those same body bounds. Its renderer reads the drawer's presentation,
+and its input/exclusion regions include the shared rail. New drawers should use
+`contentBounds` or `SideDrawerLayout.topBody`, rather than computing body X/Y.
+Layout code must use `allocatedTabBounds()` instead of calling a subclass's
+`tabBounds()` override, which may itself trigger layout.
+
Entity previews can share `api.entity.EntityPreviewCache`. It caches immutable
`EntitySnapshot` values, including failed decodes, with a bounded least-recently-used
capacity. A changed level clears the cache. The default loader creates detached
@@ -561,7 +698,33 @@ checks (including shared slot rules when implementing `SlotElement`).
`InventoryElement` contains `ItemSlotElement` and `GhostSlotElement` children. Its `storage`
name selects an independent handler from `ScreenHost.screenInventories()`; child indexes are
-local to that handler. For example, both inventories below have their own slot zero:
+local to that handler. XML machine screens can omit children to display all slots
+from the named item storage, with the count resolved after template composition:
+
+```xml
+
+
+
+```
+
+These generate ordinary item slots with local indexes starting at zero and IDs
+`_` (or `_` when the inventory has no ID).
+`slot-icon` and `slot-tooltip` apply to every generated slot. Storage owns item
+filters, limits and input/output roles; screen generation does not change them.
+Standalone screens without machine storage metadata can provide `count="4"`.
+Counts must be 1–4096; combining `count` with explicit slot children is an error.
+Auto-sized machine inventories reject unknown or empty item storage.
+
+An inventory's optional integer `value` binding identifies the selected local
+storage index. The shared renderer outlines that slot in `selection-color`
+(default green); missing, negative or out-of-range values show no outline.
+The value uses the normal synchronized getter/provider mechanism. This supports
+next-input indicators without machine-specific slot types or client renderers.
+
+Explicit children remain available for mixed item/ghost slots or per-slot
+appearance. For example, both inventories below have their own slot zero:
```xml
@@ -2122,7 +2285,7 @@ reservations. Its client renderer reuses the glass gauge drawing code and never
| `spacer` | Fills leftover room in a box | |
| `group` | Recessed grouping panel | `label`, `tint`, `padding` |
| `coloured-group` | Outline around exactly one child, without added padding | `color` |
-| `slot` | Item slot from the menu | `index`, `size` (`normal`/`large`), `kind` (`normal`/`upgrade`/`ghost`; `upgrade` holds one item), `tint`, `icon` |
+| `slot` | Item slot from the menu | `index`, `size` (`normal`/`large`), `kind` (`normal`/`upgrade`/`ghost`; `upgrade` respects storage limits up to eight items), `tint`, `icon` |
| `gauge` | General glass graduated display ([gauge textures](gauge-textures.md)) | `orientation`, `length` (size or `fill`), `color` (solid fill) or a fluid value; `tank` selects the `fluid-tank` component |
| `fluid-tank` | Complete tank component with synchronized contents, tooltip and container transfers | `tank` (storage index), `orientation`, `length`; no `value`, `max` or `interaction` |
| `energy-gauge` | Energy component with synchronized contents and an FE tooltip | Defaults: vertical, `length="54"`, `color="#E64B38"`; style and tooltip can be overridden; no `value` or `max` |
@@ -2349,14 +2512,10 @@ authorization and correction. These hooks introduce no wire-format changes.
swap part of the screen in place. This replaces the earlier Mekanism-style detached windows,
following feedback from players of games with complex interfaces. Because such buttons can be
unclear, every button needs a tooltip that says what it does.
-- **Upgrades (AE2 / Industrial Foregoing style, not Mekanism's).** Upgrades stay in an
- always-visible `` column with a small, fixed number of slots; they never move into
- a view. Upgrades are **tiered, not stacked**: an upgrade slot holds exactly one item, and a
- stronger effect comes from a higher-tier upgrade item, not from a larger stack.
-
-- **Upgrade meaning belongs to the mod.** MMDLib supplies upgrade slots (one item each) and
- their layout, and defines no upgrade items, tiers, or effects. The mod's block entity decides
- what an upgrade item is and what it does.
+- **Upgrades.** The shared `` contains storage-bounded upgrade slots.
+ Use a limit of one for individual modules, or eight for a gearbox socket.
+ MMDLib supplies the permanent gearbox item and shared processor clock; each
+ gearbox adds 12.5% speed and FE usage rate, up to +100%. Mods can add other effects.
- **JEI recipe click areas** (`jei-recipes`) are wanted, as described under JEI.
- **Information pop-outs** are wanted (PneumaticCraft style), in three kinds: `info`
(explains the screen), and `warning` and `error` (reported live by the block entity). Their
@@ -2626,6 +2785,39 @@ Automation and redstone drawer protocols are version 17 with bounded unavailable
Inline controls synchronize a separate `mmdlib:side_unavailable` field. Existing machines default
to all faces available and need no policy declaration.
+## Cycle buttons
+
+`` is a shared, slot-sized (18×18) icon button for processor modes.
+It uses the standard button renderer, click authorization and snapshot transport;
+consumer mods need no custom screen element or client registration.
+
+```xml
+
+
+
+
+```
+
+Declare the integer processor variable with `.synced()`. Each mode provides its
+stored value, GUI sprite, translated label, optional translated help, and a declared
+processor action that selects that mode. `label-fallback` and `tooltip-fallback`
+are supported. The button tooltip follows the selected mode's label and help.
+Keep 16×16 sprites padded for the vanilla button bevel; icons are drawn at native size.
+
+A left click reads the current server value, chooses the next XML entry, and invokes
+its action on the variable's processor. The last entry wraps to the first. Values
+need not be contiguous or sorted; XML order defines the cycle. Actions retain their
+availability checks and own any domain side effects (for example, resetting a seed
+cursor). The control never writes arbitrary processor state. Right clicks do nothing.
+An unrecognized saved value cycles to the first entry.
+
+There must be 2–256 entries with unique integer values. Loading validates that the
+variable is client-visible, its default matches an entry, and every action exists.
+The button owns its state and clicks, so `value`, `max`, click callbacks,
+`interaction`, and `jei-recipes` are rejected.
+
## Processor-bound buttons
Ordinary `` elements accept `processor="courier"` to route their declared
diff --git a/docs/xml-machines.md b/docs/xml-machines.md
index e146ce25..9ef25f51 100644
--- a/docs/xml-machines.md
+++ b/docs/xml-machines.md
@@ -61,6 +61,140 @@ table in a low-priority resource pack. Authored resources can override these
defaults. Crafting recipes remain ordinary files under `data//recipe/`.
The companion's SimpleCrusher is in the companion mod's own creative tab.
+## Shared gearbox upgrades
+
+`mmdlib:base_powered_machine` enables shared upgrades and supplies their drawer.
+Derived machines automatically receive a capacitor socket and, when they declare
+a processor, a gearbox socket. Their machine XML needs no `` or screen
+declaration unless adding machine-specific extra slots or replacing the layout.
+
+MMDLib owns `mmdlib:gearbox_upgrade`, a permanent item with a maximum stack of
+eight. Each adds 12.5% processor speed and FE consumption **per game tick**:
+one gives 1.125×, four give 1.5×, and eight give 2×. The clock schedules extra
+ordinary work ticks, so normal energy checks still apply and total FE per
+recipe or action does not increase. Energy-producing processors likewise run
+more work ticks; external automation and transfer rates are not accelerated.
+
+Enable capability-based component storage with ` `. MMDLib adds a gearbox socket for a processor and a capacitor socket for energy storage. The inventories `mmdlib_gearbox` and `mmdlib_capacitor` each have one manual, non-automated slot of capacity eight. ` ` displays just those sockets; its optional `storage` attribute adds a machine-owned extra grid.
+
+Existing machines may still bind a manual socket by its stable storage slot ID:
+
+```xml
+
+```
+
+For ` `,
+this changes only `upgrades/4` to an eight-item limit. The socket admits
+`GearboxUpgradeItem` instances and affects **every processor** on the machine,
+including custom `StoredProcessor` implementations and recipe processors.
+Missing slots, non-manual slots and automation-exposed sockets are rejected.
+Use `item-tag="mmdlib:gearbox_upgrades"` on the matching screen `upgrade-slot`.
+Other mods can subclass the shared item and add it to their socket's admission tag.
+Keep any such slot's `item-tag` storage filter consistent with its screen tag.
+
+Java-defined hosts can call `features.gearboxes(() -> installedCount)` before
+binding visual variables. The shared clock clamps counts to 0–8, saves each
+processor's fractional tick, and retains it across pauses, item changes and reloads.
+Disabled hosts do no work. Unpowered or blocked processors still obey their
+normal gates, and paused processors do not accumulate bonus work.
+Custom processors with per-game-tick aggregation can override
+`Processor.tick(FeatureHost, int steps)`; the default invokes their ordinary tick
+once or twice. Non-processor features continue to tick once per game tick.
+
+## Shared capacitor upgrades
+
+`mmdlib:capacitor_upgrade` stacks to eight and never wears out. Each installed
+capacitor adds 12.5% to the machine's **base** energy capacity, input rate and
+output rate, reaching 2× at eight. Values round down to whole FE; a zero rate
+stays zero. The calculation never compounds and saturates at the buffer's long
+integer limit rather than overflowing. Processor energy costs are unaffected.
+
+Bind the second socket independently or alongside the gearbox:
+
+```xml
+
+```
+
+The capacitor socket must be a different manual slot without automation, and
+the machine must declare energy storage. Its capacity becomes eight and it
+admits `CapacitorUpgradeItem` instances. Use `item-tag="mmdlib:capacitor_upgrades"`
+on its screen slot. Limits update immediately on inventory changes, even while
+paused. Installing capacitors creates no energy; removing them clamps stored
+energy to the smaller capacity. Item storage loads before energy so a fresh
+machine preserves saved energy above its base capacity.
+
+Java-defined machines can use `CapacitorUpgrades(buffer, baseCapacity,
+baseInput, baseOutput, installedCount)` and subscribe `refresh` to their socket's
+change signal. Refresh after loading items and before loading energy. The shared
+`MachineInventoryLifecycle` follows that load order.
+
+## Shared range upgrades and working areas
+
+`mmdlib:range_upgrade` is permanent. Each occupied range socket adds **one to
+the horizontal radius**, up to nine sockets. Socket capacity is one, even though
+the items stack normally in a player's inventory. Existing component sockets
+remain independent. Declare nine extra slots with `role="manual"`, `limit="1"`, `automation="false"`, and `item-tag="mmdlib:range_upgrades"`. Bind the entire group in XML:
+
+```xml
+
+```
+
+Component sockets are inferred from capabilities. `range-storage` and explicit `range-slots` are mutually exclusive. Range sockets must be
+distinct manual slots with automation disabled, must not overlap the gearbox or
+capacitor, and are forced to a one-item limit. Use `mmdlib:range_upgrades` as the
+screen admission tag, or a mod tag that includes it. Each `RangeUpgradeItem`
+subclass in a configured socket counts once, regardless of stack size.
+
+Any area-providing processor can use the effect. Implement
+`WorkingArea.Provider.baseWorkingArea()` with its unmodified local offsets.
+The default `workingArea()` applies the shared range policy. `StoredProcessor`
+automatically supplies `rangeUpgrades()` from its `ProcessorMachine`; other
+providers can override `rangeUpgrades()` to return their host's count. Java hosts
+can implement `ProcessorMachine.rangeUpgrades()` using `RangeUpgrades.count` over
+their selected sockets. There is no farming-specific item or coordinate policy.
+
+Expansion adds two blocks to width and depth per upgrade, leaving height alone.
+On an axis entirely to one side of the machine, it keeps the near edge fixed and
+grows outward; an axis spanning zero grows equally in both directions. Growth
+stops at WorkingArea's existing ±128 local-coordinate bounds. For example,
+`(-1, 0, -3)` through `(1, 0, -1)` grows from a rear 3×3 field to 21×21 with nine.
+
+`WorkingArea` supplies these coordinate helpers:
+
+- `width()`, `depth()`, `height()` and `size()` use inclusive block dimensions.
+- `blockAt(origin, facing, index)` returns an immutable world position.
+- `blocks(origin, facing)` lazily enumerates positions without accessing a world
+ or loading chunks. Retaining returned positions is safe.
+- `row(index)` gives the row within a layer, for row-based processing modes.
+- `bounds(origin, facing)` supplies the enclosing AABB for displays and future
+ world/entity queries.
+
+Traversal goes left to right, row by row, bottom layer first. Rear areas begin
+at their near row and move backward; other areas begin at `minForward`.
+Agri-Brain now uses this same indexing for scanning, planting rows and work
+particles. Callers remain responsible for loaded chunks, world limits and
+permissions before acting. Entity enumeration is not implemented yet.
+
+### Migrating development upgrade inventories
+
+`legacy-layout="upgrades"` is an opt-in migration for development saves made with
+this work's earlier combined upgrade inventory. It is not a migration selected by
+MMDLib release version, and must not be enabled merely because a mod used eleven
+slots. The source must be the named `upgrades` inventory with saved `Size=11`,
+gearbox at local index 4, capacitor at 5, and extra upgrades at
+0, 1, 2, 3, 6, 7, 8, 9, 10. Entries must have the corresponding `upgrades/`
+stable IDs or no stable ID.
+
+On the new definition, declare nine extra slots and use
+` `. Both component
+sockets must be automatic. The migration moves indexes 4 and 5 into
+`mmdlib_gearbox/0` and `mmdlib_capacitor/0`, then maps the nine extras to local
+indexes 0-8 in their original order. New saves contain the separate component
+inventories and nine-slot extras, so loading them again does not remap them.
+Unknown IDs and displaced contents remain available through normal recovery.
+New machines, other layouts, and saves without that old named inventory should
+omit this option. It can remain enabled while old worlds are still supported.
+
## Ghost inventory inputs
Declare a sample-only inventory alongside ordinary item storage:
@@ -155,6 +289,67 @@ The selector summarizes required and consumed amounts separately for single-flui
inputs with deterministic returns. Selection changes invalidate failed-search
backoff immediately.
+## Item-tag admission filters
+
+Real `` and `` storage declarations accept `item-tag="minecraft:hoes"`
+(or another namespaced item tag). For example:
+
+```xml
+
+```
+
+The filter belongs to storage and applies to manual insertion and automation,
+in addition to existing recipe filters. Named tags remain reloadable. Loading
+saved stacks and extracting items are unaffected. Ghost slots do not support this
+attribute. Slot declarations without `item-tag` retain their existing admission rules.
+
+## Work and range visualizers
+
+Configure world-display colors on the machine, independently of its screen:
+
+```xml
+
+```
+
+Both attributes accept `#RRGGBB` or the standard machine palette names. Omitted
+attributes inherit from the parent machine, then fall back to green range outlines
+and amber work particles. A child can override either color independently.
+The range toggle and outline use `range-color`; active work uses `work-color`.
+Java hosts can implement `VisualizerStyle.Provider` instead.
+
+A custom processor opts into work particles by implementing
+`machine.feature.WorkTargets.Provider`:
+
+```java
+@Override
+public List workingBlocks() {
+ return currentTargets; // Absolute world block positions, not local offsets.
+}
+```
+
+XML machines automatically attach a shared `WorkTargets` feature. After the
+processor ticks, it copies the current list while `processing()` is true. An
+empty list, idle/paused processor or suspended host stops emission. Targets are
+deduplicated, copied to immutable positions and limited to the first 256 unique
+blocks. They are transient and never restored from a disk save. The processor
+owns target selection and should return an empty list when it has no active work.
+
+The feature uses normal tracking-client updates, including initial chunk tracking,
+without an open GUI or a custom packet. Updates share the host's ten-tick sync
+interval. The client emits two rotating dust helices in a column 1.5 blocks tall,
+starting above the target's outline shape (or at block height for air). It visits
+at most four targets per machine every two ticks within 64 blocks of the camera.
+Particle settings reduce each column from nine to five or three samples per strand.
+Dust lasts six ticks to keep the rotating trails distinct. Unloading
+or removing the machine stops further emission. Work particles are automatic and
+independent of the player's range-outline toggle.
+
+For a Java host, add `new WorkTargets(key, provider::workingBlocks,
+processor::processing)` after its processor in the `FeatureHost`, use the existing
+feature sync/update-tag lifecycle, and call `MachineWorkDisplay.tick(entity,
+targets.targets(), style.workColor())` from its client ticker. No Minecraft client
+classes should be loaded from common initialization.
+
## Appearance presets
`preset="cube-front"` generates an orientable cube from `front`, `side` and `top`
@@ -412,13 +607,25 @@ membership. Roles are `input`, `output`, `storage`, and `manual`; automatic grou
modes are respectively `input`, `output`, `both`, and `disabled`. A group cannot
grant automation permissions that its members' roles prohibit. Slot `limit`
defaults to 64. When `` is present it must contain 1–54 slots overall.
-Omit `` entirely for fluid-only machines; no dummy inventory or item
-capability is created.
+Omit `` entirely for fluid-only machines; no dummy inventory is created.
+Enabled upgrades may add manual component sockets for the GUI, but a machine
+with only manual slots does not advertise an item capability. Machines with
+automatable item slots expose their full stable slot numbering.
+
+For manual component storage that must not appear as a coloured automation
+group, use ` `. This flag defaults to `true` and requires `role="manual"`.
+It removes the side-configuration entry, colour selectors and automation addons,
+while preserving the named inventory, stable slot IDs, saved items and internal
+recipe group. Generated screens render that inventory without a coloured wrapper;
+custom screens can place its slots normally. Explicit group overrides retain the
+flag. Ghost inventories do not accept this attribute.
The runtime supports an optional item storage, an optional fluid storage, an optional energy
-buffer named `energy`, and at most one recipe type and processor per machine. Supply
-`` and `` together for processing, or omit both for a plain
-tank or storage block. Storage-only machines do not apply recipe admission filters,
+buffer named `energy`, and zero or more processors. Recipe processors reference a
+``; custom processors supply a Java class. Declare several processors
+for parallel lanes (see [Several processors per machine](#several-processors-per-machine)),
+or omit `` and `` for a plain tank or storage block. Storage-only machines do not apply recipe admission filters,
register JEI catalysts, or generate processor progress/buttons in the base screen.
Without a processor, item and tank roles must be `storage` or `manual`; `input`
and `output` require a processor to consume or produce their contents.
@@ -1435,3 +1642,196 @@ emit world light. Default is false. Use transparency around glowing pixels.
MMDLib expands the declaration into conditional model parts, reusing tracking
snapshots and model invalidation when the selected frame changes. No per-machine
renderer or full-face variants are needed. Inventory models keep the base casing.
+
+## Allowed facing and placement
+
+` ` is the default.
+`facing="all"` allows all six directions. A space-separated list allows any
+nonempty subset, such as `up`, `down`, `up down`, or `north east up`.
+`placement-facing="away-from-player"` reverses the placement preference.
+Placement picks the nearest allowed look direction (opposite the look direction
+for toward-player); a fixed direction always wins. Rotation/mirroring retains
+its old direction when the transformed front is forbidden. Loaded states outside
+the declared set normalize to north if allowed, otherwise the first allowed
+Minecraft direction (down, up, north, south, west, east).
+
+Vertical fronts use north as local top. Shapes, models, displays and working
+areas share that orientation. Range upgrades expand the area's local plane.
+The companion's Facing Demo machines illustrate all, away, up-only, down-only,
+vertical and asymmetric sets; the existing crushers show horizontal defaults.
+
+## Dynamic storage admission
+
+Real slots accept `filter-class="your.ModAdmission"` or
+`filter-processor="processor_id"`, alongside existing `item-tag` restrictions.
+Tanks accept the same hooks and `fluid-tag="namespace:tag"` alongside exact `fluid`.
+All applicable rules must pass. Recipe admission still accepts the union of linked
+recipe inputs. Rules do not delete contents when tags, recipes or configuration change.
+
+Implement `StorageAdmission` with `acceptsItem(ProcessorMachine, memberId, ItemStack)`
+and/or `acceptsFluid(ProcessorMachine, memberId, FluidAmount)`. Unimplemented kinds
+refuse insertion. A class needs a public no-argument constructor and is instantiated
+per machine; a processor binding names a custom processor implementing that interface.
+The member ID is the stable storage slot/tank ID, such as `fuel/0`. Values are detached;
+the host can have a null level during construction/loading. Queries must not mutate
+storage and must handle simulated operations. Read live config/recipes or invalidate
+any private caches on reload. These hooks govern external admission; machine-product
+transactions retain their existing internal insertion semantics.
+
+The companion Admission Demo shows furnace fuel, vanilla smelting, item/fluid tags,
+a mod-config-selected fluid tag and recipe-based fluid admission. Its custom processor
+supplies rules without a recipe processor. `AdmissionDemo.fuelTag` illustrates the
+mod-owned configuration value; the fixture itself is an inspection/storage machine.
+
+## Typed processor storage
+
+`ProcessorMachine.resources()` exposes the host's existing `MachineInventory`.
+Use `items("group")`, `fluids("group")` and `energy("group")` for typed access;
+missing or wrong-kind names fail explicitly. Indexes are local to that group.
+Use `try (var tx = resources.begin())` and commit only when every operation succeeds.
+Closing without commit rolls all changes back. These are internal processing
+operations: they honor reservations but bypass external roles and item admission.
+Use copied `peek` values for inspection. Declaration prototypes have no live host.
+
+The companion Porting Workshop converts one cobblestone and 25 mB water into stone
+using one transaction. A blocked output leaves both inputs unchanged. Its processor
+uses only the common host API, with no cast to the XML block entity.
+
+## Placement callbacks
+
+Custom processors can override `placementFacing(BlockPlaceContext, Direction)`.
+This pure preference hook runs on the declaration prototype (no live host), on
+both sides. Its result must be allowed by the machine's `facing` declaration.
+`placed(MachinePlacement)` runs on live processors once after successful server
+item placement and portable payload restoration. `StoredProcessor` subclasses override
+`onPlaced(MachinePlacement)` inside the supplied state-update scope. It receives the final state,
+position, nullable placer, level and a copied placing stack. It does not run when
+loading a chunk or when a placement event cancels. Direct world `setBlock` calls
+are not item placement and do not initialize ownership.
+
+The Porting Workshop records the placing player's UUID/team in processor state.
+Sneak placement chooses the clicked face; ordinary placement faces the player.
+
+## Comparator readout
+
+` ` selects one existing
+`IRedstoneOutput` descriptor by its stable ID. The source is sampled together
+with per-face outputs, once per selected source per tick. Comparator readout is
+block-wide and independent of Emit faces and their inversion. Unknown source
+IDs fail during definition loading with the source file and line. Custom processors
+contribute descriptors through `redstoneOutputs()`; their IDs must be available
+on the host-free schema prototype. Loading reads the IDs without sampling their
+live value suppliers. No second provider is needed.
+The Porting Workshop exposes output fullness to both the redstone drawer and
+comparators, including comparators reading through an adjacent solid block.
+
+## Several processors per machine
+
+Declare repeated `` elements with unique stable IDs. They tick
+in declaration order and persist separately. Recipe and custom processors can run
+together. Repeated `` declarations provide the types used by recipe
+lanes. The first processor is the default primary unless one declares `primary="true"`;
+portable or secondary-use machines with several processors require an explicit primary.
+Primary selection controls item/placement behavior, keyless processor controls,
+and the no-argument progress/time/pause getters. It does not change tick order or
+explicitly indexed lane bindings.
+
+Recipe lanes can declare `bindings="input=left_input output=left_output"` to map
+recipe group names to the machine's physical groups. A binding list defines the
+lane's view; `energy=energy` is included automatically when available. Without a
+list, all resource groups retain their names. Custom processors use named host
+resources directly. Shared targets retain common reservation/transaction identity.
+Recipe admission unions participating lanes by physical slot/tank, then intersects
+that union with authored admission rules. `filter-inputs` names recipe-side aliases;
+omitting it filters all bound input groups.
+
+Generated progress displays and default processor buttons address each lane.
+Per-lane sounds, visuals, statistics and persistence use the same stable IDs.
+JEI registers every used recipe type and routes transfer to its bound inputs.
+Default selection by legacy keyless runtime APIs remains first-in-registration-order;
+use explicit processor keys when choosing a particular lane.
+
+Inheritance merges repeated processors/types by ID. For compatibility, when both
+parent and child declare exactly one processor (or one recipe type), that child
+still overrides the parent singleton even when renaming it. To append to such a
+parent, repeat its existing ID alongside the new declaration.
+
+The companion Parallel Workshop runs two crushing lanes plus a custom water-powered
+Charge Pump (one mB supplies 100 FE). The Shared Workshop rebinds the second lane
+to the first lane's input to demonstrate contention without duplicate products.
+
+
+### Java recipe cycle callbacks
+
+`on-start` and `on-finish` use the ordinary `MaterialExtensions.GLOBAL.events()`
+registry. Mods can register Java callbacks with `MaterialEventTypes.MACHINE_CYCLE_START`
+and `MACHINE_CYCLE_FINISH`; CraftTweaker is optional. `MachineCycle.processor()`
+identifies the lane. Callbacks fire for every actual transition, including multiple
+transitions in one accelerated tick. Loading or resuming a cycle does not replay
+its start, and interruption/failed output does not report a finish. A finish sees
+the committed recipe resources. Java-created recipe processors can use
+`RecipeProcessor.cycleCallbacks(start, finish)` directly.
+
+The companion Parallel Workshop registers both Java callbacks in `CompanionMod`
+and records their counts and lane identity in its charge pump's saved state.
+
+
+### Processor-owned energy
+
+An energy declaration uses the built-in buffer by default (`provider="builtin"`).
+To give ownership to a custom processor, set `provider` to its stable processor ID:
+
+```xml
+
+
+
+
+```
+
+The processor implements `ProcessorEnergy.createEnergyStorage(capacity, inputRate,
+outputRate)` and returns its authoritative `EnergyBuffer` (or subclass). This runs
+once during construction, before host resources are available. The same store
+backs recipe transactions, energy gauges, statistics, visual values, saving and
+the library's single NeoForge capability registration. Do not separately register
+another energy capability or save a second copy. A subclass backed by another
+storage must implement the buffer's transactional checkpoint, consumption,
+telemetry and serialization contracts consistently.
+
+`energyMode(side)` adds live restrictions to ordinary side configuration; null
+means unsided access. Cached views query it on every transfer, so temporary
+unavailability can return `IoMode.DISABLED` without swapping storage or invalidating
+capabilities. The source itself stays stable for the machine's lifetime.
+
+Custom sources default to `capacitors="false"`; their automatic capacitor socket
+is omitted and explicit incompatible sockets are rejected. Opt in only when the
+source supports the standard capacity/rate upgrades. Built-in buffers retain the
+existing capacitor behavior. Machines without an energy declaration expose no
+energy capability. The companion Battery Workshop reuses the two recipe lanes
+and supplies their energy through its BatteryBank processor, including live side
+restrictions and capacitor support.
+
+
+### Per-processor operating energy
+
+` ` adds a nonnegative FE cost per successful
+work step. It defaults to zero and requires the machine's `energy` resource.
+Recipe lanes add it to the recipe's scheduled energy; different machines or lanes
+can reuse the same recipe with different operating costs. Gearbox-accelerated
+steps each pay their cost. Starting, idle, paused, held, stalled and blocked steps
+do not charge. Recipe and operating charges commit together: insufficient power
+leaves both energy and progress unchanged. For a costed recipe, a blocked final
+step also rolls back that step's charges and progress until completion succeeds.
+
+Custom `StoredProcessor` implementations use the same option. The cost is reserved
+before `process` runs and retained only when `performedWork(result)` returns true
+(default: `RUNNING`). Override that hook if a successful completion reports `IDLE`.
+Use resource transactions for custom work; return a failure status without committing
+partial resource mutations. On failure, the reserved energy and its telemetry roll
+back. The custom processor sees the remaining energy after its operating reservation.
+Java machines can configure `operatingCost(amount)` directly on either processor type.
+
+The companion Paid Workshop runs the Parallel Workshop's unchanged recipes at 5
+and 9 FE/step overhead, alongside a custom charge pump costing 3 FE/step. Its focused
+tests cover combined-cost starvation, accelerated work, pause/idle, failed final
+output, successful completion and custom-processor refunds.
diff --git a/scripts/companion.gradle b/scripts/companion.gradle
index f2755cc7..d8305233 100644
--- a/scripts/companion.gradle
+++ b/scripts/companion.gradle
@@ -18,6 +18,9 @@ sourceSets {
}
}
+// Unit definition tests load the real companion XML and its mod-owned processors.
+sourceSets.test.runtimeClasspath += sourceSets.companion.output
+
neoForge.addModdingDependenciesTo(sourceSets.companion)
neoForge.addModdingDependenciesTo(sourceSets.companionTest)
neoForge.addModdingDependenciesTo(sourceSets.companionServerTest)
@@ -94,7 +97,7 @@ neoForge {
gameDirectory = layout.buildDirectory.dir('companion-gametest')
sourceSet = sourceSets.companionServerTest
loadedMods = [neoForge.mods.named(mod_id).get(), neoForge.mods.mmdlib_companion_test]
- systemProperty 'neoforge.enabledGameTestNamespaces', 'mmdlib_companion'
+ systemProperty 'neoforge.enabledGameTestNamespaces', project.hasProperty('portingHooksOnly') ? 'mmdlib_porting' : 'mmdlib_companion,mmdlib_porting'
}
multiblockClientSmoke {
client()
diff --git a/scripts/generate_gui_sprites.py b/scripts/generate_gui_sprites.py
index 6382ba63..33b7c788 100644
--- a/scripts/generate_gui_sprites.py
+++ b/scripts/generate_gui_sprites.py
@@ -445,6 +445,77 @@ def arrow(img, x, y, down, colour):
write_png("icon_side_config", outlined(img))
+def write_upgrade_sprites():
+ """Hand-pixelled 16px circuit-module tab and permanent component socket glyphs."""
+ palette = {
+ '.': CLEAR, 'o': (29, 39, 46, 255),
+ 's': (67, 83, 92, 255), 'm': (116, 139, 148, 255),
+ 'h': (191, 212, 215, 255), 'w': (232, 243, 233, 255),
+ 't': (27, 95, 89, 255), 'c': (53, 155, 135, 255),
+ 'b': (100, 219, 177, 255), 'g': (207, 151, 66, 255),
+ 'y': (251, 216, 118, 255),
+ }
+ sprites = {
+ 'icon_upgrades': [
+ '................',
+ '...g.g.g.g.g....',
+ '..ooooooooooo...',
+ '.gohtttttttto...',
+ '..otbbctctcto.g.',
+ '.gotctcttttto...',
+ '..ottttooyyooog.',
+ '.gotctoyyyyyyo..',
+ '..otttyyoooooyo.',
+ '.gottyyohhsooyo.',
+ '..ottyyohssooyo.',
+ '.gotctoyooooyo..',
+ '..oooooyyyyyyo..',
+ '...g.g.ooyyoo...',
+ '................',
+ '................',
+ ],
+ 'socket_gearbox': [
+ '................',
+ '....ss..........',
+ '..sshhss........',
+ '..shmmhs........',
+ '.shmssmhs.......',
+ '.shs..sms.......',
+ '..smssms..ss....',
+ '..ssmmss.swws...',
+ '....ss..shmmhs..',
+ '.......shmssmhs.',
+ '.......sms..sms.',
+ '........smssms..',
+ '........ssmmss..',
+ '..........ss....',
+ '................',
+ '................',
+ ],
+ 'socket_capacitor': [
+ '................',
+ '.....hh..hh.....',
+ '.....ms..ms.....',
+ '....ssssssss....',
+ '...shhhhhhhms...',
+ '...shmccccmss...',
+ '...shcbcbcmss...',
+ '...shcbbccmss...',
+ '...shccbcbmss...',
+ '...shmccccmss...',
+ '...shmmmmmmss...',
+ '...smmmmmmsss...',
+ '....ssssssss....',
+ '................',
+ '................',
+ '................',
+ ],
+ }
+ for name, rows in sprites.items():
+ assert len(rows) == 16 and all(len(row) == 16 for row in rows), name
+ write_png(name, [[palette[pixel] for pixel in row] for row in rows])
+
+
def main():
OUT.mkdir(parents=True, exist_ok=True)
print(f"writing to {OUT}:")
@@ -462,6 +533,7 @@ def main():
write_filter_icons()
write_flat_buttons()
write_side_config_sprites()
+ write_upgrade_sprites()
write_png("checkbox", checkbox(False))
write_png("checkbox_selected", checkbox(True))
write_png("radio", radio(False))
diff --git a/scripts/generate_upgrade_assets.py b/scripts/generate_upgrade_assets.py
new file mode 100644
index 00000000..c75b28a5
--- /dev/null
+++ b/scripts/generate_upgrade_assets.py
@@ -0,0 +1,90 @@
+"""Pixel-art upgrade modules, using the same PNG writer as our GUI sprites."""
+from pathlib import Path
+import generate_gui_sprites as sprites
+
+
+def generate():
+ # Steel frame, teal circuit board, gold contacts and a four-way range symbol.
+ palette = {
+ '.': (0, 0, 0, 0),
+ 'o': (32, 40, 46, 255),
+ 's': (84, 103, 113, 255),
+ 'h': (181, 205, 209, 255),
+ 'b': (24, 72, 70, 255),
+ 't': (37, 119, 102, 255),
+ 'g': (218, 166, 61, 255),
+ 'y': (255, 221, 112, 255),
+ 'a': (131, 241, 174, 255),
+ 'w': (218, 255, 224, 255),
+ }
+ sprites.OUT = Path(__file__).resolve().parents[1] / 'src/main/resources/assets/mmdlib/textures/item'
+ sprites.OUT.mkdir(parents=True, exist_ok=True)
+ # Matching steel module with two meshing brass gears and a dark axle hub.
+ rows = [
+ '................',
+ '..oooooooooooo..',
+ '.ohhhhhhhhhhhso.',
+ '.ohbbbbbbbbbbso.',
+ '.ohbbggbbbbbbso.',
+ '.ohbggyygbbbbso.',
+ '.ohgygooggbbbso.',
+ '.ohgygooggygbso.',
+ '.ohbggyygoogbso.',
+ '.ohbbggggoogbso.',
+ '.ohbbbbgyyggbso.',
+ '.ohbbbbbggbbbso.',
+ '.osssssssssssso.',
+ '..ooggyggyggoo..',
+ '....ygyygygy....',
+ '................',
+ ]
+ assert len(rows) == 16 and all(len(row) == 16 for row in rows)
+ sprites.write_png('gearbox_upgrade', [[palette[pixel] for pixel in row] for row in rows])
+ # Paired cylindrical capacitors with bright contacts, in the shared module frame.
+ palette['c'] = (58, 148, 207, 255)
+ palette['l'] = (137, 225, 255, 255)
+ rows = [
+ '................',
+ '..oooooooooooo..',
+ '.ohhhhhhhhhhhso.',
+ '.ohbbbbbbbbbbso.',
+ '.ohbggbbggbbbso.',
+ '.ohcllccllcbbso.',
+ '.ohcltccltcbbso.',
+ '.ohcltccltcbbso.',
+ '.ohclwcclwcbbso.',
+ '.ohcltccltcbbso.',
+ '.ohcssccsscbbso.',
+ '.ohbggbbggbbbso.',
+ '.osssssssssssso.',
+ '..ooggyggyggoo..',
+ '....ygyygygy....',
+ '................',
+ ]
+ assert len(rows) == 16 and all(len(row) == 16 for row in rows)
+ sprites.write_png('capacitor_upgrade', [[palette[pixel] for pixel in row] for row in rows])
+
+ # Shared range module: four-way expansion arrows.
+ rows = [
+ '................',
+ '..oooooooooooo..',
+ '.ohhhhhhhhhhhso.',
+ '.ohbbbbbbbbbbso.',
+ '.ohbttbaabttbso.',
+ '.ohbtbaaaabtbso.',
+ '.ohbttbaabttbso.',
+ '.ohbaabwabaabso.',
+ '.ohaaaawwaaaaso.',
+ '.ohbaabwabaabso.',
+ '.ohbttbaabttbso.',
+ '.ohbtbaaaabtbso.',
+ '.osssssssssssso.',
+ '..ooggyggyggoo..',
+ '....ygyygygy....',
+ '................',
+ ]
+ assert len(rows) == 16 and all(len(row) == 16 for row in rows)
+ sprites.write_png('range_upgrade', [[palette[pixel] for pixel in row] for row in rows])
+
+if __name__ == '__main__':
+ generate()
diff --git a/src/companion/java/zone/moddev/mc/companion/AdmissionDemo.java b/src/companion/java/zone/moddev/mc/companion/AdmissionDemo.java
new file mode 100644
index 00000000..1a1f3906
--- /dev/null
+++ b/src/companion/java/zone/moddev/mc/companion/AdmissionDemo.java
@@ -0,0 +1,64 @@
+package zone.moddev.mc.companion;
+
+import net.minecraft.core.registries.Registries;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.tags.TagKey;
+import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.crafting.RecipeType;
+import net.minecraft.world.item.crafting.SingleRecipeInput;
+
+import zone.moddev.mc.lib.machine.feature.ProcessorMachine;
+import zone.moddev.mc.lib.machine.feature.ProcessorState;
+import zone.moddev.mc.lib.machine.feature.StorageAdmission;
+import zone.moddev.mc.lib.machine.feature.StoredProcessor;
+import zone.moddev.mc.lib.machine.ingredient.FluidAmount;
+import zone.moddev.mc.lib.machine.ingredient.MachineIngredient;
+import zone.moddev.mc.lib.machine.neoforge.MachineContent;
+
+/** A custom processor can also supply live insertion rules without casts. */
+public final class AdmissionDemo extends StoredProcessor
+ implements StorageAdmission {
+ private static final ResourceLocation STILL_RECIPE_TYPE = ResourceLocation
+ .parse("mmdlib_companion:lava_smelting");
+
+ /** A consuming mod can supply this value from its own reloadable config. */
+ public static volatile ResourceLocation fuelTag = ResourceLocation
+ .parse("minecraft:lava");
+
+ @Override
+ public boolean acceptsItem(ProcessorMachine host, String member,
+ ItemStack stack) {
+ if (member.startsWith("fuel/"))
+ return stack.getBurnTime(RecipeType.SMELTING) > 0;
+ return host.level() != null
+ && host.level().getRecipeManager().getRecipeFor(RecipeType.SMELTING,
+ new SingleRecipeInput(stack), host.level()).isPresent();
+ }
+
+ @Override
+ public boolean acceptsFluid(ProcessorMachine host, String member,
+ FluidAmount fluid) {
+ if (member.equals("oil"))
+ return fluid.fluid().is(TagKey.create(Registries.FLUID, fuelTag));
+ if (host.level() == null)
+ return false;
+ // Query the current manager by type: bounded work and reload-safe.
+ return MachineContent.recipeType(STILL_RECIPE_TYPE)
+ .recipes(host.level().getRecipeManager()).stream()
+ .anyMatch(holder -> holder.value().recipe().inputs()
+ .getOrDefault("fuel", java.util.List.of()).stream().anyMatch(
+ part -> part instanceof MachineIngredient.FluidPart input
+ && input.fluids().contains(fluid.fluid())));
+ }
+
+ @Override
+ public boolean canStart(ProcessorState state, ProcessorMachine context) {
+ return false;
+ }
+
+ @Override
+ public ProcessState process(ProcessorState state, ProcessorMachine context,
+ int ticks) {
+ return ProcessState.IDLE;
+ }
+}
diff --git a/src/companion/java/zone/moddev/mc/companion/BatteryBank.java b/src/companion/java/zone/moddev/mc/companion/BatteryBank.java
new file mode 100644
index 00000000..0e000b06
--- /dev/null
+++ b/src/companion/java/zone/moddev/mc/companion/BatteryBank.java
@@ -0,0 +1,43 @@
+package zone.moddev.mc.companion;
+
+import net.minecraft.core.Direction;
+
+import zone.moddev.mc.lib.api.capabilities.EnergyBuffer;
+import zone.moddev.mc.lib.api.capabilities.IoMode;
+import zone.moddev.mc.lib.machine.feature.ProcessorEnergy;
+import zone.moddev.mc.lib.machine.feature.ProcessorMachine;
+import zone.moddev.mc.lib.machine.feature.ProcessorState;
+import zone.moddev.mc.lib.machine.feature.StoredProcessor;
+
+/**
+ * Processor-owned energy, with side policy applied to cached capability views.
+ */
+public final class BatteryBank extends StoredProcessor
+ implements ProcessorEnergy {
+ private EnergyBuffer buffer;
+ public EnergyBuffer createEnergyStorage(long capacity, long input,
+ long output) {
+ if (buffer != null)
+ throw new IllegalStateException("Already bound");
+ return buffer = new EnergyBuffer(capacity, input, output);
+ }
+ public EnergyBuffer buffer() {
+ return buffer;
+ }
+ public IoMode energyMode(Direction side) {
+ if (paused())
+ return IoMode.DISABLED;
+ return side == null
+ ? IoMode.BOTH
+ : side == Direction.UP
+ ? IoMode.INPUT
+ : side == Direction.DOWN ? IoMode.OUTPUT : IoMode.DISABLED;
+ }
+ public boolean canStart(ProcessorState state, ProcessorMachine machine) {
+ return false;
+ }
+ public ProcessState process(ProcessorState state, ProcessorMachine machine,
+ int ticks) {
+ return ProcessState.IDLE;
+ }
+}
diff --git a/src/companion/java/zone/moddev/mc/companion/ChargePump.java b/src/companion/java/zone/moddev/mc/companion/ChargePump.java
new file mode 100644
index 00000000..325c38f9
--- /dev/null
+++ b/src/companion/java/zone/moddev/mc/companion/ChargePump.java
@@ -0,0 +1,45 @@
+package zone.moddev.mc.companion;
+
+import zone.moddev.mc.lib.machine.feature.ProcessorMachine;
+import zone.moddev.mc.lib.machine.feature.ProcessorState;
+import zone.moddev.mc.lib.machine.feature.StoredProcessor;
+
+/** Example charging alongside recipe lanes: one mB water supplies 100 FE. */
+public final class ChargePump extends StoredProcessor {
+ private final ProcessorState.Key starts = variables.define(
+ "starts", com.mojang.serialization.Codec.INT, 0,
+ java.util.function.UnaryOperator.identity(), false, true);
+ private final ProcessorState.Key finishes = variables.define(
+ "finishes", com.mojang.serialization.Codec.INT, 0,
+ java.util.function.UnaryOperator.identity(), false, true);
+ private final ProcessorState.Key lastLane = variables.define(
+ "last_lane", com.mojang.serialization.Codec.STRING, "",
+ java.util.function.UnaryOperator.identity(), false, true);
+
+ public void recordCycle(String lane, boolean finished) {
+ variables.update(() -> {
+ var counter = finished ? finishes : starts;
+ variables.set(counter, variables.get(counter) + 1);
+ variables.set(lastLane, lane);
+ });
+ }
+
+ @Override
+ public boolean canStart(ProcessorState state, ProcessorMachine host) {
+ return host.resources().fluids("coolant").free(0) > 0;
+ }
+
+ @Override
+ public ProcessState process(ProcessorState state, ProcessorMachine host,
+ int ticks) {
+ var resources = host.resources();
+ try (var tx = resources.begin()) {
+ if (resources.energy("energy").insert(100, tx) != 100)
+ return ProcessState.BLOCKED;
+ if (resources.fluids("coolant").extract(0, 1, tx) != 1)
+ return ProcessState.IDLE;
+ tx.commit();
+ }
+ return ProcessState.RUNNING;
+ }
+}
diff --git a/src/companion/java/zone/moddev/mc/companion/CompanionMod.java b/src/companion/java/zone/moddev/mc/companion/CompanionMod.java
index 2e427027..a6e89e97 100644
--- a/src/companion/java/zone/moddev/mc/companion/CompanionMod.java
+++ b/src/companion/java/zone/moddev/mc/companion/CompanionMod.java
@@ -80,6 +80,12 @@ public final class CompanionMod {
}
public CompanionMod(IEventBus bus) {
+ MaterialExtensions.GLOBAL.events().registerCallback(
+ id("workshop_start"), MaterialEventTypes.MACHINE_CYCLE_START,
+ event -> recordWorkshopCycle(event, false));
+ MaterialExtensions.GLOBAL.events().registerCallback(
+ id("workshop_finish"), MaterialEventTypes.MACHINE_CYCLE_FINISH,
+ event -> recordWorkshopCycle(event, true));
MultiblockDemo.register(bus);
CompanionWidgets.register();
CompanionAddons.register(bus);
@@ -100,6 +106,16 @@ public CompanionMod(IEventBus bus) {
});
}
+ private static void recordWorkshopCycle(
+ zone.moddev.mc.lib.api.MaterialEventContexts.MachineCycle event,
+ boolean finished) {
+ if (event
+ .machine() instanceof zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity machine)
+ machine.features.findProcessor("charge", ChargePump.class)
+ .ifPresent(
+ pump -> pump.recordCycle(event.processor(), finished));
+ }
+
private static void capabilities(RegisterCapabilitiesEvent event) {
CompanionAddons.capabilities(event);
for (var machine : MACHINES) {
diff --git a/src/companion/java/zone/moddev/mc/companion/WorkshopProcessor.java b/src/companion/java/zone/moddev/mc/companion/WorkshopProcessor.java
new file mode 100644
index 00000000..240113f4
--- /dev/null
+++ b/src/companion/java/zone/moddev/mc/companion/WorkshopProcessor.java
@@ -0,0 +1,90 @@
+package zone.moddev.mc.companion;
+
+import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.Items;
+import net.minecraft.world.level.material.Fluids;
+
+import zone.moddev.mc.lib.machine.feature.ProcessorMachine;
+import zone.moddev.mc.lib.machine.feature.ProcessorState;
+import zone.moddev.mc.lib.machine.feature.StoredProcessor;
+
+/** A small transactional consumer of typed host resources; no entity cast. */
+public final class WorkshopProcessor extends StoredProcessor
+ implements zone.moddev.mc.lib.api.redstone.IRedstoneOutput {
+ private final ProcessorState.Key placements = variables.define(
+ "placements", com.mojang.serialization.Codec.INT, 0,
+ java.util.function.UnaryOperator.identity(), false, true);
+ private final ProcessorState.Key owner = variables.define("owner",
+ com.mojang.serialization.Codec.STRING, "",
+ java.util.function.UnaryOperator.identity(), false, true);
+ private final ProcessorState.Key team = variables.define("team",
+ com.mojang.serialization.Codec.STRING, "",
+ java.util.function.UnaryOperator.identity(), false, true);
+
+ @Override
+ public java.util.List redstoneOutputs() {
+ return java.util.List
+ .of(new zone.moddev.mc.lib.api.redstone.RedstoneOutput(
+ "workshop/output",
+ net.minecraft.network.chat.Component.literal("Workshop output"),
+ net.minecraft.network.chat.Component
+ .literal("Stone output fullness"),
+ 0xc07040, java.util.Optional.empty(),
+ () -> machine == null
+ ? 0
+ : zone.moddev.mc.lib.api.redstone.RedstoneControl.level(
+ machine.resources().items("output").peek(0).getCount()
+ / 64.0)));
+ }
+
+ @Override
+ public net.minecraft.core.Direction placementFacing(
+ net.minecraft.world.item.context.BlockPlaceContext context,
+ net.minecraft.core.Direction suggested) {
+ // Sneak placement demonstrates a consumer choosing the clicked face.
+ return context.getPlayer() != null
+ && context.getPlayer().isShiftKeyDown()
+ ? context.getClickedFace()
+ : suggested;
+ }
+
+ @Override
+ protected void onPlaced(
+ zone.moddev.mc.lib.machine.feature.MachinePlacement placement) {
+ variables.set(placements, variables.get(placements) + 1);
+ var player = placement.placer();
+ variables.set(owner, player == null ? "" : player.getUUID().toString());
+ variables.set(team,
+ player == null || player.getTeam() == null
+ ? ""
+ : player.getTeam().getName());
+ }
+
+ @Override
+ public boolean canStart(ProcessorState state, ProcessorMachine host) {
+ var resources = host.resources();
+ return resources.items("input").peek(0).is(Items.COBBLESTONE)
+ && resources.items("input").free(0) > 0
+ && resources.fluids("water").peek(0).fluid().value() == Fluids.WATER
+ && resources.fluids("water").free(0) >= 25;
+ }
+
+ @Override
+ public ProcessState process(ProcessorState state, ProcessorMachine host,
+ int ticks) {
+ var resources = host.resources();
+ for (int step = 0; step < ticks; step++) {
+ if (!canStart(state, host))
+ return ProcessState.IDLE;
+ try (var tx = resources.begin()) {
+ if (resources.items("input").extract(0, 1, tx) != 1
+ || resources.fluids("water").extract(0, 25, tx) != 25
+ || resources.items("output")
+ .insert(new ItemStack(Items.STONE), tx) != 1)
+ return ProcessState.BLOCKED;
+ tx.commit();
+ }
+ }
+ return ProcessState.RUNNING;
+ }
+}
diff --git a/src/companion/resources/META-INF/neoforge.mods.toml b/src/companion/resources/META-INF/neoforge.mods.toml
index 4497db97..43a44da0 100644
--- a/src/companion/resources/META-INF/neoforge.mods.toml
+++ b/src/companion/resources/META-INF/neoforge.mods.toml
@@ -6,7 +6,7 @@ license="LGPL-2.1-only"
modId="mmdlib_companion"
version="${file.jarVersion}"
displayName="MMDLib Machine Companion"
-description='''Four playable examples of MMDLib's recipe processors and reservations.'''
+description='''Playable examples of MMDLib machines, recipes, storage, automation, placement and processor extensions. Open each machine's Info panel for its purpose and a hands-on check.'''
[[dependencies.mmdlib_companion]]
modId="neoforge"
diff --git a/src/companion/resources/assets/mmdlib_companion/lang/en_us.json b/src/companion/resources/assets/mmdlib_companion/lang/en_us.json
index cdeb6ad6..ce6eb94f 100644
--- a/src/companion/resources/assets/mmdlib_companion/lang/en_us.json
+++ b/src/companion/resources/assets/mmdlib_companion/lang/en_us.json
@@ -19,7 +19,7 @@
"screen.mmdlib_companion.lane_b": "Lane B",
"screen.mmdlib_companion.single": "One iron in, one gold out",
"screen.mmdlib_companion.power": "Powers adjacent blocks on enabled sides",
- "mmdlib_companion:creative_power.info": "*Creative Power Source*\n\nSupplies up to 1,000 FE per enabled face each tick.\n\nUse the side configuration panel to enable or disable outputs. Statistics shows the measured output rate.",
+ "mmdlib_companion:creative_power.info": "*Creative Power Source*\n\nTests automatic energy export, per-face side settings and transfer statistics. Its buffer refills every tick without fuel.\n\nPlace it beside a powered companion machine and enable the connecting output face. It supplies up to 1,000 FE per enabled face per tick, subject to the receiving machine's input rules.\n\nDisable one face and confirm that receiver stops charging while other enabled faces continue. Check Statistics for the actual transferred energy.",
"screen.mmdlib_companion.rate": "1,000 FE per face per tick",
"block.mmdlib_companion.crusher": "Crusher",
"block.mmdlib_companion.transmuter": "Iron-to-Gold Converter",
@@ -45,9 +45,9 @@
"screen.mmdlib_companion.recipes.tip": "Show crushing recipes in JEI, when installed.",
"screen.mmdlib_companion.tank.tip": "Water or lava: {value} / {max} mB. Left-click to fill; right-click to drain with a fluid container.",
"screen.mmdlib_companion.tank.refused": "Cannot transfer fluid. The tank holds water or lava, one type at a time, up to 4 buckets.",
- "mmdlib_companion:crusher.info": "*Crusher*\n\nCrush ore into raw materials, or stone into gravel and sand.\n\nPlace a power source beside the machine. Pause to release reserved items.\n\nThe left tank holds 4 buckets of water or lava for display. Left-click the gauge with a fluid container on the cursor to fill it; right-click to drain it, or right-click the block with a bucket. Empty the tank before changing fluids. Crushing does not use the fluid.",
- "mmdlib_companion:transmuter.info": "*Iron to gold*\n\nInsert one iron ingot. The same slot holds the gold when the cycle finishes.\n\nSupply power from an adjacent block. Pause to release the input.",
- "mmdlib_companion:dual_crusher.info": "*Dual crusher*\n\nTwo lanes share the input and output slots. Each lane reserves its own items and space.\n\nPause either lane independently to release its share.",
+ "mmdlib_companion:crusher.info": "*Crusher*\n\nTests Java recipe processing, item reservations, a custom progress dial and editable screen controls. Supply FE and insert cobblestone to make gravel, gravel to make sand, or a supported ore to make raw material. The Recipes button opens JEI when installed.\n\nClick the progress dial or processor button to pause and release reserved items. Resume to reclaim them. Settings lets you rename the machine, set its energy reserve and pause its lane; a reserve above the current charge holds processing.\n\nThe separate 4,000 mB tank tests fluid-container interactions and accepts water or lava, one fluid at a time. Left-click its gauge with a filled container to fill it; right-click with an empty container to drain it. You can also use a bucket on the block. Crushing does not consume this fluid.",
+ "mmdlib_companion:transmuter.info": "*Iron-to-Gold Converter*\n\nTests consuming an input and placing its product in the same physical slot, including reservations and a one-item slot limit.\n\nSupply 4,000 FE and insert one iron ingot. After 200 work ticks, one gold ingot replaces it in that slot. Remove the gold before starting another cycle.\n\nPause during processing to release the input, then resume. With insufficient power, progress should stall without consuming the ingot.",
+ "mmdlib_companion:dual_crusher.info": "*Dual Crusher*\n\nTests two Java recipe lanes competing for the same input stack, output space and energy buffer.\n\nSupply FE and insert several cobblestone or gravel items. Both lanes can advance when enough unreserved input and output space remain. Each lane has its own progress display and pause button.\n\nTry a single input item: only one lane may claim it, and it must produce only one result. Pause one lane to release its reservations while the other keeps working. A full output must prevent new work without consuming input.",
"item.mmdlib_companion.mechanical_puller": "Mechanical Puller",
"item.mmdlib_companion.mechanical_pusher": "Mechanical Pusher",
"item.mmdlib_companion.input_pump": "Input Pump",
@@ -59,7 +59,7 @@
"item.mmdlib_companion.tag_filter": "Tag Filter",
"item.mmdlib_companion.fluid_filter": "Fluid Filter",
"block.mmdlib_companion.logistics": "Logistics Workbench",
- "mmdlib_companion:logistics.info": "Seven independent inventories. Install a module, enable a side, and configure its optional filter.",
+ "mmdlib_companion:logistics.info": "*Logistics Workbench*\n\nTests automation modules, filters and independent side settings for seven resource groups: item input, item output, two input tanks, two output tanks and energy. Recipe processing is disabled.\n\nPlace a chest or tank beside it. Open the side configuration, select a resource group, enable the connecting face and install a suitable puller, pusher, pump or relay. Powered modules need FE; filters can restrict which items or fluids move.\n\nConfigure different groups and faces independently, then check that only the intended resources transfer. Try an allow-list or deny-list filter and compare accepted and rejected contents. The workbench does not move input contents to its outputs by itself.",
"screen.mmdlib_companion.group.input": "Item input",
"screen.mmdlib_companion.group.output": "Item output",
"screen.mmdlib_companion.group.energy": "Energy",
@@ -76,5 +76,19 @@
"screen.mmdlib_companion.structure": "Status in Info tab",
"screen.mmdlib_companion.operations": "Active ticks",
"screen.mmdlib_companion.operations.tip": "Active ticks: {value}",
- "screen.mmdlib_companion.multiblock.info": "Keep the block above the middle part clear. Breaking any part dismantles this machine."
+ "screen.mmdlib_companion.multiblock.info": "*Multiblock Test Bench*\n\nTests automatic placement of a three-block structure, shared resource ports, structure validation and dismantling. Place the bench with room for its two attached parts and keep the block above the middle part clear.\n\nThe far end is the socket for items, fluids and energy; its ports access the controller's displayed stores. The middle belt is not a resource port. Try opening the screen through a part and transferring resources through the socket.\n\nWhile the structure is valid, Active ticks increases and the energy store gains 1 FE per tick. Obstruct the required clearance and check the status: work must stop until the structure is valid again.\n\nBreaking any member dismantles the structure. Stored items and remaining fluid or energy must be recovered rather than duplicated or silently lost.",
+ "mmdlib_companion:simple_crusher.info": "*Simple Crusher*\n\nTests a machine defined entirely in XML: generated inventory and progress controls, recipe admission, ore recipe generation, side settings and shared upgrades.\n\nSupply FE and insert cobblestone or gravel. Each produces gravel or sand respectively in 100 work ticks for 2,000 FE. Supported ore tags also generate ore-to-ingot recipes; JEI shows the recipes available in this pack.\n\nUnrelated items should be refused at the input. Fill both output slots to check that blocked work leaves resources intact. Try the pause button, gearbox upgrades for faster work and capacitor upgrades for a larger energy buffer.",
+ "mmdlib_companion:simple_lava_furnace.info": "*Simple Lava Furnace*\n\nTests fluid-powered recipes, a mod-provided smelting recipe generator, and recipe filters on both item and fluid inputs. It uses lava instead of FE.\n\nFill the 8,000 mB fuel tank with lava and insert an item with a smelting recipe, such as raw iron. The recipe reserves its item, lava and output space, then produces the smelted result when the cycle completes.\n\nWater and unrelated items should be refused. Pause to release reservations, or fill the output to check that a new cycle cannot consume resources. JEI shows the generated recipes and their lava amounts.",
+ "mmdlib_companion:admission_demo.info": "*Admission Demo*\n\nTests storage admission without a recipe processor. This machine only stores accepted contents; it does not burn, smelt or distill anything.\n\nTry coal in Burnable fuel, raw iron in Smeltable items and logs in Logs only. Stone should be refused by all three. The fuel slot uses a processor rule, the smelting slot uses a separate Java rule, and the log slot uses an item tag.\n\nThe Water tag tank accepts water. Configured fuel tag uses the lava tag by default. Recipe fluid accepts lava when the companion lava-smelting recipes are available. Water should be refused by those last two tanks.\n\nTry manual insertion, hoppers or pipes, and fluid containers. The same restrictions should apply. The developer check changes the supplied fuel tag at runtime and verifies that fluid already stored is preserved.",
+ "mmdlib_companion:porting_workshop.info": "*Porting Workshop*\n\nTests a custom processor using typed item/fluid transactions, six-way placement, placer ownership and comparator output from an existing redstone source. It needs no FE.\n\nInsert cobblestone and water: each work step converts one cobblestone and 25 mB of water into one stone. Fill the stone output and confirm that blocked work consumes neither input nor water.\n\nNormal placement faces toward you. Sneak while placing to choose the clicked face instead. Successful placement records the player's identity and team; loading the machine must not count as another placement.\n\nAttach a comparator, directly or through a solid block. Its strength follows stone output fullness: empty is 0 and a full stack is 15. No emitting redstone face needs to be enabled.",
+ "mmdlib_companion:parallel_workshop.info": "*Parallel Workshop*\n\nTests two XML recipe lanes running alongside a custom water-powered charge pump. Each lane has separate input/output slots and a pause control, while all three processors share one energy store.\n\nAdd water, or supply FE externally. Insert cobblestone in the left input and gravel in the right input. Expect gravel on the left and sand on the right. Each recipe takes 100 work ticks and 2,000 FE; the pump converts 1 mB of water into 100 FE per successful step.\n\nPause one recipe lane and confirm the other lane and pump can continue. Try gearboxes to accelerate work and reload the world to check saved state.\n\nJava start/finish callbacks also record cycle counts and the last lane in the charge pump's saved state; they do not require CraftTweaker.",
+ "mmdlib_companion:shared_workshop.info": "*Shared Workshop*\n\nTests two XML recipe lanes sharing the same physical input while keeping separate outputs. Both lanes use the left input; the visible right input is intentionally unused.\n\nAdd water to run the charge pump, or supply FE externally. Put one cobblestone in the left input: only one lane may reserve it and only one gravel should be produced. Add a larger stack to let both lanes work.\n\nThe left lane ticks first and can claim the last available item. Pause it to let the right lane claim shared input. Output space and reserved inputs must never be counted twice. This example also binds a second name to the same energy store.",
+ "mmdlib_companion:battery_workshop.info": "*Battery Workshop*\n\nTests energy supplied by a custom BatteryBank processor. The gauge, recipe lanes, charging pump, automation and saved energy must all use the same store. It starts with 200,000 FE capacity and supports capacitor upgrades.\n\nPut a Creative Power Source above it, or add water for the charge pump. Feed cobblestone or gravel to either recipe lane and watch the shared energy gauge fall as recipes work.\n\nFor manual play, charge it from above; this fixture currently exposes an input-only energy group to sided automation. Horizontal connections must refuse transfers. The developer checks also exercise unsided extraction. Pausing the battery processor disables direct energy connections, including existing ones, without pausing the recipe lanes or water pump.\n\nReload the world and check that the stored charge is preserved. It must not reveal a second, separate recipe buffer.",
+ "mmdlib_companion:paid_workshop.info": "*Paid Workshop*\n\nTests per-processor operating energy on the Parallel Workshop's unchanged recipes. Supply FE first, or seed at least 3 FE before relying on the water pump: the pump cannot start from an empty buffer.\n\nAdd water and cobblestone or gravel to the lane inputs. Each 100-step recipe still costs 2,000 FE, plus 5 FE per successful left-lane step or 9 FE per right-lane step: 2,500 FE left and 2,900 FE right per completed cycle.\n\nThe pump pays 3 FE before producing 100 FE from 1 mB of water, for a net gain of 97 FE. Pause the pump when comparing recipe costs in the gauge or Statistics.\n\nGearbox-accelerated steps each pay their cost. Idle, paused, held, stalled or blocked work must not charge operating energy. If a combined recipe and operating charge cannot be paid, energy and progress stay unchanged.",
+ "mmdlib_companion:facing_all.info": "*Facing Demo: All Directions*\n\nTests allowed facing directions and placement preference. Allows all six directions and faces toward the placer.\n\nPlace it while looking horizontally, up and down. The dispenser face should point back toward you.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.",
+ "mmdlib_companion:facing_away.info": "*Facing Demo: Away from Player*\n\nTests allowed facing directions and placement preference. Allows all six directions and faces away from the placer.\n\nPlace it while looking horizontally, up and down. The dispenser face should point along your look direction, opposite to the All Directions demo.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.",
+ "mmdlib_companion:facing_up.info": "*Facing Demo: Up Only*\n\nTests allowed facing directions and placement preference. Allows only an upward-facing front.\n\nPlace it from different sides and viewing angles. The dispenser face must always point up, regardless of where you stand.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.",
+ "mmdlib_companion:facing_down.info": "*Facing Demo: Down Only*\n\nTests allowed facing directions and placement preference. Allows only a downward-facing front.\n\nPlace it from different sides and viewing angles. The dispenser face must always point down, regardless of where you stand.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.",
+ "mmdlib_companion:facing_vertical.info": "*Facing Demo: Up or Down*\n\nTests allowed facing directions and placement preference. Allows only upward and downward fronts, preferring the direction toward the placer.\n\nLook down while placing to get an upward-facing front, or look up to get a downward-facing front. Horizontal fronts must never be selected.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.",
+ "mmdlib_companion:facing_asymmetric.info": "*Facing Demo: North, East or Up*\n\nTests allowed facing directions and placement preference. Allows only north, east and up, preferring the allowed direction nearest to the placer.\n\nPlace it from several sides, including ones that would normally choose south, west or down. The front must always remain north, east or up.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement."
}
diff --git a/src/companion/resources/mmdlib/machine/admission_demo.xml b/src/companion/resources/mmdlib/machine/admission_demo.xml
new file mode 100644
index 00000000..c3d2a51a
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/admission_demo.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/battery_workshop.xml b/src/companion/resources/mmdlib/machine/battery_workshop.xml
new file mode 100644
index 00000000..98b7e642
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/battery_workshop.xml
@@ -0,0 +1,5 @@
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/facing_all.xml b/src/companion/resources/mmdlib/machine/facing_all.xml
new file mode 100644
index 00000000..6747c3a0
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/facing_all.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/facing_asymmetric.xml b/src/companion/resources/mmdlib/machine/facing_asymmetric.xml
new file mode 100644
index 00000000..69303e9f
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/facing_asymmetric.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/facing_away.xml b/src/companion/resources/mmdlib/machine/facing_away.xml
new file mode 100644
index 00000000..76c58fa4
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/facing_away.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/facing_down.xml b/src/companion/resources/mmdlib/machine/facing_down.xml
new file mode 100644
index 00000000..8d32d077
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/facing_down.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/facing_up.xml b/src/companion/resources/mmdlib/machine/facing_up.xml
new file mode 100644
index 00000000..216468e3
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/facing_up.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/facing_vertical.xml b/src/companion/resources/mmdlib/machine/facing_vertical.xml
new file mode 100644
index 00000000..00d2436c
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/facing_vertical.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/paid_workshop.xml b/src/companion/resources/mmdlib/machine/paid_workshop.xml
new file mode 100644
index 00000000..07450b82
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/paid_workshop.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/parallel_workshop.xml b/src/companion/resources/mmdlib/machine/parallel_workshop.xml
new file mode 100644
index 00000000..75f35495
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/parallel_workshop.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/porting_workshop.xml b/src/companion/resources/mmdlib/machine/porting_workshop.xml
new file mode 100644
index 00000000..5f28dcd1
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/porting_workshop.xml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/companion/resources/mmdlib/machine/shared_workshop.xml b/src/companion/resources/mmdlib/machine/shared_workshop.xml
new file mode 100644
index 00000000..1c51a6e1
--- /dev/null
+++ b/src/companion/resources/mmdlib/machine/shared_workshop.xml
@@ -0,0 +1,4 @@
+
+
+
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/DrawerExtensionClientSmoke.java b/src/companionTest/java/zone/moddev/mc/companion/test/DrawerExtensionClientSmoke.java
index ab6b53a2..799b8e95 100644
--- a/src/companionTest/java/zone/moddev/mc/companion/test/DrawerExtensionClientSmoke.java
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/DrawerExtensionClientSmoke.java
@@ -13,6 +13,7 @@
import zone.moddev.mc.lib.gui.client.RedstoneDrawer;
import zone.moddev.mc.lib.gui.client.SideConfigDrawer;
import zone.moddev.mc.lib.gui.client.StatsDrawer;
+import zone.moddev.mc.lib.gui.client.WorkingAreaDisplay;
import zone.moddev.mc.lib.gui.drawer.DrawerDefinition;
import zone.moddev.mc.lib.gui.drawer.DrawerPlacement;
import zone.moddev.mc.lib.gui.drawer.DrawerRegistry;
@@ -25,6 +26,7 @@
final class DrawerExtensionClientSmoke {
private static Probe probe;
private static boolean done;
+ private static int upgradeStep;
private static final ResourceLocation TYPE = ResourceLocation
.parse("test:drawer");
@@ -37,17 +39,100 @@ static void install() {
new DrawerDefinition(TYPE, "test:drawer",
DrawerPlacement.top(Edge.LEFT, 50)),
new DrawerDefinition(TYPE, "test:right",
- DrawerPlacement.top(Edge.RIGHT, 5))));
+ DrawerPlacement.top(Edge.RIGHT, 5)),
+ new DrawerDefinition(TYPE, "test:above_upgrades",
+ DrawerPlacement.top(Edge.RIGHT, -20))));
DrawerFactories.GLOBAL.register(TYPE, Probe::new);
+ installUpgrades();
+ }
+
+ private static void installUpgrades() {
+ var id = ResourceLocation.parse("mmdlib_companion:crusher");
+ var original = zone.moddev.mc.lib.gui.Screens.get(id).orElseThrow()
+ .screen();
+ String xml = """
+
+
+
+
+
+
+ """;
+ try {
+ var fixture = zone.moddev.mc.lib.gui.load.ScreenReader.read(id,
+ "drawer-layout-fixture.xml", new java.io.ByteArrayInputStream(
+ xml.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
+ var tabs = new java.util.ArrayList<>(original.tabs());
+ tabs.addAll(fixture.tabs());
+ var replacement = new zone.moddev.mc.lib.gui.model.Screen(
+ original.id(), original.source(), original.title(),
+ original.blockEntity(), original.playerInventory(),
+ original.body(), tabs);
+ var screens = new java.util.HashMap<>(
+ zone.moddev.mc.lib.gui.Screens.all());
+ screens.put(id,
+ zone.moddev.mc.lib.gui.load.ScreenBinder.bind(replacement,
+ DrawerExtensionClientSmoke.class.getClassLoader()));
+ zone.moddev.mc.lib.gui.Screens.install(screens);
+ } catch (java.io.IOException failure) {
+ throw new IllegalStateException(failure);
+ }
+ }
+
+ private static boolean upgrades(MachineScreen screen) {
+ if (upgradeStep == 3)
+ return true;
+ var drawer = (zone.moddev.mc.lib.gui.client.UpgradesDrawer) screen
+ .drawers().entries().stream()
+ .filter(
+ zone.moddev.mc.lib.gui.client.UpgradesDrawer.class::isInstance)
+ .findFirst().orElseThrow();
+ if (drawer.pending())
+ return false;
+ if (upgradeStep == 1) {
+ if (!drawer.open())
+ throw new AssertionError("Upgrade drawer failed to open");
+ var body = drawer.bodyBounds();
+ int top = zone.moddev.mc.lib.gui.layout.SideDrawerLayout
+ .top(screen.panelBounds());
+ var element = (zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement) screen
+ .getMenu().bound.screen().find("layout_upgrades").orElseThrow();
+ var content = screen.bounds(element.children().getFirst());
+ if (body.y() != top || content.x() != body.x() + 6
+ || content.y() != top + 6 || drawer.tabBounds().y() <= top
+ || body.bottom() < drawer.tabBounds().bottom())
+ throw new AssertionError(
+ "Upgrade body, children and rail disagree after tab reordering");
+ screen.resize(net.minecraft.client.Minecraft.getInstance(),
+ screen.width, screen.height);
+ if (!body.equals(drawer.bodyBounds()))
+ throw new AssertionError(
+ "Upgrade geometry changed on equal resize");
+ } else if (upgradeStep == 2) {
+ if (drawer.open())
+ throw new AssertionError("Upgrade drawer failed to close");
+ upgradeStep = 3;
+ return true;
+ }
+ var tab = drawer.tabBounds();
+ screen.mouseClicked(tab.x() + 5, tab.y() + 5, 0);
+ screen.mouseReleased(tab.x() + 5, tab.y() + 5, 0);
+ upgradeStep++;
+ return false;
}
static boolean run(MachineScreen screen) {
if (done)
return true;
+ if (!upgrades(screen))
+ return false;
if (probe == null) {
+ workingAreas(screen);
probe = (Probe) screen.drawers().entries().stream()
.filter(d -> d.id().equals("test:drawer")).findFirst()
.orElseThrow();
+ probe.verifyContentBounds();
var right = screen.drawers().entries().stream()
.filter(d -> d.id().equals("test:right")).findFirst()
.orElseThrow();
@@ -96,6 +181,50 @@ static boolean run(MachineScreen screen) {
return true;
}
+ private static void workingAreas(MachineScreen screen) {
+ var machine = screen.getMenu().blockEntity;
+ var first = new net.minecraft.nbt.CompoundTag();
+ first.putString("dimension",
+ machine.getLevel().dimension().location().toString());
+ first.putLong("origin", machine.getBlockPos().asLong());
+ first.putString("processor", "first");
+ first.putBoolean("available", true);
+ first.putDouble("maxX", 1);
+ first.putDouble("maxY", 1);
+ first.putDouble("maxZ", 1);
+ var second = first.copy();
+ second.putString("processor", "second");
+ second.putDouble("maxX", 4);
+ WorkingAreaDisplay.toggle(first);
+ if (!WorkingAreaDisplay.visible(first)
+ || WorkingAreaDisplay.visible(second))
+ throw new AssertionError(
+ "Area toggles must distinguish processors on one machine");
+ WorkingAreaDisplay.toggle(second);
+ var unavailable = new net.minecraft.nbt.CompoundTag();
+ unavailable.putString("dimension", first.getString("dimension"));
+ unavailable.putLong("origin", first.getLong("origin"));
+ unavailable.putString("processor", "first");
+ unavailable.putBoolean("available", false);
+ WorkingAreaDisplay.update(unavailable);
+ if (WorkingAreaDisplay.visible(first)
+ || !WorkingAreaDisplay.visible(second))
+ throw new AssertionError(
+ "Unavailable area must clear only its own outline");
+ WorkingAreaDisplay.toggle(unavailable);
+ WorkingAreaDisplay.update(first);
+ if (WorkingAreaDisplay.visible(first))
+ throw new AssertionError(
+ "Unavailable area cannot be enabled or silently restored");
+ WorkingAreaDisplay.toggle(first);
+ WorkingAreaDisplay.toggle(second);
+ if (!WorkingAreaDisplay.visible(first)
+ || WorkingAreaDisplay.visible(second))
+ throw new AssertionError(
+ "Toggling one processor must preserve the other outline");
+ WorkingAreaDisplay.toggle(first);
+ }
+
static zone.moddev.mc.lib.gui.layout.ContainerDrawerLayout containerLayout(
MachineScreen screen, boolean equipment) {
return ((ContainerDrawer) screen.drawers().entries().stream()
@@ -114,6 +243,30 @@ private static final class Probe extends Drawer {
0x92bcb4);
}
+ private boolean measuringContent;
+
+ @Override
+ public zone.moddev.mc.lib.gui.layout.Rect tabBounds() {
+ if (measuringContent)
+ throw new AssertionError(
+ "Content placement must not re-enter subclass tab layout");
+ return super.tabBounds();
+ }
+
+ void verifyContentBounds() {
+ measuringContent = true;
+ try {
+ var body = contentBounds(80, 100,
+ zone.moddev.mc.lib.gui.layout.SideDrawerLayout.HeightLimit.SCREEN);
+ if (body.y() != zone.moddev.mc.lib.gui.layout.SideDrawerLayout
+ .top(screen.panelBounds()))
+ throw new AssertionError(
+ "Content stays aligned with the panel top");
+ } finally {
+ measuringContent = false;
+ }
+ }
+
public boolean available() {
return enabled;
}
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/DrawerMemoryClientSmoke.java b/src/companionTest/java/zone/moddev/mc/companion/test/DrawerMemoryClientSmoke.java
index 88ced14b..0327256b 100644
--- a/src/companionTest/java/zone/moddev/mc/companion/test/DrawerMemoryClientSmoke.java
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/DrawerMemoryClientSmoke.java
@@ -155,8 +155,7 @@ static boolean run() {
require(!bag.open(),
"Curios restoration keeps backpack drawer closed");
screen.keyPressed(256, 0, 0);
- var panel = screen.panelBounds();
- click(screen, new Rect(panel.right(), panel.y() + 4, 22, 24));
+ click(screen, sideTab(screen));
advance();
}
case 8 -> {
@@ -167,9 +166,7 @@ static boolean run() {
throw new AssertionError("Fixture has automation");
if (!menu.components().get(BuiltinMenuComponents.AUTOMATION)
.open()) {
- var panel = screen.panelBounds();
- click(screen,
- new Rect(panel.right(), panel.y() + 4, 22, 24));
+ click(screen, sideTab(screen));
return false;
}
server(player -> {
@@ -259,9 +256,7 @@ static boolean run() {
return false;
if (!menu.components().get(BuiltinMenuComponents.AUTOMATION)
.open()) {
- var panel = screen.panelBounds();
- click(screen,
- new Rect(panel.right(), panel.y() + 4, 22, 24));
+ click(screen, sideTab(screen));
return false;
}
require(
@@ -279,9 +274,7 @@ static boolean run() {
return false;
if (!menu.components().get(BuiltinMenuComponents.AUTOMATION)
.open()) {
- var panel = screen.panelBounds();
- click(screen,
- new Rect(panel.right(), panel.y() + 4, 22, 24));
+ click(screen, sideTab(screen));
return false;
}
require(
@@ -302,6 +295,12 @@ static boolean run() {
return false;
}
+ private static Rect sideTab(MachineScreen screen) {
+ return screen.drawers().entries().stream().filter(
+ zone.moddev.mc.lib.gui.client.SideConfigDrawer.class::isInstance)
+ .findFirst().orElseThrow().tabBounds();
+ }
+
private static String describeClient(Minecraft mc) {
if (!(mc.screen instanceof MachineScreen screen))
return String.valueOf(mc.screen);
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/FluidOnlyMachineTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/FluidOnlyMachineTests.java
index a56e8ac8..2625ddd6 100644
--- a/src/companionTest/java/zone/moddev/mc/companion/test/FluidOnlyMachineTests.java
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/FluidOnlyMachineTests.java
@@ -24,13 +24,19 @@
@PrefixGameTestTemplate(false)
public final class FluidOnlyMachineTests {
private static DefinedMachineEntity place(GameTestHelper h, String name) {
+ return place(h, name, false);
+ }
+
+ private static DefinedMachineEntity place(GameTestHelper h, String name,
+ boolean upgraded) {
var id = ResourceLocation.parse("mmdlib_companion:test/" + name);
var pos = h.absolutePos(new BlockPos(2, 2, 2));
h.getLevel().setBlock(pos,
BuiltInRegistries.BLOCK.get(id).defaultBlockState(), 3);
var machine = (DefinedMachineEntity) h.getLevel().getBlockEntity(pos);
require(machine != null, "XML-only fixture registered and placed");
- require(machine.items.getSlots() == 0, "No dummy item slots");
+ require(machine.items.getSlots() == (upgraded ? 2 : 0),
+ "Only explicitly enabled component sockets are allocated");
require(h.getLevel().getCapability(Capabilities.ItemHandler.BLOCK, pos,
null) == null, "No empty item capability advertised");
var player = h.makeMockServerPlayerInLevel();
@@ -57,6 +63,26 @@ public static void fluidOnlyProcessorConsumesAndProducesFluid(
h.succeed();
}
+ @GameTest(template = "empty")
+ public static void fluidOnlyUpgradesDoNotAdvertiseAnItemCapability(
+ GameTestHelper h) {
+ var machine = place(h, "upgraded_fluid_still", true);
+ for (var side : net.minecraft.core.Direction.values())
+ require(
+ h.getLevel().getCapability(Capabilities.ItemHandler.BLOCK,
+ machine.getBlockPos(), side) == null,
+ "Component-only storage does not connect pipes on any face");
+ require(
+ h.getLevel().getCapability(Capabilities.FluidHandler.BLOCK,
+ machine.getBlockPos(), null) != null,
+ "Fluid capability remains available");
+ require(
+ h.getLevel().getCapability(Capabilities.EnergyStorage.BLOCK,
+ machine.getBlockPos(), null) != null,
+ "Energy capability remains available");
+ h.succeed();
+ }
+
@GameTest(template = "empty")
public static void tankNamesRemainTranslatableWithoutAutomation(
GameTestHelper h) {
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java
index 2d36d968..5839f923 100644
--- a/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java
@@ -27,6 +27,7 @@
import zone.moddev.mc.lib.machine.feature.RecipeProcessor;
import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity;
import zone.moddev.mc.lib.machine.neoforge.GeneratedMachineRecipes;
+import zone.moddev.mc.lib.machine.neoforge.MachineContent;
import zone.moddev.mc.lib.machine.neoforge.MachineRecipeTypes;
import zone.moddev.mc.lib.machine.recipe.MachineRecipe;
import zone.moddev.mc.lib.machine.recipe.MachineRecipeEntry;
@@ -114,11 +115,16 @@ public static void authoredRecipesValidateGroupsAndResourceKinds(
load(h, read(h, "mmdlib_companion:bad_recipe", json));
throw new AssertionError("Invalid authored recipe accepted");
} catch (IllegalArgumentException expected) {
+ // Several companion machines now share this recipe type; the
+ // first invalid consumer need not be the original crusher.
require(
- expected.getMessage()
- .contains("mmdlib_companion:bad_recipe")
- && expected.getMessage().contains(MACHINE.toString()),
- "Error identifies both recipe and machine");
+ MachineContent.definitions().values().stream()
+ .filter(machine -> machine.processes(TYPE))
+ .anyMatch(machine -> expected.getMessage()
+ .startsWith("Recipe mmdlib_companion:bad_recipe: "
+ + machine.id() + ": ")),
+ "Error identifies both recipe and an affected machine: "
+ + expected.getMessage());
}
}
require(load(h, read(h, "mmdlib_companion:valid_recipe", SINGLE))
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/PortingHooksTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/PortingHooksTests.java
new file mode 100644
index 00000000..b124cf09
--- /dev/null
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/PortingHooksTests.java
@@ -0,0 +1,491 @@
+package zone.moddev.mc.companion.test;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.core.registries.BuiltInRegistries;
+import net.minecraft.gametest.framework.GameTest;
+import net.minecraft.gametest.framework.GameTestHelper;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.Items;
+import net.minecraft.world.level.material.Fluids;
+
+import net.neoforged.neoforge.fluids.FluidStack;
+import net.neoforged.neoforge.fluids.capability.IFluidHandler.FluidAction;
+import net.neoforged.neoforge.gametest.GameTestHolder;
+import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;
+
+import zone.moddev.mc.companion.AdmissionDemo;
+import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity;
+
+@GameTestHolder("mmdlib_porting")
+@PrefixGameTestTemplate(false)
+public final class PortingHooksTests {
+ static DefinedMachineEntity place(GameTestHelper h, String name) {
+ var pos = h.absolutePos(new BlockPos(2, 2, 2));
+ h.getLevel().setBlock(pos,
+ BuiltInRegistries.BLOCK
+ .get(ResourceLocation.parse("mmdlib_companion:" + name))
+ .defaultBlockState(),
+ 3);
+ return (DefinedMachineEntity) h.getLevel().getBlockEntity(pos);
+ }
+
+ @GameTest(template = "empty")
+ public static void loadingRepairsInvalidFacingWithoutReplacingTheEntity(
+ GameTestHelper h) {
+ var machine = place(h, "facing_up");
+ machine.items.insertItem(0, new ItemStack(Items.DIAMOND, 3), false);
+ var property = net.minecraft.world.level.block.state.properties.BlockStateProperties.FACING;
+ h.getLevel().setBlock(machine.getBlockPos(),
+ machine.getBlockState().setValue(property,
+ net.minecraft.core.Direction.DOWN),
+ net.minecraft.world.level.block.Block.UPDATE_CLIENTS);
+ machine.onLoad();
+ h.assertTrue(machine.facing() == net.minecraft.core.Direction.UP,
+ "Load repairs disallowed facing");
+ h.assertTrue(
+ h.getLevel().getBlockEntity(machine.getBlockPos()) == machine
+ && machine.items.getStackInSlot(0).getCount() == 3,
+ "Facing repair preserves entity identity and inventory");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void keylessBindingsSelectTheDeclaredPrimary(
+ GameTestHelper h) {
+ var machine = place(h, "parallel_workshop");
+ var left = machine.features.processor("left").orElseThrow();
+ var right = machine.features.processor("right").orElseThrow();
+ machine.energy.setStored(10000);
+ machine.items.inventory("left_input").insertItem(0,
+ new ItemStack(Items.COBBLESTONE), false);
+ machine.serverTick();
+ left.tick(machine.features, 4);
+ h.assertTrue(left.progress() > 0 && right.progress() == 0,
+ "Primary recipe has distinct progress");
+ h.assertTrue(
+ machine.getProgress() == left.progress()
+ && machine.getTime() == left.time(),
+ "Keyless recipe getters use primary");
+ h.assertTrue(
+ machine.features.findProcessor(java.util.Optional.empty())
+ .orElseThrow() == left,
+ "Keyless controls select primary even after a custom processor");
+ left.setPaused(true);
+ h.assertTrue(machine.getPaused(),
+ "Keyless pause uses primary, not the preceding charge processor");
+ h.assertTrue(
+ machine.getProgress(0) == 0
+ && machine.getProgress(1) == left.progress(),
+ "Indexed bindings keep declaration order");
+ machine.features.primaryProcessor("right");
+ h.assertTrue(
+ machine.getProgress() == right.progress()
+ && machine.getTime() == right.time() && !machine.getPaused(),
+ "Selecting the second recipe lane changes every keyless getter");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void operatingCostIsAtomicAndTracksAcceleratedWork(
+ GameTestHelper h) {
+ var machine = place(h, "paid_workshop");
+ machine.energy.setStored(10000);
+ machine.items.inventory("left_input").insertItem(0,
+ new ItemStack(Items.COBBLESTONE), false);
+ machine.serverTick();
+ var lane = machine.features.processor("left").orElseThrow();
+ h.assertTrue(lane.progress() == 0 && machine.energy.stored() == 10000,
+ "Starting is free");
+ machine.energy.setStored(24);
+ machine.serverTick();
+ h.assertTrue(
+ lane.progress() == 0 && machine.energy.stored() == 24
+ && machine.energy.used().signum() == 0,
+ "Combined 20 recipe plus 5 operating FE cannot partially debit");
+ machine.energy.setStored(75);
+ lane.tick(machine.features, 2);
+ h.assertTrue(
+ lane.progress() == 2 && machine.energy.stored() == 25
+ && machine.energy.used().intValue() == 50,
+ "Accelerated steps each pay recipe plus operating cost");
+ lane.setPaused(true);
+ lane.tick(machine.features, 2);
+ h.assertTrue(machine.energy.stored() == 25 && lane.progress() == 2,
+ "Pause is free");
+ lane.setPaused(false);
+ machine.energy.setStored(10000);
+ lane.tick(machine.features, 98);
+ h.assertTrue(
+ machine.energy.stored() == 7550
+ && machine.energy.used().intValue() == 2500,
+ "Full cycle costs recipe 2000 plus operating 500");
+ h.assertTrue(machine.items.inventory("left_output").getStackInSlot(0)
+ .is(Items.GRAVEL), "Cycle completed");
+ lane.tick(machine.features, 5);
+ h.assertTrue(machine.energy.stored() == 7550, "Idle steps are free");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void blockedLastStepRollsBackOperatingAndRecipeEnergy(
+ GameTestHelper h) {
+ var machine = place(h, "paid_workshop");
+ machine.energy.setStored(10000);
+ machine.items.inventory("left_input").insertItem(0,
+ new ItemStack(Items.COBBLESTONE), false);
+ machine.serverTick();
+ var lane = machine.features.processor("left").orElseThrow();
+ lane.tick(machine.features, 99);
+ long before = machine.energy.stored();
+ var used = machine.energy.used();
+ machine.items.inventory("left_output").restoreStack(0,
+ new ItemStack(Items.DIRT, 64));
+ lane.tick(machine.features, 3);
+ h.assertTrue(
+ lane.progress() == 99 && machine.energy.stored() == before
+ && machine.energy.used().equals(used),
+ "Blocked final step rolls back both charges, progress and telemetry");
+ machine.items.inventory("left_output").restoreStack(0, ItemStack.EMPTY);
+ lane.tick(machine.features, 1);
+ h.assertTrue(
+ machine.energy.stored() == before - 25 && machine.items
+ .inventory("left_output").getStackInSlot(0).is(Items.GRAVEL),
+ "Unblocking charges only once");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void customProcessorOperatingCostRefundsFailedWork(
+ GameTestHelper h) {
+ var machine = place(h, "paid_workshop");
+ machine.fluids.fill(new FluidStack(Fluids.WATER, 10),
+ FluidAction.EXECUTE);
+ machine.energy.setStored(2);
+ machine.serverTick();
+ h.assertTrue(
+ machine.energy.stored() == 2
+ && machine.fluids.getFluidInTank(0).getAmount() == 10,
+ "Custom processor stalls before work without operating power");
+ machine.energy.setStored(3);
+ machine.serverTick();
+ h.assertTrue(
+ machine.energy.stored() == 100
+ && machine.fluids.getFluidInTank(0).getAmount() == 9
+ && machine.energy.used().intValue() == 3,
+ "Custom work pays overhead then produces energy");
+ machine.energy.setStored(machine.energy.capacity());
+ var used = machine.energy.used();
+ machine.serverTick();
+ h.assertTrue(
+ machine.energy.stored() == machine.energy.capacity()
+ && machine.energy.used().equals(used)
+ && machine.fluids.getFluidInTank(0).getAmount() == 9,
+ "Blocked custom work refunds overhead and telemetry");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void customEnergyHasOneOwnerAndLiveCapabilityPolicy(
+ GameTestHelper h) {
+ var machine = place(h, "battery_workshop");
+ var bank = machine.features.findProcessor("battery",
+ zone.moddev.mc.companion.BatteryBank.class).orElseThrow();
+ h.assertTrue(
+ bank.buffer() == machine.energy
+ && machine.screenEnergy() == machine.energy,
+ "Provider, recipes, persistence and screen share one buffer");
+ var capability = h.getLevel().getCapability(
+ net.neoforged.neoforge.capabilities.Capabilities.EnergyStorage.BLOCK,
+ machine.getBlockPos(), null);
+ h.assertTrue(
+ capability != null && capability.receiveEnergy(2000, true) == 2000,
+ "Custom capability simulates");
+ h.assertTrue(machine.energy.stored() == 0,
+ "Simulation leaves buffer empty");
+ capability.receiveEnergy(2000, false);
+ h.assertTrue(machine.resources().energy("energy").stored() == 2000,
+ "Transactions see capability input");
+ var east = h.getLevel().getCapability(
+ net.neoforged.neoforge.capabilities.Capabilities.EnergyStorage.BLOCK,
+ machine.getBlockPos(), net.minecraft.core.Direction.EAST);
+ h.assertTrue(east != null && east.receiveEnergy(100, false) == 0,
+ "Provider side policy enforced");
+ bank.setPaused(true);
+ h.assertTrue(
+ capability.extractEnergy(100, false) == 0
+ && capability.receiveEnergy(100, false) == 0,
+ "Cached view observes dynamic provider availability");
+ bank.setPaused(false);
+ h.assertTrue(capability.extractEnergy(100, false) == 100,
+ "Provider permits export");
+ capability.receiveEnergy(2000, false);
+ var saved = machine.saveWithFullMetadata(h.getLevel().registryAccess());
+ machine.energy.setStored(0);
+ machine.loadWithComponents(saved, h.getLevel().registryAccess());
+ h.assertTrue(capability.getEnergyStored() == 3900,
+ "Same capability sees restored authoritative energy");
+ machine.items.inventory("left_input").insertItem(0,
+ new ItemStack(Items.COBBLESTONE), false);
+ for (int tick = 0; tick < 102; tick++)
+ machine.serverTick();
+ h.assertTrue(
+ machine.items.inventory("left_output").getStackInSlot(0)
+ .is(Items.GRAVEL) && machine.energy.stored() == 1900,
+ "Recipe uses provider energy without a second buffer");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void callbacksKeepEveryAcceleratedTransition(
+ GameTestHelper h) {
+ var machine = place(h, "parallel_workshop");
+ machine.energy.setStored(100000);
+ machine.items.inventory("left_input").insertItem(0,
+ new ItemStack(Items.COBBLESTONE, 3), false);
+ machine.serverTick();
+ var lane = machine.features.processor("left").orElseThrow();
+ var observer = machine.features.findProcessor("charge").orElseThrow();
+ lane.tick(machine.features, 303);
+ h.assertTrue(
+ observer.variable("starts").equals(3)
+ && observer.variable("finishes").equals(3),
+ "Every start and finish delivered during one accelerated tick");
+ h.assertTrue(observer.variable("last_lane").equals("left"),
+ "Event identifies its lane");
+ var saved = machine.saveWithFullMetadata(h.getLevel().registryAccess());
+ machine.loadWithComponents(saved, h.getLevel().registryAccess());
+ machine.serverTick();
+ h.assertTrue(
+ observer.variable("starts").equals(3)
+ && observer.variable("finishes").equals(3),
+ "Loading and idle work do not replay callbacks");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void recipeLanesAndChargingRunTogether(GameTestHelper h) {
+ var machine = place(h, "parallel_workshop");
+ h.assertTrue(machine.features.allProcessors().size() == 3,
+ "Recipe and custom processors coexist");
+ machine.items.inventory("left_input").insertItem(0,
+ new ItemStack(Items.COBBLESTONE), false);
+ machine.items.inventory("right_input").insertItem(0,
+ new ItemStack(Items.GRAVEL), false);
+ machine.fluids.fill(new FluidStack(Fluids.WATER, 200),
+ FluidAction.EXECUTE);
+ for (int tick = 0; tick < 102; tick++)
+ machine.serverTick();
+ h.assertTrue(machine.items.inventory("left_output").getStackInSlot(0)
+ .is(Items.GRAVEL), "Left lane output");
+ h.assertTrue(machine.items.inventory("right_output").getStackInSlot(0)
+ .is(Items.SAND), "Right lane output");
+ h.assertTrue(machine.energy.stored() > 0,
+ "Charge pump supplies shared energy beside recipes");
+ var player = h.makeMockServerPlayerInLevel();
+ new zone.moddev.mc.lib.gui.runtime.MachineMenu(1, player.getInventory(),
+ machine);
+ var saved = machine.saveWithFullMetadata(h.getLevel().registryAccess());
+ machine.loadWithComponents(saved, h.getLevel().registryAccess());
+ h.assertTrue(
+ machine.features.processor("left").orElseThrow().completedCycles()
+ .intValue() == 1
+ && machine.features.processor("right").orElseThrow()
+ .completedCycles().intValue() == 1,
+ "Lanes persist independently");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void sharedInputCannotBeReservedTwice(GameTestHelper h) {
+ var machine = place(h, "shared_workshop");
+ machine.energy.setStored(10000);
+ machine.items.inventory("left_input").insertItem(0,
+ new ItemStack(Items.COBBLESTONE), false);
+ for (int tick = 0; tick < 105; tick++)
+ machine.serverTick();
+ int products = machine.items.inventory("left_output").getStackInSlot(0)
+ .getCount()
+ + machine.items.inventory("right_output").getStackInSlot(0)
+ .getCount();
+ h.assertTrue(products == 1,
+ "Two lanes sharing physical input produce only one result");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty", timeoutTicks = 60)
+ public static void comparatorsReadSharedSourcesWithoutEmittingFaces(
+ GameTestHelper h) {
+ var machine = place(h, "porting_workshop");
+ var origin = machine.getBlockPos();
+ var comparator = origin.east(2);
+ h.getLevel().setBlock(origin.east(),
+ net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(),
+ 3);
+ h.getLevel().setBlock(comparator.below(),
+ net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(),
+ 3);
+ h.getLevel().setBlock(comparator,
+ net.minecraft.world.level.block.Blocks.COMPARATOR
+ .defaultBlockState().setValue(
+ net.minecraft.world.level.block.state.properties.BlockStateProperties.HORIZONTAL_FACING,
+ net.minecraft.core.Direction.WEST),
+ 3);
+ machine.items.insertResult(1, new ItemStack(Items.STONE, 32), false);
+ machine.serverTick();
+ h.assertTrue(machine.getBlockState().hasAnalogOutputSignal(),
+ "XML block opts into comparator readout");
+ h.assertTrue(machine.getBlockState().getAnalogOutputSignal(h.getLevel(),
+ origin) == 7, "Readout samples existing source");
+ h.assertTrue(
+ machine.screenRedstone()
+ .signal(net.minecraft.core.Direction.WEST) == 0,
+ "No emitting face needed");
+ h.runAfterDelay(4, () -> {
+ var reader = (net.minecraft.world.level.block.entity.ComparatorBlockEntity) h
+ .getLevel().getBlockEntity(comparator);
+ h.assertTrue(reader.getOutputSignal() == 7,
+ "Comparator reads through a solid block");
+ machine.items.extractItem(1, 32, false);
+ machine.serverTick();
+ h.runAfterDelay(4, () -> {
+ h.assertTrue(reader.getOutputSignal() == 0,
+ "Storage change notifies comparator");
+ h.succeed();
+ });
+ });
+ }
+
+ @GameTest(template = "empty")
+ public static void placementHooksWaitForAcceptanceAndKeepOwner(
+ GameTestHelper h) {
+ var player = h.makeMockServerPlayerInLevel();
+ player.gameMode.changeGameModeForPlayer(
+ net.minecraft.world.level.GameType.CREATIVE);
+ var pos = h.absolutePos(new BlockPos(2, 2, 2));
+ player.setPos(
+ net.minecraft.world.phys.Vec3.atCenterOf(pos.offset(3, 0, 0)));
+ player.setShiftKeyDown(true);
+ h.getLevel().setBlock(pos.below(),
+ net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(),
+ 3);
+ var item = zone.moddev.mc.lib.machine.neoforge.MachineContent
+ .item(ResourceLocation.parse("mmdlib_companion:porting_workshop"));
+ var stack = new ItemStack(item);
+ player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND,
+ stack);
+ var hit = new net.minecraft.world.phys.BlockHitResult(
+ net.minecraft.world.phys.Vec3.atCenterOf(pos.below()),
+ net.minecraft.core.Direction.UP, pos.below(), false);
+ DefinedMachineEntity[] captured = {null};
+ java.util.function.Consumer cancel = event -> {
+ if (event.getEntity() == player && event.getPos().equals(pos)) {
+ captured[0] = (DefinedMachineEntity) h.getLevel()
+ .getBlockEntity(pos);
+ event.setCanceled(true);
+ }
+ };
+ net.neoforged.neoforge.common.NeoForge.EVENT_BUS.addListener(cancel);
+ try {
+ player.gameMode.useItemOn(player, h.getLevel(), stack,
+ net.minecraft.world.InteractionHand.MAIN_HAND, hit);
+ } finally {
+ net.neoforged.neoforge.common.NeoForge.EVENT_BUS.unregister(cancel);
+ }
+ h.assertTrue(captured[0] != null,
+ "Cancellation saw the candidate machine");
+ h.assertTrue(
+ captured[0].features.findProcessor("workshop").orElseThrow()
+ .variable("placements").equals(0),
+ "Rejected placement never calls placed");
+ player.gameMode.useItemOn(player, h.getLevel(), stack,
+ net.minecraft.world.InteractionHand.MAIN_HAND, hit);
+ var machine = (DefinedMachineEntity) h.getLevel().getBlockEntity(pos);
+ var processor = machine.features.findProcessor("workshop")
+ .orElseThrow();
+ h.assertTrue(machine.facing() == net.minecraft.core.Direction.UP,
+ "Custom placement chooses clicked face");
+ h.assertTrue(
+ processor.variable("owner").equals(player.getUUID().toString()),
+ "Placer ownership recorded");
+ machine.onLoad();
+ h.assertTrue(processor.variable("placements").equals(1),
+ "Loading does not replay placement");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void typedResourceTransactionsRollbackBlockedOutput(
+ GameTestHelper h) {
+ var machine = place(h, "porting_workshop");
+ machine.items.insertItem(0, new ItemStack(Items.COBBLESTONE, 2), false);
+ machine.fluids.fill(new FluidStack(Fluids.WATER, 100),
+ FluidAction.EXECUTE);
+ machine.items.insertResult(1, new ItemStack(Items.DIRT, 64), false);
+ machine.serverTick();
+ h.assertTrue(machine.items.getStackInSlot(0).getCount() == 2,
+ "Blocked output rolls back item input");
+ h.assertTrue(machine.fluids.getFluidInTank(0).getAmount() == 100,
+ "Blocked output rolls back fluid input");
+ machine.items.extractItem(1, 64, false);
+ machine.serverTick();
+ h.assertTrue(machine.items.getStackInSlot(1).is(Items.STONE),
+ "Custom processor inserts its product");
+ h.assertTrue(machine.items.getStackInSlot(0).getCount() == 1,
+ "One input consumed");
+ h.assertTrue(machine.fluids.getFluidInTank(0).getAmount() == 75,
+ "Fluid consumed in same transaction");
+ h.succeed();
+ }
+
+ @GameTest(template = "empty")
+ public static void admissionRulesRejectWrongInputsAndFollowConfig(
+ GameTestHelper h) {
+ var machine = place(h, "admission_demo");
+ h.assertTrue(machine.items
+ .insertItem(0, new ItemStack(Items.STONE), false).getCount() == 1,
+ "Fuel slot refuses nonfuel");
+ h.assertTrue(machine.items
+ .insertItem(0, new ItemStack(Items.COAL), true).isEmpty(),
+ "Fuel simulation accepts coal");
+ h.assertTrue(machine.items.getStackInSlot(0).isEmpty(),
+ "Simulation does not insert");
+ h.assertTrue(machine.items
+ .insertItem(1, new ItemStack(Items.RAW_IRON), false).isEmpty(),
+ "Smelting input accepted");
+ h.assertTrue(machine.items
+ .insertItem(2, new ItemStack(Items.STONE), false).getCount() == 1,
+ "Item tag enforced");
+ h.assertTrue(
+ !machine.fluids.isFluidValid(0, new FluidStack(Fluids.LAVA, 100)),
+ "Fluid tag enforced");
+ var old = AdmissionDemo.fuelTag;
+ try {
+ AdmissionDemo.fuelTag = ResourceLocation.parse("minecraft:lava");
+ h.assertTrue(
+ machine.fluids.isFluidValid(1,
+ new FluidStack(Fluids.LAVA, 100)),
+ "Configured tag accepts lava");
+ h.assertTrue(machine.fluids.fill(new FluidStack(Fluids.LAVA, 100),
+ FluidAction.EXECUTE) == 100, "Fuel inserted");
+ AdmissionDemo.fuelTag = ResourceLocation.parse("minecraft:water");
+ h.assertTrue(
+ !machine.fluids.isFluidValid(1,
+ new FluidStack(Fluids.LAVA, 100)),
+ "Live config changes admission");
+ h.assertTrue(machine.fluids.getFluidInTank(1).getAmount() == 100,
+ "Existing contents retained");
+ h.assertTrue(
+ machine.fluids.isFluidValid(2,
+ new FluidStack(Fluids.LAVA, 100)),
+ "Custom recipe lookup accepts recipe fluid");
+ h.assertTrue(
+ !machine.fluids.isFluidValid(2,
+ new FluidStack(Fluids.WATER, 100)),
+ "Recipe lookup rejects unrelated fluid");
+ } finally {
+ AdmissionDemo.fuelTag = old;
+ }
+ h.succeed();
+ }
+}
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/RedstoneClientSmoke.java b/src/companionTest/java/zone/moddev/mc/companion/test/RedstoneClientSmoke.java
index 7f11c130..3d04afaa 100644
--- a/src/companionTest/java/zone/moddev/mc/companion/test/RedstoneClientSmoke.java
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/RedstoneClientSmoke.java
@@ -217,8 +217,10 @@ static boolean run(MachineScreen screen) {
model.open() && !model.pending() && model.lower(0) == 4
&& model.upper(0) == 10,
"Escape cancels range preview");
- click(screen, new Rect(panel.right(), y, AutomationLayout.RAIL,
- AutomationLayout.TAB_HEIGHT), 0);
+ var sideTab = screen.drawers().entries().stream().filter(
+ zone.moddev.mc.lib.gui.client.SideConfigDrawer.class::isInstance)
+ .findFirst().orElseThrow().tabBounds();
+ click(screen, sideTab, 0);
}
case 14 -> {
if (!menu.components().get(BuiltinMenuComponents.AUTOMATION)
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/SimpleCrusherTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/SimpleCrusherTests.java
index 54525a9b..48a63725 100644
--- a/src/companionTest/java/zone/moddev/mc/companion/test/SimpleCrusherTests.java
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/SimpleCrusherTests.java
@@ -45,6 +45,44 @@ private static void require(boolean value, String message) {
throw new AssertionError(message);
}
+ @GameTest(template = "empty")
+ public static void gearboxClockAcceleratesRecipesAndRetainsCompletion(
+ GameTestHelper h) {
+ var machine = place(h);
+ machine.energy.setStored(10000);
+ machine.items.insertItem(0, new ItemStack(Items.IRON_ORE, 2), false);
+ var processor = machine.features.processors().getFirst();
+ // The same FeatureHost API is available to Java-defined machines with
+ // any number of processors.
+ var accelerated = new zone.moddev.mc.lib.machine.feature.FeatureHost(
+ machine::setChanged).gearboxes(() -> 8).add(processor);
+ accelerated.tick(h.getLevel()); // Select recipe, then run its first
+ // work tick.
+ require(processor.progress() == 1 && machine.energy.stored() == 9980,
+ "The shared clock runs recipe selection and work in two substeps");
+ accelerated.tick(h.getLevel());
+ require(processor.progress() == 3 && machine.energy.stored() == 9940,
+ "Two recipe work ticks consume twice the normal FE per game tick");
+ for (int tick = 2; tick < 66; tick++)
+ accelerated.tick(h.getLevel());
+ require(
+ processor.completedCycles().intValueExact() == 1
+ && processor.justFinished().isPresent()
+ && machine.items.getStackInSlot(1).getCount() == 2
+ && machine.energy.stored() == 7400,
+ "Finishing in the first substep retains completion events while the second starts the next cycle");
+ processor.setPaused(true);
+ accelerated.tick(h.getLevel());
+ require(machine.energy.stored() == 7400,
+ "Pause consumes no extra recipe energy");
+ processor.setPaused(false);
+ machine.energy.setStored(20);
+ accelerated.tick(h.getLevel());
+ require(machine.energy.stored() == 0,
+ "The second recipe substep cannot draw unpaid energy");
+ h.succeed();
+ }
+
@GameTest(template = "empty")
public static void generatedRecipesDriveAClasslessCrusher(
GameTestHelper h) {
@@ -87,7 +125,7 @@ public static void capabilitiesSaveAndReservationsUseInheritedStorage(
pos, Direction.NORTH);
var power = h.getLevel().getCapability(Capabilities.EnergyStorage.BLOCK,
pos, Direction.NORTH);
- require(items != null && items.getSlots() == 3 && power != null,
+ require(items != null && items.getSlots() == 5 && power != null,
"Capabilities registered automatically");
require(items.insertItem(1, new ItemStack(Items.IRON_ORE), false)
.getCount() == 1, "Outputs refuse automation insertion");
diff --git a/src/companionTest/resources/data/mmdlib_porting/structure/empty.nbt b/src/companionTest/resources/data/mmdlib_porting/structure/empty.nbt
new file mode 100644
index 00000000..0a144900
Binary files /dev/null and b/src/companionTest/resources/data/mmdlib_porting/structure/empty.nbt differ
diff --git a/src/companionTest/resources/mmdlib/machine/test/upgraded_fluid_still.xml b/src/companionTest/resources/mmdlib/machine/test/upgraded_fluid_still.xml
new file mode 100644
index 00000000..683cda62
--- /dev/null
+++ b/src/companionTest/resources/mmdlib/machine/test/upgraded_fluid_still.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
diff --git a/src/main/java/zone/moddev/mc/lib/MMDLib.java b/src/main/java/zone/moddev/mc/lib/MMDLib.java
index e669a21c..ae184843 100644
--- a/src/main/java/zone/moddev/mc/lib/MMDLib.java
+++ b/src/main/java/zone/moddev/mc/lib/MMDLib.java
@@ -68,6 +68,17 @@ public class MMDLib {
*/
public static final DeferredRegister- ITEMS = DeferredRegister
.create(Registries.ITEM, MODID);
+ public static final net.neoforged.neoforge.registries.DeferredHolder
- GEARBOX_UPGRADE = ITEMS
+ .register("gearbox_upgrade",
+ zone.moddev.mc.lib.common.item.GearboxUpgradeItem::new);
+
+ public static final net.neoforged.neoforge.registries.DeferredHolder
- CAPACITOR_UPGRADE = ITEMS
+ .register("capacitor_upgrade",
+ zone.moddev.mc.lib.common.item.CapacitorUpgradeItem::new);
+
+ public static final net.neoforged.neoforge.registries.DeferredHolder
- RANGE_UPGRADE = ITEMS
+ .register("range_upgrade",
+ zone.moddev.mc.lib.common.item.RangeUpgradeItem::new);
private final zone.moddev.mc.lib.common.runtime.RuntimeContentRegistrar runtime;
private final DeferredRegister
> machineTypes = DeferredRegister
diff --git a/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java b/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java
index 695c292a..5832350f 100644
--- a/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java
+++ b/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java
@@ -550,12 +550,24 @@ public record BlockAction(Level level, BlockPos position, BlockState state,
* @param machineId the machine definition's ID
* @param recipe the cycle's recipe
* @param time the cycle's length, in ticks
+ * @param processor the stable processor ID, empty for legacy Java callers
*/
public record MachineCycle(
net.minecraft.world.level.block.entity.BlockEntity machine,
ServerLevel level, BlockPos position,
net.minecraft.resources.ResourceLocation machineId,
- net.minecraft.resources.ResourceLocation recipe, int time) {
+ net.minecraft.resources.ResourceLocation recipe, int time,
+ String processor) {
+ /**
+ * Compatibility constructor for callers without a processor identity.
+ */
+ public MachineCycle(
+ net.minecraft.world.level.block.entity.BlockEntity machine,
+ ServerLevel level, BlockPos position,
+ net.minecraft.resources.ResourceLocation machineId,
+ net.minecraft.resources.ResourceLocation recipe, int time) {
+ this(machine, level, position, machineId, recipe, time, "");
+ }
/** Requires every value. */
public MachineCycle {
Objects.requireNonNull(machine);
@@ -563,6 +575,7 @@ public record MachineCycle(
position = Objects.requireNonNull(position).immutable();
Objects.requireNonNull(machineId);
Objects.requireNonNull(recipe);
+ Objects.requireNonNull(processor);
}
}
}
diff --git a/src/main/java/zone/moddev/mc/lib/api/capabilities/EnergyBuffer.java b/src/main/java/zone/moddev/mc/lib/api/capabilities/EnergyBuffer.java
index 38644c1f..46f8ecd7 100644
--- a/src/main/java/zone/moddev/mc/lib/api/capabilities/EnergyBuffer.java
+++ b/src/main/java/zone/moddev/mc/lib/api/capabilities/EnergyBuffer.java
@@ -99,12 +99,9 @@ public Runnable checkpoint() {
/**
* An empty buffer. Negative values are treated as zero.
*
- * @param capacity
- * the most energy it holds
- * @param maxInsert
- * the most automation may insert per call
- * @param maxExtract
- * the most automation may extract per call
+ * @param capacity the most energy it holds
+ * @param maxInsert the most automation may insert per call
+ * @param maxExtract the most automation may extract per call
*/
public EnergyBuffer(long capacity, long maxInsert, long maxExtract) {
this.capacity = Math.max(0, capacity);
@@ -167,8 +164,14 @@ public void setCapacity(long capacity) {
* {@link #extract} ignore them.
*/
public void setRates(long maxInsert, long maxExtract) {
- this.maxInsert = Math.max(0, maxInsert);
- this.maxExtract = Math.max(0, maxExtract);
+ long input = Math.max(0, maxInsert);
+ long output = Math.max(0, maxExtract);
+ if (this.maxInsert == input && this.maxExtract == output)
+ return;
+ this.maxInsert = input;
+ this.maxExtract = output;
+ changes.changed();
+ onChange.run();
}
/**
diff --git a/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemInventories.java b/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemInventories.java
index a2afe994..4d98a647 100644
--- a/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemInventories.java
+++ b/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemInventories.java
@@ -37,6 +37,26 @@ public record Address(String inventory, int slot) {
private final List addresses;
private final Map indexes;
private ListTag recovery = new ListTag();
+ private final Map> legacyLayouts = new HashMap<>();
+
+ /**
+ * Explicit old named-inventory layout, applied only when its saved size
+ * matches.
+ */
+ public ItemInventories migrateLayout(String inventory,
+ List targets) {
+ if (targets.isEmpty()
+ || targets.stream().anyMatch(target -> !indexes.containsKey(target))
+ || targets.stream().distinct().count() != targets.size()
+ || (inventories.containsKey(inventory)
+ && inventories.get(inventory).getSlots() == targets.size()))
+ throw new IllegalArgumentException(
+ "Migration must identify a distinct old layout and unique current slots");
+ if (legacyLayouts.putIfAbsent(inventory, List.copyOf(targets)) != null)
+ throw new IllegalArgumentException(
+ "Duplicate inventory migration: " + inventory);
+ return this;
+ }
public ItemInventories(Map inventories) {
this(inventories, inventories.entrySet().stream()
@@ -306,11 +326,26 @@ public void deserializeNBT(HolderLookup.Provider registries,
var named = tag.getCompound("Inventories");
for (String name : named.getAllKeys()) {
var saved = named.getCompound(name);
+ var layout = legacyLayouts.get(name);
+ boolean migrate = layout != null
+ && saved.getInt("Size") == layout.size();
var values = saved.getList("Items", Tag.TAG_COMPOUND).copy();
values.addAll(saved.getList("Recovery", Tag.TAG_COMPOUND).copy());
for (var value : values) {
var entry = (CompoundTag) value;
int local = entry.getInt("Slot");
+ if (migrate && local >= 0 && local < layout.size()
+ && (!entry.contains("SlotId") || entry.getString("SlotId")
+ .equals(name + "/" + local))) {
+ var target = layout.get(local);
+ entry.putInt("Slot",
+ index(target.inventory(), target.slot()));
+ entry.putString("SlotId",
+ target.inventory() + "::" + inventories
+ .get(target.inventory()).slotId(target.slot()));
+ entries.add(entry);
+ continue;
+ }
int current = index(name, local);
entry.putInt("Slot", current);
entry.putString("SlotId",
diff --git a/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java b/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java
index e7cab99b..6555844e 100644
--- a/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java
+++ b/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java
@@ -48,6 +48,28 @@ public enum Mode {
// neighbours.
private int connections = -1;
private boolean paused, legacyAny;
+ private int comparatorSource = -1;
+ private int comparatorLevel;
+
+ /**
+ * Machine-owned selection; independent of per-face settings and inversion.
+ */
+ public RedstoneControl comparatorSource(String id) {
+ comparatorSource = -1;
+ if (id != null) {
+ for (int i = 0; i < outputs.size(); i++)
+ if (outputs.get(i).id().equals(id))
+ comparatorSource = i;
+ if (comparatorSource < 0)
+ throw new IllegalArgumentException(
+ "Unknown comparator source: " + id);
+ }
+ return this;
+ }
+
+ public int comparatorLevel() {
+ return comparatorLevel;
+ }
public RedstoneControl(BlockEntity owner, List> groups,
ToDoubleFunction> fullness) {
@@ -295,6 +317,21 @@ public void updateOutputs() {
outputsChanged |= outgoing[face] != output;
outgoing[face] = output;
}
+ int nextComparator = 0;
+ if (comparatorSource >= 0) {
+ int face = 0;
+ while (face < 6 && (mode(face) != Mode.EMIT
+ || source(face) != comparatorSource))
+ face++;
+ nextComparator = face < 6
+ ? sampledLevels[face]
+ : outputs.get(comparatorSource).level();
+ }
+ if (nextComparator != comparatorLevel) {
+ comparatorLevel = nextComparator;
+ level.updateNeighbourForOutputSignal(owner.getBlockPos(),
+ owner.getBlockState().getBlock());
+ }
if (connections != newConnections) {
boolean firstTick = connections < 0;
connections = newConnections;
diff --git a/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java b/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java
index 91b66701..2ccac731 100644
--- a/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java
+++ b/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java
@@ -18,32 +18,44 @@
* is gone.
*/
public final class MachineSoundsClient {
- private static final Map LOOPS = new WeakHashMap<>();
+ private static final Map> LOOPS = new WeakHashMap<>();
private MachineSoundsClient() {
}
/** Starts {@code machine}'s loop if a cycle runs and it is not playing. */
public static void tick(DefinedMachineEntity machine) {
- var id = machine.definition.sounds().running().orElse(null);
- if (id == null || !machine.running())
- return;
- var loop = LOOPS.get(machine);
- if (loop != null && !loop.isStopped())
- return;
- loop = new Loop(machine, id);
- LOOPS.put(machine, loop);
- Minecraft.getInstance().getSoundManager().play(loop);
+ for (var config : machine.processorConfigurations()) {
+ var id = config.sounds().running().orElse(null);
+ if (id == null || !running(machine, config.id()))
+ continue;
+ var loops = LOOPS.computeIfAbsent(machine,
+ ignored -> new java.util.HashMap<>());
+ var loop = loops.get(config.id());
+ if (loop != null && !loop.isStopped())
+ continue;
+ loop = new Loop(machine, config.id(), id);
+ loops.put(config.id(), loop);
+ Minecraft.getInstance().getSoundManager().play(loop);
+ }
+ }
+
+ private static boolean running(DefinedMachineEntity machine, String key) {
+ return machine.features.findProcessor(key)
+ .map(zone.moddev.mc.lib.machine.feature.Processor::processing)
+ .orElse(false);
}
private static final class Loop extends AbstractTickableSoundInstance {
private final DefinedMachineEntity machine;
+ private final String processor;
- Loop(DefinedMachineEntity machine,
+ Loop(DefinedMachineEntity machine, String processor,
net.minecraft.resources.ResourceLocation id) {
super(SoundDefinition.event(id), SoundSource.BLOCKS,
RandomSource.create());
this.machine = machine;
+ this.processor = processor;
var pos = machine.getBlockPos();
x = pos.getX() + .5;
y = pos.getY() + .5;
@@ -55,7 +67,7 @@ private static final class Loop extends AbstractTickableSoundInstance {
@Override
public void tick() {
- if (machine.isRemoved() || !machine.running())
+ if (machine.isRemoved() || !running(machine, processor))
stop();
}
}
diff --git a/src/main/java/zone/moddev/mc/lib/client/MachineWorkDisplay.java b/src/main/java/zone/moddev/mc/lib/client/MachineWorkDisplay.java
new file mode 100644
index 00000000..30476755
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/client/MachineWorkDisplay.java
@@ -0,0 +1,73 @@
+package zone.moddev.mc.lib.client;
+
+import java.util.List;
+
+import net.minecraft.client.Minecraft;
+import net.minecraft.core.BlockPos;
+import net.minecraft.core.particles.DustParticleOptions;
+import net.minecraft.world.level.block.entity.BlockEntity;
+
+import org.joml.Vector3f;
+
+/**
+ * Lightweight particles on active target blocks, independent of any open
+ * screen.
+ */
+public final class MachineWorkDisplay {
+ private MachineWorkDisplay() {
+ }
+
+ /**
+ * Call once per client machine tick with a synchronized target snapshot.
+ */
+ public static void tick(BlockEntity machine, List targets,
+ int color) {
+ var client = Minecraft.getInstance();
+ var level = client.level;
+ if (level == null || level != machine.getLevel() || machine.isRemoved()
+ || client.isPaused() || targets.isEmpty())
+ return;
+ long tick = level.getGameTime();
+ // Spread machines over two ticks and bound the denser column effect.
+ if (Math.floorMod(tick + machine.getBlockPos().asLong(), 2) != 0)
+ return;
+ var camera = client.gameRenderer.getMainCamera().getPosition();
+ var particle = new DustParticleOptions(
+ new Vector3f(((color >> 16) & 255) / 255f,
+ ((color >> 8) & 255) / 255f, (color & 255) / 255f),
+ .35f);
+ int levels = switch (client.options.particles().get()) {
+ case ALL -> 9;
+ case DECREASED -> 5;
+ case MINIMAL -> 3;
+ };
+ int count = Math.min(targets.size(), 4);
+ int start = (int) Math.floorMod(tick / 2 * 4, targets.size());
+ for (int i = 0; i < count; i++) {
+ var target = targets.get((start + i) % targets.size());
+ if (!level.hasChunkAt(target)
+ || target.distToCenterSqr(camera) > 64 * 64)
+ continue;
+ var shape = level.getBlockState(target).getShape(level, target);
+ double baseY = target.getY() + .05
+ + (shape.isEmpty()
+ ? 0
+ : shape.max(net.minecraft.core.Direction.Axis.Y));
+ // Two opposing helices rotate around the block center. Short-lived
+ // dust leaves a visible trail without filling in a static cylinder.
+ for (int sample = 0; sample < levels; sample++) {
+ double progress = sample / (double) (levels - 1);
+ double angle = tick * .22 + progress * Math.PI * 2;
+ for (int strand = 0; strand < 2; strand++) {
+ double phase = angle + strand * Math.PI;
+ var spark = client.particleEngine.createParticle(particle,
+ target.getX() + .5 + Math.cos(phase) * .20,
+ baseY + progress * 1.5,
+ target.getZ() + .5 + Math.sin(phase) * .20, 0, 0, 0);
+ if (spark != null)
+ spark.setLifetime(6);
+ }
+ }
+ }
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java b/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java
index 15ea9198..56bb716e 100644
--- a/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java
+++ b/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java
@@ -101,7 +101,7 @@ public void registerRecipeCatalysts(
IRecipeCatalystRegistration registration) {
zone.moddev.mc.lib.machine.neoforge.MachineContent.definitions()
.forEach(
- (id, machine) -> machine.processingType().ifPresent(type -> {
+ (id, machine) -> machine.processingTypes().forEach(type -> {
registration.addRecipeCatalyst(
new net.minecraft.world.item.ItemStack(
BuiltInRegistries.ITEM.get(id)),
diff --git a/src/main/java/zone/moddev/mc/lib/common/item/CapacitorUpgradeItem.java b/src/main/java/zone/moddev/mc/lib/common/item/CapacitorUpgradeItem.java
new file mode 100644
index 00000000..dc0d18de
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/common/item/CapacitorUpgradeItem.java
@@ -0,0 +1,30 @@
+package zone.moddev.mc.lib.common.item;
+
+import java.util.List;
+
+import net.minecraft.ChatFormatting;
+import net.minecraft.network.chat.Component;
+import net.minecraft.world.item.Item;
+import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.TooltipFlag;
+
+/** Permanent energy capacity and transfer upgrade. */
+public class CapacitorUpgradeItem extends Item {
+ public static final int MAX_UPGRADES = 8;
+
+ public CapacitorUpgradeItem() {
+ super(new Properties().stacksTo(MAX_UPGRADES));
+ }
+
+ @Override
+ public void appendHoverText(ItemStack stack, TooltipContext context,
+ List tooltip, TooltipFlag flag) {
+ super.appendHoverText(stack, context, tooltip, flag);
+ tooltip
+ .add(Component.translatable("item.mmdlib.capacitor_upgrade.effect")
+ .withStyle(ChatFormatting.GRAY));
+ tooltip
+ .add(Component.translatable("item.mmdlib.capacitor_upgrade.limit")
+ .withStyle(ChatFormatting.GRAY));
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/common/item/GearboxUpgradeItem.java b/src/main/java/zone/moddev/mc/lib/common/item/GearboxUpgradeItem.java
new file mode 100644
index 00000000..51931117
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/common/item/GearboxUpgradeItem.java
@@ -0,0 +1,28 @@
+package zone.moddev.mc.lib.common.item;
+
+import java.util.List;
+
+import net.minecraft.ChatFormatting;
+import net.minecraft.network.chat.Component;
+import net.minecraft.world.item.Item;
+import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.TooltipFlag;
+
+/** Permanent processor acceleration, in eighths of the base rate. */
+public class GearboxUpgradeItem extends Item {
+ public static final int MAX_UPGRADES = 8;
+
+ public GearboxUpgradeItem() {
+ super(new Properties().stacksTo(MAX_UPGRADES));
+ }
+
+ @Override
+ public void appendHoverText(ItemStack stack, TooltipContext context,
+ List tooltip, TooltipFlag flag) {
+ super.appendHoverText(stack, context, tooltip, flag);
+ tooltip.add(Component.translatable("item.mmdlib.gearbox_upgrade.effect")
+ .withStyle(ChatFormatting.GRAY));
+ tooltip.add(Component.translatable("item.mmdlib.gearbox_upgrade.limit")
+ .withStyle(ChatFormatting.GRAY));
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/common/item/RangeUpgradeItem.java b/src/main/java/zone/moddev/mc/lib/common/item/RangeUpgradeItem.java
new file mode 100644
index 00000000..9fa91bfa
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/common/item/RangeUpgradeItem.java
@@ -0,0 +1,29 @@
+package zone.moddev.mc.lib.common.item;
+
+import java.util.List;
+
+import net.minecraft.ChatFormatting;
+import net.minecraft.network.chat.Component;
+import net.minecraft.world.item.Item;
+import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.TooltipFlag;
+
+/**
+ * Permanent range module; installed sockets, not stack counts, determine its
+ * effect.
+ */
+public class RangeUpgradeItem extends Item {
+ public RangeUpgradeItem() {
+ super(new Properties());
+ }
+
+ @Override
+ public void appendHoverText(ItemStack stack, TooltipContext context,
+ List tooltip, TooltipFlag flag) {
+ super.appendHoverText(stack, context, tooltip, flag);
+ tooltip.add(Component.translatable("item.mmdlib.range_upgrade.effect")
+ .withStyle(ChatFormatting.GRAY));
+ tooltip.add(Component.translatable("item.mmdlib.range_upgrade.limit")
+ .withStyle(ChatFormatting.GRAY));
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/BuiltinElementClients.java b/src/main/java/zone/moddev/mc/lib/gui/client/BuiltinElementClients.java
index 3a5a6049..63e2e383 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/BuiltinElementClients.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/BuiltinElementClients.java
@@ -88,7 +88,16 @@ private static List> declarations() {
}), ElementClient.of(INVENTORY_CONTROLS).renderer((element, c) -> {
}), ElementClient.of(PLAYER_SLOTS).renderer((element, c) -> {
}), ElementClient.of(INVENTORY).renderer((element, c) -> {
- }),
+ }).renderer(ElementRenderers.Pass.OVERLAY,
+ ElementRenderers.Clip.ELEMENT, (element, c) -> element
+ .selectedSlot(c.value()).ifPresent(slot -> {
+ if (!c.access().visible(slot))
+ return;
+ var bounds = c.access().bounds(slot);
+ c.graphics().renderOutline(bounds.x(), bounds.y(),
+ bounds.width(), bounds.height(),
+ element.selectionColor());
+ })),
ElementClient.of(CONTAINER_INVENTORY)
.renderer(ContainerCellRenderer::inventory),
ElementClient.of(CONTAINER_SLOT)
@@ -104,8 +113,16 @@ private static List> declarations() {
.behavior(ContextBehavior::new),
ElementClient.of(SIDE_TAB)
.renderer(ContainerElementRenderer::sideTab),
+ ElementClient
+ .of(zone.moddev.mc.lib.gui.load.BuiltinElements.UPGRADES_DRAWER)
+ .renderer(ElementRenderers.Pass.BACKGROUND,
+ ElementRenderers.Clip.VIEWPORT, UpgradesDrawer::render),
ElementClient.of(BUTTON_CONTROL).renderer(ButtonRenderer::draw)
.behavior(ButtonBehavior::new),
+ ElementClient.of(
+ zone.moddev.mc.lib.gui.load.BuiltinElements.WORKING_AREA_BUTTON)
+ .renderer(WorkingAreaButtonBehavior::render)
+ .behavior(WorkingAreaButtonBehavior::new),
ElementClient.of(LABEL).renderer(TextControlRenderer::label),
ElementClient
.of(zone.moddev.mc.lib.gui.load.BuiltinElements.ENTITY_PORTRAIT)
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ContainerDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/ContainerDrawer.java
index f8a7a45d..c15d9704 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/ContainerDrawer.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/ContainerDrawer.java
@@ -168,7 +168,7 @@ private void layout() {
? menu.state().sizes().get(menu.state().selected())
: 0;
layout = ContainerDrawerLayout.of(screen.panelBounds(),
- screen.drawerBottom(), slots, super.tabBounds(),
+ screen.drawerBottom(), slots, allocatedTabBounds(),
menu.policy().layout(), edge(), screen.width);
}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java
index 16eeb072..76e00428 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java
@@ -9,9 +9,10 @@
import zone.moddev.mc.lib.gui.model.Edge;
/**
- * Client-owned drawer behavior. Subclasses supply their appearance, geometry,
- * content, input and preference restoration. The screen dispatches these hooks
- * without knowing the drawer's type.
+ * Client-owned drawer behavior. Subclasses supply appearance, content sizing,
+ * input and preference restoration. Standard body geometry comes from
+ * contentBounds and SideDrawerLayout; the screen dispatches hooks without
+ * knowing the drawer's type.
*/
public abstract class Drawer {
protected final MachineScreen screen;
@@ -93,6 +94,11 @@ public boolean pending() {
public abstract boolean open();
public Rect tabBounds() {
+ return allocatedTabBounds();
+ }
+
+ /** Layout-safe tab lookup that never dispatches into a subclass. */
+ protected final Rect allocatedTabBounds() {
return screen.drawers().tabBounds(this);
}
@@ -154,6 +160,16 @@ protected final void drawFrame(GuiGraphics graphics, Rect tab, Rect body,
drawIcon(graphics, tab);
}
+ /** Shared panel-top placement for standard drawer content. */
+ protected final Rect contentBounds(int width, int height,
+ zone.moddev.mc.lib.gui.layout.SideDrawerLayout.HeightLimit limit) {
+ return zone.moddev.mc.lib.gui.layout.SideDrawerLayout.topBody(
+ screen.panelBounds(), screen.drawerBottom(), edge(),
+ // tabBounds() may invoke a subclass layout that calls this method.
+ // The registry owns the allocated rectangle and needs no layout.
+ allocatedTabBounds(), width, height, limit);
+ }
+
protected void drawIcon(GuiGraphics graphics, Rect tab) {
iconSprite().draw(graphics, tab.x() + 3, tab.y() + 4);
}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/DrawerFactories.java b/src/main/java/zone/moddev/mc/lib/gui/client/DrawerFactories.java
index 7f7e553a..ea895e6f 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/DrawerFactories.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/DrawerFactories.java
@@ -26,6 +26,7 @@ public final class DrawerFactories {
public static DrawerFactories builtins() {
var registry = new DrawerFactories();
registry.register(BuiltinDrawers.STATS, StatsDrawer::new);
+ registry.register(BuiltinDrawers.UPGRADES, UpgradesDrawer::new);
registry.register(BuiltinDrawers.BACKPACK, (screen,
definition) -> new ContainerDrawer(screen, definition, false));
registry.register(BuiltinDrawers.CURIOS, (screen,
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/PopoutDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/PopoutDrawer.java
index c3164ef4..85fb419b 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/PopoutDrawer.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/PopoutDrawer.java
@@ -97,10 +97,7 @@ private Rect body() {
int width = bodyWidth();
int top = SideDrawerLayout.top(screen.panelBounds());
int height = Math.max(tab.bottom() - top, lines().size() * 10 + 12);
- return SideDrawerLayout.body(screen.panelBounds(),
- screen.drawerBottom(),
- edge() == Edge.LEFT ? tab.x() - width : tab.right(), top, width,
- height);
+ return contentBounds(width, height, SideDrawerLayout.HeightLimit.PANEL);
}
public Optional presentation(Class type) {
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/RedstoneDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/RedstoneDrawer.java
index ffa6ee0d..bfb4e00b 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/RedstoneDrawer.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/RedstoneDrawer.java
@@ -17,7 +17,6 @@
import zone.moddev.mc.lib.api.capabilities.RelativeFace;
import zone.moddev.mc.lib.api.redstone.RedstoneControl;
-import zone.moddev.mc.lib.gui.layout.AutomationLayout;
import zone.moddev.mc.lib.gui.layout.Rect;
import zone.moddev.mc.lib.gui.layout.RedstoneLayout;
import zone.moddev.mc.lib.gui.layout.SideDrawerLayout;
@@ -67,14 +66,11 @@ void layout() {
if (sliderHandle >= 0 && (!model.faceAvailable(sliderFace)
|| model.revision() != sliderRevision))
sliderHandle = -1;
- var panel = screen.panelBounds();
tab = super.tabBounds();
if (!model.open())
return;
int height = contentHeight();
- body = SideDrawerLayout.body(panel, screen.drawerBottom(),
- SideDrawerLayout.bodyX(edge(), tab, RedstoneLayout.WIDTH),
- panel.y() + AutomationLayout.TOP, RedstoneLayout.WIDTH, height,
+ body = contentBounds(RedstoneLayout.WIDTH, height,
SideDrawerLayout.HeightLimit.SCREEN);
editorScroll = Math.clamp(editorScroll, 0,
Math.max(0, height - body.height()));
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java
index a6cd56d1..d8b2e064 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java
@@ -162,9 +162,8 @@ public void layout() {
AutomationLayout.EDITOR_Y + editorHeight
+ AutomationLayout.PADDING)
: baseHeight;
- body = SideDrawerLayout.body(panel, screen.drawerBottom(),
- SideDrawerLayout.bodyX(edge(), tab, WIDTH), tab.y(), WIDTH,
- desiredHeight, SideDrawerLayout.HeightLimit.SCREEN);
+ body = contentBounds(WIDTH, desiredHeight,
+ SideDrawerLayout.HeightLimit.SCREEN);
model.position(body.x() - panel.x(), body.y() - panel.y());
syncSlots();
int shown = Math.max(1,
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/StatsDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/StatsDrawer.java
index 4a69db7c..ea8593cb 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/StatsDrawer.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/StatsDrawer.java
@@ -10,7 +10,6 @@
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.FormattedCharSequence;
-import zone.moddev.mc.lib.gui.layout.AutomationLayout;
import zone.moddev.mc.lib.gui.layout.Rect;
import zone.moddev.mc.lib.gui.layout.SideDrawerLayout;
import zone.moddev.mc.lib.gui.runtime.StatsPage;
@@ -96,7 +95,6 @@ private void updatePage() {
void layout() {
updatePage();
- var panel = screen.panelBounds();
tab = super.tabBounds();
if (!open)
return;
@@ -117,9 +115,7 @@ void layout() {
.stream())
.toList();
}
- body = SideDrawerLayout.body(panel, screen.drawerBottom(),
- SideDrawerLayout.bodyX(edge(), tab, width),
- panel.y() + AutomationLayout.TOP, width, 28 + lines.size() * 9,
+ body = contentBounds(width, 28 + lines.size() * 9,
SideDrawerLayout.HeightLimit.SCREEN);
scroll = Math.clamp(scroll, 0,
Math.max(0, lines.size() * 9 - Math.max(0, body.height() - 28)));
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/UpgradesDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/UpgradesDrawer.java
new file mode 100644
index 00000000..bf0e1907
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/UpgradesDrawer.java
@@ -0,0 +1,111 @@
+package zone.moddev.mc.lib.gui.client;
+
+import java.util.List;
+
+import net.minecraft.client.gui.GuiGraphics;
+import net.minecraft.network.chat.Component;
+import net.minecraft.resources.ResourceLocation;
+
+import zone.moddev.mc.lib.gui.drawer.DrawerDefinition;
+import zone.moddev.mc.lib.gui.layout.Rect;
+import zone.moddev.mc.lib.gui.layout.SideDrawerLayout;
+import zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement;
+
+/** Upgrade inventory drawer using ordinary native slots and element actions. */
+public class UpgradesDrawer extends Drawer {
+ private final UpgradesDrawerElement element;
+ public UpgradesDrawer(MachineScreen screen, DrawerDefinition definition) {
+ super(screen, definition,
+ IconSprite.gui(ResourceLocation.parse("mmdlib:icon_upgrades")),
+ 0xf0cd82);
+ element = (UpgradesDrawerElement) definition.element().orElseThrow();
+ }
+ public boolean open() {
+ return screen.getMenu().elementStates().get(element,
+ UpgradesDrawerElement.OPEN);
+ }
+ public boolean pending() {
+ return screen.getMenu().elementPending(element);
+ }
+ private boolean setOpen(boolean value) {
+ return !pending() && screen.submitElementAction(element,
+ UpgradesDrawerElement.SET_OPEN, value);
+ }
+ public void close() {
+ if (open())
+ setOpen(false);
+ }
+ public void closeLocal() {
+ }
+ public boolean restore(Selection selection) {
+ if (pending())
+ return false;
+ if (!open()) {
+ setOpen(true);
+ return false;
+ }
+ activated();
+ return true;
+ }
+ public Rect bodyBounds() {
+ var size = element
+ .bodySize(text -> net.minecraft.client.Minecraft.getInstance().font
+ .width(ScreenText.component(text)));
+ return contentBounds(size[0], size[1],
+ SideDrawerLayout.HeightLimit.SCREEN);
+ }
+ public record Presentation(Rect body, int colour) {
+ }
+ @Override
+ public java.util.Optional presentation(Class type) {
+ return type == Presentation.class
+ ? java.util.Optional
+ .of(type.cast(new Presentation(bodyBounds(), colour())))
+ : super.presentation(type);
+ }
+ public boolean contains(double x, double y) {
+ return tabContains(x, y)
+ || open() && (bodyBounds().contains(x, y) || SideDrawerLayout
+ .rail(allocatedTabBounds(), bodyBounds()).contains(x, y));
+ }
+ public List exclusions() {
+ return open()
+ ? List.of(tabBounds(), bodyBounds(),
+ SideDrawerLayout.rail(allocatedTabBounds(), bodyBounds()))
+ : List.of(tabBounds());
+ }
+ public boolean click(double x, double y, int button) {
+ if (button != 0 || !tabContains(x, y))
+ return false;
+ boolean next = !open();
+ if (setOpen(next)) {
+ if (next)
+ activated();
+ remember(next, selection());
+ }
+ return true;
+ }
+ public void tooltip(GuiGraphics graphics, int x, int y) {
+ if (tabContains(x, y))
+ graphics.renderTooltip(
+ net.minecraft.client.Minecraft.getInstance().font,
+ Component.translatable("screen.mmdlib.upgrades.title"), x, y);
+ }
+ /**
+ * Draw before child slot frames; the ordinary menu draws their synchronized
+ * contents.
+ */
+ public static void render(UpgradesDrawerElement element,
+ ElementRenderers.Context context) {
+ var tab = context.bounds();
+ context.access().drawerPresentation(element, Presentation.class)
+ .ifPresent(p -> {
+ if (context.access().state().get(element,
+ UpgradesDrawerElement.OPEN))
+ SideDrawerRenderer.open(context.graphics(), tab, p.body(),
+ zone.moddev.mc.lib.gui.model.Edge.RIGHT, p.colour());
+ else
+ SideDrawerRenderer.tab(context.graphics(), tab, p.colour());
+ });
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/WorkingAreaButtonBehavior.java b/src/main/java/zone/moddev/mc/lib/gui/client/WorkingAreaButtonBehavior.java
new file mode 100644
index 00000000..f43d109c
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/WorkingAreaButtonBehavior.java
@@ -0,0 +1,55 @@
+package zone.moddev.mc.lib.gui.client;
+
+import java.util.List;
+
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.network.chat.Component;
+
+import zone.moddev.mc.lib.gui.model.elements.WorkingAreaButtonElement;
+
+/**
+ * Purely local selection: toggling an outline does not change machine
+ * operation.
+ */
+public final class WorkingAreaButtonBehavior implements ElementBehavior {
+ private final ElementAccess access;
+ public WorkingAreaButtonBehavior(WorkingAreaButtonElement element,
+ ElementAccess access) {
+ this.access = access;
+ }
+ private CompoundTag data() {
+ return access.presentation().state().get(access.element(),
+ WorkingAreaButtonElement.AREA);
+ }
+ public Click mouseClicked(double x, double y, int button) {
+ if (button != 0)
+ return Click.PASS;
+ WorkingAreaDisplay.toggle(data());
+ ClickSounds.play(access.element());
+ return Click.CONSUME;
+ }
+ public void tick() {
+ WorkingAreaDisplay.update(data());
+ }
+ public List tooltip(int x, int y) {
+ return List.of(Component.translatable(WorkingAreaDisplay.visible(data())
+ ? "screen.mmdlib.working_area.hide"
+ : "screen.mmdlib.working_area.show"));
+ }
+ public static void render(WorkingAreaButtonElement element,
+ ElementRenderers.Context context) {
+ ButtonRenderer.draw(element, context);
+ var data = context.access().state().get(element,
+ WorkingAreaButtonElement.AREA);
+ int colour = WorkingAreaDisplay.visible(data)
+ ? 0xff000000 | WorkingAreaDisplay.color(data)
+ : 0xff808080;
+ var bounds = context.bounds();
+ var g = context.graphics();
+ g.renderOutline(bounds.x() + 2, bounds.y() + 2, 10, 10, colour);
+ g.fill(bounds.x() + 6, bounds.y() + 4, bounds.x() + 7, bounds.y() + 10,
+ colour);
+ g.fill(bounds.x() + 4, bounds.y() + 6, bounds.x() + 10, bounds.y() + 7,
+ colour);
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/WorkingAreaDisplay.java b/src/main/java/zone/moddev/mc/lib/gui/client/WorkingAreaDisplay.java
new file mode 100644
index 00000000..96f6c64a
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/WorkingAreaDisplay.java
@@ -0,0 +1,141 @@
+package zone.moddev.mc.lib.gui.client;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.multiplayer.ClientLevel;
+import net.minecraft.client.renderer.LevelRenderer;
+import net.minecraft.client.renderer.RenderType;
+import net.minecraft.core.BlockPos;
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.world.level.block.entity.BlockEntity;
+import net.minecraft.world.phys.AABB;
+
+import net.neoforged.api.distmarker.Dist;
+import net.neoforged.bus.api.SubscribeEvent;
+import net.neoforged.fml.common.EventBusSubscriber;
+import net.neoforged.neoforge.client.event.RenderLevelStageEvent;
+
+/** Connection-local overlays, retained after the machine screen is closed. */
+@EventBusSubscriber(modid = "mmdlib", value = Dist.CLIENT)
+public final class WorkingAreaDisplay {
+ private static final Map AREAS = new LinkedHashMap<>();
+ private static ClientLevel level;
+ private record Key(BlockPos origin, String processor) {
+ static Key of(CompoundTag data) {
+ return new Key(BlockPos.of(data.getLong("origin")),
+ data.getString("processor"));
+ }
+ }
+ private record Entry(BlockEntity owner, AABB bounds, int color) {
+ }
+
+ private WorkingAreaDisplay() {
+ }
+
+ @SubscribeEvent
+ public static void disconnected(
+ net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent.LoggingOut event) {
+ AREAS.clear();
+ level = null;
+ }
+
+ private static void refresh() {
+ var current = Minecraft.getInstance().level;
+ if (level != current) {
+ AREAS.clear();
+ level = current;
+ }
+ if (level != null)
+ AREAS.entrySet()
+ .removeIf(entry -> entry.getValue().owner().isRemoved()
+ || !level.hasChunkAt(entry.getKey().origin())
+ || level.getBlockEntity(entry.getKey().origin()) != entry
+ .getValue().owner());
+ }
+
+ private static boolean valid(CompoundTag data) {
+ return level != null && data.contains("origin")
+ && !data.getString("processor").isEmpty() && level.dimension()
+ .location().toString().equals(data.getString("dimension"));
+ }
+
+ public static boolean visible(CompoundTag data) {
+ refresh();
+ return valid(data) && data.getBoolean("available")
+ && AREAS.containsKey(Key.of(data));
+ }
+
+ public static void update(CompoundTag data) {
+ refresh();
+ if (!valid(data))
+ return;
+ var key = Key.of(data);
+ if (!data.getBoolean("available")) {
+ AREAS.remove(key);
+ return;
+ }
+ AREAS.computeIfPresent(key,
+ (ignored, previous) -> new Entry(previous.owner(), bounds(data),
+ color(data)));
+ }
+
+ public static void toggle(CompoundTag data) {
+ refresh();
+ if (!valid(data))
+ return;
+ var key = Key.of(data);
+ if (AREAS.remove(key) != null || !data.getBoolean("available"))
+ return;
+ var pos = key.origin();
+ if (!level.hasChunkAt(pos))
+ return;
+ var owner = level.getBlockEntity(pos);
+ if (owner == null)
+ return;
+ if (AREAS.size() >= 32)
+ AREAS.remove(AREAS.keySet().iterator().next());
+ AREAS.put(key, new Entry(owner, bounds(data), color(data)));
+ }
+
+ public static int color(CompoundTag data) {
+ return data.contains("color")
+ ? data.getInt("color") & 0xffffff
+ : zone.moddev.mc.lib.machine.presentation.VisualizerStyle.DEFAULT
+ .rangeColor();
+ }
+
+ private static AABB bounds(CompoundTag data) {
+ return new AABB(data.getDouble("minX"), data.getDouble("minY"),
+ data.getDouble("minZ"), data.getDouble("maxX"),
+ data.getDouble("maxY"), data.getDouble("maxZ"));
+ }
+
+ @SubscribeEvent
+ public static void render(RenderLevelStageEvent event) {
+ if (event
+ .getStage() != RenderLevelStageEvent.Stage.AFTER_TRANSLUCENT_BLOCKS)
+ return;
+ refresh();
+ if (AREAS.isEmpty())
+ return;
+ var camera = event.getCamera().getPosition();
+ var pose = event.getPoseStack();
+ pose.pushPose();
+ pose.translate(-camera.x, -camera.y, -camera.z);
+ var buffers = Minecraft.getInstance().renderBuffers().bufferSource();
+ var lines = buffers.getBuffer(RenderType.lines());
+ for (var entry : AREAS.values()) {
+ if (entry.owner().getBlockPos().distToCenterSqr(camera) > 128 * 128)
+ continue;
+ LevelRenderer.renderLineBox(pose, lines,
+ entry.bounds().inflate(.002),
+ ((entry.color() >> 16) & 255) / 255f,
+ ((entry.color() >> 8) & 255) / 255f,
+ (entry.color() & 255) / 255f, .85f);
+ }
+ buffers.endBatch(RenderType.lines());
+ pose.popPose();
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java
index 492e02a7..75b418d2 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java
@@ -79,7 +79,7 @@ private void layout() {
rowHeight = Math.max(rowHeight, choice.presentation().height());
}
body = zone.moddev.mc.lib.gui.layout.RecipeDrawerLayout.body(edge(),
- tabBounds(), screen.panelBounds(), screen.width,
+ allocatedTabBounds(), screen.panelBounds(), screen.width,
screen.drawerBottom(), width, rowHeight);
pageSize = zone.moddev.mc.lib.gui.layout.RecipeDrawerLayout
.pageSize(body, rowHeight);
diff --git a/src/main/java/zone/moddev/mc/lib/gui/drawer/BuiltinDrawers.java b/src/main/java/zone/moddev/mc/lib/gui/drawer/BuiltinDrawers.java
index 0170e3f8..8075cc59 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/drawer/BuiltinDrawers.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/drawer/BuiltinDrawers.java
@@ -16,7 +16,7 @@ public final class BuiltinDrawers {
public static final ResourceLocation SIDES = id("side_config"),
REDSTONE = id("redstone"), STATS = id("stats"),
BACKPACK = id("backpack"), CURIOS = id("curios"), POPOUT = id("popout"),
- SIDE_TAB = id("side_tab");
+ SIDE_TAB = id("side_tab"), UPGRADES = id("upgrades");
private BuiltinDrawers() {
}
@@ -26,6 +26,13 @@ private static ResourceLocation id(String name) {
}
static void register(DrawerRegistry registry) {
+ registry.register(UPGRADES, c -> c.screen().tabs().stream().filter(
+ zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement.class::isInstance)
+ .map(element -> new DrawerDefinition(UPGRADES,
+ element.common().id().orElseThrow(),
+ DrawerPlacement.top(Edge.RIGHT, -10), Optional.of(element), 0,
+ true))
+ .toList());
registry.register(SIDES,
c -> c.enabled().contains(SIDES)
|| c.host() != null && c.host().screenAutomation() != null
diff --git a/src/main/java/zone/moddev/mc/lib/gui/layout/ContainerDrawerLayout.java b/src/main/java/zone/moddev/mc/lib/gui/layout/ContainerDrawerLayout.java
index d18615c5..8c6a8875 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/layout/ContainerDrawerLayout.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/layout/ContainerDrawerLayout.java
@@ -40,9 +40,9 @@ public static ContainerDrawerLayout of(Rect panel, int bottom, int slots,
public static ContainerDrawerLayout of(Rect panel, int bottom, int slots,
Rect tab, zone.moddev.mc.lib.gui.runtime.ContainerPolicy.Layout policy,
zone.moddev.mc.lib.gui.model.Edge edge, int screenWidth) {
- var body = SideDrawerLayout.body(panel, bottom,
- SideDrawerLayout.bodyX(edge, tab, policy.width()),
- SideDrawerLayout.top(panel), policy.width(), Integer.MAX_VALUE);
+ var body = SideDrawerLayout.topBody(panel, bottom, edge, tab,
+ policy.width(), Integer.MAX_VALUE,
+ SideDrawerLayout.HeightLimit.PANEL);
int columns = policy.columns();
int rows = Math.min(policy.maxRows(),
Math.max(0, (body.height() - policy.cellY() - policy.footer())
diff --git a/src/main/java/zone/moddev/mc/lib/gui/layout/LayoutContribution.java b/src/main/java/zone/moddev/mc/lib/gui/layout/LayoutContribution.java
index ba7bdc71..c3b1b165 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/layout/LayoutContribution.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/layout/LayoutContribution.java
@@ -79,6 +79,9 @@ default Map regions() {
}
interface Panel {
+ /** Main-panel geometry in the same coordinates as element bounds. */
+ Rect bounds();
+
Rect bounds(Element element);
void place(Element element, Rect bounds);
diff --git a/src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java b/src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java
index 5a043498..12a159a0 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java
@@ -15,23 +15,9 @@ private RecipeDrawerLayout() {
public static Rect body(Edge edge, Rect tab, Rect panel, int screenWidth,
int screenBottom, int recipeWidth, int rowHeight) {
int width = Math.max(160, recipeWidth) + 2 * INSET;
- int right = Math.max(SideDrawerLayout.MARGIN,
- screenWidth - SideDrawerLayout.MARGIN);
- int leftEnd = Math.clamp(tab.x(), SideDrawerLayout.MARGIN, right);
- int rightStart = Math.clamp(tab.right(), SideDrawerLayout.MARGIN,
- right);
- int leftRoom = leftEnd - SideDrawerLayout.MARGIN;
- int rightRoom = right - rightStart;
- boolean left = edge == Edge.LEFT;
- // Open inward when the outer margin cannot fit the recipes. Never
- // clamp the body across the fixed navigation rail.
- if ((left ? leftRoom : rightRoom) < width
- && (left ? rightRoom > leftRoom : leftRoom > rightRoom))
- left = !left;
- width = Math.min(width, left ? leftRoom : rightRoom);
- int x = left ? leftEnd - width : rightStart;
- return SideDrawerLayout.body(panel, screenBottom, x,
- SideDrawerLayout.top(panel), width, panel.height());
+ return SideDrawerLayout.topBody(panel, screenWidth, screenBottom, edge,
+ tab, width, panel.height(), SideDrawerLayout.HeightLimit.PANEL,
+ SideDrawerLayout.WidthPolicy.INWARD_IF_NEEDED);
}
public static Rect content(Rect body) {
diff --git a/src/main/java/zone/moddev/mc/lib/gui/layout/ScreenLayout.java b/src/main/java/zone/moddev/mc/lib/gui/layout/ScreenLayout.java
index 9b022ee7..263e7271 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/layout/ScreenLayout.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/layout/ScreenLayout.java
@@ -48,8 +48,8 @@ private ScreenLayout(LayoutContext text) {
/**
* Lays out {@code screen}, measuring text with {@code text}.
*
- * @throws IllegalArgumentException
- * if the tabs on one edge do not fit the panel's height
+ * @throws IllegalArgumentException if the tabs on one edge do not fit the
+ * panel's height
*/
public static ScreenLayout of(Screen screen, TextMeasure text) {
return of(screen, text, false);
@@ -120,6 +120,10 @@ private static ScreenLayout arrange(Screen screen, LayoutContext text,
.toList();
layout.place(screen);
var placement = new LayoutContribution.Panel() {
+ public Rect bounds() {
+ return layout.panel();
+ }
+
public Rect bounds(Element element) {
return layout.bounds(element);
}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java b/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java
index c4f1c0ac..b5975a31 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java
@@ -15,6 +15,11 @@ public enum HeightLimit {
PANEL, SCREEN
}
+ /** Horizontal fitting is a policy; panel-top anchoring is always shared. */
+ public enum WidthPolicy {
+ OUTWARD, INWARD_IF_NEEDED
+ }
+
private SideDrawerLayout() {
}
@@ -37,6 +42,34 @@ public static int top(Rect panel) {
return Math.max(MARGIN, panel.y() + MARGIN);
}
+ /** Standard content anchor: tab order never changes the body's top edge. */
+ public static Rect topBody(Rect panel, int screenBottom,
+ zone.moddev.mc.lib.gui.model.Edge edge, Rect tab, int width,
+ int desiredHeight, HeightLimit limit) {
+ return topBody(panel, Integer.MAX_VALUE, screenBottom, edge, tab, width,
+ desiredHeight, limit, WidthPolicy.OUTWARD);
+ }
+
+ public static Rect topBody(Rect panel, int screenWidth, int screenBottom,
+ zone.moddev.mc.lib.gui.model.Edge edge, Rect tab, int width,
+ int desiredHeight, HeightLimit limit, WidthPolicy fitting) {
+ int x = bodyX(edge, tab, width);
+ if (fitting == WidthPolicy.INWARD_IF_NEEDED) {
+ int right = Math.max(MARGIN, screenWidth - MARGIN);
+ int leftEnd = Math.clamp(tab.x(), MARGIN, right);
+ int rightStart = Math.clamp(tab.right(), MARGIN, right);
+ int leftRoom = leftEnd - MARGIN, rightRoom = right - rightStart;
+ boolean left = edge == zone.moddev.mc.lib.gui.model.Edge.LEFT;
+ if ((left ? leftRoom : rightRoom) < width
+ && (left ? rightRoom > leftRoom : leftRoom > rightRoom))
+ left = !left;
+ width = Math.min(width, left ? leftRoom : rightRoom);
+ x = left ? leftEnd - width : rightStart;
+ }
+ return body(panel, screenBottom, x, top(panel), width,
+ Math.max(desiredHeight, tab.bottom() - top(panel)), limit);
+ }
+
/** The screen/overlay limit already includes its own margin. */
public static int bottom(Rect panel, int screenBottom) {
return Math.min(panel.bottom() - MARGIN, screenBottom);
diff --git a/src/main/java/zone/moddev/mc/lib/gui/load/BuiltinElements.java b/src/main/java/zone/moddev/mc/lib/gui/load/BuiltinElements.java
index f0168f63..9d1cebba 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/load/BuiltinElements.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/load/BuiltinElements.java
@@ -46,6 +46,7 @@
import zone.moddev.mc.lib.gui.model.elements.CheckboxElement;
import zone.moddev.mc.lib.gui.model.elements.ContainerSlotElement;
import zone.moddev.mc.lib.gui.model.elements.CustomElement;
+import zone.moddev.mc.lib.gui.model.elements.CycleButtonElement;
import zone.moddev.mc.lib.gui.model.elements.EnergyGaugeElement;
import zone.moddev.mc.lib.gui.model.elements.FluidTankElement;
import zone.moddev.mc.lib.gui.model.elements.GaugeElement;
@@ -87,6 +88,14 @@ private BuiltinElements() {
public static final ElementType INVENTORY = builtin(
"inventory", InventoryElement.class, BuiltinElements::inventory,
"widget");
+ public static final ElementType UPGRADE_SLOT = builtin(
+ "upgrade-slot",
+ zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement.class,
+ x -> new zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement(
+ x.common(), x.integer("index"), slot(x, false).appearance(),
+ ResourceLocation.parse(x.attribute("item-tag")),
+ x.optional("max-stack-size").map(Integer::parseInt).orElse(1)),
+ "widget", "slots");
public static final ElementType SLOT = builtin("slot",
SlotElement.class, x -> slot(x, false), "widget", "slots")
.withXml(name("item-slot"),
@@ -127,6 +136,13 @@ private BuiltinElements() {
x.common(), x.attribute("variable"), x.size("width", 1),
x.size("height", 1), x.text("empty-text")),
"widget");
+ public static final ElementType WORKING_AREA_BUTTON = builtin(
+ "working-area-button",
+ zone.moddev.mc.lib.gui.model.elements.WorkingAreaButtonElement.class,
+ x -> new zone.moddev.mc.lib.gui.model.elements.WorkingAreaButtonElement(
+ x.common(),
+ Optional.ofNullable(x.node().attributes().get("processor-key"))),
+ "widget", "buttons");
public static final ElementType PROCESSOR_BUTTON = builtin(
"processor-button", ProcessorButtonElement.class,
BuiltinElements::processorButton, "widget", "buttons");
@@ -137,6 +153,11 @@ private BuiltinElements() {
"widget");
public static final ElementType BUTTON = builtin("button",
ButtonElement.class, BuiltinElements::button, "widget", "buttons");
+ public static final ElementType CYCLE_BUTTON = builtin(
+ "cycle-button", CycleButtonElement.class,
+ x -> new CycleButtonElement(x.common(), x.attribute("variable"),
+ x.children(CycleButtonElement.Mode.class)),
+ "widget", "buttons");
public static final ElementType CHECKBOX = builtin(
"checkbox", CheckboxElement.class, BuiltinElements::checkbox, "widget");
public static final ElementType RADIO_GROUP = builtin(
@@ -160,6 +181,12 @@ private BuiltinElements() {
public static final ElementType PLAYER_OFFHAND = builtin(
"player-offhand", PlayerOffhandElement.class,
x -> new PlayerOffhandElement(x.common()), "widget");
+ public static final ElementType UPGRADES_DRAWER = builtin(
+ "upgrades-drawer",
+ zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement.class,
+ x -> new zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement(
+ x.common(), x.children()),
+ "dock");
public static final ElementType SIDE_TAB = builtin(
"side-tab", SideTabElement.class, BuiltinElements::sideTab, "dock");
public static final ElementType POPOUT = builtin("popout",
@@ -204,19 +231,31 @@ private static ElementType builtin(String local,
static void register(ScreenTags tags) {
for (var element : List.of(BOX, SPACER, INVENTORY_CONTROLS, CUSTOM,
- GROUP, INVENTORY, SLOT, GHOST_SLOT, LEGACY_GAUGE, ENERGY_GAUGE,
- METER, SPRITE, ANIMATED_SPRITE, PROGRESS_SPRITE, COLOURED_GROUP,
- PROGRESS, LABEL, ENTITY_PORTRAIT, PROCESSOR_BUTTON, RECIPE_SELECTOR,
- BUTTON, CHECKBOX, RADIO_GROUP, RADIO, CONTEXT, VIEW, SIDE_CONFIG,
- PLAYER_INVENTORY, PLAYER_ARMOUR, PLAYER_OFFHAND, SIDE_TAB, POPOUT,
- FLUID_TANK))
+ GROUP, INVENTORY, SLOT, UPGRADE_SLOT, GHOST_SLOT, LEGACY_GAUGE,
+ ENERGY_GAUGE, METER, SPRITE, ANIMATED_SPRITE, PROGRESS_SPRITE,
+ COLOURED_GROUP, PROGRESS, LABEL, ENTITY_PORTRAIT, PROCESSOR_BUTTON,
+ WORKING_AREA_BUTTON, RECIPE_SELECTOR, BUTTON, CYCLE_BUTTON,
+ CHECKBOX, RADIO_GROUP, RADIO, CONTEXT, VIEW, SIDE_CONFIG,
+ PLAYER_INVENTORY, PLAYER_ARMOUR, PLAYER_OFFHAND, SIDE_TAB,
+ UPGRADES_DRAWER, POPOUT, FLUID_TANK))
element.register(tags);
+ tags.register("machine-upgrades",
+ ScreenSchemas.builtin("machine-upgrades", Element.class, x -> {
+ throw x.error(
+ "machine-upgrades requires a machine definition; use ordinary inventories for an explicit layout");
+ }, ScreenTag.Role.ELEMENT, "widget"));
tags.register("screen", ScreenSchemas.builtin("screen", Screen.class,
BuiltinElements::screen, ScreenTag.Role.DOCUMENT));
tags.register("property",
ScreenSchemas.builtin("property", Property.class,
x -> new Property(x.attribute("name"), x.attribute("value")),
ScreenTag.Role.DATA));
+ tags.register("cycle-mode",
+ ScreenSchemas.builtin("cycle-mode", CycleButtonElement.Mode.class,
+ x -> new CycleButtonElement.Mode(x.integer("value"),
+ x.id("icon").orElseThrow(), x.text("label").orElseThrow(),
+ x.text("tooltip"), x.id("action").orElseThrow()),
+ ScreenTag.Role.DATA));
tags.register("placeholder",
ScreenSchemas.builtin("placeholder", Object.class, x -> {
throw x.error("Unexpanded placeholder");
@@ -307,8 +346,41 @@ private static GroupElement group(ScreenXml x) {
private static InventoryElement inventory(ScreenXml x) {
var node = x.node();
var c = x.common();
+ var children = x.children();
+ if (node.attributes().containsKey("count")) {
+ if (!children.isEmpty())
+ throw x.error(
+ "An inventory cannot combine count with explicit slots");
+ int count = x.integer("count");
+ if (count < 1 || count > 4096)
+ throw x.error("Inventory count must be 1..4096");
+ var generated = new ArrayList();
+ String prefix = c.id().orElse(x.attribute("storage"));
+ for (int index = 0; index < count; index++) {
+ var attributes = new java.util.LinkedHashMap();
+ attributes.put("id", prefix + "_" + index);
+ attributes.put("index", Integer.toString(index));
+ attributes.put("kind", "normal");
+ attributes.put("size", "normal");
+ attributes.put("item-size", "16");
+ x.optional("slot-icon")
+ .ifPresent(icon -> attributes.put("icon", icon));
+ x.optional("slot-tooltip")
+ .ifPresent(tooltip -> attributes.put("tooltip", tooltip));
+ generated.add(x.read(
+ new ScreenReader.Node("slot", attributes, List.of(),
+ node.source(), node.line(), node.namespace()),
+ Element.class));
+ }
+ children = List.copyOf(generated);
+ } else if (node.attributes().containsKey("slot-icon")
+ || node.attributes().containsKey("slot-tooltip")) {
+ throw x.error(
+ "slot-icon and slot-tooltip require generated inventory slots");
+ }
return new InventoryElement(c, node.attributes().get("storage"),
- x.integer("columns"), x.size("spacing", 0), x.children());
+ x.integer("columns"), x.size("spacing", 0), children,
+ x.color("selection-color").orElse(0xff55ff88));
}
private static SlotElement slot(ScreenXml x, boolean ghost) {
diff --git a/src/main/java/zone/moddev/mc/lib/gui/load/ScreenFillGenerator.java b/src/main/java/zone/moddev/mc/lib/gui/load/ScreenFillGenerator.java
index 72cc9d39..236b6716 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/load/ScreenFillGenerator.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/load/ScreenFillGenerator.java
@@ -15,6 +15,23 @@ public interface ScreenFillGenerator {
List generate(ResourceLocation screen,
ScreenReader.Node template);
+ /**
+ * Creates generation context from the fully composed, unexpanded screen.
+ */
+ default ScreenFillGenerator forScreen(ResourceLocation screen,
+ ScreenReader.Node composed) {
+ return this;
+ }
+
+ /**
+ * Supplies definition-context defaults for an ordinary element after
+ * composition.
+ */
+ default ScreenReader.Node prepareElement(ResourceLocation screen,
+ ScreenReader.Node element) {
+ return element;
+ }
+
/**
* Contextual filter for literal placeholder defaults. An authored fill
* replaces the placeholder's attributes, so this never filters an
diff --git a/src/main/java/zone/moddev/mc/lib/gui/load/ScreenTemplates.java b/src/main/java/zone/moddev/mc/lib/gui/load/ScreenTemplates.java
index 46003ded..fb6cdbcc 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/load/ScreenTemplates.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/load/ScreenTemplates.java
@@ -140,7 +140,8 @@ Node expand(ResourceLocation id) {
var root = resolve(id);
if (flag(root, "abstract"))
throw error(root, "An abstract screen cannot be opened or bound");
- return root.withChildren(expand(id, root.children()));
+ return root.withChildren(
+ expand(id, root.children(), generator.forScreen(id, root)));
}
private Map placeholders(Node root) {
@@ -193,7 +194,8 @@ private List apply(List nodes, Map fills,
return result;
}
- private List expand(ResourceLocation id, List nodes) {
+ private List expand(ResourceLocation id, List nodes,
+ ScreenFillGenerator generator) {
var result = new ArrayList();
for (var node : nodes) {
if (tags.is(node, ScreenTag.Role.PLACEHOLDER)) {
@@ -204,12 +206,13 @@ private List expand(ResourceLocation id, List nodes) {
var generated = generator.generate(id, node);
for (var child : generated)
rejectTemplates(child);
- result.addAll(generated);
+ result.addAll(expand(id, generated, generator));
} else if (!node.attributes().containsKey("default-filter")
|| generator.includeDefault(id, node))
- result.addAll(expand(id, node.children()));
+ result.addAll(expand(id, node.children(), generator));
} else
- result.add(node.withChildren(expand(id, node.children())));
+ result.add(generator.prepareElement(id,
+ node.withChildren(expand(id, node.children(), generator))));
}
return result;
}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/SlotKind.java b/src/main/java/zone/moddev/mc/lib/gui/model/SlotKind.java
index 95a48251..46bf421c 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/model/SlotKind.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/model/SlotKind.java
@@ -4,7 +4,10 @@
public enum SlotKind {
/** An ordinary slot. */
NORMAL,
- /** An upgrade slot: one item, gold tint, ghost outline. */
+ /**
+ * An upgrade slot: storage-bounded stack up to eight, gold tint, ghost
+ * outline.
+ */
UPGRADE,
/**
* A JEI ghost slot: sets the item the slot expects, never holds real items.
diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/containers/InventoryElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/containers/InventoryElement.java
index 9125d7d6..cc549e85 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/model/containers/InventoryElement.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/model/containers/InventoryElement.java
@@ -44,9 +44,15 @@ public class InventoryElement implements InventoryScope {
private final int columns;
private final int spacing;
private final List children;
+ private final int selectionColor;
public InventoryElement(Common common, String inventory, int columns,
int spacing, List children) {
+ this(common, inventory, columns, spacing, children, 0xff55ff88);
+ }
+
+ public InventoryElement(Common common, String inventory, int columns,
+ int spacing, List children, int selectionColor) {
Objects.requireNonNull(common);
if (inventory == null || !inventory.matches("[a-z0-9_.-]{1,64}"))
throw new IllegalArgumentException("Invalid inventory name");
@@ -63,6 +69,31 @@ public InventoryElement(Common common, String inventory, int columns,
this.columns = columns;
this.spacing = spacing;
this.children = children;
+ this.selectionColor = selectionColor;
+ }
+
+ /**
+ * A synchronized zero-based storage index; negative, missing or unknown
+ * indexes select nothing.
+ */
+ public java.util.Optional selectedSlot(Object value) {
+ if (!(value instanceof Number number))
+ return java.util.Optional.empty();
+ int index = number.intValue();
+ if (index < 0 || number.doubleValue() != index)
+ return java.util.Optional.empty();
+ return slots().stream().filter(slot -> slot.index() == index)
+ .findFirst();
+ }
+
+ public int selectionColor() {
+ return selectionColor;
+ }
+
+ @Override
+ public Set> valueKinds(
+ zone.moddev.mc.lib.gui.WidgetTypes widgets) {
+ return Set.of(zone.moddev.mc.lib.gui.value.ValueTypes.WHOLE);
}
public List slots() {
@@ -377,6 +408,7 @@ public boolean equals(Object object) {
&& java.util.Objects.equals(inventory, other.inventory)
&& java.util.Objects.equals(columns, other.columns)
&& java.util.Objects.equals(spacing, other.spacing)
+ && selectionColor == other.selectionColor
&& java.util.Objects.equals(children, other.children);
}
@@ -388,6 +420,7 @@ public int hashCode() {
hash = 31 * hash + java.util.Objects.hashCode(columns);
hash = 31 * hash + java.util.Objects.hashCode(spacing);
hash = 31 * hash + java.util.Objects.hashCode(children);
+ hash = 31 * hash + Integer.hashCode(selectionColor);
return hash;
}
@@ -395,6 +428,6 @@ public int hashCode() {
public String toString() {
return "InventoryElement[common=" + common + ", inventory=" + inventory
+ ", columns=" + columns + ", spacing=" + spacing + ", children="
- + children + "]";
+ + children + ", selectionColor=" + selectionColor + "]";
}
}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/containers/UpgradesDrawerElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/containers/UpgradesDrawerElement.java
new file mode 100644
index 00000000..49ce6d10
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/model/containers/UpgradesDrawerElement.java
@@ -0,0 +1,120 @@
+package zone.moddev.mc.lib.gui.model.containers;
+
+import java.util.List;
+import java.util.Map;
+
+import net.minecraft.network.RegistryFriendlyByteBuf;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.resources.ResourceLocation;
+
+import zone.moddev.mc.lib.gui.ElementAction;
+import zone.moddev.mc.lib.gui.layout.ElementLayouts;
+import zone.moddev.mc.lib.gui.layout.LayoutContribution;
+import zone.moddev.mc.lib.gui.layout.Rect;
+import zone.moddev.mc.lib.gui.layout.SideDrawerLayout;
+import zone.moddev.mc.lib.gui.layout.TextMeasure;
+import zone.moddev.mc.lib.gui.model.Common;
+import zone.moddev.mc.lib.gui.model.Element;
+import zone.moddev.mc.lib.gui.runtime.component.BuiltinMenuComponents;
+import zone.moddev.mc.lib.gui.sync.ElementStateView;
+import zone.moddev.mc.lib.gui.sync.ElementSync;
+import zone.moddev.mc.lib.gui.sync.SynchronizedElement;
+
+/**
+ * A collapsible inventory dock; contents use ordinary slot binding and
+ * synchronization.
+ */
+public class UpgradesDrawerElement
+ implements SynchronizedElement, SelectiveContainer {
+ public static final ElementSync OPEN = ElementSync
+ .field(ResourceLocation.parse("mmdlib:upgrades_open"),
+ ByteBufCodecs.BOOL.cast(), 1,
+ element -> false)
+ .affectsLayout().build();
+ public static final ElementAction SET_OPEN = new ElementAction<>(
+ ResourceLocation.parse("mmdlib:upgrades_open"),
+ ByteBufCodecs.BOOL.cast(), 1,
+ (context, open) -> {
+ var session = context.menu().components()
+ .require(BuiltinMenuComponents.UPGRADES);
+ if (session.element() != context.element())
+ return false;
+ session.open(open);
+ return true;
+ });
+ private final Common common;
+ private final List children;
+
+ public UpgradesDrawerElement(Common common, List children) {
+ this.common = common;
+ this.children = List.copyOf(children);
+ }
+ public Common common() {
+ return common;
+ }
+ public List children() {
+ return children;
+ }
+ public List> synchronizedValues() {
+ return List.of(OPEN);
+ }
+ public List extends ElementAction>> actions() {
+ return List.of(SET_OPEN);
+ }
+ public boolean childVisible(Element child, ElementStateView state) {
+ return state.get(this, OPEN);
+ }
+ public int[] measure(TextMeasure text) {
+ return new int[]{26, 24};
+ }
+
+ public int[] bodySize(TextMeasure text) {
+ var size = ElementLayouts.stack(children, 2, text);
+ return new int[]{size[0] + 12, Math.max(24, size[1] + 12)};
+ }
+ /**
+ * Uses the same panel anchor as client drawers, independent of tab order.
+ */
+ public Rect body(Rect panel, Rect tab, int bottom, TextMeasure text) {
+ var size = bodySize(text);
+ return SideDrawerLayout.topBody(panel, bottom,
+ zone.moddev.mc.lib.gui.model.Edge.RIGHT, tab, size[0], size[1],
+ SideDrawerLayout.HeightLimit.SCREEN);
+ }
+ public Map childLayout(Rect bounds, TextMeasure text) {
+ // The contribution places children after all tabs and the panel exist.
+ return ElementLayouts.stackPositions(children, bounds, 2, text);
+ }
+ @Override
+ public java.util.Optional layoutContribution(
+ LayoutContribution.Context context) {
+ return java.util.Optional.of(new LayoutContribution() {
+ public void beforeOffsets(Panel panel) {
+ var body = body(panel.bounds(),
+ panel.bounds(UpgradesDrawerElement.this), Integer.MAX_VALUE,
+ context.text());
+ ElementLayouts
+ .stackPositions(children,
+ new Rect(body.x() + 6, body.y() + 6, body.width() - 12,
+ body.height() - 12),
+ 2, context.text())
+ .forEach(panel::place);
+ }
+ });
+ }
+ public void validate() {
+ SynchronizedElement.super.validate();
+ if (common.id().isEmpty() || children.isEmpty())
+ throw new IllegalArgumentException(
+ "Upgrades drawer needs an id and content");
+ }
+ public void validateScreen(zone.moddev.mc.lib.gui.model.Screen screen) {
+ if (screen.elements().stream()
+ .filter(UpgradesDrawerElement.class::isInstance).count() != 1)
+ throw new IllegalArgumentException(
+ "Only one upgrades drawer is supported per screen");
+ }
+ public String toString() {
+ return "UpgradesDrawer[" + common + "," + children + "]";
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/elements/CycleButtonElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/elements/CycleButtonElement.java
new file mode 100644
index 00000000..632109d1
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/model/elements/CycleButtonElement.java
@@ -0,0 +1,179 @@
+package zone.moddev.mc.lib.gui.model.elements;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+
+import net.minecraft.network.chat.Component;
+import net.minecraft.resources.ResourceLocation;
+
+import zone.moddev.mc.lib.gui.layout.TextMeasure;
+import zone.moddev.mc.lib.gui.model.Common;
+import zone.moddev.mc.lib.gui.model.ElementSnapshot;
+import zone.moddev.mc.lib.gui.model.ProcessorVariable;
+import zone.moddev.mc.lib.gui.model.Text;
+import zone.moddev.mc.lib.gui.model.TooltipContext;
+import zone.moddev.mc.lib.gui.runtime.ScreenClick;
+import zone.moddev.mc.lib.gui.runtime.ScreenHost;
+import zone.moddev.mc.lib.machine.feature.Processor;
+
+/** XML-defined cycle of processor modes, using declared server actions. */
+public class CycleButtonElement implements ButtonControl {
+ public record Mode(int value, ResourceLocation icon, Text label,
+ Optional tooltip, ResourceLocation action) {
+ public Mode {
+ Objects.requireNonNull(icon);
+ Objects.requireNonNull(label);
+ Objects.requireNonNull(tooltip);
+ Objects.requireNonNull(action);
+ }
+ }
+
+ private final Common common;
+ private final ProcessorVariable variable;
+ private final List modes;
+
+ public CycleButtonElement(Common common, String variable,
+ List modes) {
+ this.common = Objects.requireNonNull(common);
+ this.variable = ProcessorVariable.parse(variable);
+ this.modes = List.copyOf(modes);
+ }
+
+ public Common common() {
+ return common;
+ }
+ public ProcessorVariable variable() {
+ return variable;
+ }
+ public List modes() {
+ return modes;
+ }
+ public boolean flat() {
+ return false;
+ }
+ public Optional text() {
+ return Optional.empty();
+ }
+ public boolean interactive() {
+ return true;
+ }
+ public int[] measure(TextMeasure measure) {
+ return new int[]{18, 18};
+ }
+
+ public Optional modeFor(Object value) {
+ if (!(value instanceof Number number))
+ return Optional.empty();
+ int integer = number.intValue();
+ if (number.doubleValue() != integer)
+ return Optional.empty();
+ return modes.stream().filter(mode -> mode.value() == integer)
+ .findFirst();
+ }
+
+ /**
+ * Unknown state recovers to the first declared mode; XML order owns
+ * cycling.
+ */
+ public Mode nextMode(Object value) {
+ int current = modeFor(value).map(modes::indexOf).orElse(-1);
+ return modes.get((current + 1) % modes.size());
+ }
+
+ public Optional iconFor(Object value) {
+ return modeFor(value).or(() -> modes.stream().findFirst())
+ .map(Mode::icon);
+ }
+ public Optional labelFor(Object value) {
+ return modeFor(value).map(Mode::label);
+ }
+
+ public void appendTooltip(TooltipContext context, List rows) {
+ modeFor(context.value()).ifPresent(mode -> {
+ rows.add(context.text(mode.label()));
+ mode.tooltip().ifPresent(text -> rows.add(context.text(text)));
+ });
+ context.appendDefaults(rows);
+ }
+
+ public void validate() {
+ ButtonControl.super.validate();
+ if (modes.size() < 2 || modes.size() > 256 || modes.stream()
+ .map(Mode::value).distinct().count() != modes.size())
+ throw new IllegalArgumentException(
+ "cycle-button requires 2..256 modes with unique values");
+ if (common.tooltip().isEmpty())
+ throw new IllegalArgumentException(
+ "cycle-button needs a tooltip saying how to cycle");
+ if (common.value().isPresent() || common.max().isPresent()
+ || common.clicks().any() || common.interaction().isPresent()
+ || !common.jeiRecipes().isEmpty())
+ throw new IllegalArgumentException(
+ "cycle-button owns its variable and mode actions");
+ }
+
+ private Processor> processor(ScreenHost host) {
+ if (host.screenFeatures() == null)
+ throw new IllegalArgumentException(
+ "cycle-button requires processor state");
+ return host.screenFeatures().findProcessor(variable.processor())
+ .orElseThrow(() -> new IllegalArgumentException(
+ "Unknown processor: " + variable.processor()));
+ }
+
+ private void validateActions(Processor> processor) {
+ for (var mode : modes)
+ if (!processor.actions().containsKey(mode.action()))
+ throw new IllegalArgumentException(
+ "Unknown cycle mode action: " + mode.action());
+ }
+
+ public void validateDefinition(Map> processors) {
+ if (modeFor(variable.defaultValue(processors)).isEmpty())
+ throw new IllegalArgumentException(
+ "cycle-button variable default must match a declared integer mode");
+ validateActions(processors.get(variable.processor()));
+ }
+ public void validateHostType(Class> type) {
+ if (!ScreenHost.class.isAssignableFrom(type))
+ throw new IllegalArgumentException(
+ "cycle-button requires a ScreenHost");
+ }
+ public void validateHost(ScreenHost host) {
+ variable.read(host);
+ validateActions(processor(host));
+ }
+ public Optional snapshot(ScreenHost host) {
+ return Optional
+ .of(new ElementSnapshot(variable.read(host), modes.size() - 1));
+ }
+ public boolean interact(ScreenClick click) {
+ if (click.button() != 0 || click.option() != 0
+ || !(click.menu().blockEntity instanceof ScreenHost host))
+ return false;
+ var next = nextMode(variable.read(host));
+ var result = processor(host).invoke(next.action(), click.player());
+ result.message().ifPresent(
+ message -> click.player().displayClientMessage(message, true));
+ return result.accepted();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return other != null && other.getClass() == getClass()
+ && common.equals(((CycleButtonElement) other).common)
+ && variable.equals(((CycleButtonElement) other).variable)
+ && modes.equals(((CycleButtonElement) other).modes);
+ }
+ @Override
+ public int hashCode() {
+ return Objects.hash(common, variable, modes);
+ }
+ @Override
+ public String toString() {
+ return "CycleButtonElement[common=" + common + ",variable=" + variable
+ + ",modes=" + modes + "]";
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/elements/ItemSlotElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/elements/ItemSlotElement.java
index 0c676936..ff83d39d 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/model/elements/ItemSlotElement.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/model/elements/ItemSlotElement.java
@@ -86,7 +86,9 @@ public boolean mayPickup(Player player) {
}
public int getMaxStackSize() {
- return upgrade ? 1 : super.getMaxStackSize();
+ return upgrade
+ ? Math.min(1, super.getMaxStackSize())
+ : super.getMaxStackSize();
}
public SlotPlan plan() {
diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/elements/UpgradeSlotElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/elements/UpgradeSlotElement.java
new file mode 100644
index 00000000..2fea5e91
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/model/elements/UpgradeSlotElement.java
@@ -0,0 +1,78 @@
+package zone.moddev.mc.lib.gui.model.elements;
+
+import java.util.function.BooleanSupplier;
+
+import net.minecraft.core.registries.Registries;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.tags.TagKey;
+import net.minecraft.world.item.Item;
+import net.minecraft.world.item.ItemStack;
+
+import net.neoforged.neoforge.items.IItemHandlerModifiable;
+
+import zone.moddev.mc.lib.gui.layout.Rect;
+import zone.moddev.mc.lib.gui.model.Common;
+import zone.moddev.mc.lib.gui.model.SlotKind;
+
+/**
+ * Manual upgrade socket, bounded by its storage and the admitted item's stack
+ * limit.
+ */
+public class UpgradeSlotElement extends ItemSlotElement {
+ private final TagKey- tag;
+ private final int maxStackSize;
+ public UpgradeSlotElement(Common common, int index, Appearance appearance,
+ ResourceLocation tag) {
+ this(common, index, appearance, tag, 1);
+ }
+ public UpgradeSlotElement(Common common, int index, Appearance appearance,
+ ResourceLocation tag, int maxStackSize) {
+ super(common, index, SlotKind.UPGRADE, appearance);
+ if (maxStackSize < 1 || maxStackSize > 64)
+ throw new IllegalArgumentException(
+ "Upgrade max-stack-size must be between 1 and 64");
+ this.maxStackSize = maxStackSize;
+ this.tag = TagKey.create(Registries.ITEM, tag);
+ }
+ public int maxStackSize() {
+ return maxStackSize;
+ }
+ public TagKey
- acceptedItems() {
+ return tag;
+ }
+ @Override
+ public java.util.Optional
tint() {
+ return java.util.Optional.of(appearance().tint().orElse(0xffffff));
+ }
+ @Override
+ public java.util.List associatedGroups(
+ zone.moddev.mc.lib.gui.model.Screen screen,
+ java.util.List groups) {
+ return java.util.List.of();
+ }
+ public MenuSlot createSlot(IItemHandlerModifiable storage, int local,
+ Rect bounds, BooleanSupplier visible, BooleanSupplier interacting,
+ Runnable changed) {
+ var xy = itemPosition(bounds);
+ return new MenuSlot(storage, local, xy[0], xy[1], visible, interacting,
+ changed, false) {
+ public int getMaxStackSize() {
+ return Math.min(maxStackSize, super.getMaxStackSize());
+ }
+ public boolean mayPlace(ItemStack stack) {
+ return stack.is(tag) && super.mayPlace(stack);
+ }
+ };
+ }
+ public String toString() {
+ return "UpgradeSlot[" + super.toString() + "," + tag.location() + ","
+ + maxStackSize + "]";
+ }
+ public boolean equals(Object other) {
+ return super.equals(other) && other instanceof UpgradeSlotElement slot
+ && tag.equals(slot.tag) && maxStackSize == slot.maxStackSize;
+ }
+ public int hashCode() {
+ return 31 * (31 * super.hashCode() + tag.hashCode()) + maxStackSize;
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/elements/WorkingAreaButtonElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/elements/WorkingAreaButtonElement.java
new file mode 100644
index 00000000..973240bc
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/model/elements/WorkingAreaButtonElement.java
@@ -0,0 +1,106 @@
+package zone.moddev.mc.lib.gui.model.elements;
+
+import java.util.List;
+import java.util.Optional;
+
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.network.RegistryFriendlyByteBuf;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.level.block.entity.BlockEntity;
+
+import zone.moddev.mc.lib.api.capabilities.RelativeFace;
+import zone.moddev.mc.lib.gui.model.Common;
+import zone.moddev.mc.lib.gui.model.Text;
+import zone.moddev.mc.lib.gui.runtime.ScreenHost;
+import zone.moddev.mc.lib.gui.sync.ElementSync;
+import zone.moddev.mc.lib.gui.sync.SynchronizedElement;
+import zone.moddev.mc.lib.machine.feature.Processor;
+import zone.moddev.mc.lib.machine.feature.WorkingArea;
+
+/**
+ * A client-local display toggle; the server supplies the actual working bounds.
+ */
+public class WorkingAreaButtonElement
+ implements ButtonControl, SynchronizedElement {
+ public static final ElementSync AREA = ElementSync
+ .field(ResourceLocation.parse("mmdlib:working_area"),
+ ByteBufCodecs.COMPOUND_TAG.cast(), 1024,
+ element -> new CompoundTag())
+ .sample(
+ (source, previous) -> ((WorkingAreaButtonElement) source.element())
+ .sample((ScreenHost) source.machine()))
+ .build();
+
+ public List> synchronizedValues() {
+ return List.of(AREA);
+ }
+ private final Common common;
+ private final Optional processor;
+
+ public WorkingAreaButtonElement(Common common, Optional processor) {
+ this.common = common;
+ this.processor = processor;
+ }
+
+ public Common common() {
+ return common;
+ }
+ public boolean flat() {
+ return true;
+ }
+ public Optional text() {
+ return Optional.empty();
+ }
+ public Optional iconFor(Object value) {
+ return Optional.empty();
+ }
+ public Optional labelFor(Object value) {
+ return Optional.empty();
+ }
+
+ private Processor> provider(ScreenHost host) {
+ if (host.screenFeatures() == null)
+ throw new IllegalArgumentException(
+ "Working-area button requires a processor");
+ return host.screenFeatures().findProcessor(processor)
+ .filter(WorkingArea.Provider.class::isInstance)
+ .orElseThrow(() -> new IllegalArgumentException(
+ "Processor does not provide a working area"));
+ }
+
+ public void validateHost(ScreenHost host) {
+ provider(host);
+ }
+
+ private CompoundTag sample(ScreenHost host) {
+ var entity = (BlockEntity) host;
+ var selected = provider(host);
+ var area = ((WorkingArea.Provider) selected).workingArea();
+ var tag = new CompoundTag();
+ tag.putString("dimension",
+ entity.getLevel().dimension().location().toString());
+ tag.putLong("origin", entity.getBlockPos().asLong());
+ tag.putString("processor", selected.key());
+ tag.putBoolean("available", area != null);
+ if (area != null) {
+ var state = entity.getBlockState();
+ var facing = RelativeFace.facing(state);
+ var bounds = area.bounds(entity.getBlockPos(), facing);
+ tag.putInt("color",
+ zone.moddev.mc.lib.machine.presentation.VisualizerStyle.of(host)
+ .rangeColor());
+ tag.putDouble("minX", bounds.minX);
+ tag.putDouble("minY", bounds.minY);
+ tag.putDouble("minZ", bounds.minZ);
+ tag.putDouble("maxX", bounds.maxX);
+ tag.putDouble("maxY", bounds.maxY);
+ tag.putDouble("maxZ", bounds.maxZ);
+ }
+ return tag;
+ }
+
+ public String toString() {
+ return "WorkingAreaButton[" + common + "," + processor + "]";
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/runtime/UpgradesMenu.java b/src/main/java/zone/moddev/mc/lib/gui/runtime/UpgradesMenu.java
new file mode 100644
index 00000000..2dd53aad
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/gui/runtime/UpgradesMenu.java
@@ -0,0 +1,38 @@
+package zone.moddev.mc.lib.gui.runtime;
+
+import net.minecraft.resources.ResourceLocation;
+
+import zone.moddev.mc.lib.gui.drawer.BuiltinDrawers;
+import zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement;
+import zone.moddev.mc.lib.gui.runtime.component.DrawerSession;
+
+/**
+ * Participates in server-side drawer exclusion; ordinary inventory elements own
+ * the slots.
+ */
+public final class UpgradesMenu implements DrawerSession {
+ private final MachineMenu menu;
+ private final UpgradesDrawerElement element;
+ public UpgradesMenu(MachineMenu menu, UpgradesDrawerElement element) {
+ this.menu = menu;
+ this.element = element;
+ }
+ public UpgradesDrawerElement element() {
+ return element;
+ }
+ public ResourceLocation drawerType() {
+ return BuiltinDrawers.UPGRADES;
+ }
+ public void open(boolean open) {
+ if (open)
+ menu.components().activate(this);
+ menu.elementStates().set(element, UpgradesDrawerElement.OPEN, open);
+ }
+ public void closeServer() {
+ open(false);
+ }
+ public boolean pendingInventory() {
+ return menu.blockEntity.getLevel().isClientSide
+ && menu.elementPending(element);
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/gui/runtime/component/BuiltinMenuComponents.java b/src/main/java/zone/moddev/mc/lib/gui/runtime/component/BuiltinMenuComponents.java
index a56da7f0..cddf49dd 100644
--- a/src/main/java/zone/moddev/mc/lib/gui/runtime/component/BuiltinMenuComponents.java
+++ b/src/main/java/zone/moddev/mc/lib/gui/runtime/component/BuiltinMenuComponents.java
@@ -19,6 +19,9 @@
* as mods.
*/
public final class BuiltinMenuComponents {
+ public static final MenuComponentKey UPGRADES = new MenuComponentKey<>(
+ BuiltinDrawers.UPGRADES,
+ zone.moddev.mc.lib.gui.runtime.UpgradesMenu.class);
public static final MenuComponentKey TOOLTIPS = new MenuComponentKey<>(
ResourceLocation.parse("mmdlib:tooltips"), TooltipMenuComponent.class);
public static final MenuComponentKey RESERVATIONS = new MenuComponentKey<>(
@@ -42,6 +45,16 @@ private BuiltinMenuComponents() {
}
static void register(MenuComponentRegistry registry) {
+ registry.register(UPGRADES, 15, c -> c.menu().bound.screen().tabs()
+ .stream()
+ .filter(
+ zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement.class::isInstance)
+ .map(
+ zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement.class::cast)
+ .findFirst()
+ .map(element -> new zone.moddev.mc.lib.gui.runtime.UpgradesMenu(
+ c.menu(), element))
+ .orElse(null));
registry.register(TOOLTIPS, 25, TooltipMenuComponent::new,
TooltipMenuComponent.ROWS);
registry.register(INVENTORY, -1000, InventoryMenuComponent::new,
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/AdmissionDeclaration.java b/src/main/java/zone/moddev/mc/lib/machine/definition/AdmissionDeclaration.java
new file mode 100644
index 00000000..e506117a
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/AdmissionDeclaration.java
@@ -0,0 +1,43 @@
+package zone.moddev.mc.lib.machine.definition;
+
+import zone.moddev.mc.lib.machine.feature.StorageAdmission;
+
+/** Either a per-machine rule instance or an explicitly named processor. */
+public record AdmissionDeclaration(Class extends StorageAdmission> type,
+ String processor) {
+ public AdmissionDeclaration {
+ if ((type == null) == (processor == null)
+ || processor != null && processor.isBlank())
+ throw new IllegalArgumentException(
+ "Specify one filter-class or filter-processor");
+ }
+
+ public static AdmissionDeclaration load(String name, String processor,
+ ClassLoader loader) {
+ if (name == null)
+ return processor == null
+ ? null
+ : new AdmissionDeclaration(null, processor);
+ if (processor != null)
+ throw new IllegalArgumentException(
+ "Specify one filter-class or filter-processor");
+ try {
+ var type = Class.forName(name, false, loader)
+ .asSubclass(StorageAdmission.class);
+ type.getConstructor();
+ return new AdmissionDeclaration(type, null);
+ } catch (ReflectiveOperationException | ClassCastException ex) {
+ throw new IllegalArgumentException(
+ "Invalid admission class: " + name, ex);
+ }
+ }
+
+ public StorageAdmission create() {
+ try {
+ return type.getConstructor().newInstance();
+ } catch (ReflectiveOperationException ex) {
+ throw new IllegalArgumentException(
+ "Cannot instantiate admission class: " + type.getName(), ex);
+ }
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java b/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java
index a2cd060b..9ffc4351 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java
@@ -45,13 +45,6 @@ public void validate(Map> processors) {
public net.minecraft.world.phys.Vec3 offset(
net.minecraft.core.Direction facing) {
- return switch (facing) {
- case NORTH -> new net.minecraft.world.phys.Vec3(x, y, z);
- case EAST -> new net.minecraft.world.phys.Vec3(1 - z, y, x);
- case SOUTH -> new net.minecraft.world.phys.Vec3(1 - x, y, 1 - z);
- case WEST -> new net.minecraft.world.phys.Vec3(z, y, 1 - x);
- default -> throw new IllegalArgumentException(
- "Entity display requires horizontal facing");
- };
+ return MachineFacing.point(facing, x, y, z);
}
}
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java b/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java
index b7c5f039..c8871efd 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java
@@ -36,13 +36,6 @@ public void validate(Map> processors) {
*/
public net.minecraft.world.phys.Vec3 offset(
net.minecraft.core.Direction facing) {
- return switch (facing) {
- case SOUTH -> new net.minecraft.world.phys.Vec3(x, y, 1.002);
- case NORTH -> new net.minecraft.world.phys.Vec3(1 - x, y, -.002);
- case EAST -> new net.minecraft.world.phys.Vec3(1.002, y, 1 - x);
- case WEST -> new net.minecraft.world.phys.Vec3(-.002, y, x);
- default -> throw new IllegalArgumentException(
- "Item display requires horizontal facing");
- };
+ return MachineFacing.point(facing, 1 - x, y, -.002);
}
}
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java
index 0f0e7f2b..cffac47a 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java
@@ -7,7 +7,34 @@ public record MachineBehavior(ProcessorDeclaration processor, int stackSize,
boolean noOcclusion, boolean immovable, boolean portable, boolean drawers,
List shapes,
net.minecraft.resources.ResourceLocation secondaryAction,
- EntityDisplay entityDisplay, ItemDisplay itemDisplay) {
+ EntityDisplay entityDisplay, ItemDisplay itemDisplay,
+ zone.moddev.mc.lib.machine.presentation.VisualizerStyle visualizers,
+ String gearboxSlot, String capacitorSlot, List rangeSlots,
+ String legacyUpgradeStorage, MachineFacing facing, String comparatorSource,
+ List processors) {
+ public MachineBehavior(ProcessorDeclaration processor, int stackSize,
+ boolean noOcclusion, boolean immovable, boolean portable,
+ boolean drawers, List shapes,
+ net.minecraft.resources.ResourceLocation secondaryAction,
+ EntityDisplay entityDisplay, ItemDisplay itemDisplay,
+ zone.moddev.mc.lib.machine.presentation.VisualizerStyle visualizers,
+ String gearboxSlot, String capacitorSlot, List rangeSlots,
+ String legacyUpgradeStorage) {
+ this(processor, stackSize, noOcclusion, immovable, portable, drawers,
+ shapes, secondaryAction, entityDisplay, itemDisplay, visualizers,
+ gearboxSlot, capacitorSlot, rangeSlots, legacyUpgradeStorage,
+ MachineFacing.DEFAULT, null, List.of());
+ }
+ public MachineBehavior(ProcessorDeclaration processor, int stackSize,
+ boolean noOcclusion, boolean immovable, boolean portable,
+ boolean drawers, List shapes,
+ net.minecraft.resources.ResourceLocation secondaryAction,
+ EntityDisplay entityDisplay, ItemDisplay itemDisplay) {
+ this(processor, stackSize, noOcclusion, immovable, portable, drawers,
+ shapes, secondaryAction, entityDisplay, itemDisplay,
+ zone.moddev.mc.lib.machine.presentation.VisualizerStyle.DEFAULT,
+ null, null, List.of(), null);
+ }
public MachineBehavior(ProcessorDeclaration processor, int stackSize,
boolean noOcclusion, boolean immovable, boolean portable,
boolean drawers, List shapes,
@@ -26,6 +53,14 @@ public MachineBehavior(ProcessorDeclaration processor, int stackSize,
public static final MachineBehavior DEFAULT = new MachineBehavior(null, 64,
false, false, false, true, List.of(), null);
public MachineBehavior {
+ java.util.Objects.requireNonNull(visualizers);
+ java.util.Objects.requireNonNull(facing);
+ rangeSlots = List.copyOf(rangeSlots);
+ processors = List.copyOf(processors);
+ if (rangeSlots.size() > 9
+ || new java.util.HashSet<>(rangeSlots).size() != rangeSlots.size())
+ throw new IllegalArgumentException(
+ "Expected at most nine distinct range sockets");
if (stackSize < 1 || stackSize > 64)
throw new IllegalArgumentException("Stack size must be 1..64");
if (portable && (processor == null
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java
index 03aef1e4..82554929 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java
@@ -54,10 +54,23 @@ public static Set ghostInputsFor(
continue;
var ghosts = new HashSet();
machine.ghosts().forEach(ghost -> ghosts.add(ghost.id()));
- if (result == null)
- result = ghosts;
- else
- result.retainAll(ghosts);
+ for (var config : machine.processors()) {
+ if (config.recipeType() == null
+ || !config.recipeType().id().equals(recipeType))
+ continue;
+ var aliases = new HashSet();
+ if (config.bindings().isEmpty())
+ aliases.addAll(ghosts);
+ else
+ config.bindings().forEach((alias, target) -> {
+ if (ghosts.contains(target))
+ aliases.add(alias);
+ });
+ if (result == null)
+ result = aliases;
+ else
+ result.retainAll(aliases);
+ }
}
return result == null ? Set.of() : Set.copyOf(result);
}
@@ -232,6 +245,37 @@ public Map groupNames() {
return Collections.unmodifiableMap(names);
}
+ public List processors() {
+ if (!behavior.processors().isEmpty())
+ return behavior.processors();
+ if (processor == null)
+ return List.of();
+ var inputGroups = new java.util.ArrayList();
+ groups.stream().filter(g -> g.mode() == IoMode.INPUT)
+ .forEach(g -> inputGroups.add(g.id()));
+ if (fluids != null)
+ fluids.groups().stream().filter(g -> g.mode() == IoMode.INPUT)
+ .forEach(g -> inputGroups.add(g.id()));
+ return List.of(new ProcessorConfiguration(processor, processorName,
+ recipeType, behavior.processor(), Map.of(), inputGroups,
+ recipeSelection, sounds, events));
+ }
+
+ public List processingTypes() {
+ return processors().stream().map(ProcessorConfiguration::recipeType)
+ .filter(java.util.Objects::nonNull).distinct().toList();
+ }
+
+ public Map> processorSchemas() {
+ var result = new LinkedHashMap>();
+ processors().forEach(config -> {
+ if (config.declaration() != null)
+ result.put(config.id(),
+ config.declaration().schema(config.id()));
+ });
+ return Collections.unmodifiableMap(result);
+ }
+
public boolean hasProcessor() {
return processor != null;
}
@@ -245,7 +289,8 @@ public Optional processingType() {
}
public boolean processes(ResourceLocation type) {
- return recipeType != null && recipeType.id().equals(type);
+ return processingTypes().stream()
+ .anyMatch(recipe -> recipe.id().equals(type));
}
public Map visualDefaults() {
@@ -270,7 +315,11 @@ public List visualConditions() {
}
public record Power(String id, long capacity, long input, long output,
- int color, String name) {
+ int color, String name, String provider, boolean capacitors) {
+ public Power(String id, long capacity, long input, long output,
+ int color, String name) {
+ this(id, capacity, input, output, color, name, null, true);
+ }
public Power(String id, long capacity, long input, long output,
int color) {
this(id, capacity, input, output, color, "Energy");
@@ -326,11 +375,23 @@ public List inventorySlots(String name) {
.filter(i -> names.get(i).equals(name)).boxed().toList();
}
- public record Slot(String id, Role role, int limit) {
+ public record Slot(String id, Role role, int limit,
+ ResourceLocation itemTag, AdmissionDeclaration admission) {
+ public Slot(String id, Role role, int limit, ResourceLocation itemTag) {
+ this(id, role, limit, itemTag, null);
+ }
+ public Slot(String id, Role role, int limit) {
+ this(id, role, limit, null);
+ }
}
public record Tank(String id, Role role, int capacity,
- ResourceLocation fluid) {
+ ResourceLocation fluid, ResourceLocation fluidTag,
+ AdmissionDeclaration admission) {
+ public Tank(String id, Role role, int capacity,
+ ResourceLocation fluid) {
+ this(id, role, capacity, fluid, null, null);
+ }
}
public record Fluids(String id, List tanks, List groups) {
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java
index 17c74cf6..740ad5e9 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java
@@ -90,6 +90,100 @@ public static Map load(
return Collections.unmodifiableMap(plans);
}
+ private static ProcessorConfiguration processorConfiguration(Node node,
+ Map recipes, Set resources,
+ Set inputs, Map loaders,
+ String machineName) {
+ try {
+ String id = required(node, "id");
+ long operatingCost = node.attributes()
+ .containsKey("energy-per-tick")
+ ? number(node, "energy-per-tick", 0, Long.MAX_VALUE)
+ : 0;
+ if (operatingCost > 0 && !resources.contains("energy"))
+ throw error(node, "energy-per-tick requires energy storage");
+ var bindings = new LinkedHashMap();
+ if (node.attributes().containsKey("bindings")) {
+ for (String pair : required(node, "bindings").split("\\s+")) {
+ String[] parts = pair.split("=", -1);
+ if (parts.length != 2 || parts[0].isBlank()
+ || !resources.contains(parts[1])
+ || bindings.putIfAbsent(parts[0], parts[1]) != null)
+ throw error(node, "Invalid processor binding: " + pair);
+ }
+ if (resources.contains("energy"))
+ bindings.putIfAbsent("energy", "energy");
+ } else
+ resources.forEach(key -> bindings.put(key, key));
+ if (node.attributes().containsKey("class")) {
+ for (var option : List.of("recipe-type", "filter-inputs",
+ "selectable", "default-recipe", "running-sound",
+ "finish-sound", "on-start", "on-finish"))
+ if (node.attributes().containsKey(option))
+ throw error(node,
+ "Custom processors cannot take " + option);
+ if (node.attributes().containsKey("bindings"))
+ throw error(node,
+ "Custom processors use named host resources directly");
+ return new ProcessorConfiguration(id,
+ node.attributes().getOrDefault("name", machineName), null,
+ ProcessorDeclaration.load(required(node, "class"),
+ loaders.get(node.source())),
+ Map.of(), List.of(), null, MachineDefinition.Sounds.NONE,
+ MachineDefinition.Events.NONE, operatingCost);
+ }
+ var recipeNode = recipes.get(resource(node, "recipe-type"));
+ if (recipeNode == null)
+ throw error(node, "Unknown recipe type");
+ var filterInputs = node.attributes().containsKey("filter-inputs")
+ ? List.of(required(node, "filter-inputs").split("\\s+"))
+ : bindings.entrySet().stream()
+ .filter(entry -> inputs.contains(entry.getValue()))
+ .map(Map.Entry::getKey).toList();
+ var expectedInputs = bindings.entrySet().stream()
+ .filter(entry -> inputs.contains(entry.getValue()))
+ .map(Map.Entry::getKey)
+ .collect(java.util.stream.Collectors.toSet());
+ if (!new HashSet<>(filterInputs).equals(expectedInputs))
+ throw error(node,
+ "filter-inputs must name all bound input groups");
+ for (var key : filterInputs)
+ if (!inputs.contains(bindings.get(key)))
+ throw error(node,
+ "filter-inputs must name bound input groups");
+ boolean selectable = bool(node, "selectable", false);
+ if (!selectable && node.attributes().containsKey("default-recipe"))
+ throw error(node, "default-recipe requires selectable='true'");
+ return new ProcessorConfiguration(id,
+ node.attributes().getOrDefault("name", machineName),
+ recipeType(recipeNode, loaders), null, bindings, filterInputs,
+ selectable
+ ? new MachineDefinition.RecipeSelection(
+ optionalResource(node, "default-recipe").orElse(null))
+ : null,
+ new MachineDefinition.Sounds(
+ optionalResource(node, "running-sound"),
+ optionalResource(node, "finish-sound")),
+ new MachineDefinition.Events(optionalResource(node, "on-start"),
+ optionalResource(node, "on-finish")),
+ operatingCost);
+ } catch (IllegalArgumentException ex) {
+ throw error(node, ex.getMessage());
+ }
+ }
+
+ private static AdmissionDeclaration admission(Node node,
+ Map loaders) {
+ try {
+ return AdmissionDeclaration.load(
+ node.attributes().get("filter-class"),
+ node.attributes().get("filter-processor"),
+ loaders.get(node.source()));
+ } catch (IllegalArgumentException ex) {
+ throw error(node, ex.getMessage());
+ }
+ }
+
private static Node resolve(ResourceLocation id,
Map nodes, Map resolved,
Set visiting) {
@@ -116,6 +210,9 @@ private static Node resolve(ResourceLocation id,
private static String key(Node parent, Node node) {
// These sections contain singletons; their ID is configuration, not
// merge identity.
+ if (parent.name().equals("machine")
+ && Set.of("processor", "recipe-type").contains(node.name()))
+ return node.name() + ":" + required(node, "id");
if (Set.of("machine", "storage", "recipe-type").contains(parent.name()))
return node.name();
if (parent.name().equals("appearance") && isDisplay(node))
@@ -145,16 +242,28 @@ private static Node merge(Node base, Node child) {
"model"))
attrs.remove(attribute);
attrs.putAll(child.attributes());
+ var singletonOverrides = new HashSet();
+ if (base.name().equals("machine"))
+ for (var kind : List.of("processor", "recipe-type"))
+ if (base.children().stream().filter(n -> n.name().equals(kind))
+ .count() == 1
+ && child.children().stream()
+ .filter(n -> n.name().equals(kind)).count() == 1)
+ singletonOverrides.add(kind);
var children = new ArrayList<>(base.children());
var indexes = new HashMap();
for (int i = 0; i < children.size(); i++) {
- var key = key(base, children.get(i));
+ var key = singletonOverrides.contains(children.get(i).name())
+ ? children.get(i).name()
+ : key(base, children.get(i));
if (key != null && indexes.putIfAbsent(key, i) != null)
throw error(children.get(i), "Duplicate definition " + key);
}
var seen = new HashSet();
for (var node : child.children()) {
- var key = key(child, node);
+ var key = singletonOverrides.contains(node.name())
+ ? node.name()
+ : key(child, node);
if (key != null && !seen.add(key))
throw error(node, "Duplicate definition " + key);
var index = key == null ? null : indexes.get(key);
@@ -173,11 +282,15 @@ private static Node merge(Node base, Node child) {
private static final Map> ATTRIBUTES = Map.ofEntries(
Map.entry("machine", Set.of("version", "abstract", "extends", "name")),
Map.entry("block",
- Set.of("hardness", "facing", "drop", "mineable", "requires-tool",
- "stack-size", "no-occlusion", "immovable", "portable",
- "on-secondary-use", "drawers")),
+ Set.of("hardness", "facing", "placement-facing", "drop", "mineable",
+ "requires-tool", "stack-size", "no-occlusion", "immovable",
+ "portable", "on-secondary-use", "drawers")),
Map.entry("appearance",
Set.of("preset", "front", "side", "top", "bottom", "model")),
+ Map.entry("visualizers", Set.of("range-color", "work-color")),
+ Map.entry("upgrades",
+ Set.of("gearbox-slot", "capacitor-slot", "range-slots",
+ "range-storage", "legacy-layout")),
Map.entry("entity-display",
Set.of("variable", "offset", "width", "height", "yaw", "item-yaw",
"block", "item", "item-property")),
@@ -191,21 +304,22 @@ private static Node merge(Node base, Node child) {
"frames", "variable", "emissive", "when")),
Map.entry("storage", Set.of()), Map.entry("items", Set.of("id")),
Map.entry("fluids", Set.of("id")),
- Map.entry("tank",
- Set.of("id", "capacity", "role", "fluid", "color", "automation",
- "name")),
+ Map.entry("tank", Set.of("id", "capacity", "role", "fluid", "fluid-tag",
+ "filter-class", "filter-processor", "color", "automation", "name")),
Map.entry("tanks",
- Set.of("id", "count", "capacity", "role", "fluid", "color",
- "automation", "name")),
+ Set.of("id", "count", "capacity", "role", "fluid", "fluid-tag",
+ "filter-class", "filter-processor", "color", "automation",
+ "name")),
Map.entry("energy",
Set.of("id", "capacity", "input-rate", "output-rate", "color",
- "name")),
+ "name", "provider", "capacitors")),
Map.entry("slots",
Set.of("id", "count", "role", "limit", "color", "type",
- "default-item", "name")),
+ "default-item", "name", "automation", "item-tag",
+ "filter-class", "filter-processor")),
Map.entry("slot",
Set.of("id", "count", "role", "limit", "type", "default-item",
- "name")),
+ "name", "item-tag", "filter-class", "filter-processor")),
Map.entry("groups", Set.of()),
Map.entry("group",
Set.of("id", "storage", "members", "mode", "color", "name")),
@@ -213,13 +327,15 @@ private static Node merge(Node base, Node child) {
Map.entry("processor",
Set.of("id", "name", "recipe-type", "filter-inputs", "selectable",
"default-recipe", "class", "running-sound", "finish-sound",
- "on-start", "on-finish")),
- Map.entry("redstone", Set.of("enabled", "pause")),
+ "on-start", "on-finish", "bindings", "primary",
+ "energy-per-tick")),
+ Map.entry("redstone", Set.of("enabled", "pause", "comparator-source")),
Map.entry("shape", Set.of("id", "when", "bounds")),
Map.entry("shapes", Set.of()), Map.entry("recovery", Set.of("policy")));
private static final Map> CHILDREN = Map.of("machine",
Set.of("block", "appearance", "storage", "groups", "recipe-type",
- "processor", "redstone", "recovery", "screen", "shapes"),
+ "processor", "redstone", "recovery", "screen", "shapes",
+ "visualizers", "upgrades"),
"storage", Set.of("energy", "items", "fluids"), "fluids",
Set.of("tank", "tanks"), "items", Set.of("slot", "slots"), "groups",
Set.of("group"), "appearance",
@@ -257,8 +373,8 @@ private static void validateTree(Node node) {
case "recipe-type" -> List.of("id");
case "processor" -> List.of("recipe-type", "default-recipe",
"running-sound", "finish-sound", "on-start", "on-finish");
- case "tank", "tanks" -> List.of("fluid");
- case "slot", "slots" -> List.of("default-item");
+ case "tank", "tanks" -> List.of("fluid", "fluid-tag");
+ case "slot", "slots" -> List.of("default-item", "item-tag");
default -> List.of();
};
for (var attribute : resources)
@@ -270,6 +386,10 @@ private static void validateTree(Node node) {
if (Set.of("slots", "tank", "tanks", "energy", "group")
.contains(node.name()))
color(node, 0);
+ if (node.name().equals("visualizers")) {
+ color(node, "range-color", 0);
+ color(node, "work-color", 0);
+ }
if (Set.of("slot", "slots", "tank", "tanks", "energy", "group")
.contains(node.name()) && node.attributes().containsKey("name"))
required(node, "name");
@@ -290,7 +410,7 @@ private static MachineDefinition plan(ResourceLocation id, Node root,
if (!"1".equals(root.attributes().get("version")))
throw error(root, "Expected machine version=1");
var block = one(root, "block");
- requireChoice(block, "facing", "horizontal");
+
requireChoice(block, "drop", "self");
var appearance = one(root, "appearance");
requireChoice(appearance, "preset", "cube-front", "model");
@@ -319,6 +439,13 @@ private static MachineDefinition plan(ResourceLocation id, Node root,
}
var storage = one(root, "storage");
var power = optional(storage, "energy");
+ String energyProvider = power == null
+ ? null
+ : power.attributes().get("provider");
+ if ("builtin".equals(energyProvider))
+ energyProvider = null;
+ boolean energyCapacitors = power != null
+ && bool(power, "capacitors", energyProvider == null);
var items = optional(storage, "items");
String itemId = items == null ? null : required(items, "id");
if (items != null && (itemId.equals("energy")
@@ -367,7 +494,9 @@ private static MachineDefinition plan(ResourceLocation id, Node root,
if (tankIds.putIfAbsent(member, tanks.size()) != null)
throw error(node, "Duplicate tank " + member);
members.add(tanks.size());
- tanks.add(new Tank(member, role, capacity, filter));
+ tanks.add(new Tank(member, role, capacity, filter,
+ optionalResource(node, "fluid-tag").orElse(null),
+ admission(node, loaders)));
}
if (fluidGroups.putIfAbsent(tankId, new Group(tankId, members,
mode(role),
@@ -401,6 +530,13 @@ private static MachineDefinition plan(ResourceLocation id, Node root,
if (!Set.of("item", "ghost").contains(slotType))
throw error(node, "Slot type must be item or ghost");
if (slotType.equals("ghost")) {
+ if (node.attributes().containsKey("item-tag")
+ || node.attributes().containsKey("filter-class")
+ || node.attributes().containsKey("filter-processor"))
+ throw error(node,
+ "Storage filters are only supported for real item slots");
+ if (node.attributes().containsKey("automation"))
+ throw error(node, "Ghost slots do not expose automation");
if (role != Role.INPUT
|| node.attributes().containsKey("limit"))
throw error(node,
@@ -433,9 +569,17 @@ private static MachineDefinition plan(ResourceLocation id, Node root,
if (ids.putIfAbsent(memberId, slots.size()) != null)
throw error(node, "Duplicate slot " + memberId);
members.add(slots.size());
- slots.add(new Slot(memberId, role, limit));
+ slots.add(new Slot(memberId, role, limit,
+ node.attributes().containsKey("item-tag")
+ ? resource(node, "item-tag")
+ : null,
+ admission(node, loaders)));
}
if (node.name().equals("slots")) {
+ boolean automation = bool(node, "automation", true);
+ if (!automation && role != Role.MANUAL)
+ throw error(node,
+ "Slots without automation must use role=manual");
IoMode mode = switch (role) {
case INPUT -> IoMode.INPUT;
case OUTPUT -> IoMode.OUTPUT;
@@ -443,7 +587,7 @@ private static MachineDefinition plan(ResourceLocation id, Node root,
case MANUAL -> IoMode.DISABLED;
};
if (groups.putIfAbsent(slotId, new Group(slotId, members, mode,
- color(node, defaultItemColor(groups, mode)), true,
+ color(node, defaultItemColor(groups, mode)), automation,
node.attributes().getOrDefault("name", slotId))) != null)
throw error(node, "Duplicate group " + slotId);
}
@@ -528,7 +672,8 @@ else if (prior != null)
prior == null
? defaultItemColor(groups, mode)
: prior.color()),
- true, node.attributes().getOrDefault("name",
+ prior == null || prior.automation(),
+ node.attributes().getOrDefault("name",
prior == null ? groupId : prior.name())));
}
var covered = new HashSet();
@@ -566,26 +711,55 @@ else if (prior != null)
"Group mode conflicts with tank role: " + group.id());
}
}
- var recipe = optional(root, "recipe-type");
- var processor = optional(root, "processor");
- boolean custom = processor != null
- && processor.attributes().containsKey("class");
- if (custom && (recipe != null
- || processor.attributes().containsKey("recipe-type")
- || processor.attributes().containsKey("selectable")
- || processor.attributes().containsKey("filter-inputs")))
- throw error(processor,
- "Custom processors do not declare recipe processing options");
- if (custom)
- for (var cycleOnly : List.of("running-sound", "finish-sound",
- "on-start", "on-finish"))
- if (processor.attributes().containsKey(cycleOnly))
- throw error(processor, "Custom processors have no recipe "
- + "cycles, so they cannot take " + cycleOnly);
- if (!custom && (recipe == null) != (processor == null))
- throw error(root,
- "recipe-type and processor must be supplied together");
+ var resourceKeys = new LinkedHashSet();
+ resourceKeys.addAll(groups.keySet());
+ resourceKeys.addAll(fluidGroups.keySet());
+ ghosts.forEach(ghost -> resourceKeys.add(ghost.id()));
+ if (power != null)
+ resourceKeys.add("energy");
+ var inputKeys = new LinkedHashSet();
+ groups.values().stream().filter(g -> g.mode() == IoMode.INPUT)
+ .forEach(g -> inputKeys.add(g.id()));
+ fluidGroups.values().stream().filter(g -> g.mode() == IoMode.INPUT)
+ .forEach(g -> inputKeys.add(g.id()));
+ var processorNodes = root.children().stream()
+ .filter(n -> n.name().equals("processor")).toList();
+ var primaryNodes = processorNodes.stream()
+ .filter(n -> bool(n, "primary", false)).toList();
+ if (primaryNodes.size() > 1)
+ throw error(root, "Only one primary processor is allowed");
+ if (processorNodes.size() > 1 && primaryNodes.isEmpty()
+ && (bool(block, "portable", false)
+ || block.attributes().containsKey("on-secondary-use")))
+ throw error(block,
+ "Multiple processors require an explicit primary for portable/secondary actions");
+ var processor = primaryNodes.isEmpty()
+ ? (processorNodes.isEmpty() ? null : processorNodes.getFirst())
+ : primaryNodes.getFirst();
+ var recipeNodes = new LinkedHashMap();
+ for (var node : root.children())
+ if (node.name().equals("recipe-type")
+ && recipeNodes.putIfAbsent(resource(node, "id"), node) != null)
+ throw error(node, "Duplicate recipe type");
+ var processorConfigs = new ArrayList();
+ var processorIds = new HashSet();
+ for (var node : processorNodes) {
+ var config = processorConfiguration(node, recipeNodes, resourceKeys,
+ inputKeys, loaders, required(root, "name"));
+ if (!processorIds.add(config.id()))
+ throw error(node, "Duplicate processor ID " + config.id());
+ processorConfigs.add(config);
+ }
+ var primary = processor == null
+ ? null
+ : processorConfigs.stream()
+ .filter(config -> config.id().equals(required(processor, "id")))
+ .findFirst().orElseThrow();
+ boolean custom = primary != null && primary.declaration() != null;
+ var recipeType = primary == null ? null : primary.recipeType();
if (processor == null) {
+ if (!recipeNodes.isEmpty())
+ throw error(root, "recipe-type requires a processor");
if (slots.stream().anyMatch(
slot -> slot.role() == Role.INPUT || slot.role() == Role.OUTPUT)
|| !ghosts.isEmpty())
@@ -596,20 +770,6 @@ else if (prior != null)
throw error(fluidNode,
"Machines without a processor require storage/manual tank roles");
}
- var recipeType = recipe == null ? null : recipeType(recipe, loaders);
- if (!custom && processor != null
- && !recipeType.id().equals(resource(processor, "recipe-type")))
- throw error(processor, "Unknown recipe type");
- // All input groups are linked automatically when processing is enabled.
- var inputs = java.util.stream.Stream
- .concat(groups.values().stream(), fluidGroups.values().stream())
- .filter(g -> g.mode() == IoMode.INPUT).map(Group::id).toList();
- if (processor != null
- && processor.attributes().containsKey("filter-inputs")
- && !new HashSet<>(Arrays
- .asList(required(processor, "filter-inputs").split("\\s+")))
- .equals(new HashSet<>(inputs)))
- throw error(processor, "filter-inputs must name the input groups");
var redstone = optional(root, "redstone");
if (redstone != null)
requireChoice(redstone, "pause", "processing-only");
@@ -735,17 +895,146 @@ else if (prior != null)
throw error(itemDisplayNode, ex.getMessage());
}
}
- ProcessorDeclaration declaration = null;
- zone.moddev.mc.lib.machine.feature.Processor> prototype = null;
- if (custom) {
- try {
- declaration = ProcessorDeclaration.load(
- required(processor, "class"),
- loaders.get(processor.source()));
- prototype = declaration.schema(required(processor, "id"));
- } catch (IllegalArgumentException ex) {
- throw error(processor, ex.getMessage());
+ ProcessorDeclaration declaration = primary == null
+ ? null
+ : primary.declaration();
+ zone.moddev.mc.lib.machine.feature.Processor> prototype = declaration == null
+ ? null
+ : declaration.schema(primary.id());
+ var schemas = new LinkedHashMap>();
+ processorConfigs.forEach(config -> {
+ if (config.declaration() != null)
+ schemas.put(config.id(),
+ config.declaration().schema(config.id()));
+ });
+ if (redstone != null
+ && redstone.attributes().containsKey("comparator-source")) {
+ var source = required(redstone, "comparator-source");
+ var outputIds = new HashSet();
+ for (var config : processorConfigs) {
+ if (config.recipeType() != null)
+ outputIds.addAll(
+ zone.moddev.mc.lib.machine.feature.RecipeProcessor
+ .redstoneOutputIds(config.id()));
+ else
+ outputIds.addAll(
+ config.declaration().redstoneOutputIds(config.id()));
}
+ if (!outputIds.contains(source))
+ throw error(redstone, "Unknown comparator source: " + source);
+ }
+ var visualizers = optional(root, "visualizers");
+ var visualizerStyle = zone.moddev.mc.lib.machine.presentation.VisualizerStyle.DEFAULT;
+ if (visualizers != null) {
+ visualizerStyle = new zone.moddev.mc.lib.machine.presentation.VisualizerStyle(
+ color(visualizers, "range-color", visualizerStyle.rangeColor()),
+ color(visualizers, "work-color", visualizerStyle.workColor()));
+ }
+ if (energyProvider != null) {
+ final String provider = energyProvider;
+ if (processorConfigs.stream()
+ .noneMatch(config -> config.id().equals(provider)
+ && config.declaration() != null
+ && zone.moddev.mc.lib.machine.feature.ProcessorEnergy.class
+ .isAssignableFrom(config.declaration().type())))
+ throw error(power,
+ "Energy provider must name a processor implementing ProcessorEnergy: "
+ + provider);
+ }
+ var upgrades = optional(root, "upgrades");
+ String gearboxSlot = upgrades == null
+ ? null
+ : upgrades.attributes().get("gearbox-slot");
+ String capacitorSlot = upgrades == null
+ ? null
+ : upgrades.attributes().get("capacitor-slot");
+ // The library owns standard sockets; machine storage declares only
+ // extras.
+ if (upgrades != null) {
+ for (String reserved : List.of("mmdlib_gearbox",
+ "mmdlib_capacitor"))
+ if (fluidGroups.containsKey(reserved) || ghosts.stream()
+ .anyMatch(ghost -> ghost.id().equals(reserved)))
+ throw error(upgrades,
+ "Reserved component storage: " + reserved);
+ if (gearboxSlot == null && processor != null)
+ gearboxSlot = componentSocket(root, slots, groups, ids,
+ "gearbox");
+ if (capacitorSlot == null && power != null && energyCapacitors)
+ capacitorSlot = componentSocket(root, slots, groups, ids,
+ "capacitor");
+ if (itemId == null && !slots.isEmpty())
+ itemId = "items";
+ }
+ List rangeSlots = upgrades != null
+ && upgrades.attributes().containsKey("range-slots")
+ ? List.of(
+ required(upgrades, "range-slots").trim().split("[\\s,]+"))
+ : List.of();
+ if (upgrades != null
+ && upgrades.attributes().containsKey("range-storage")) {
+ if (!rangeSlots.isEmpty())
+ throw error(upgrades,
+ "Use range-storage or range-slots, not both");
+ var group = groups.get(required(upgrades, "range-storage"));
+ if (group == null)
+ throw error(upgrades, "Unknown range-storage");
+ rangeSlots = group.members().stream()
+ .map(index -> slots.get(index).id()).toList();
+ }
+ if (rangeSlots.size() > 9
+ || new java.util.HashSet<>(rangeSlots).size() != rangeSlots.size())
+ throw error(upgrades,
+ "range-slots requires at most nine distinct slots");
+ for (String rangeSlot : rangeSlots) {
+ var index = ids.get(rangeSlot);
+ if (index == null || slots.get(index).role() != Role.MANUAL)
+ throw error(upgrades,
+ "range-slots must name real manual item slots");
+ if (rangeSlot.equals(gearboxSlot)
+ || rangeSlot.equals(capacitorSlot))
+ throw error(upgrades,
+ "Range sockets cannot overlap component sockets");
+ if (groups.values().stream().anyMatch(
+ group -> group.automation() && group.members().contains(index)))
+ throw error(upgrades, "range-slots must not expose automation");
+ var slot = slots.get(index);
+ slots.set(index, new Slot(slot.id(), slot.role(), 1, slot.itemTag(),
+ slot.admission()));
+ }
+ if (capacitorSlot != null && !energyCapacitors)
+ throw error(upgrades,
+ "Selected energy provider does not enable capacitor upgrades");
+ if (capacitorSlot != null && power == null)
+ throw error(upgrades, "capacitor-slot requires energy storage");
+ if (capacitorSlot != null && capacitorSlot.equals(gearboxSlot))
+ throw error(upgrades,
+ "Gearbox and capacitor require different slots");
+ String legacyUpgradeStorage = upgrades == null
+ ? null
+ : upgrades.attributes().get("legacy-layout");
+ if (legacyUpgradeStorage != null
+ && (!"mmdlib_gearbox/0".equals(gearboxSlot)
+ || !"mmdlib_capacitor/0".equals(capacitorSlot)
+ || rangeSlots.size() != 9 || !legacyUpgradeStorage
+ .equals(upgrades.attributes().get("range-storage"))))
+ throw error(upgrades,
+ "legacy-layout requires automatic components and nine range-storage slots in the same named inventory");
+ for (String attribute : List.of("gearbox-slot", "capacitor-slot")) {
+ if (upgrades == null
+ || !upgrades.attributes().containsKey(attribute))
+ continue;
+ var index = ids.get(required(upgrades, attribute));
+ if (index == null || slots.get(index).role() != Role.MANUAL)
+ throw error(upgrades,
+ attribute + " must name a real manual item slot");
+ if (groups.values().stream().anyMatch(
+ group -> group.automation() && group.members().contains(index)))
+ throw error(upgrades,
+ attribute + " must not expose automation");
+ var slot = slots.get(index);
+ slots.set(index, new Slot(slot.id(), slot.role(), 8, slot.itemTag(),
+ slot.admission()));
}
MachineBehavior behavior;
try {
@@ -759,31 +1048,61 @@ else if (prior != null)
block.attributes().containsKey("on-secondary-use")
? resource(block, "on-secondary-use")
: null,
- display, itemDisplay);
+ display, itemDisplay, visualizerStyle, gearboxSlot,
+ capacitorSlot, rangeSlots, legacyUpgradeStorage,
+ MachineFacing.parse(
+ block.attributes().getOrDefault("facing", "horizontal"),
+ block.attributes().getOrDefault("placement-facing",
+ "toward-player")),
+ redstone == null
+ ? null
+ : redstone.attributes().get("comparator-source"),
+ processorConfigs.size() == 1
+ && !processor.attributes().containsKey("bindings")
+ && processorConfigs.getFirst().energyPerTick() == 0
+ ? List.of()
+ : processorConfigs);
} catch (IllegalArgumentException ex) {
throw error(block, ex.getMessage());
}
+ var admissions = new ArrayList();
+ slots.forEach(slot -> {
+ if (slot.admission() != null)
+ admissions.add(slot.admission());
+ });
+ tanks.forEach(tank -> {
+ if (tank.admission() != null)
+ admissions.add(tank.admission());
+ });
+ for (var admission : admissions)
+ if (admission.processor() != null && processorConfigs.stream()
+ .noneMatch(config -> config.id().equals(admission.processor())
+ && config.declaration() != null
+ && zone.moddev.mc.lib.machine.feature.StorageAdmission.class
+ .isAssignableFrom(config.declaration().type())))
+ throw error(root,
+ "filter-processor must name a processor implementing StorageAdmission: "
+ + admission.processor());
if (behavior.secondaryAction() != null && (prototype == null
|| !prototype.actions().containsKey(behavior.secondaryAction())))
throw error(block, "Unknown secondary-use processor action: "
+ behavior.secondaryAction());
if (display != null) {
- if (!custom || (display.item() && !behavior.portable()))
+ if (schemas.isEmpty() || (display.item() && !behavior.portable()))
throw error(displayNode,
"Entity displays require a custom processor; item displays require portable machines");
try {
- display.validate(Map.of(required(processor, "id"), prototype));
+ display.validate(schemas);
} catch (IllegalArgumentException ex) {
throw error(displayNode, ex.getMessage());
}
}
if (itemDisplay != null) {
- if (prototype == null)
+ if (schemas.isEmpty())
throw error(itemDisplayNode,
"Item displays require a custom processor with a synchronized variable");
try {
- itemDisplay
- .validate(Map.of(required(processor, "id"), prototype));
+ itemDisplay.validate(schemas);
} catch (IllegalArgumentException ex) {
throw error(itemDisplayNode, ex.getMessage());
}
@@ -798,7 +1117,7 @@ else if (prior != null)
number(power, "capacity", 1, Long.MAX_VALUE),
number(power, "input-rate", 0, Long.MAX_VALUE),
number(power, "output-rate", 0, Long.MAX_VALUE),
- energyColor, energyName),
+ energyColor, energyName, energyProvider, energyCapacitors),
fluidNode == null
? null
: new Fluids(required(fluidNode, "id"), tanks,
@@ -1048,6 +1367,21 @@ private static long number(Node node, String key, long min, long max) {
throw error(node, key + " must be in " + min + ".." + max);
}
+ private static String componentSocket(Node origin, List slots,
+ Map groups, Map ids, String kind) {
+ String inventory = "mmdlib_" + kind;
+ String id = inventory + "/0";
+ if (groups.containsKey(inventory) || ids.containsKey(id))
+ throw error(origin, "Reserved component storage: " + inventory);
+ int index = slots.size();
+ slots.add(new Slot(id, Role.MANUAL, 8,
+ ResourceLocation.parse("mmdlib:" + kind + "_upgrades")));
+ ids.put(id, index);
+ groups.put(inventory, new Group(inventory, List.of(index),
+ IoMode.DISABLED, 0xffffff, false, kind));
+ return id;
+ }
+
private static int defaultItemColor(Map groups,
IoMode mode) {
int ordinal = (int) groups.values().stream()
@@ -1056,7 +1390,11 @@ private static int defaultItemColor(Map groups,
}
private static int color(Node node, int fallback) {
- var value = node.attributes().get("color");
+ return color(node, "color", fallback);
+ }
+
+ private static int color(Node node, String attribute, int fallback) {
+ var value = node.attributes().get(attribute);
if (value == null)
return fallback;
try {
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFacing.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFacing.java
new file mode 100644
index 00000000..3958e29e
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFacing.java
@@ -0,0 +1,97 @@
+package zone.moddev.mc.lib.machine.definition;
+
+import java.util.EnumSet;
+import java.util.Set;
+
+import net.minecraft.core.Direction;
+import net.minecraft.world.phys.Vec3;
+
+/** Allowed fronts and the independent placement preference. */
+public record MachineFacing(Set directions, boolean towardPlayer) {
+ public static final MachineFacing DEFAULT = parse("horizontal",
+ "toward-player");
+
+ public MachineFacing {
+ directions = Set.copyOf(directions);
+ if (directions.isEmpty())
+ throw new IllegalArgumentException(
+ "Facing requires at least one direction");
+ }
+
+ public static MachineFacing parse(String faces, String placement) {
+ var directions = EnumSet.noneOf(Direction.class);
+ if (faces.equals("horizontal"))
+ directions.addAll(Set.of(Direction.NORTH, Direction.SOUTH,
+ Direction.EAST, Direction.WEST));
+ else if (faces.equals("all"))
+ directions = EnumSet.allOf(Direction.class);
+ else
+ for (var name : faces.trim().split("\\s+")) {
+ var direction = Direction.byName(name);
+ if (direction == null || !directions.add(direction))
+ throw new IllegalArgumentException(
+ "Invalid or duplicate facing: " + name);
+ }
+ if (!placement.equals("toward-player")
+ && !placement.equals("away-from-player"))
+ throw new IllegalArgumentException(
+ "Invalid placement-facing: " + placement);
+ return new MachineFacing(directions, placement.equals("toward-player"));
+ }
+
+ public boolean horizontal() {
+ return directions.stream().noneMatch(d -> d.getAxis().isVertical());
+ }
+
+ public Direction defaultDirection() {
+ return directions.contains(Direction.NORTH)
+ ? Direction.NORTH
+ : java.util.Arrays.stream(Direction.values())
+ .filter(directions::contains).findFirst().orElseThrow();
+ }
+
+ /**
+ * Ordered nearest-look directions, as supplied by the placement context.
+ */
+ public Direction placement(Direction[] nearest) {
+ for (var direction : nearest) {
+ var front = towardPlayer ? direction.getOpposite() : direction;
+ if (directions.contains(front))
+ return front;
+ }
+ return defaultDirection();
+ }
+
+ public Direction transformed(Direction current, Direction proposed) {
+ return directions.contains(proposed) ? proposed : current;
+ }
+
+ /**
+ * Rotates north-authored block coordinates; vertical fronts have north as
+ * top.
+ */
+ public static Vec3 point(Direction front, double x, double y, double z) {
+ return switch (front) {
+ case NORTH -> new Vec3(x, y, z);
+ case EAST -> new Vec3(1 - z, y, x);
+ case SOUTH -> new Vec3(1 - x, y, 1 - z);
+ case WEST -> new Vec3(z, y, 1 - x);
+ case UP -> new Vec3(1 - x, 1 - z, 1 - y);
+ case DOWN -> new Vec3(x, z, 1 - y);
+ };
+ }
+
+ /** Model JSON rotations, matching point(). */
+ public static int modelX(Direction front) {
+ return front == Direction.UP ? 270 : front == Direction.DOWN ? 90 : 0;
+ }
+
+ public static int modelY(Direction front) {
+ return switch (front) {
+ case EAST -> 90;
+ case SOUTH, UP -> 180;
+ case WEST -> 270;
+ default -> 0;
+ };
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java
index a027a422..c2b3da79 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java
@@ -17,6 +17,7 @@
import zone.moddev.mc.lib.gui.load.ScreenException;
import zone.moddev.mc.lib.gui.load.ScreenFillGenerator;
import zone.moddev.mc.lib.gui.load.ScreenReader.Node;
+import zone.moddev.mc.lib.gui.load.ScreenTags;
import zone.moddev.mc.lib.gui.model.ElementGroup;
import zone.moddev.mc.lib.gui.model.Screen;
import zone.moddev.mc.lib.machine.feature.Processor;
@@ -34,6 +35,16 @@ public interface Generator {
private static final Map GENERATORS = new LinkedHashMap<>();
static {
+ register(ResourceLocation.parse("mmdlib:component-upgrades"),
+ (machine, node) -> {
+ options(node, Set.of());
+ if (machine.behavior().gearboxSlot() == null
+ && machine.behavior().capacitorSlot() == null)
+ return List.of();
+ return List.of(n(node, "upgrades-drawer",
+ Map.of("id", "upgrades"),
+ List.of(n(node, "machine-upgrades", Map.of(), List.of()))));
+ });
register(ResourceLocation.parse("mmdlib:processing"),
MachineScreenGenerators::processing);
register(ResourceLocation.parse("mmdlib:resource-groups"),
@@ -43,9 +54,9 @@ public interface Generator {
register(ResourceLocation.parse("mmdlib:processors"),
(machine, node) -> {
options(node, Set.of());
- return machine.processingType().isEmpty()
- ? List.of()
- : List.of(progress(machine, node));
+ return machine.processors().stream()
+ .filter(config -> config.recipeType() != null)
+ .map(config -> progress(machine, config, node)).toList();
});
}
@@ -57,26 +68,102 @@ private MachineScreenGenerators() {
*/
public static ScreenFillGenerator forMachines(
Map machines) {
+ return forMachines(machines, null);
+ }
+
+ private static ScreenFillGenerator forMachines(
+ Map machines, Node composed) {
return new ScreenFillGenerator() {
+ @Override
+ public ScreenFillGenerator forScreen(ResourceLocation id,
+ Node root) {
+ return forMachines(machines, root);
+ }
+
@Override
public List generate(ResourceLocation id, Node node) {
- return MachineScreenGenerators.generate(machines.get(id), node);
+ var machine = machines.get(id);
+ if (machine != null && composed != null) {
+ var generator = MachineDefinitions.resource(node,
+ "generator");
+ if (generator.equals(
+ ResourceLocation.parse("mmdlib:component-upgrades"))
+ && declaresUpgradeLayout(composed))
+ return List.of();
+ var claimed = upgradeSlots(machine, composed);
+ if (generator
+ .equals(ResourceLocation.parse("mmdlib:processing")))
+ return processing(machine, node, claimed);
+ if (generator.equals(
+ ResourceLocation.parse("mmdlib:resource-groups")))
+ return resources(machine, node, claimed);
+ }
+ return MachineScreenGenerators.generate(machine, node);
+ }
+
+ @Override
+ public Node prepareElement(ResourceLocation id, Node node) {
+ var machine = machines.get(id);
+ if (machine != null && machine.processors().size() > 1
+ && node.tag().equals(ScreenTags.name("inventory-controls"))
+ && node.children().size() == 1
+ && node.children().getFirst().name()
+ .equals("processor-button")
+ && node.children().getFirst().attributes()
+ .equals(Map.of("id", "toggle_0"))) {
+ var buttons = machine.processors().stream()
+ .map(config -> n(node, "processor-button",
+ Map.of("id", "toggle_" + config.id(),
+ "processor-key", config.id()),
+ List.of()))
+ .toList();
+ return new Node(node.name(), node.attributes(), buttons,
+ node.source(), node.line(), node.namespace());
+ }
+ if (machine != null
+ && node.tag().equals(ScreenTags.name("machine-upgrades")))
+ return upgradeSockets(machine, node);
+ if (machine == null
+ || !node.tag().equals(ScreenTags.name("inventory"))
+ || !node.children().isEmpty()
+ || node.attributes().containsKey("count"))
+ return node;
+ String storage = node.attributes().get("storage");
+ int count = machine.inventorySlots(storage).size();
+ if (count == 0)
+ throw MachineDefinitions.error(node,
+ "Automatic inventory requires a non-empty item storage: "
+ + storage);
+ var attributes = new LinkedHashMap<>(node.attributes());
+ attributes.put("count", Integer.toString(count));
+ return new Node(node.name(), attributes, node.children(),
+ node.source(), node.line(), node.namespace());
}
@Override
public boolean includeDefault(ResourceLocation id, Node node) {
var filter = MachineDefinitions.resource(node,
"default-filter");
+ var machine = machines.get(id);
if (!filter.equals(
ResourceLocation.parse("mmdlib:processor-controls")))
throw MachineDefinitions.error(node,
"Unknown machine default filter " + filter);
- var machine = machines.get(id);
return machine == null || machine.hasProcessor();
}
};
}
+ /**
+ * An authored upgrade layout replaces the inherited components-only drawer.
+ */
+ private static boolean declaresUpgradeLayout(Node node) {
+ return node.tag().equals(ScreenTags.name("upgrades-drawer"))
+ || node.tag().equals(ScreenTags.name("machine-upgrades"))
+ || node.children().stream()
+ .anyMatch(MachineScreenGenerators::declaresUpgradeLayout);
+ }
+
public static synchronized void register(ResourceLocation id,
Generator generator) {
if (GENERATORS.putIfAbsent(id,
@@ -85,6 +172,107 @@ public static synchronized void register(ResourceLocation id,
"Duplicate fill generator " + id);
}
+ /**
+ * Compose independent library sockets and the machine's own upgrade
+ * inventory.
+ */
+ private static Node upgradeSockets(MachineDefinition machine, Node node) {
+ if (!node.children().isEmpty())
+ throw MachineDefinitions.error(node,
+ "machine-upgrades is a shorthand without children; use ordinary inventories for an explicit layout");
+ String storage = node.attributes().get("storage");
+ var members = storage == null
+ ? List.of()
+ : machine.inventorySlots(storage);
+ if (storage != null && members.isEmpty())
+ throw MachineDefinitions.error(node,
+ "Unknown upgrade storage: " + storage);
+ var behavior = machine.behavior();
+ var components = new ArrayList();
+ var componentIndexes = new java.util.HashSet();
+ String prefix = node.attributes().containsKey("id")
+ ? node.attributes().get("id") + "_"
+ : "";
+ for (String kind : List.of("gearbox", "capacitor")) {
+ String address = kind.equals("gearbox")
+ ? behavior.gearboxSlot()
+ : behavior.capacitorSlot();
+ if (address == null)
+ continue;
+ int index = java.util.stream.IntStream
+ .range(0, machine.slots().size())
+ .filter(i -> machine.slots().get(i).id().equals(address))
+ .findFirst().orElseThrow();
+ componentIndexes.add(index);
+ String inventory = machine.inventoryNames().get(index);
+ int local = machine.inventorySlots(inventory).indexOf(index);
+ var slot = upgradeSocket(machine, node, index, local, prefix + kind,
+ kind);
+ components.add(n(node, "inventory",
+ Map.of("storage", inventory, "columns", "1", "spacing", "0"),
+ List.of(slot)));
+ }
+ var extras = members.stream()
+ .filter(index -> !componentIndexes.contains(index)).toList();
+ if (extras.size() > 9)
+ throw MachineDefinitions.error(node,
+ "Machine upgrades supports at most nine extra sockets");
+ var rows = new ArrayList();
+ if (!components.isEmpty())
+ rows.add(n(node, "vbox",
+ Map.of("padding", "0", "spacing", "0", "align", "center"),
+ List.of(n(node, "hbox",
+ Map.of("padding", "0", "spacing", "6", "align", "center"),
+ components))));
+ if (!extras.isEmpty()) {
+ var slots = new ArrayList();
+ for (int index : extras) {
+ int local = members.indexOf(index);
+ slots.add(upgradeSocket(machine, node, index, local,
+ prefix + storage + "_" + local, "range"));
+ }
+ rows.add(n(node, "inventory",
+ Map.of("storage", storage, "columns", "3", "spacing", "2"),
+ slots));
+ }
+ if (rows.isEmpty())
+ throw MachineDefinitions.error(node,
+ "Machine has no upgrade sockets");
+ var attributes = new LinkedHashMap<>(node.attributes());
+ attributes.remove("storage");
+ attributes.put("padding", "0");
+ attributes.put("spacing", "8");
+ attributes.put("align", "center");
+ return n(node, "vbox", attributes, rows);
+ }
+
+ private static Node upgradeSocket(MachineDefinition machine, Node node,
+ int index, int local, String id, String kind) {
+ var slot = machine.slots().get(index);
+ if (slot.role() != zone.moddev.mc.lib.api.capabilities.Role.MANUAL
+ || (kind.equals("range") && slot.itemTag() == null
+ && !machine.behavior().rangeSlots().contains(slot.id())))
+ throw MachineDefinitions.error(node,
+ "Upgrade socket must be manual and declare an upgrade binding or item-tag: "
+ + slot.id());
+ var attributes = new LinkedHashMap();
+ attributes.put("id", id);
+ attributes.put("index", Integer.toString(local));
+ attributes.put("item-tag",
+ slot.itemTag() != null
+ ? slot.itemTag().toString()
+ : "mmdlib:" + kind + "_upgrades");
+ attributes.put("kind", "upgrade");
+ attributes.put("max-stack-size", kind.equals("range") ? "1" : "8");
+ attributes.put("size", "normal");
+ attributes.put("item-size", "16");
+ if (!kind.equals("range")) {
+ attributes.put("icon", "mmdlib:socket_" + kind);
+ attributes.put("tooltip", "screen.mmdlib.upgrades." + kind);
+ }
+ return n(node, "upgrade-slot", attributes, List.of());
+ }
+
public static List generate(MachineDefinition machine, Node node) {
if (machine == null)
throw MachineDefinitions.error(node,
@@ -115,12 +303,10 @@ public static void validate(MachineDefinition machine, Screen screen) {
Map.of("processors",
!machine.hasProcessor()
? Set.of()
- : Set.of(machine.processor())));
- Map> declared = machine.behavior()
- .processor() == null
- ? Map.of()
- : Map.of(machine.processor(),
- machine.behavior().processor().schema(machine.processor()));
+ : machine.processors().stream()
+ .map(ProcessorConfiguration::id)
+ .collect(java.util.stream.Collectors.toSet())));
+ Map> declared = machine.processorSchemas();
var defaults = machine.visualDefaults(
machine.hasProcessor() ? declared.get(machine.processor()) : null);
for (var element : screen.elements()) {
@@ -143,6 +329,8 @@ public static Map> compileHighlights(
validate(machine, screen);
var groups = new ArrayList();
for (var group : machine.groups()) {
+ if (!group.automation())
+ continue;
var local = java.util.stream.IntStream
.range(0, machine.inventorySlots(group.id()).size()).boxed()
.toList();
@@ -181,28 +369,44 @@ private static void options(Node node, Set allowed) {
"Unknown generator option " + key);
}
- private static Node progress(MachineDefinition machine, Node node) {
- return n(node, "progress",
- Map.of("id", "generated_progress", "value", "#getProgress", "max",
- "#getTime", "jei-recipes",
- machine.recipeType().id().toString()),
- List.of());
+ private static Node progress(MachineDefinition machine,
+ ProcessorConfiguration config, Node node) {
+ return n(node, "progress", Map.of("id",
+ machine.processors().size() == 1
+ ? "generated_progress"
+ : "generated_progress_" + config.id(),
+ "value",
+ machine.processors().size() == 1
+ ? "#getProgress"
+ : "#getProgress(" + machine.processors().indexOf(config) + ")",
+ "max",
+ machine.processors().size() == 1
+ ? "#getTime"
+ : "#getTime(" + machine.processors().indexOf(config) + ")",
+ "jei-recipes", config.recipeType().id().toString()), List.of());
}
private static List processing(MachineDefinition machine, Node node) {
+ return processing(machine, node,
+ upgradeSlots(machine, machine.screen()));
+ }
+
+ private static List processing(MachineDefinition machine, Node node,
+ Set claimed) {
options(node, Set.of());
var main = new ArrayList();
main.add(spacer(node));
- main.addAll(groups(machine, node, IoMode.INPUT, 3));
- if (machine.processingType().isPresent())
- main.add(progress(machine, node));
- main.addAll(groups(machine, node, IoMode.OUTPUT, 3));
+ main.addAll(groups(machine, node, IoMode.INPUT, 3, claimed));
+ for (var config : machine.processors())
+ if (config.recipeType() != null)
+ main.add(progress(machine, config, node));
+ main.addAll(groups(machine, node, IoMode.OUTPUT, 3, claimed));
main.add(spacer(node));
var rows = new ArrayList();
rows.add(spacer(node));
rows.add(
n(node, "hbox", Map.of("spacing", "6", "align", "center"), main));
- var storage = groups(machine, node, IoMode.BOTH, 3);
+ var storage = groups(machine, node, IoMode.BOTH, 3, claimed);
if (!storage.isEmpty()) {
storage.addFirst(spacer(node));
storage.addLast(spacer(node));
@@ -216,6 +420,12 @@ private static List processing(MachineDefinition machine, Node node) {
}
private static List resources(MachineDefinition machine, Node node) {
+ return resources(machine, node,
+ upgradeSlots(machine, machine.screen()));
+ }
+
+ private static List resources(MachineDefinition machine, Node node,
+ Set claimed) {
options(node, Set.of("role", "columns"));
String role = MachineDefinitions.required(node, "role");
IoMode mode = switch (role) {
@@ -234,7 +444,7 @@ private static List resources(MachineDefinition machine, Node node) {
}
if (columns < 1 || columns > 9)
throw MachineDefinitions.error(node, "columns must be 1..9");
- return groups(machine, node, mode, columns);
+ return groups(machine, node, mode, columns, claimed);
}
private static List tanks(MachineDefinition machine, Node node) {
@@ -249,7 +459,7 @@ private static List tanks(MachineDefinition machine, Node node) {
}
private static List groups(MachineDefinition machine, Node node,
- IoMode mode, int columns) {
+ IoMode mode, int columns, Set claimed) {
var result = new ArrayList();
if (mode == IoMode.INPUT)
for (var ghost : machine.ghosts()) {
@@ -263,31 +473,95 @@ private static List groups(MachineDefinition machine, Node node,
result.add(n(node, "inventory", Map.of("storage", ghost.id(),
"columns", Integer.toString(columns)), children));
}
- for (var group : machine.groups())
- if (group.mode() == mode
- || (mode == IoMode.BOTH && group.mode() == IoMode.DISABLED)) {
+ for (var group : machine.groups()) {
+ var unclaimed = group.members().stream()
+ .filter(index -> !claimed.contains(index)).toList();
+ if (!unclaimed.isEmpty() && (group.mode() == mode
+ || (mode == IoMode.BOTH && group.mode() == IoMode.DISABLED))) {
var rows = new ArrayList();
rows.add(spacer(node));
var children = new ArrayList();
var members = machine.inventorySlots(group.id());
- for (int index : group.members())
+ for (int index : unclaimed)
children.add(n(node, "item-slot",
Map.of("id", "slot_" + index, "index",
Integer.toString(members.indexOf(index))),
List.of()));
- rows.add(n(node, "coloured-group",
- Map.of("id", "inventory_" + group.id(), "color",
- String.format("#%06X", group.color() & 0xffffff)),
- List.of(n(node, "inventory",
- Map.of("storage", group.id(), "columns",
- Integer.toString(columns), "spacing", "2"),
- children))));
+ var inventory = n(node, "inventory",
+ Map.of("storage", group.id(), "columns",
+ Integer.toString(columns), "spacing", "2"),
+ children);
+ rows.add(
+ group.automation()
+ ? n(node, "coloured-group",
+ Map.of("id", "inventory_" + group.id(), "color",
+ String.format("#%06X",
+ group.color() & 0xffffff)),
+ List.of(inventory))
+ : inventory);
rows.add(spacer(node));
result.add(n(node, "vbox", Map.of("spacing", "2"), rows));
}
+ }
return result;
}
+ /**
+ * Only upgrade layouts reserve slots; unrelated manual slots stay visible.
+ */
+ private static Set upgradeSlots(MachineDefinition machine,
+ Node screen) {
+ var claimed = new java.util.HashSet();
+ collectUpgradeSlots(machine, screen, null, false, claimed);
+ if (!declaresUpgradeLayout(screen) && hasComponentGenerator(screen)) {
+ for (int i = 0; i < machine.slots().size(); i++) {
+ String id = machine.slots().get(i).id();
+ if (id.equals(machine.behavior().gearboxSlot())
+ || id.equals(machine.behavior().capacitorSlot()))
+ claimed.add(i);
+ }
+ }
+ return Set.copyOf(claimed);
+ }
+
+ private static boolean hasComponentGenerator(Node node) {
+ return "mmdlib:component-upgrades"
+ .equals(node.attributes().get("generator"))
+ || node.children().stream()
+ .anyMatch(MachineScreenGenerators::hasComponentGenerator);
+ }
+
+ private static void collectUpgradeSlots(MachineDefinition machine,
+ Node node, String inventory, boolean upgrade, Set claimed) {
+ if (node.tag().equals(ScreenTags.name("machine-upgrades"))) {
+ collectUpgradeSlots(machine, upgradeSockets(machine, node),
+ inventory, true, claimed);
+ return;
+ }
+ upgrade |= node.tag().equals(ScreenTags.name("upgrades-drawer"));
+ if (node.tag().equals(ScreenTags.name("inventory"))) {
+ inventory = node.attributes().get("storage");
+ if (upgrade && node.children().isEmpty()) {
+ var members = machine.inventorySlots(inventory);
+ int count = Integer.parseInt(node.attributes()
+ .getOrDefault("count", Integer.toString(members.size())));
+ claimed.addAll(
+ members.subList(0, Math.min(count, members.size())));
+ }
+ }
+ if (upgrade && inventory != null
+ && Set.of("slot", "item-slot", "upgrade-slot").stream()
+ .anyMatch(name -> node.tag().equals(ScreenTags.name(name)))) {
+ var members = machine.inventorySlots(inventory);
+ int local = Integer
+ .parseInt(node.attributes().getOrDefault("index", "0"));
+ if (local >= 0 && local < members.size())
+ claimed.add(members.get(local));
+ }
+ for (var child : node.children())
+ collectUpgradeSlots(machine, child, inventory, upgrade, claimed);
+ }
+
private static Node n(Node origin, String name,
Map attributes, List children) {
return new Node(name, attributes, List.copyOf(children),
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorConfiguration.java b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorConfiguration.java
new file mode 100644
index 00000000..5812ed76
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorConfiguration.java
@@ -0,0 +1,36 @@
+package zone.moddev.mc.lib.machine.definition;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A stable processor identity and its private view of shared physical
+ * resources.
+ */
+public record ProcessorConfiguration(String id, String name,
+ MachineDefinition.RecipeType recipeType, ProcessorDeclaration declaration,
+ Map bindings, List filterInputs,
+ MachineDefinition.RecipeSelection selection,
+ MachineDefinition.Sounds sounds, MachineDefinition.Events events,
+ long energyPerTick) {
+ public ProcessorConfiguration(String id, String name,
+ MachineDefinition.RecipeType recipeType,
+ ProcessorDeclaration declaration, Map bindings,
+ List filterInputs, MachineDefinition.RecipeSelection selection,
+ MachineDefinition.Sounds sounds, MachineDefinition.Events events) {
+ this(id, name, recipeType, declaration, bindings, filterInputs,
+ selection, sounds, events, 0);
+ }
+ public ProcessorConfiguration {
+ if (id == null || id.isBlank()
+ || (recipeType == null) == (declaration == null))
+ throw new IllegalArgumentException(
+ "A processor needs an ID and exactly one implementation");
+ if (energyPerTick < 0)
+ throw new IllegalArgumentException(
+ "Negative processor energy cost");
+ bindings = java.util.Collections
+ .unmodifiableMap(new java.util.LinkedHashMap<>(bindings));
+ filterInputs = List.copyOf(filterInputs);
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java
index 25e54b42..0baabf89 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java
@@ -25,14 +25,25 @@ public synchronized zone.moddev.mc.lib.machine.feature.Processor> schema(
return schemas.computeIfAbsent(key, id -> new Schema(create(id, null)));
}
+ /** Declared source IDs, without evaluating live redstone levels. */
+ public java.util.List redstoneOutputIds(String key) {
+ return ((Schema) schema(key)).redstoneOutputIds;
+ }
+
private static final class Schema implements
zone.moddev.mc.lib.machine.feature.Processor {
private final StoredProcessor prototype;
+ private final java.util.List