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 `",
+ """
+
+
+ """)
+ .replace("",
+ "");
+ write(xml);
+ var id = ResourceLocation.parse("test:crusher");
+ var definition = MachineDefinitions.load(sources()).get(id);
+ assertEquals("mmdlib_gearbox/0", definition.behavior().gearboxSlot());
+ assertEquals("upgrades/5", definition.behavior().capacitorSlot());
+ assertEquals(8,
+ definition.slots().stream()
+ .filter(slot -> slot.id().equals("upgrades/5")).findFirst()
+ .orElseThrow().limit());
+ write(xml.replace(" MachineDefinitions.load(sources()));
+ }
+ }
+
+ @Test
+ void gearboxSocketKeepsItsIdentityAndRaisesOnlyItsLimit() throws Exception {
+ String xml = crusher()
+ .replace("",
+ """
+
+
+ """)
+ .replace("",
+ "");
+ write(xml);
+ var definition = MachineDefinitions.load(sources())
+ .get(ResourceLocation.parse("test:crusher"));
+ assertEquals("upgrades/4", definition.behavior().gearboxSlot());
+ for (var slot : definition.slots()) {
+ if (slot.id().startsWith("upgrades/"))
+ assertEquals(slot.id().equals("upgrades/4") ? 8 : 1,
+ slot.limit());
+ }
+ for (String slot : List.of("missing", "input/0", "upgrades/99")) {
+ write(xml.replace("gearbox-slot=\"upgrades/4\"",
+ "gearbox-slot=\"" + slot + "\""));
+ assertThrows(IllegalArgumentException.class,
+ () -> MachineDefinitions.load(sources()));
+ }
+ write(xml.replace("automation=\"false\"", "automation=\"true\""));
+ assertThrows(IllegalArgumentException.class,
+ () -> MachineDefinitions.load(sources()));
+ }
+
+ @Test
+ void itemTagFiltersBelongToStoredSlots() throws Exception {
+ write(crusher().replace("role=\"input\"",
+ "role=\"input\" item-tag=\"minecraft:hoes\""));
+ var definition = MachineDefinitions.load(sources())
+ .get(ResourceLocation.parse("test:crusher"));
+ assertTrue(definition.slots().stream()
+ .filter(slot -> slot
+ .role() == zone.moddev.mc.lib.api.capabilities.Role.INPUT)
+ .allMatch(slot -> ResourceLocation.parse("minecraft:hoes")
+ .equals(slot.itemTag())));
+ }
+
+ @Test
+ void visualizerColorsDefaultInheritAndRejectMalformedValues()
+ throws Exception {
+ write(crusher());
+ var id = ResourceLocation.parse("test:crusher");
+ assertEquals(
+ zone.moddev.mc.lib.machine.presentation.VisualizerStyle.DEFAULT,
+ MachineDefinitions.load(sources()).get(id).behavior()
+ .visualizers());
+ String base = crusher().replace("",
+ "");
+ write(base);
+ var style = MachineDefinitions.load(sources()).get(id).behavior()
+ .visualizers();
+ assertEquals(0x123456, style.rangeColor());
+ assertEquals(0xabcdef, style.workColor());
+ Files.writeString(directory.resolve("machine/child.xml"),
+ """
+
+
+
+ """);
+ var child = MachineDefinitions.load(sources())
+ .get(ResourceLocation.parse("test:child"));
+ assertEquals(0x123456, child.behavior().visualizers().rangeColor());
+ assertEquals(0x010203, child.behavior().visualizers().workColor());
+ for (String invalid : List.of("#12345", "#ff123456", "banana")) {
+ write(base.replace("#ABCDEF", invalid));
+ assertThrows(IllegalArgumentException.class,
+ () -> MachineDefinitions.load(sources()));
+ }
+ }
+
private String fluidMachine(String name) throws Exception {
return Files.readString(
Path.of("src/companionTest/resources/mmdlib/machine/test/" + name
@@ -156,7 +302,11 @@ void publicConstructorsRejectMismatchedProcessingConfiguration()
@Test
void originalConstructorRetainsAutomaticCubeDefaults() throws Exception {
- write(crusher());
+ // Preserve the original defaults without inherited component sockets.
+ write(crusher()
+ .replace("mmdlib:base_powered_machine", "mmdlib:base_machine")
+ .replace("",
+ ""));
var d = MachineDefinitions.load(sources())
.get(ResourceLocation.parse("test:crusher"));
var compatible = new MachineDefinition(d.id(), d.checksum(), d.name(),
@@ -216,7 +366,8 @@ void ghostInputsAreDeclaredUnderItemsWithoutAllocatingRealStorage()
"" + ghost));
var machine = MachineDefinitions.load(sources())
.get(ResourceLocation.parse("test:crusher"));
- assertEquals(3, machine.slots().size());
+ assertEquals(5, machine.slots().size()); // Three process slots plus
+ // inherited components.
assertEquals(1, machine.ghosts().size());
assertEquals("pattern", machine.ghosts().getFirst().id());
assertEquals(ResourceLocation.parse("minecraft:stone"),
@@ -577,7 +728,8 @@ void groupNamesGenerateTranslationsForAllResourceKinds() throws Exception {
.get(ResourceLocation.parse("test:crusher"));
var expected = Map.of("energy", "Power Supply", "water",
"Water Catalyst", "buffer", "Fluid Buffer", "pattern",
- "Rock Selection", "input", "input", "output", "Products");
+ "Rock Selection", "input", "input", "output", "Products",
+ "mmdlib_gearbox", "gearbox", "mmdlib_capacitor", "capacitor");
assertEquals(expected, machine.groupNames());
assertThrows(UnsupportedOperationException.class,
() -> machine.groupNames().put("injected", "Invalid"));
@@ -633,9 +785,12 @@ void inheritedNamesAndExplicitGroupOverridesKeepStableIds()
.get(ResourceLocation.parse("test:crusher"));
assertEquals(
Map.of("input", "Raw Materials", "output", "Finished Products",
- "water", "Reusable Water", "energy", "Electricity"),
+ "water", "Reusable Water", "energy", "Electricity",
+ "mmdlib_gearbox", "gearbox", "mmdlib_capacitor", "capacitor"),
machine.groupNames());
- assertEquals(List.of("input/0", "input/1", "output/0", "output/1"),
+ assertEquals(
+ List.of("input/0", "input/1", "output/0", "output/1",
+ "mmdlib_gearbox/0", "mmdlib_capacitor/0"),
machine.slots().stream().map(MachineDefinition.Slot::id).toList());
assertFalse(machine.fluids().groups().getFirst().automation());
assertEquals("test:crusher.group.input",
@@ -689,6 +844,38 @@ void manualTanksCanRemainRecipeGroupsWithoutAutomation() throws Exception {
() -> MachineDefinitions.load(sources()));
}
+ @Test
+ void manualItemStorageCanOptOutOfAutomationWithoutLosingItsIdentity()
+ throws Exception {
+ var xml = crusher().replace("",
+ "");
+ write(xml);
+ var machine = MachineDefinitions.load(sources())
+ .get(ResourceLocation.parse("test:crusher"));
+ assertFalse(machine.groups().stream()
+ .filter(group -> group.id().equals("upgrades")).findFirst()
+ .orElseThrow().automation());
+ assertTrue(machine.groups().getFirst().automation());
+ assertEquals(11, machine.inventorySlots("upgrades").size());
+ assertEquals("upgrades/0", machine.slots()
+ .get(machine.inventorySlots("upgrades").getFirst()).id());
+ write(xml.replace(" group.id().equals("upgrades")).findFirst()
+ .orElseThrow();
+ assertFalse(upgrades.automation());
+ assertEquals("Components", upgrades.name());
+ write(xml.replace("role=\"manual\"", "role=\"storage\""));
+ assertTrue(assertThrows(IllegalArgumentException.class,
+ () -> MachineDefinitions.load(sources())).getMessage()
+ .contains("role=manual"));
+ write(xml.replace("automation=\"false\"", "automation=\"invalid\""));
+ assertThrows(IllegalArgumentException.class,
+ () -> MachineDefinitions.load(sources()));
+ }
+
@Test
void inheritsPowerAndExpandsStableGroupsAndCustomProperties()
throws Exception {
@@ -700,7 +887,9 @@ void inheritsPowerAndExpandsStableGroupsAndCustomProperties()
assertEquals(1000, machine.power().input());
assertEquals(0xd85b5b, machine.power().color());
assertEquals("Energy", machine.power().name());
- assertEquals(List.of("input/0", "output/0", "output/1"),
+ assertEquals(
+ List.of("input/0", "output/0", "output/1", "mmdlib_gearbox/0",
+ "mmdlib_capacitor/0"),
machine.slots().stream().map(s -> s.id()).toList());
assertEquals(List.of(1, 2), machine.groups().get(1).members());
assertEquals(Map.of("hardness-level-ratio", ".10"),
@@ -717,7 +906,9 @@ void growingCountKeepsExistingMemberIdentities() throws Exception {
"count=\"3\" role=\"output\""));
var machine = MachineDefinitions.load(sources()).values().iterator()
.next();
- assertEquals(List.of("input/0", "output/0", "output/1", "output/2"),
+ assertEquals(
+ List.of("input/0", "output/0", "output/1", "output/2",
+ "mmdlib_gearbox/0", "mmdlib_capacitor/0"),
machine.slots().stream().map(s -> s.id()).toList());
}
@@ -862,7 +1053,8 @@ void singletonOverridesCanChangeTheirIds() throws Exception {
assertEquals("other_processor", plan.processor());
assertEquals(ResourceLocation.parse("test:other"),
plan.recipeType().id());
- assertEquals(3, plan.slots().size());
+ assertEquals(5, plan.slots().size()); // Three process slots plus
+ // inherited components.
assertNotNull(plan.recipeType().generator());
assertEquals(100000, plan.power().capacity());
write(crusher().replace("",
@@ -878,12 +1070,15 @@ void inheritedScreensPreserveEveryUnnamedSiblingInOrder() throws Exception {
.replace("",
""));
- var base = Files
- .readString(Path.of(
- "src/main/resources/mmdlib/machine/base_powered_machine.xml"))
- .replace("extends=\"mmdlib:base_powered_machine\"/>",
- ">");
+ var base = """
+
+
+
+
+
+
+ """;
Files.writeString(directory.resolve("machine/base.xml"), base);
var plan = MachineDefinitions.load(sources())
.get(ResourceLocation.parse("test:crusher"));
diff --git a/src/test/java/zone/moddev/mc/lib/machine/MachineInlineColorsTest.java b/src/test/java/zone/moddev/mc/lib/machine/MachineInlineColorsTest.java
index de506d45..654425ed 100644
--- a/src/test/java/zone/moddev/mc/lib/machine/MachineInlineColorsTest.java
+++ b/src/test/java/zone/moddev/mc/lib/machine/MachineInlineColorsTest.java
@@ -71,14 +71,15 @@ void inlineNamesAndHexReachGroupsAndGeneratedOutlines() throws Exception {
assertEquals(0x123abc, machine.power().color());
assertEquals(128, machine.power().input());
assertEquals(0, machine.power().output());
- assertEquals(List.of(0xa184ce, 0x4dc6d8), machine.groups().stream()
- .map(MachineDefinition.Group::color).toList());
+ assertEquals(List.of(0xa184ce, 0x4dc6d8, 0xffffff, 0xffffff), machine
+ .groups().stream().map(MachineDefinition.Group::color).toList());
assertEquals(List.of(0x508ee0, 0xee963c), machine.fluids().groups()
.stream().map(MachineDefinition.Group::color).toList());
assertEquals(List.of(1, 2), machine.fluids().groups().get(1).members());
var screen = ScreenLoader
.load(sources(), Map.of(machine.id(), machine.screen()),
- (id, node) -> MachineScreenGenerators.generate(machine, node))
+ MachineScreenGenerators
+ .forMachines(Map.of(machine.id(), machine)))
.get(machine.id()).screen();
assertEquals(0xff4dc6d8, ((ColouredGroupElement) screen
.find("inventory_output").orElseThrow()).colour());
@@ -139,7 +140,7 @@ void defaultsAdvancePerGroupNotPerSlotAndKeepExplicitGroupsInOrder()
var plan = load(xml);
assertEquals(
List.of(0x568bd8, 0x4dc6d8, 0x010203, 0xcf84aa, 0x568bd8, 0x83b967,
- 0x8c9eac, 0xaaa0b7),
+ 0x8c9eac, 0xaaa0b7, 0xffffff, 0xffffff),
plan.groups().stream().map(MachineDefinition.Group::color)
.toList());
assertEquals(List.of(0x508ee0, 0xee963c), plan.fluids().groups()
diff --git a/src/test/java/zone/moddev/mc/lib/machine/UpgradeScreenGenerationTest.java b/src/test/java/zone/moddev/mc/lib/machine/UpgradeScreenGenerationTest.java
new file mode 100644
index 00000000..23ca85f8
--- /dev/null
+++ b/src/test/java/zone/moddev/mc/lib/machine/UpgradeScreenGenerationTest.java
@@ -0,0 +1,149 @@
+package zone.moddev.mc.lib.machine;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import java.util.List;
+import java.util.Map;
+
+import net.minecraft.resources.ResourceLocation;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import zone.moddev.mc.lib.common.loading.DefinitionLoader.SourceRoot;
+import zone.moddev.mc.lib.gui.load.ScreenLoader;
+import zone.moddev.mc.lib.gui.model.InventoryScope;
+import zone.moddev.mc.lib.gui.model.Screen;
+import zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement;
+import zone.moddev.mc.lib.gui.model.elements.SlotElement;
+import zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement;
+import zone.moddev.mc.lib.machine.definition.MachineDefinitions;
+import zone.moddev.mc.lib.machine.definition.MachineScreenGenerators;
+
+class UpgradeScreenGenerationTest {
+ @TempDir
+ Path directory;
+
+ private Screen load(String upgrades, String screenAttributes, String fills)
+ throws Exception {
+ Files.createDirectories(directory.resolve("machine"));
+ Files.writeString(directory.resolve("machine/upgrades.xml"),
+ """
+
+
+
+
+
+
+
+ %s
+
+
+ %s
+
+
+ """
+ .formatted(upgrades, screenAttributes, fills));
+ var sources = List.of(
+ new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"),
+ getClass().getClassLoader()),
+ new SourceRoot("test", directory, getClass().getClassLoader()));
+ var id = ResourceLocation.parse("test:upgrades");
+ var definitions = MachineDefinitions.load(sources);
+ var definition = definitions.get(id);
+ var screen = ScreenLoader
+ .load(sources, Map.of(id, definition.screen()),
+ MachineScreenGenerators.forMachines(definitions))
+ .get(id).screen();
+ MachineScreenGenerators.validate(definition, screen);
+ assertEquals(1, count(screen, "tools"));
+ return screen;
+ }
+
+ private long count(Screen screen, String inventory) {
+ return screen.elements().stream().filter(SlotElement.class::isInstance)
+ .map(SlotElement.class::cast)
+ .filter(slot -> !slot.playerInventory())
+ .filter(slot -> InventoryScope.name(screen, slot).equals(inventory))
+ .count();
+ }
+
+ @Test
+ void explicitComponentsLeaveOtherSlotsInTheGeneratedBody()
+ throws Exception {
+ var screen = load(
+ "",
+ "", "");
+ assertEquals(9, count(screen, "upgrades"));
+ assertTrue(
+ screen.find("gearbox").orElseThrow() instanceof UpgradeSlotElement);
+ assertEquals(8,
+ ((UpgradeSlotElement) screen.find("gearbox").orElseThrow())
+ .maxStackSize());
+ assertEquals(8,
+ ((UpgradeSlotElement) screen.find("capacitor").orElseThrow())
+ .maxStackSize());
+ assertFalse(screen.find("slot_4").isPresent());
+ assertFalse(screen.find("slot_5").isPresent());
+ assertTrue(screen.find("slot_0").isPresent());
+ }
+
+ @Test
+ void authoredDrawerOwnsItsExtrasWhileDefaultProcessingStillRendersTools()
+ throws Exception {
+ var screen = load("", "", """
+
+
+
+ """);
+ assertEquals(9, count(screen, "upgrades"));
+ assertEquals(11, screen.elements().stream()
+ .filter(UpgradeSlotElement.class::isInstance).count());
+ assertFalse(screen.find("slot_0").isPresent());
+ }
+
+ @Test
+ void inheritedUpgradeLayoutSuppressesDefaultDrawerAfterComposition()
+ throws Exception {
+ Files.createDirectories(directory.resolve("screen"));
+ Files.writeString(directory.resolve("screen/custom.xml"),
+ """
+
+
+
+ """);
+ var screen = load("",
+ "extends=\"test:custom\"", "");
+ assertEquals(9, count(screen, "upgrades"));
+ assertEquals(0, screen.elements().stream()
+ .filter(UpgradesDrawerElement.class::isInstance).count());
+ }
+
+ @Test
+ void explicitDrawerReservesOnlyItsPlacedSlots() throws Exception {
+ var screen = load("", "",
+ """
+
+
+
+ """);
+ assertEquals(9, count(screen, "upgrades"));
+ assertFalse(screen.find("slot_2").isPresent());
+ assertTrue(screen.find("slot_1").isPresent());
+ assertEquals(1, count(screen, "mmdlib_gearbox"));
+ assertEquals(1, count(screen, "mmdlib_capacitor"));
+ }
+
+ @Test
+ void removingUpgradeDrawerDoesNotHideItsStorage() throws Exception {
+ var screen = load("", "", "");
+ assertEquals(1, count(screen, "mmdlib_gearbox"));
+ assertEquals(1, count(screen, "mmdlib_capacitor"));
+ }
+}
diff --git a/src/test/java/zone/moddev/mc/lib/machine/WorkingAreaTest.java b/src/test/java/zone/moddev/mc/lib/machine/WorkingAreaTest.java
new file mode 100644
index 00000000..b6b0cf5a
--- /dev/null
+++ b/src/test/java/zone/moddev/mc/lib/machine/WorkingAreaTest.java
@@ -0,0 +1,136 @@
+package zone.moddev.mc.lib.machine;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.core.Direction;
+import net.minecraft.world.phys.AABB;
+
+import org.junit.jupiter.api.Test;
+
+import zone.moddev.mc.lib.machine.feature.WorkingArea;
+
+class WorkingAreaTest {
+ @Test
+ void rearExpansionAndTraversalAgreeForEveryFacingAndRange() {
+ var base = new WorkingArea(-1, 0, -3, 1, 0, -1);
+ var origin = new BlockPos(10, 64, 20);
+ for (int count = 0; count <= 9; count++) {
+ var area = base.expandHorizontal(count);
+ assertEquals(3 + 2 * count, area.width());
+ assertEquals(area.width(), area.depth());
+ assertEquals(1, area.height());
+ for (var front : Direction.Plane.HORIZONTAL) {
+ var positions = new java.util.ArrayList();
+ area.blocks(origin, front).forEach(positions::add);
+ assertEquals(area.size(), positions.size());
+ assertEquals(area.size(),
+ new java.util.HashSet<>(positions).size());
+ assertTrue(!positions.contains(origin));
+ for (int index = 0; index < positions.size(); index++) {
+ var expected = origin
+ .relative(front.getClockWise(),
+ -1 - count + index % area.width())
+ .relative(front, -1 - index / area.width());
+ assertEquals(expected, positions.get(index));
+ assertEquals(expected, area.blockAt(origin, front, index));
+ assertEquals(index / area.width(), area.row(index));
+ assertTrue(area.bounds(origin, front).contains(
+ net.minecraft.world.phys.Vec3.atCenterOf(expected)));
+ }
+ }
+ }
+ }
+
+ @Test
+ void nonAgriculturalProvidersShareGrowthWithoutChangingHeight() {
+ WorkingArea.Provider centered = new WorkingArea.Provider() {
+ public WorkingArea baseWorkingArea() {
+ return new WorkingArea(-2, -1, -2, 2, 1, 2);
+ }
+ public int rangeUpgrades() {
+ return 2;
+ }
+ };
+ assertEquals(new WorkingArea(-4, -1, -4, 4, 1, 4),
+ centered.workingArea());
+ var front = new WorkingArea(-1, 2, 1, 1, 3, 3).expandHorizontal(1);
+ assertEquals(new WorkingArea(-2, 2, 1, 2, 3, 5), front);
+ assertEquals(50, front.size());
+ assertEquals(new BlockPos(-2, 2, -1),
+ front.blockAt(BlockPos.ZERO, Direction.NORTH, 0));
+ assertEquals(new BlockPos(-2, 3, -1),
+ front.blockAt(BlockPos.ZERO, Direction.NORTH, 25));
+ assertEquals(new WorkingArea(1, 0, -2, 5, 0, 2),
+ new WorkingArea(1, 0, -1, 3, 0, 1).expandHorizontal(1));
+ }
+
+ @Test
+ void iterationKeepsImmutableCoordinatesAndRejectsInvalidIndexes() {
+ var area = new WorkingArea(-1, 0, -3, 1, 0, -1);
+ var origin = new BlockPos.MutableBlockPos(4, 5, 6);
+ var blocks = area.blocks(origin, Direction.SOUTH);
+ origin.set(100, 100, 100);
+ var iterator = blocks.iterator();
+ assertEquals(new BlockPos(5, 5, 5), iterator.next());
+ while (iterator.hasNext())
+ iterator.next();
+ assertThrows(java.util.NoSuchElementException.class, iterator::next);
+ assertThrows(IndexOutOfBoundsException.class,
+ () -> area.blockAt(BlockPos.ZERO, Direction.NORTH, -1));
+ assertThrows(IndexOutOfBoundsException.class,
+ () -> area.row(area.size()));
+ assertEquals(new BlockPos(1, -1, 0),
+ area.blocks(BlockPos.ZERO, Direction.UP).iterator().next());
+ assertEquals(new BlockPos(-1, 1, 0),
+ area.blocks(BlockPos.ZERO, Direction.DOWN).iterator().next());
+ assertEquals(-128, new WorkingArea(-128, 0, -128, -1, 0, -1)
+ .expandHorizontal(9).minForward());
+ }
+
+ @Test
+ void frontFieldRotatesWithoutIncludingTheControllerAndKeepsInclusiveSize() {
+ var area = new WorkingArea(-4, 0, 1, 4, 0, 9);
+ var origin = new BlockPos(10, 64, 20);
+ assertEquals(new AABB(6, 64, 11, 15, 65, 20),
+ area.bounds(origin, Direction.NORTH));
+ assertEquals(new AABB(6, 64, 21, 15, 65, 30),
+ area.bounds(origin, Direction.SOUTH));
+ assertEquals(new AABB(11, 64, 16, 20, 65, 25),
+ area.bounds(origin, Direction.EAST));
+ assertEquals(new AABB(1, 64, 16, 10, 65, 25),
+ area.bounds(origin, Direction.WEST));
+ }
+ @Test
+ void verticalFieldsUseNorthAsLocalUpAndExpandInTheirLocalPlane() {
+ var origin = new BlockPos(10, 64, 20);
+ var area = new WorkingArea(-1, 2, 1, 1, 2, 3).expandHorizontal(1);
+ assertEquals(25, area.size());
+ assertEquals(new AABB(8, 65, 18, 13, 70, 19),
+ area.bounds(origin, Direction.UP));
+ assertEquals(new AABB(8, 59, 18, 13, 64, 19),
+ area.bounds(origin, Direction.DOWN));
+ assertEquals(new BlockPos(12, 65, 18),
+ area.blockAt(origin, Direction.UP, 0));
+ assertEquals(new BlockPos(8, 69, 18),
+ area.blockAt(origin, Direction.UP, 24));
+ assertEquals(new BlockPos(8, 63, 18),
+ area.blockAt(origin, Direction.DOWN, 0));
+ assertEquals(new BlockPos(12, 59, 18),
+ area.blockAt(origin, Direction.DOWN, 24));
+ }
+
+ @Test
+ void rejectsReversedAndUnboundedAreas() {
+ assertThrows(IllegalArgumentException.class,
+ () -> new WorkingArea(2, 0, 0, 1, 1, 1));
+ assertThrows(IllegalArgumentException.class,
+ () -> new WorkingArea(-129, 0, 0, 0, 0, 0));
+ for (var facing : Direction.values())
+ assertEquals(new AABB(0, 0, 0, 1, 1, 1),
+ new WorkingArea(0, 0, 0, 0, 0, 0).bounds(BlockPos.ZERO,
+ facing));
+ }
+}
diff --git a/src/test/java/zone/moddev/mc/lib/machine/XmlProcessorTest.java b/src/test/java/zone/moddev/mc/lib/machine/XmlProcessorTest.java
index 65bd3838..4dc88e6e 100644
--- a/src/test/java/zone/moddev/mc/lib/machine/XmlProcessorTest.java
+++ b/src/test/java/zone/moddev/mc/lib/machine/XmlProcessorTest.java
@@ -33,6 +33,264 @@
public class XmlProcessorTest {
@TempDir
Path directory;
+ @Test
+ void poweredBaseInheritsComponentsAndExactlyOneDrawer() throws Exception {
+ Files.createDirectories(directory.resolve("machine"));
+ var file = directory.resolve("machine/powered.xml");
+ var sources = List.of(
+ new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"),
+ getClass().getClassLoader()),
+ new SourceRoot("test", directory, getClass().getClassLoader()));
+ var id = ResourceLocation.parse("test:powered");
+ for (boolean processor : List.of(false, true)) {
+ Files.writeString(file,
+ """
+
+
+ %s
+
+
+ """
+ .formatted(processor
+ ? ""
+ : ""));
+ var definitions = MachineDefinitions.load(sources);
+ var definition = definitions.get(id);
+ assertEquals(processor ? "mmdlib_gearbox/0" : null,
+ definition.behavior().gearboxSlot());
+ assertEquals("mmdlib_capacitor/0",
+ definition.behavior().capacitorSlot());
+ var screen = ScreenLoader
+ .load(sources, Map.of(id, definition.screen()),
+ MachineScreenGenerators.forMachines(definitions))
+ .get(id).screen();
+ MachineScreenGenerators.validate(definition, screen);
+ assertEquals(1, screen.elements().stream().filter(
+ zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement.class::isInstance)
+ .count());
+ assertEquals(processor ? 2 : 1, screen.elements().stream().filter(
+ zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement.class::isInstance)
+ .count());
+ assertEquals(processor, screen.find("gearbox").isPresent());
+ assertTrue(screen.find("capacitor").isPresent());
+ }
+ }
+
+ @Test
+ void sharedComponentsFollowCapabilitiesAndExtrasStayMachineOwned()
+ throws Exception {
+ Files.createDirectories(directory.resolve("machine"));
+ var file = directory.resolve("machine/components.xml");
+ var sources = List.of(
+ new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"),
+ getClass().getClassLoader()),
+ new SourceRoot("test", directory, getClass().getClassLoader()));
+ var id = ResourceLocation.parse("test:components");
+ for (boolean power : List.of(false, true))
+ for (boolean processor : List.of(false, true)) {
+ Files.writeString(file,
+ """
+
+
+
+
+ %s
+
+
+ %s
+
+
+
+
+
+ """
+ .formatted(power
+ ? ""
+ : "",
+ processor
+ ? ""
+ : ""));
+ var definitions = MachineDefinitions.load(sources);
+ var definition = definitions.get(id);
+ assertEquals(processor,
+ definition.behavior().gearboxSlot() != null);
+ assertEquals(power,
+ definition.behavior().capacitorSlot() != null);
+ assertEquals(9, definition.inventorySlots("extra").size());
+ assertEquals(9 + (power ? 1 : 0) + (processor ? 1 : 0),
+ definition.slots().size());
+ assertTrue(definition.groups().stream()
+ .noneMatch(group -> group.automation()));
+ var screen = ScreenLoader
+ .load(sources, Map.of(id, definition.screen()),
+ MachineScreenGenerators.forMachines(definitions))
+ .get(id).screen();
+ MachineScreenGenerators.validate(definition, screen);
+ assertEquals(processor, screen.find("gearbox").isPresent());
+ assertEquals(power, screen.find("capacitor").isPresent());
+ for (int i = 0; i < 9; i++) {
+ var slot = (zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement) screen
+ .find("extra_" + i).orElseThrow();
+ assertEquals("extra",
+ zone.moddev.mc.lib.gui.model.InventoryScope.name(screen,
+ slot));
+ assertEquals(i, slot.index());
+ assertEquals(ResourceLocation.parse("test:custom_upgrades"),
+ slot.acceptedItems().location());
+ }
+ for (String kind : List.of("gearbox", "capacitor"))
+ screen.find(kind).ifPresent(element -> {
+ var slot = (zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement) element;
+ assertEquals("mmdlib_" + kind,
+ zone.moddev.mc.lib.gui.model.InventoryScope
+ .name(screen, slot));
+ assertEquals(0, slot.index());
+ });
+ }
+ }
+
+ @Test
+ void automaticUpgradeSocketsUseDeclaredAddressesAndSharedPresentation()
+ throws Exception {
+ Files.createDirectories(directory.resolve("machine"));
+ var file = directory.resolve("machine/upgrades.xml");
+ String xml = """
+
+
+
+
+
+
+
+
+
+
+
+
+ """;
+ var sources = List.of(
+ new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"),
+ getClass().getClassLoader()),
+ new SourceRoot("test", directory, getClass().getClassLoader()));
+ var id = ResourceLocation.parse("test:upgrades");
+ for (boolean customFilter : List.of(false, true)) {
+ Files.writeString(file, customFilter
+ ? xml.replace("id=\"upgrades\" count=\"11\"",
+ "id=\"upgrades\" count=\"11\" item-tag=\"test:allowed\"")
+ : xml);
+ var definitions = MachineDefinitions.load(sources);
+ var definition = definitions.get(id);
+ var screen = ScreenLoader
+ .load(sources, Map.of(id, definition.screen()),
+ MachineScreenGenerators.forMachines(definitions))
+ .get(id).screen();
+ MachineScreenGenerators.validate(definition, screen);
+ var slots = screen.elements().stream().filter(
+ zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement.class::isInstance)
+ .map(
+ zone.moddev.mc.lib.gui.model.elements.UpgradeSlotElement.class::cast)
+ .toList();
+ assertEquals(List.of(4, 5, 0, 1, 2, 3, 6, 7, 8, 9, 10),
+ slots.stream().map(slot -> slot.index()).toList());
+ for (int index = 0; index < slots.size(); index++) {
+ String kind = index == 0
+ ? "gearbox"
+ : index == 1 ? "capacitor" : "range";
+ var slot = slots.get(index);
+ assertEquals(
+ ResourceLocation.parse(customFilter
+ ? "test:allowed"
+ : "mmdlib:" + kind + "_upgrades"),
+ slot.acceptedItems().location());
+ assertEquals(18, slot.extent());
+ if (index < 2) {
+ assertEquals(
+ ResourceLocation.parse("mmdlib:socket_" + kind),
+ slot.icon().orElseThrow());
+ assertEquals("screen.mmdlib.upgrades." + kind,
+ slot.common().tooltip().orElseThrow().key());
+ assertEquals(slot, screen.find(kind).orElseThrow());
+ }
+ }
+ }
+ for (String invalid : List.of(
+ xml.replace("storage=\"upgrades\"", "storage=\"other\""),
+ xml.replace("count=\"11\"", "count=\"12\""),
+ xml.replace("gearbox-slot=\"upgrades/4\"",
+ "gearbox-slot=\"other/0\""),
+ xml.replace(" upgrades/10\"", "\""))) {
+ Files.writeString(file, invalid);
+ var definitions = MachineDefinitions.load(sources);
+ assertThrows(Exception.class,
+ () -> ScreenLoader.load(sources,
+ Map.of(id, definitions.get(id).screen()),
+ MachineScreenGenerators.forMachines(definitions)));
+ }
+ }
+
+ @Test
+ void automaticInventoryCountsComeFromStorageAfterTemplateComposition()
+ throws Exception {
+ Files.createDirectories(directory.resolve("machine"));
+ var file = directory.resolve("machine/inventories.xml");
+ String xml = """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """;
+ var sources = List.of(
+ new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"),
+ getClass().getClassLoader()),
+ new SourceRoot("test", directory, getClass().getClassLoader()));
+ for (int count : List.of(4, 6)) {
+ Files.writeString(file,
+ xml.replace("count=\"4\"", "count=\"" + count + "\""));
+ var definitions = MachineDefinitions.load(sources);
+ var id = ResourceLocation.parse("test:inventories");
+ var definition = definitions.get(id);
+ var screen = ScreenLoader
+ .load(sources, Map.of(id, definition.screen()),
+ MachineScreenGenerators.forMachines(definitions))
+ .get(id).screen();
+ MachineScreenGenerators.validate(definition, screen);
+ var seeds = (zone.moddev.mc.lib.gui.model.containers.InventoryElement) screen
+ .find("seed").orElseThrow();
+ var output = (zone.moddev.mc.lib.gui.model.containers.InventoryElement) screen
+ .find("output").orElseThrow();
+ assertEquals(count, seeds.slots().size());
+ assertEquals(9, output.slots().size());
+ assertEquals(ResourceLocation.parse("minecraft:hoes"),
+ definition.slots().getFirst().itemTag());
+ assertEquals(zone.moddev.mc.lib.api.capabilities.Role.OUTPUT,
+ definition.slots().getLast().role());
+ }
+ Files.writeString(file,
+ xml.replace("storage=\"seeds\"", "storage=\"missing\""));
+ var definitions = MachineDefinitions.load(sources);
+ var id = ResourceLocation.parse("test:inventories");
+ assertThrows(Exception.class,
+ () -> ScreenLoader.load(sources,
+ Map.of(id, definitions.get(id).screen()),
+ MachineScreenGenerators.forMachines(definitions)));
+ }
public static final class Courier extends StoredProcessor {
final ProcessorState.Key occupant = variables
.define("occupant",
diff --git a/src/test/java/zone/moddev/mc/lib/machine/feature/CapacitorUpgradesTest.java b/src/test/java/zone/moddev/mc/lib/machine/feature/CapacitorUpgradesTest.java
new file mode 100644
index 00000000..b4a0239f
--- /dev/null
+++ b/src/test/java/zone/moddev/mc/lib/machine/feature/CapacitorUpgradesTest.java
@@ -0,0 +1,80 @@
+package zone.moddev.mc.lib.machine.feature;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.Test;
+
+import zone.moddev.mc.lib.api.capabilities.EnergyBuffer;
+
+class CapacitorUpgradesTest {
+ @Test
+ void everyCountScalesCapacityAndBothAutomationRatesFromTheBase() {
+ var count = new AtomicInteger();
+ var energy = new EnergyBuffer(100000, 1000, 400);
+ var capacitors = new CapacitorUpgrades(energy, 100000, 1000, 400,
+ count::get);
+ for (int n = 0; n <= 10; n++) {
+ count.set(n);
+ capacitors.refresh();
+ capacitors.refresh(); // Other slots in the same inventory may also
+ // notify.
+ int bounded = Math.min(n, 8);
+ assertEquals(100000 + 12500L * bounded, energy.capacity());
+ energy.setStored(0);
+ assertEquals(1000 + 125 * bounded,
+ energy.receiveEnergy(9999, true));
+ energy.setStored(energy.capacity());
+ assertEquals(400 + 50 * bounded, energy.extractEnergy(9999, true));
+ }
+ }
+
+ @Test
+ void changesPreserveStoredEnergyUntilCapacityShrinksBelowIt() {
+ var count = new AtomicInteger(8);
+ var energy = new EnergyBuffer(100000, 1000, 0);
+ energy.setStored(50000);
+ var capacitors = new CapacitorUpgrades(energy, 100000, 1000, 0,
+ count::get);
+ capacitors.refresh();
+ assertEquals(50000, energy.stored());
+ assertFalse(energy.canExtract());
+ energy.setStored(180000);
+ count.set(4);
+ capacitors.refresh();
+ assertEquals(150000, energy.stored());
+ count.set(0);
+ capacitors.refresh();
+ assertEquals(100000, energy.stored());
+ assertEquals(0, energy.used().longValueExact());
+ }
+
+ @Test
+ void wholeFeRoundingAndLargeValuesNeverOverflow() {
+ var energy = new EnergyBuffer(Long.MAX_VALUE, 7, 0);
+ var count = new AtomicInteger(1);
+ var capacitors = new CapacitorUpgrades(energy, Long.MAX_VALUE, 7, 0,
+ count::get);
+ capacitors.refresh();
+ assertEquals(Long.MAX_VALUE, energy.capacity());
+ assertEquals(7, energy.receiveEnergy(100, true));
+ count.set(8);
+ capacitors.refresh();
+ assertEquals(14, energy.receiveEnergy(100, true));
+ count.set(-1);
+ capacitors.refresh();
+ assertEquals(7, energy.receiveEnergy(100, true));
+ }
+
+ @Test
+ void rateChangesNotifyObserversOnlyWhenLimitsChange() {
+ var energy = new EnergyBuffer(1000, 100, 50);
+ var notifications = new AtomicInteger();
+ energy.changes().subscribe(notifications::incrementAndGet);
+ energy.setRates(200, 100);
+ energy.setRates(200, 100);
+ assertEquals(1, notifications.get());
+ }
+}
diff --git a/src/test/java/zone/moddev/mc/lib/machine/feature/ProcessorClockTest.java b/src/test/java/zone/moddev/mc/lib/machine/feature/ProcessorClockTest.java
new file mode 100644
index 00000000..4ec3d0cb
--- /dev/null
+++ b/src/test/java/zone/moddev/mc/lib/machine/feature/ProcessorClockTest.java
@@ -0,0 +1,154 @@
+package zone.moddev.mc.lib.machine.feature;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import com.mojang.serialization.Codec;
+import com.mojang.serialization.JsonOps;
+
+import org.junit.jupiter.api.Test;
+
+class ProcessorClockTest {
+ /**
+ * Consumer processor deliberately unrelated to StoredProcessor or
+ * RecipeProcessor.
+ */
+ private static final class Consumer implements Processor {
+ final String key;
+ boolean paused;
+ int ticks;
+ int energy = 1000;
+ ProcessState inactive;
+ ProcessState status = ProcessState.IDLE;
+ Consumer(String key) {
+ this.key = key;
+ }
+ public String key() {
+ return key;
+ }
+ public Codec codec() {
+ return Codec.INT;
+ }
+ public Integer state() {
+ return ticks;
+ }
+ public void restore(Integer value) {
+ ticks = value;
+ }
+ public boolean paused() {
+ return paused;
+ }
+ public void setPaused(boolean value) {
+ paused = value;
+ }
+ public boolean processing() {
+ return status == ProcessState.RUNNING;
+ }
+ public ProcessState executionStatus() {
+ return status;
+ }
+ public void defineVisualVariables(
+ zone.moddev.mc.lib.machine.presentation.VisualVariables.Builder variables) {
+ }
+ public void tick(FeatureHost host) {
+ if (inactive != null) {
+ status = inactive;
+ return;
+ }
+ if (paused) {
+ status = ProcessState.PAUSED;
+ return;
+ }
+ if (energy < 5) {
+ status = ProcessState.STALLED;
+ return;
+ }
+ ticks++;
+ energy -= 5;
+ status = ProcessState.RUNNING;
+ }
+ }
+
+ @Test
+ void everyStackSizeScalesAllProcessorsAndTheirNormalEnergyUse() {
+ for (int count = 0; count <= 10; count++) {
+ int installed = count;
+ var clock = new ProcessorClock(() -> installed);
+ var host = new FeatureHost(() -> {
+ });
+ var a = new Consumer("a");
+ var b = new Consumer("b");
+ for (int tick = 0; tick < 8; tick++) {
+ clock.tick(a, host);
+ clock.tick(b, host);
+ }
+ assertEquals(8 + Math.min(8, count), a.ticks);
+ assertEquals(a.ticks, b.ticks);
+ assertEquals(1000 - a.ticks * 5, a.energy);
+ assertEquals(a.energy, b.energy);
+ }
+ }
+
+ @Test
+ void fractionalWorkPersistsAndPausedProcessorsDoNotBankWork() {
+ var clock = new ProcessorClock(() -> 1);
+ var host = new FeatureHost(() -> {
+ }).add(clock);
+ var processor = new Consumer("worker");
+ for (int tick = 0; tick < 7; tick++)
+ clock.tick(processor, host);
+ processor.setPaused(true);
+ for (int tick = 0; tick < 40; tick++)
+ clock.tick(processor, host);
+ assertEquals(7, processor.ticks);
+ var restored = new ProcessorClock(() -> 1);
+ new FeatureHost(() -> {
+ }).add(restored).load(JsonOps.INSTANCE, host.save(JsonOps.INSTANCE));
+ processor.setPaused(false);
+ restored.tick(processor, host);
+ assertEquals(9, processor.ticks);
+ }
+
+ @Test
+ void inactiveProcessorsDoNotChangeSavedFractionsOrDirtyTheHost() {
+ for (int installed = 1; installed <= 8; installed++) {
+ int count = installed;
+ var changes = new java.util.concurrent.atomic.AtomicInteger();
+ var host = new FeatureHost(changes::incrementAndGet);
+ var clock = new ProcessorClock(() -> count);
+ var processor = new Consumer("worker");
+ clock.tick(processor, host);
+ var saved = clock.state();
+ changes.set(0);
+ for (var state : Processor.ProcessState.values()) {
+ if (state == Processor.ProcessState.RUNNING)
+ continue;
+ processor.inactive = state;
+ for (int tick = 0; tick < 40; tick++)
+ clock.tick(processor, host);
+ assertEquals(saved, clock.state(), state.name());
+ assertEquals(0, changes.get(), state.name());
+ }
+ processor.inactive = null;
+ clock.tick(processor, host);
+ assertEquals((2 * count) % 8,
+ clock.state().getOrDefault("worker", 0));
+ }
+ }
+
+ @Test
+ void extraWorkNeverBypassesTheProcessorsEnergyGate() {
+ var clock = new ProcessorClock(() -> 8);
+ var host = new FeatureHost(() -> {
+ });
+ var processor = new Consumer("worker");
+ processor.energy = 5;
+ clock.tick(processor, host);
+ assertEquals(1, processor.ticks);
+ assertEquals(0, processor.energy);
+ assertFalse(processor.processing());
+ processor.energy = 10;
+ clock.tick(processor, host);
+ assertEquals(3, processor.ticks);
+ }
+}
diff --git a/src/test/java/zone/moddev/mc/lib/machine/feature/WorkTargetsTest.java b/src/test/java/zone/moddev/mc/lib/machine/feature/WorkTargetsTest.java
new file mode 100644
index 00000000..59297d62
--- /dev/null
+++ b/src/test/java/zone/moddev/mc/lib/machine/feature/WorkTargetsTest.java
@@ -0,0 +1,85 @@
+package zone.moddev.mc.lib.machine.feature;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.nbt.NbtOps;
+
+import org.junit.jupiter.api.Test;
+
+class WorkTargetsTest {
+ @Test
+ void tracksChangingTargetsAndClearsOnPauseIdleOrHostSuspension() {
+ var source = new ArrayList();
+ var active = new AtomicBoolean(true);
+ var feature = new WorkTargets("work", () -> source, active::get);
+ var host = new FeatureHost(() -> {
+ }).add(feature);
+ var mutable = new BlockPos.MutableBlockPos(1, 2, 3);
+ source.add(mutable);
+ source.add(new BlockPos(1, 2, 3));
+ feature.tick(host);
+ mutable.set(4, 5, 6);
+ assertEquals(List.of(new BlockPos(1, 2, 3)), feature.targets());
+ source.clear();
+ source.add(new BlockPos(7, 8, 9));
+ feature.tick(host);
+ assertEquals(source, feature.targets());
+ active.set(false);
+ feature.tick(host);
+ assertTrue(feature.targets().isEmpty());
+ active.set(true);
+ feature.tick(host);
+ feature.suspended(host);
+ assertTrue(feature.targets().isEmpty());
+ feature.tick(host);
+ source.clear();
+ feature.tick(host);
+ assertTrue(feature.targets().isEmpty());
+ }
+
+ @Test
+ void trackingClientsReceiveUpdatesAndClearsButDiskNeverRestoresActiveWork() {
+ var source = new ArrayList<>(List.of(new BlockPos(20, 64, -20)));
+ var feature = new WorkTargets("work", () -> source, () -> true);
+ var host = new FeatureHost(() -> {
+ }).add(feature);
+ var remote = new WorkTargets("work", List::of, () -> false);
+ var client = new FeatureHost(() -> {
+ }).add(remote);
+ feature.tick(host);
+ client.loadOnClient(NbtOps.INSTANCE,
+ host.saveForClient(NbtOps.INSTANCE));
+ assertEquals(source, remote.targets());
+ var disk = host.save(NbtOps.INSTANCE);
+ client.load(NbtOps.INSTANCE, disk);
+ assertTrue(remote.targets().isEmpty());
+ client.loadOnClient(NbtOps.INSTANCE,
+ host.saveForClient(NbtOps.INSTANCE));
+ source.clear();
+ feature.tick(host);
+ client.loadOnClient(NbtOps.INSTANCE,
+ host.saveForClient(NbtOps.INSTANCE));
+ assertTrue(remote.targets().isEmpty());
+ }
+
+ @Test
+ void capsProviderListsAndRejectsOversizedWireData() {
+ var source = java.util.stream.IntStream
+ .range(0, WorkTargets.MAX_TARGETS + 1)
+ .mapToObj(x -> new BlockPos(x, 0, 0)).toList();
+ var feature = new WorkTargets("work", () -> source, () -> true);
+ feature.tick(new FeatureHost(() -> {
+ }).add(feature));
+ assertEquals(WorkTargets.MAX_TARGETS, feature.targets().size());
+ var oversized = BlockPos.CODEC.listOf()
+ .encodeStart(NbtOps.INSTANCE, source).getOrThrow();
+ assertTrue(WorkTargets.CODEC.parse(NbtOps.INSTANCE, oversized).error()
+ .isPresent());
+ }
+}