diff --git a/CHANGELOG.md b/CHANGELOG.md index 4009165b..c96da9fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,12 @@ for forms that are not named `_
`, and `in_all: false` for forms a material must name. `!all` still excludes every form, and a script's `removeItems("all")` / `removeBlocks("all")` still clear them. +- XML machine drawer migration. Machines with configurable resources that inherit + only `mmdlib:base_machine` now need + `` to retain the Side + Configuration drawer. Standalone definitions also need explicit features for + the Statistics, Curios, and Backpack drawers they use. + See [upgrading existing XML machines](docs/xml-machines.md#upgrading-existing-xml-machines). ## Unreleased — 2.0.2 diff --git a/docs/gui-screens.md b/docs/gui-screens.md index f1b83142..44b6d443 100644 --- a/docs/gui-screens.md +++ b/docs/gui-screens.md @@ -878,7 +878,8 @@ opacity with `+1` at the top, without creating a real stack. Mixed consume/produ both signed counts on the top row. Tooltips provide reservation counts and the planned output's name. Clearing the plan removes the badge and ghost. Player inventory, equipment and filter slots are unaffected by default; custom elements can opt into overlays using the hooks above. -Chance outputs show their reserved capacity, not a guarantee that the product will be rolled. +Only guaranteed item outputs reserve capacity. Chance items roll when the cycle finishes +and use any remaining room after the guaranteed products. No extra packet or XML binding is needed; `MachineMenu.reservationPlan(index)` exposes the existing synchronized snapshot for real machine slots. @@ -2195,9 +2196,20 @@ for the same component; a plain `` remains a general display with getter With a fluid container on the cursor, **left-click fills the tank** and **right-click drains it into the container**. Input and manual tanks can be drained by players. Insertion retains fluid/recipe filters and rejects output tanks; both directions respect reservations. Each -click handles one container, including partial modded containers. Stacked results go into the +click handles one container, including partial modded containers. Tank gauges fade the reserved +portion of the current fluid and preview reserved output as translucent fluid. When one tank +reserves both, it shows the two previews side by side. Hover to see exact amounts and the +planned output fluid. Stacked results go into the player inventory (or drop when full); creative containers remain unchanged. +Click the small brass valve below a tank with fluid to open or close it. An open +valve discards up to 5 mB of unreserved fluid per game tick, even with the screen +closed. The valve closes automatically when the tank is empty and takes up no +layout space. +Use `drain-button="false"` to hide it on a tank. +`BaseMachine` ticks the valves automatically. Custom screen hosts can call +`FluidStorage.tickDrains()` from their server tick. + Getters and element-owned snapshots run only on the server, each tick while the screen is open. The client only receives their values. diff --git a/docs/multiblocks.md b/docs/multiblocks.md index 1dae52e9..6a3d4c0a 100644 --- a/docs/multiblocks.md +++ b/docs/multiblocks.md @@ -1,6 +1,6 @@ -# Java multiblock machines +# Multiblock machines -MMDLib provides whole-machine placement for fixed Java-defined structures. One controller owns storage and processing; linked physical parts expose interactions and optional resource ports. The companion's **Multiblock Test Bench** is a complete registration example in `MultiblockDemo` and `MultiblockDemoEntity`. +MMDLib provides whole-machine placement for fixed structures defined in Java or XML. One controller owns storage and processing. Linked physical parts expose interactions and optional resource ports. The companion's **Multiblock Test Bench** is a complete registration example in `MultiblockDemo` and `MultiblockDemoEntity`. The common structure model is in `zone.moddev.mc.lib.machine.multiblock`. NeoForge placement, blocks, linked block entities and capability adapters live in `machine.neoforge`. These APIs do not depend on the XML machine-definition runtime. Screens can still use ordinary MMDLib XML. @@ -30,6 +30,27 @@ The controller is the sole member with role `controller`, at offset zero. Member Required space is separate from physical membership. A rule is a mod-owned `(Level, BlockPos) -> boolean` predicate. Set `continuous` for conditions that suspend operation while obstructed; otherwise a requirement is checked only at formation. Clearance rules for an animal gym should allow the intended animal while refusing obstructing blocks. Requirements never become removable dummy blocks. +### Load a fixed layout from XML + +Bundle `data//mmdlib/multiblock/.xml` and pass its ID and a class from the owning mod to `MultiblockDefinitions.load(id, OwnerMod.class)` after the member blocks are registered. Reuse the returned definition for the placement item and controller. + +```xml + + + + + + + +``` + +Member states use vanilla block-state syntax. The `air` rule uses `BlockState.isAir()`. Port kinds are `items`, `fluids`, and `energy`. Face names are relative to a viewer looking at the front (`front back left right top bottom`). The `continuous`, `unsided`, `input`, and `output` flags default to `false`. `version` is the saved structure version. To move an existing fixed layout to XML, preserve its version, member keys, member states, and requirements in their original order so saved manifests still match. + +XML defines the layout for Java-registered blocks, block entities, and placement items. It is read from the bundled resource at startup. Custom processors, models, and lifecycle callbacks use the same APIs as Java-defined layouts. + ## Register the blocks and item Register a controller block/type, one or more physical part blocks/types and one `MultiblockItem`. No independent part item or part loot is needed for packaged machines. diff --git a/docs/xml-machines.md b/docs/xml-machines.md index a4a2e292..6ece6d64 100644 --- a/docs/xml-machines.md +++ b/docs/xml-machines.md @@ -111,12 +111,19 @@ 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. +Enable capability-based component storage with +``. MMDLib adds a gearbox socket for a +processor and a capacitor socket for eligible energy storage. Set `gearbox="false"` +or `capacitor="false"` to omit the corresponding socket. The inventories +`mmdlib_gearbox` and `mmdlib_capacitor` each have one manual, non-automated slot of capacity +eight. `` displays the enabled sockets. Its optional `storage` +attribute adds a machine-owned extra grid. Existing `` declarations are +also supported. Existing machines may still bind a manual socket by its stable storage slot ID: ```xml - + ``` For ``, @@ -148,7 +155,8 @@ 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 @@ -199,6 +207,8 @@ stops at WorkingArea's existing ±128 local-coordinate bounds. For example, - `width()`, `depth()`, `height()` and `size()` use inclusive block dimensions. - `blockAt(origin, facing, index)` returns an immutable world position. +- `snakeBlockAt(origin, facing, index)` alternates left-to-right and right-to-left rows; + each layer starts left-to-right. `row(index)` keeps the same meaning. - `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. @@ -207,8 +217,7 @@ stops at WorkingArea's existing ±128 local-coordinate bounds. For example, 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 +Agri-Brain uses snake traversal for scanning and work particles, with unchanged row numbers for planting. Callers remain responsible for loaded chunks, world limits and permissions before acting. Entity enumeration is not implemented yet. ### Migrating development upgrade inventories @@ -582,15 +591,91 @@ the root model's `textures` object, without `#`. Its declarations and conditions must match the Java subscriptions. Getters are never invoked on the rendering thread. +## Machine features and drawers + +Use `` to install a feature. An abstract +machine can declare a mod's common features and let its children override individual +settings by ID. An override can omit `type`. Use `enabled="false"` on the feature +to disable it, or on its nested `` to hide its drawer while retaining the +feature's behavior. The drawer also accepts `edge="left|right"`, +`anchor="top|bottom"`, and an integer `order`. Lower order values sit closer to +the anchor. Drawer attributes inherit individually. + +```xml + + + + + + + + + +``` + +This base removes Backpack, keeps a capacitor socket and its drawer, and pauses +processing when a signal of 1–15 reaches any face. The redstone drawer can be +re-enabled by a child. The default redstone mode is `ignore`. A saved face +configuration takes precedence over the default. + +| Feature type | ID in MMDLib's bases | Drawer or behavior | +| --- | --- | --- | +| `mmdlib:info` | `info` | Screen popouts with `kind="info"` | +| `mmdlib:stats` | `statistics` | Machine statistics | +| `mmdlib:curios` | `curios` | A player's available Curios equipment | +| `mmdlib:backpack` | `backpack` | A player's available equipped containers | +| `mmdlib:side_config` | `automation` | Side configuration for machines with configurable resources | +| `mmdlib:redstone` | `redstone` | Redstone input, output and comparator configuration | +| `mmdlib:upgrades` | `upgrades` | Upgrade sockets and their screen layout | +| `mmdlib:popout` | | Warning and error popouts declared in the screen | +| `mmdlib:side_tab` | | Side tabs declared in the screen | + +The common machine base declares Info, Statistics, Curios, Backpack, and Redstone. +Redstone defaults to ignoring input and uses any saved face settings on load. +The powered preset adds Side Configuration and Upgrades. A machine without an inherited +Redstone feature can still opt in through the version-1 `` shorthand. + +Mods can register a feature type, its allowed XML attributes, and a per-machine +factory using `MachineFeatureTypes.register` on both sides. The factory returns a +`MachineFeature` whose key is the XML feature ID. To contribute drawers, also +implement `MachineFeatureDrawers` and return common-side drawer definitions. The +usual client drawer factory and menu component registrations handle rendering and +server interactions. + +### Upgrading existing XML machines + +Side Configuration, Statistics, Curios, and Backpack now require a matching +feature, declared on the machine or inherited from a base. For an existing machine +with configurable resources that inherits only `mmdlib:base_machine`, add this +line inside `` or in a shared base to retain its Side Configuration drawer: + +```xml + +``` + +`mmdlib:base_powered_machine` already declares this feature. + +For standalone XML definitions, also add the declarations for the other drawers +you want to retain. Both MMDLib machine bases already supply these features: + +```xml + + + +``` + ## Base machine and storage The generic [`base_machine.xml`](../src/main/resources/mmdlib/machine/base_machine.xml) -provides block settings, redstone control, recovery and the common screen with generated -tank fills. It declares no storage. The powered base extends it: +provides block settings, the shared drawer features, recovery and the common screen +with generated tank fills. It declares no storage. The powered base extends it: ```xml + + @@ -984,6 +1069,60 @@ area before the base template's energy gauge. Generated processor arrows open their recipe type in JEI when clicked. SimpleCrusher needs no `` or `` of its own. +Generated arrows show a warning badge and a red **Output blocked** tooltip +when a ready recipe cannot place its products. Set `processor-key` on an authored +`` element to link it to the same warning. + +Use machine-level `` to declare resources and processors in the order they +should appear in the generated screen. + +```xml + + + + + + + +``` + +An inventory takes the same storage attributes as ``. It defaults to one +slot and three display columns. Set `columns` to change its width. A tank takes +the usual storage attributes and an optional `tooltip` translation key. Use +`` to show a group of tanks together. A processor uses the same +attributes as a top-level processor. An empty `` places the inherited +energy gauge. Supply the usual energy attributes on it to define energy storage +there as well. + +The loader reuses the inherited item and fluid storage IDs, with `items` and +`fluids` as defaults. Keep part IDs stable for save data and recipe bindings. +A child that declares its own `` supplies a new row while inheriting +storage and processors under the usual machine inheritance rules. + +Use a machine-level `` when the controls should reference declarations +that already live elsewhere. Declare one row per machine XML using either +`` or ``. + +```xml + + + + + + + +``` + +Entries appear from left to right. `tank`, `processor`, and `inventory` +reference their existing machine IDs. An inventory can reference an item group +or ghost inventory and defaults to three columns. A tank accepts an optional +`tooltip` translation key. `energy` shows the machine's energy gauge. + +The layout supplies the machine, tank, and energy regions of the standard +screen. Only the controls listed in the layout appear in that row. A derived +machine inherits the layout or replaces it as a whole. Use `` to +restore the screen's usual fills. + A machine can replace that region: ```xml @@ -1306,8 +1445,9 @@ Buttons without a processor target continue to use ordinary callback routing. `` also accepts `stack-size="1"`, `no-occlusion="true"`, `immovable="true"`, `drawers="false"` and `portable="true"`. -These are opt-in policies; existing machines retain their defaults. `drawers` -controls the stats and automation drawers, while redstone remains separately configured. +The legacy `drawers="false"` shorthand suppresses Statistics and Side Configuration +together. [Machine features](#machine-features-and-drawers) can control each drawer +individually. ```xml @@ -1750,7 +1890,8 @@ Sneak placement chooses the clicked face; ordinary placement faces the player. ## Comparator readout -`` selects one existing +`` +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 diff --git a/scripts/generate_gui_sprites.py b/scripts/generate_gui_sprites.py index 33b7c788..bf133ca1 100644 --- a/scripts/generate_gui_sprites.py +++ b/scripts/generate_gui_sprites.py @@ -256,6 +256,31 @@ def write_flat_buttons(): write_png(name, img, {"type": "nine_slice", "width": 14, "height": 14, "border": 1}) +def write_tank_drain(): + """Brass drain valve, drawn at its native 11x10 GUI size.""" + palette = { + ".": CLEAR, + "#": (70, 39, 24, 255), + "S": (117, 64, 30, 255), + "M": (171, 99, 38, 255), + "H": (219, 153, 60, 255), + "L": (255, 208, 111, 255), + } + rows = [ + ".........##", + "......###L#", + "....##LHM#.", + "....#H###..", + "...##H##...", + "###LHLHH##.", + "#HLMLMMHLH#", + "#SM#HMS#SS#", + ".##.#HS###.", + ".....##....", + ] + write_png("icon_tank_drain", [[palette[pixel] for pixel in row] for row in rows]) + + def write_filter_icons(): """White/black list cards for the flat grey mode toggle.""" for mode, fill in (("whitelist", 0xF1), ("blacklist", 0x24)): @@ -532,6 +557,7 @@ def main(): write_processor_progress_icon() write_filter_icons() write_flat_buttons() + write_tank_drain() write_side_config_sprites() write_upgrade_sprites() write_png("checkbox", checkbox(False)) diff --git a/src/companion/resources/mmdlib/machine/admission_demo.xml b/src/companion/resources/mmdlib/machine/admission_demo.xml index c3d2a51a..1b2bbce4 100644 --- a/src/companion/resources/mmdlib/machine/admission_demo.xml +++ b/src/companion/resources/mmdlib/machine/admission_demo.xml @@ -1,5 +1,6 @@ + diff --git a/src/companion/resources/mmdlib/machine/porting_workshop.xml b/src/companion/resources/mmdlib/machine/porting_workshop.xml index 5f28dcd1..575685d2 100644 --- a/src/companion/resources/mmdlib/machine/porting_workshop.xml +++ b/src/companion/resources/mmdlib/machine/porting_workshop.xml @@ -10,6 +10,7 @@ - + + diff --git a/src/companion/resources/mmdlib/machine/simple_lava_furnace.xml b/src/companion/resources/mmdlib/machine/simple_lava_furnace.xml index d88c5b2c..af9fb5a7 100644 --- a/src/companion/resources/mmdlib/machine/simple_lava_furnace.xml +++ b/src/companion/resources/mmdlib/machine/simple_lava_furnace.xml @@ -1,5 +1,6 @@ + diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/CreativePowerClientSmoke.java b/src/companionTest/java/zone/moddev/mc/companion/test/CreativePowerClientSmoke.java index b6b2c956..63754883 100644 --- a/src/companionTest/java/zone/moddev/mc/companion/test/CreativePowerClientSmoke.java +++ b/src/companionTest/java/zone/moddev/mc/companion/test/CreativePowerClientSmoke.java @@ -6,6 +6,7 @@ import zone.moddev.mc.lib.api.capabilities.IoMode; import zone.moddev.mc.lib.api.capabilities.RelativeFace; import zone.moddev.mc.lib.gui.client.MachineScreen; +import zone.moddev.mc.lib.gui.drawer.BuiltinDrawers; import zone.moddev.mc.lib.gui.layout.AutomationLayout; import zone.moddev.mc.lib.gui.model.containers.PlayerInventoryElement; import zone.moddev.mc.lib.gui.runtime.component.BuiltinMenuComponents; @@ -40,10 +41,9 @@ static boolean run(MachineScreen screen) { .isPresent() || screen.layout.region(PlayerInventoryElement.TOOLBAR) .isPresent() - || !menu.components().get(BuiltinMenuComponents.BACKPACK) - .state().icons().isEmpty() - || !menu.components().get(BuiltinMenuComponents.CURIOS) - .state().icons().isEmpty()) + || screen.layout.drawers().stream().anyMatch( + drawer -> drawer.type().equals(BuiltinDrawers.BACKPACK) + || drawer.type().equals(BuiltinDrawers.CURIOS))) throw new AssertionError( "Generator has no inventory, addon slots or equipment drawers"); if (menu.components().require(BuiltinMenuComponents.STATS) diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/MultiblockTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/MultiblockTests.java index 508f988e..dc63249b 100644 --- a/src/companionTest/java/zone/moddev/mc/companion/test/MultiblockTests.java +++ b/src/companionTest/java/zone/moddev/mc/companion/test/MultiblockTests.java @@ -1,13 +1,20 @@ package zone.moddev.mc.companion.test; +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import java.nio.charset.StandardCharsets; + import java.util.List; import java.util.Map; import java.util.function.Consumer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +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.InteractionHand; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; @@ -29,6 +36,7 @@ import zone.moddev.mc.companion.MultiblockDemo; import zone.moddev.mc.companion.MultiblockDemoEntity; import zone.moddev.mc.lib.gui.runtime.MachineMenu; +import zone.moddev.mc.lib.machine.multiblock.MultiblockDefinitions; import zone.moddev.mc.lib.machine.multiblock.MultiblockInstance; import zone.moddev.mc.lib.machine.multiblock.ResolvedStructure; import zone.moddev.mc.lib.machine.multiblock.StructureMember; @@ -39,6 +47,40 @@ @GameTestHolder("mmdlib_companion") @PrefixGameTestTemplate(false) public final class MultiblockTests { + @GameTest(template = "empty") + public static void invalidXmlLayoutFailsBeforePlacement( + GameTestHelper helper) throws IOException { + String xml = """ + + + + + """; + var cases = List.of( + List.of("minecraft:furnace[facing=up]", "controller", + "invalid.xml:3:", "facing"), + List.of("minecraft:furnace[facing=north]", "missing", + "invalid.xml:", "Unknown port member missing")); + for (var entry : cases) { + var input = new ByteArrayInputStream( + xml.formatted(entry.get(0), entry.get(1)) + .getBytes(StandardCharsets.UTF_8)); + try { + MultiblockDefinitions.read( + ResourceLocation.parse("mmdlib_companion:invalid"), + "invalid.xml", input, BuiltInRegistries.BLOCK.asLookup()); + throw new AssertionError("Invalid fixed layout accepted"); + } catch (IllegalArgumentException ex) { + require( + ex.getMessage().contains(entry.get(2)) + && ex.getMessage().contains(entry.get(3)), + "XML error identifies the offending entry"); + } + } + helper.succeed(); + } + @GameTest(template = "empty") public static void capabilityQueriesDoNotValidateOrDismantle( GameTestHelper helper) { diff --git a/src/main/java/zone/moddev/mc/lib/api/capabilities/FluidStorage.java b/src/main/java/zone/moddev/mc/lib/api/capabilities/FluidStorage.java index 1a24d25b..0209eaeb 100644 --- a/src/main/java/zone/moddev/mc/lib/api/capabilities/FluidStorage.java +++ b/src/main/java/zone/moddev/mc/lib/api/capabilities/FluidStorage.java @@ -1,10 +1,13 @@ package zone.moddev.mc.lib.api.capabilities; import java.util.ArrayList; +import java.util.BitSet; import java.util.List; +import java.util.Objects; import java.util.function.Consumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; +import java.util.function.IntUnaryOperator; import java.util.function.Predicate; import java.util.function.Supplier; @@ -36,6 +39,8 @@ */ public class FluidStorage implements IFluidHandler, INBTSerializable { + public static final int DRAIN_RATE = 5; + private final ChangeSignal changes = new ChangeSignal(); /** @@ -49,6 +54,7 @@ public ChangeSignal changes() { private final List tanks = new ArrayList<>(); private final List roles = new ArrayList<>(); private final List tankIds = new ArrayList<>(); + private final BitSet openDrains = new BitSet(); private final List> insertionRules = new ArrayList<>(); private final ListTag recovery = new ListTag(); private final ReservationPlans plans = new ReservationPlans<>(0, @@ -103,6 +109,8 @@ public FluidTank setValidator(Predicate validator) { @Override protected void onContentsChanged() { + if (isEmpty()) + openDrains.clear(index); revision++; changes.changed(); onChange.run(); @@ -153,6 +161,25 @@ public FluidTank tank(int index) { return tanks.get(index); } + public boolean drainOpen(int index) { + return openDrains.get(Objects.checkIndex(index, getTanks())); + } + + /** Toggles a nonempty tank's valve without draining immediately. */ + public void toggleDrain(int index) { + if (tank(index).isEmpty()) + return; + openDrains.flip(index); + onChange.run(); + } + + /** Tick once on the server. Each open valve discards unreserved fluid. */ + public void tickDrains() { + for (int index = openDrains.nextSetBit( + 0); index >= 0; index = openDrains.nextSetBit(index + 1)) + tank(index).drain(DRAIN_RATE, FluidAction.EXECUTE); + } + /** * Stable save identity; saves without identities continue to load by index. */ @@ -204,6 +231,7 @@ public ListTag recoveryContents() { */ public void clear() { recovery.clear(); + openDrains.clear(); for (int tank = 0; tank < getTanks(); tank++) { setPlan(tank, TankPlan.NONE); restoreFluid(tank, FluidStack.EMPTY); @@ -421,6 +449,8 @@ public CompoundTag serializeNBT(HolderLookup.Provider provider) { var entry = tanks.get(i).writeToNBT(provider, new CompoundTag()); if (tankIds.get(i) != null) entry.putString("TankId", tankIds.get(i)); + if (drainOpen(i)) + entry.putBoolean("DrainOpen", true); list.add(entry); } CompoundTag tag = new CompoundTag(); @@ -436,8 +466,7 @@ public CompoundTag serializeNBT(HolderLookup.Provider provider) { @Override public void deserializeNBT(HolderLookup.Provider provider, CompoundTag tag) { - deserializeNBT(provider, tag, - java.util.function.IntUnaryOperator.identity()); + deserializeNBT(provider, tag, IntUnaryOperator.identity()); } /** @@ -445,9 +474,10 @@ public void deserializeNBT(HolderLookup.Provider provider, * its save version. */ public void deserializeNBT(HolderLookup.Provider provider, CompoundTag tag, - java.util.function.IntUnaryOperator legacyTanks) { + IntUnaryOperator legacyTanks) { var saved = tag.getList("Tanks", Tag.TAG_COMPOUND); var list = new ListTag(); + openDrains.clear(); for (int i = 0; i < saved.size(); i++) { var tank = saved.getCompound(i); var entry = tank.getCompound("Fluid").copy(); @@ -464,9 +494,8 @@ public void deserializeNBT(HolderLookup.Provider provider, CompoundTag tag, tank.setFluid(FluidStack.EMPTY); for (var value : list) { var entry = (CompoundTag) value; - int index = entry.contains("TankId") - ? tankIds.indexOf(entry.getString("TankId")) - : legacyTanks.applyAsInt(entry.getInt("Tank")); + int index = savedTankIndex(entry, entry.getInt("Tank"), + legacyTanks); if (!entry.contains("TankId")) { entry.putInt("Tank", index); if (inRange(index) && tankIds.get(index) != null) @@ -495,8 +524,24 @@ public void deserializeNBT(HolderLookup.Provider provider, CompoundTag tag, recovery.add(extra); } } + for (int i = 0; i < saved.size(); i++) { + var tank = saved.getCompound(i); + if (!tank.getBoolean("DrainOpen") + || tank.getCompound("Fluid").isEmpty()) + continue; + int index = savedTankIndex(tank, i, legacyTanks); + if (inRange(index) && !tanks.get(index).isEmpty()) + openDrains.set(index); + } revision++; changes.changed(); onChange.run(); } + + private int savedTankIndex(CompoundTag entry, int index, + IntUnaryOperator legacyTanks) { + return entry.contains("TankId") + ? tankIds.indexOf(entry.getString("TankId")) + : legacyTanks.applyAsInt(index); + } } 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 6555844e..86b202ca 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 @@ -34,6 +34,7 @@ public enum Mode { private static final RelativeFace[] FACES = RelativeFace.values(); private final BlockEntity owner; private final List outputs; + private final Mode defaultMode; private final int[] modes = new int[6], incoming = new int[6], outgoing = new int[6], lower = new int[6], upper = new int[6]; private final boolean[] outside = new boolean[6], inverted = new boolean[6]; @@ -82,7 +83,13 @@ public RedstoneControl(BlockEntity owner, List> groups, * nothing. */ public RedstoneControl(BlockEntity owner, Collection parts) { + this(owner, parts, Mode.IGNORE); + } + + public RedstoneControl(BlockEntity owner, Collection parts, + Mode defaultMode) { this.owner = Objects.requireNonNull(owner); + this.defaultMode = Objects.requireNonNull(defaultMode); var found = new LinkedHashMap(); for (var part : parts) if (part instanceof IRedstoneOutput provider) @@ -94,6 +101,7 @@ public RedstoneControl(BlockEntity owner, Collection parts) { if (found.size() > 4096) throw new IllegalArgumentException("Too many redstone outputs"); outputs = List.copyOf(found.values()); + Arrays.fill(modes, defaultMode.ordinal()); Arrays.fill(lower, 1); Arrays.fill(upper, 15); Arrays.fill(sourceIds, ""); @@ -427,7 +435,7 @@ public void load(CompoundTag tag, HolderLookup.Provider registries) { : tag.getInt("without"); for (int i = 0; i < 6; i++) { modes[i] = saved.length == 6 && saved[i] >= 0 - && saved[i] < MODES.length ? saved[i] : 0; + && saved[i] < MODES.length ? saved[i] : defaultMode.ordinal(); lower[i] = lows.length == 6 ? Math.clamp(lows[i], 0, 15) : 1; upper[i] = highs.length == 6 ? Math.clamp(highs[i], lower[i], 15) 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 63e2e383..a59b251e 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 @@ -78,9 +78,10 @@ private static List> declarations() { .ifPresent(view -> view.render(c))) .behavior(FilterCustomBehavior::new), ElementClient.of(SPRITE).renderer(SpriteRenderer::draw), - ElementClient.of(PROGRESS) - .renderer((element, c) -> SpriteRenderer - .draw(element.spriteElement(), c)), + ElementClient.of(PROGRESS).renderer( + (element, c) -> SpriteRenderer.draw(element.spriteElement(), c)) + .overlay(ProgressBehavior::badge) + .behavior(ProgressBehavior::new), ElementClient.of(COLOURED_GROUP).renderer((element, c) -> { }).behavior(ColouredGroupBehavior::new), ElementClient.of(BOX).renderer((element, c) -> { @@ -146,10 +147,9 @@ private static List> declarations() { .renderer((element, c) -> GaugeRenderer.draw(c.graphics(), c.bounds(), element.orientation(), element.fill(c.value()), c.ratio(), c.groupColour())), - ElementClient.of(FLUID_TANK) - .renderer((element, c) -> GaugeRenderer.draw(c.graphics(), - c.bounds(), element.orientation(), element.fill(c.value()), - c.ratio(), c.groupColour())), + ElementClient.of(FLUID_TANK).renderer(GaugeRenderer::tank) + .foreground(FluidTankBehavior::drawDrain) + .behavior(FluidTankBehavior::new), ElementClient.of(ENERGY_GAUGE) .renderer((element, c) -> EnergyGaugeRenderer.draw(c.graphics(), c.bounds(), element, c.ratio(), c.groupColour())), diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ElementBehavior.java b/src/main/java/zone/moddev/mc/lib/gui/client/ElementBehavior.java index 050989f8..55bb8a4b 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ElementBehavior.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ElementBehavior.java @@ -1,6 +1,9 @@ package zone.moddev.mc.lib.gui.client; import java.util.List; +import java.util.Optional; + +import zone.moddev.mc.lib.gui.layout.Rect; /** * One element's state for one open screen. Factories must return fresh @@ -10,6 +13,14 @@ * capture without committing. */ public interface ElementBehavior { + /** + * A non-modal foreground control outside the element's layout bounds. Its + * nonempty {@link #tooltip} is displayed on its own. + */ + default Optional additionalHitBounds() { + return Optional.empty(); + } + /** * Optional transient chooser drawn above normal elements, outside the * owner's layout box. diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ElementInput.java b/src/main/java/zone/moddev/mc/lib/gui/client/ElementInput.java index 1d33634e..ff883e3f 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ElementInput.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ElementInput.java @@ -127,10 +127,22 @@ public E hit(double x, double y) { .get(overlay).overlayBounds().orElseThrow().contains(x, y)) ? overlay : null; - if (!closed && hitArea.test(x, y)) + if (!closed && hitArea.test(x, y)) { + var additional = additionalHit(x, y); + if (additional != null) + return additional; for (var element : order.reversed()) if (isShown(element) && bounds.apply(element).contains(x, y)) return element; + } + return null; + } + + private E additionalHit(double x, double y) { + for (var element : order.reversed()) + if (isShown(element) && instances.get(element).additionalHitBounds() + .filter(area -> area.contains(x, y)).isPresent()) + return element; return null; } @@ -236,14 +248,22 @@ public boolean click(double x, double y, int button) { instances.get(overlay).dismissOverlay(); return true; } - if (hitArea.test(x, y)) + if (hitArea.test(x, y)) { + var additional = additionalHit(x, y); + if (additional != null) { + blurUnless(additional); + if (click(additional, x, y, button)) + return true; + } for (var element : order.reversed()) { - if (!isShown(element) || !bounds.apply(element).contains(x, y)) + if (element == additional || !isShown(element) + || !bounds.apply(element).contains(x, y)) continue; blurUnless(element); if (click(element, x, y, button)) return true; } + } clearFocus(); return false; } diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderAccess.java b/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderAccess.java index 7663d460..73a67d44 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderAccess.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderAccess.java @@ -12,6 +12,7 @@ import zone.moddev.mc.lib.gui.model.Text; import zone.moddev.mc.lib.gui.model.elements.SlotElement; import zone.moddev.mc.lib.gui.sync.ElementStateView; +import zone.moddev.mc.lib.machine.inventory.TankPlan; /** * Read-only client presentation services. No machine, menu, packets or storage @@ -125,6 +126,10 @@ default ItemStack hint(SlotElement element) { return ItemStack.EMPTY; } + default TankPlan tankPlan(int tank) { + return TankPlan.NONE; + } + default Optional drawerPresentation(Element element, Class type) { return Optional.empty(); } diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderers.java b/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderers.java index dd6a0958..e4b6e2ff 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderers.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ElementRenderers.java @@ -20,6 +20,7 @@ import zone.moddev.mc.lib.gui.load.ScreenException; import zone.moddev.mc.lib.gui.model.Element; import zone.moddev.mc.lib.gui.model.Screen; +import zone.moddev.mc.lib.machine.inventory.TankPlan; /** * Client renderer registry. Register built-in or mod-owned element classes @@ -110,6 +111,10 @@ public Optional groupColour() { : access.groupColour(element); } + public TankPlan tankPlan(int tank) { + return access == null ? TankPlan.NONE : access.tankPlan(tank); + } + public ElementRenderAccess access() { return Objects.requireNonNull(access, "This render context has no presentation services"); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ElementTooltips.java b/src/main/java/zone/moddev/mc/lib/gui/client/ElementTooltips.java index f4ca2996..8023e73a 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ElementTooltips.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ElementTooltips.java @@ -30,6 +30,13 @@ public static List collect(Element target, boolean shift, boolean control, boolean alt) { if (!access.visible(target)) return List.of(); + var targetBehavior = behaviors.apply(target); + if (targetBehavior.additionalHitBounds() + .filter(bounds -> bounds.contains(x, y)).isPresent()) { + var foregroundRows = targetBehavior.tooltip(x, y); + if (!foregroundRows.isEmpty()) + return copyRows(foregroundRows); + } var rows = new ArrayList(); var visited = Collections .newSetFromMap(new IdentityHashMap()); @@ -40,17 +47,20 @@ public static List collect(Element target, "Cyclic tooltip parent chain"); var context = new Context(target, current, Optional.ofNullable(child), x, y, shift, control, alt, access); - var behavior = behaviors.apply(current); if (child == null) { current.appendTooltip(context, rows); - behavior.appendTooltip(context, rows); + targetBehavior.appendTooltip(context, rows); } else { current.appendChildTooltip(context, rows); - behavior.appendChildTooltip(context, rows); + behaviors.apply(current).appendChildTooltip(context, rows); } child = current; current = access.parent(current).orElse(null); } + return copyRows(rows); + } + + private static List copyRows(List rows) { return rows.stream().map(Component::copy).map(Component.class::cast) .toList(); } diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/FluidTankBehavior.java b/src/main/java/zone/moddev/mc/lib/gui/client/FluidTankBehavior.java new file mode 100644 index 00000000..b73bb938 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/client/FluidTankBehavior.java @@ -0,0 +1,93 @@ +package zone.moddev.mc.lib.gui.client; + +import java.util.List; +import java.util.Optional; + +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; + +import net.neoforged.neoforge.fluids.FluidStack; + +import zone.moddev.mc.lib.gui.ElementActions; +import zone.moddev.mc.lib.gui.layout.Rect; +import zone.moddev.mc.lib.gui.model.elements.FluidTankElement; + +final class FluidTankBehavior extends DefaultElementBehavior { + private static final int DRAIN_WIDTH = 11; + private static final int DRAIN_HEIGHT = 10; + + private final FluidTankElement tank; + + FluidTankBehavior(FluidTankElement tank, ElementAccess access) { + super(access); + this.tank = tank; + } + + private static Rect drainBounds(Rect gauge) { + return new Rect(gauge.x() + (gauge.width() - DRAIN_WIDTH) / 2, + gauge.bottom(), DRAIN_WIDTH, DRAIN_HEIGHT); + } + + static void drawDrain(FluidTankElement tank, + ElementRenderers.Context context) { + if (!tank.drainButton()) + return; + var valve = drainBounds(context.bounds()); + boolean open = tank.drainOpen(context.access().state()); + boolean hovered = valve.contains(context.mouseX(), context.mouseY()); + float opacity = open ? 1f : hovered ? 0.8f : 0.35f; + var graphics = context.graphics(); + graphics.flush(); + graphics.setColor(1, 1, 1, opacity); + try { + ElementDrawing.sprite(graphics, "icon_tank_drain", valve); + } finally { + graphics.setColor(1, 1, 1, 1); + } + } + + @Override + public Optional additionalHitBounds() { + return tank.drainButton() + ? Optional.of(drainBounds(access.bounds())) + : Optional.empty(); + } + + @Override + public Click mouseClicked(double x, double y, int button) { + if (!overDrain(x, y)) + return super.mouseClicked(x, y, button); + if (button == 0 && access.value() instanceof FluidStack fluid + && !fluid.isEmpty()) + access.click(ElementActions.CLICK, button, + FluidTankElement.DRAIN_OPTION); + return Click.CONSUME; + } + + @Override + public List tooltip(int x, int y) { + if (!overDrain(x, y)) + return List.of(); + var presentation = access.presentation(); + var tankRows = presentation.serverTooltip(tank); + var name = tankRows.isEmpty() + ? tank.defaultTankName().copy().withStyle(ChatFormatting.GOLD) + : tankRows.getFirst(); + if (!(access.value() instanceof FluidStack fluid) || fluid.isEmpty()) + return List.of(name, + Component.translatable("screen.mmdlib.tank.drain.empty")); + return List.of(name, + Component.translatable("screen.mmdlib.tank.contents", + fluid.getAmount(), fluid.getHoverName()), + Component + .translatable(tank.drainOpen(presentation.state()) + ? "screen.mmdlib.tank.drain.close" + : "screen.mmdlib.tank.drain.open") + .withStyle(ChatFormatting.GRAY)); + } + + private boolean overDrain(double x, double y) { + return tank.drainButton() + && drainBounds(access.bounds()).contains(x, y); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/GaugeRenderer.java b/src/main/java/zone/moddev/mc/lib/gui/client/GaugeRenderer.java index 6dd571be..ec6f7650 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/GaugeRenderer.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/GaugeRenderer.java @@ -18,15 +18,47 @@ import zone.moddev.mc.lib.gui.layout.Rect; import zone.moddev.mc.lib.gui.model.GaugeFill; import zone.moddev.mc.lib.gui.model.Orientation; +import zone.moddev.mc.lib.gui.model.elements.FluidTankElement; +import zone.moddev.mc.lib.machine.neoforge.FluidStacks; /** * Graduated glass gauge, with clipped fluid tiles kept upright in both * orientations. */ final class GaugeRenderer { + private static final float GHOST_OPACITY = .45f; + + private record Reservation(double input, double output, GaugeFill fill) { + static final Reservation NONE = new Reservation(0, 0, null); + } + + private enum BandWidth { + FULL, INPUT_HALF, OUTPUT_HALF + } + private GaugeRenderer() { } + static void tank(FluidTankElement element, ElementRenderers.Context c) { + var plan = c.tankPlan(element.tank()); + var reservation = Reservation.NONE; + if (!plan.isNone() && c.maximum() instanceof Number capacity + && capacity.doubleValue() > 0) { + int held = c.value() instanceof FluidStack fluid + ? fluid.getAmount() + : 0; + var output = plan.add(); + reservation = new Reservation( + Math.min(held, plan.take()) / capacity.doubleValue(), + output.isEmpty() ? 0 : output.amount() / capacity.doubleValue(), + output.isEmpty() + ? null + : element.fill(FluidStacks.stack(output))); + } + draw(c.graphics(), c.bounds(), element.orientation(), + element.fill(c.value()), c.ratio(), c.groupColour(), reservation); + } + /** * Shared slim casing and medium-grey empty interior for fluid and energy * gauges. @@ -58,11 +90,17 @@ static void draw(GuiGraphics g, Rect r, Orientation orientation, static void draw(GuiGraphics g, Rect r, Orientation orientation, GaugeFill fill, double ratio, java.util.Optional groupColour) { + draw(g, r, orientation, fill, ratio, groupColour, Reservation.NONE); + } + + private static void draw(GuiGraphics g, Rect r, Orientation orientation, + GaugeFill fill, double ratio, java.util.Optional groupColour, + Reservation reservation) { var state = RenderState.capture(); try { g.flush(); g.setColor(1, 1, 1, 1); - drawGauge(g, r, orientation, fill, ratio, groupColour); + drawGauge(g, r, orientation, fill, ratio, groupColour, reservation); } finally { try { g.flush(); @@ -74,31 +112,32 @@ static void draw(GuiGraphics g, Rect r, Orientation orientation, private static void drawGauge(GuiGraphics g, Rect r, Orientation orientation, GaugeFill fill, double ratio, - java.util.Optional groupColour) { + java.util.Optional groupColour, Reservation reservation) { boolean vertical = orientation == Orientation.VERTICAL; int length = vertical ? r.height() : r.width(); shell(g, r, vertical, length, "body", 1, ElementDrawing.backgroundTint(0xffffff, groupColour)); - int filled = (int) Math.round((length - 2) * ratio); - FluidStack fluid = fill.fluid().orElse(null); - int color = fill.colour().orElseGet(() -> IClientFluidTypeExtensions - .of(fluid.getFluid()).getTintColor(fluid)); - for (int step = 0; step < filled; step++) { - int row = length - 2 - step; - int inset = (row == 1 || row == length - 2) ? 2 : 1; - Rect strip = vertical - ? new Rect(r.x() + inset, r.y() + row, 18 - 2 * inset, 1) - : new Rect(r.x() + length - 1 - row, r.y() + inset, 1, - 18 - 2 * inset); - if (fluid != null) - fluid(g, strip, r, fluid, color); - else - g.fill(strip.x(), strip.y(), strip.right(), strip.bottom(), - color | 0xff000000); - if (vertical && step == filled - 1) - g.fill(strip.x(), strip.y(), strip.right(), strip.bottom(), - 0x4dffffff); - } + int inner = length - 2; + int filled = Math.max(reservation.input() > 0 && ratio > 0 ? 1 : 0, + (int) Math.round(inner * ratio)); + double freeRatio = Math.max(0, ratio - reservation.input()); + int free = reservation.input() > 0 && filled > 0 + ? Math.min(filled - 1, (int) Math.round(inner * freeRatio)) + : filled; + int preview = reservation.output() > 0 + ? Math.min(inner, + Math.max(free + 1, + (int) Math.round( + inner * Math.min(1, freeRatio + reservation.output())))) + : free; + // A tank can reserve both a withdrawal and a deposit in the same space. + boolean split = free < filled && preview > free; + band(g, r, vertical, fill, 0, free, 1, BandWidth.FULL); + band(g, r, vertical, fill, free, filled, GHOST_OPACITY, + split ? BandWidth.INPUT_HALF : BandWidth.FULL); + if (preview > free) + band(g, r, vertical, reservation.fill(), free, preview, + GHOST_OPACITY, split ? BandWidth.OUTPUT_HALF : BandWidth.FULL); // Continue the same curvature above the fluid with a softer reflection. // Clip the two strengths separately so filled pixels keep their // lighting. @@ -128,7 +167,6 @@ private static void drawGauge(GuiGraphics g, Rect r, g.disableScissor(); } } - int inner = length - 2; for (int n = 1; n < 20; n++) { boolean major = n == 5 || n == 10 || n == 15; if (!major && ((inner / 20f < 3 && n % 2 != 0) || inner / 10f < 3)) @@ -144,6 +182,35 @@ private static void drawGauge(GuiGraphics g, Rect r, } } + private static void band(GuiGraphics g, Rect r, boolean vertical, + GaugeFill fill, int from, int to, float opacity, BandWidth width) { + if (from >= to) + return; + int length = vertical ? r.height() : r.width(); + var stack = fill.fluid().orElse(null); + int color = fill.colour().orElseGet(() -> IClientFluidTypeExtensions + .of(stack.getFluid()).getTintColor(stack)); + int alpha = stack == null ? 255 : color >>> 24; + int tint = (Math.round(alpha * opacity) << 24) | (color & 0xffffff); + for (int step = from; step < to; step++) { + int row = length - 2 - step; + int inset = row == 1 || row == length - 2 ? 2 : 1; + int start = width == BandWidth.OUTPUT_HALF ? 9 : inset; + int end = width == BandWidth.INPUT_HALF ? 9 : 18 - inset; + Rect strip = vertical + ? new Rect(r.x() + start, r.y() + row, end - start, 1) + : new Rect(r.x() + 1 + step, r.y() + start, 1, end - start); + if (stack != null) + fluid(g, strip, r, stack, tint); + else + g.fill(strip.x(), strip.y(), strip.right(), strip.bottom(), + tint); + if (vertical && step == to - 1) + g.fill(strip.x(), strip.y(), strip.right(), strip.bottom(), + (Math.round(0x4d * opacity) << 24) | 0xffffff); + } + } + private static void shell(GuiGraphics g, Rect r, boolean vertical, int length, String layer) { shell(g, r, vertical, length, layer, 1); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/MachineScreen.java b/src/main/java/zone/moddev/mc/lib/gui/client/MachineScreen.java index c3290736..e861bb5a 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/MachineScreen.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/MachineScreen.java @@ -26,7 +26,9 @@ import zone.moddev.mc.lib.gui.model.elements.SlotElement; import zone.moddev.mc.lib.gui.runtime.MachineMenu; import zone.moddev.mc.lib.gui.runtime.ScreenRuntime; +import zone.moddev.mc.lib.gui.runtime.component.BuiltinMenuComponents; import zone.moddev.mc.lib.gui.sync.ElementStateView; +import zone.moddev.mc.lib.machine.inventory.TankPlan; /** * Client presentation of a data-defined machine; getters are never invoked @@ -102,6 +104,14 @@ public ItemStack hint(SlotElement element) { return menu.slotHint(element).copy(); } + public TankPlan tankPlan(int tank) { + var reservations = menu.components() + .get(BuiltinMenuComponents.RESERVATIONS); + return reservations == null + ? TankPlan.NONE + : reservations.tankPlan(tank); + } + public Optional drawerPresentation(Element element, Class type) { return drawers.presentation(element, type); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ProgressBehavior.java b/src/main/java/zone/moddev/mc/lib/gui/client/ProgressBehavior.java new file mode 100644 index 00000000..c3ec28c0 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ProgressBehavior.java @@ -0,0 +1,38 @@ +package zone.moddev.mc.lib.gui.client; + +import java.util.List; + +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +import zone.moddev.mc.lib.gui.model.elements.ProgressElement; + +final class ProgressBehavior extends DefaultElementBehavior { + private static final ResourceLocation WARNING = ResourceLocation + .parse("mmdlib:icon_error"); + private final ProgressElement element; + + ProgressBehavior(ProgressElement element, ElementAccess access) { + super(access); + this.element = element; + } + + static void badge(ProgressElement element, ElementRenderers.Context c) { + if (element.processorKey().isPresent() + && element.outputBlocked(c.access().state())) { + var bounds = c.bounds(); + c.graphics().blitSprite(WARNING, bounds.right() - 8, + bounds.bottom() - 8, 8, 8); + } + } + + @Override + public List tooltip(int x, int y) { + return element.outputBlocked(access.presentation().state()) + ? List.of( + Component.translatable("screen.mmdlib.progress.output_blocked") + .withStyle(ChatFormatting.RED)) + : List.of(); + } +} 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 8075cc59..03cc7292 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 @@ -8,6 +8,7 @@ import zone.moddev.mc.lib.gui.layout.ElementLayouts; import zone.moddev.mc.lib.gui.model.Edge; +import zone.moddev.mc.lib.gui.model.PopoutKind; import zone.moddev.mc.lib.gui.model.containers.SideTabElement; import zone.moddev.mc.lib.gui.model.elements.PopoutElement; @@ -16,7 +17,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"), UPGRADES = id("upgrades"); + SIDE_TAB = id("side_tab"), UPGRADES = id("upgrades"), INFO = id("info"); private BuiltinDrawers() { } @@ -25,6 +26,13 @@ private static ResourceLocation id(String name) { return ResourceLocation.fromNamespaceAndPath("mmdlib", name); } + /** The Info feature controls the info popouts supplied by the screen. */ + public static ResourceLocation featureType(DrawerDefinition drawer) { + return drawer.type().equals(POPOUT) + && drawer.element().orElse(null) instanceof PopoutElement popout + && popout.kind() == PopoutKind.INFO ? INFO : drawer.type(); + } + static void register(DrawerRegistry registry) { registry.register(UPGRADES, c -> c.screen().tabs().stream().filter( zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement.class::isInstance) diff --git a/src/main/java/zone/moddev/mc/lib/gui/drawer/DrawerRegistry.java b/src/main/java/zone/moddev/mc/lib/gui/drawer/DrawerRegistry.java index bc7d239d..244e73c1 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/drawer/DrawerRegistry.java +++ b/src/main/java/zone/moddev/mc/lib/gui/drawer/DrawerRegistry.java @@ -15,6 +15,7 @@ import net.minecraft.resources.ResourceLocation; import zone.moddev.mc.lib.gui.layout.TextMeasure; +import zone.moddev.mc.lib.gui.model.Element; import zone.moddev.mc.lib.gui.model.Screen; import zone.moddev.mc.lib.gui.runtime.ScreenHost; @@ -25,6 +26,9 @@ public final class DrawerRegistry { public static final DrawerRegistry GLOBAL = builtins(); + private record Contribution(String featureId, DrawerDefinition drawer) { + } + public record Context(Screen screen, TextMeasure text, ScreenHost host, Set enabled) { public Context { @@ -65,10 +69,7 @@ public synchronized void replace(ResourceLocation type, } public synchronized List resolve(Context context) { - var result = new ArrayList(); - var ids = new HashSet(); - var elements = Collections.newSetFromMap( - new IdentityHashMap()); + var contributions = new ArrayList(); for (var entry : providers.entrySet()) for (var definition : List .copyOf(entry.getValue().apply(context))) { @@ -76,21 +77,42 @@ public synchronized List resolve(Context context) { throw new IllegalArgumentException( "Drawer provider returned another type: " + definition.type()); - if (!ids - .add(definition.placement().edge() + "/" + definition.id())) - throw new IllegalArgumentException( - "Duplicate drawer: " + definition.id()); - definition.element().ifPresent(element -> { - if (context.screen().tabs().stream().noneMatch( - tab -> tab == element) || !elements.add(element)) - throw new IllegalArgumentException( - "Drawer element must be a unique screen tab"); - }); - result.add(definition); - if (result.size() > 4096) - throw new IllegalArgumentException( - "Too many drawer declarations"); + contributions.add(new Contribution(null, definition)); } + var host = context.host(); + var features = host == null ? null : host.screenFeatures(); + if (features != null) + for (var contributor : features + .contributors(MachineFeatureDrawers.class)) + for (var drawer : List.copyOf(contributor.drawers(context))) + contributions + .add(new Contribution(contributor.key(), drawer)); + + if (contributions.size() > 4096) + throw new IllegalArgumentException("Too many drawer declarations"); + var result = new ArrayList(); + var ids = new HashSet(); + var elements = Collections + .newSetFromMap(new IdentityHashMap()); + for (var contribution : contributions) { + var drawer = contribution.drawer(); + drawer.element().ifPresent(element -> { + if (context.screen().tabs().stream() + .noneMatch(tab -> tab == element) || !elements.add(element)) + throw new IllegalArgumentException( + "Drawer element must be a unique screen tab"); + }); + var settings = host == null + ? DrawerSettings.DEFAULT + : host.screenDrawerSettings(contribution.featureId(), drawer); + if (!settings.enabled()) + continue; + var placed = settings.apply(drawer); + if (!ids.add(placed.placement().edge() + "/" + placed.id())) + throw new IllegalArgumentException( + "Duplicate drawer: " + placed.id()); + result.add(placed); + } for (var tab : context.screen().tabs()) if (!elements.contains(tab)) throw new IllegalArgumentException( diff --git a/src/main/java/zone/moddev/mc/lib/gui/drawer/DrawerSettings.java b/src/main/java/zone/moddev/mc/lib/gui/drawer/DrawerSettings.java new file mode 100644 index 00000000..b7d0afdb --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/drawer/DrawerSettings.java @@ -0,0 +1,25 @@ +package zone.moddev.mc.lib.gui.drawer; + +import zone.moddev.mc.lib.gui.model.Edge; + +/** Optional overrides for a machine feature's drawer placement. */ +public record DrawerSettings(boolean enabled, Edge edge, + DrawerPlacement.Anchor anchor, Integer order) { + public static final DrawerSettings DEFAULT = new DrawerSettings(true, null, + null, null); + public static final DrawerSettings HIDDEN = new DrawerSettings(false, null, + null, null); + + DrawerDefinition apply(DrawerDefinition definition) { + if (edge == null && anchor == null && order == null) + return definition; + var placement = definition.placement(); + return new DrawerDefinition(definition.type(), definition.id(), + new DrawerPlacement(edge == null ? placement.edge() : edge, + anchor == null ? placement.anchor() : anchor, + order == null ? placement.order() : order, placement.width(), + placement.height(), placement.overlap(), placement.gap()), + definition.element(), definition.toolbarWidth(), + definition.interactive()); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/gui/drawer/MachineFeatureDrawers.java b/src/main/java/zone/moddev/mc/lib/gui/drawer/MachineFeatureDrawers.java new file mode 100644 index 00000000..95e33e88 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/drawer/MachineFeatureDrawers.java @@ -0,0 +1,13 @@ +package zone.moddev.mc.lib.gui.drawer; + +import java.util.List; + +/** + * Optional presentation of an installed machine feature. Register its drawers' + * client factories separately. Definitions must agree on both sides. + */ +public interface MachineFeatureDrawers { + String key(); + + List drawers(DrawerRegistry.Context context); +} 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 9d1cebba..a52d2054 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 @@ -295,7 +295,8 @@ private static FluidTankElement fluidTank(ScreenXml x) { if (x.optional("color").isPresent()) throw x.error("A fluid tank uses its fluid texture"); return new FluidTankElement(x.common(), x.integer("tank"), - x.enumValue(Orientation.class, "orientation"), x.length(8)); + x.enumValue(Orientation.class, "orientation"), x.length(8), + x.optional("drain-button").isEmpty() || x.flag("drain-button")); } private static CustomElement customElement(ScreenXml x) { @@ -403,6 +404,8 @@ private static Element gauge(ScreenXml x) { var c = x.common(); if (node.attributes().containsKey("tank")) return fluidTank(x); + if (x.optional("drain-button").isPresent()) + throw x.error("drain-button requires a tank binding"); return new GaugeElement(c, x.enumValue(Orientation.class, "orientation"), x.length(8), x.color("color")); @@ -465,7 +468,8 @@ private static ProgressElement progress(ScreenXml x) { var node = x.node(); var c = x.common(); return new ProgressElement(c, x.id("icon"), - x.enumValue(ProgressDirection.class, "direction")); + x.enumValue(ProgressDirection.class, "direction"), + Optional.ofNullable(node.attributes().get("processor-key"))); } private static LabelElement label(ScreenXml x) { diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/elements/FluidTankElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/elements/FluidTankElement.java index 81172f2b..49d26111 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/model/elements/FluidTankElement.java +++ b/src/main/java/zone/moddev/mc/lib/gui/model/elements/FluidTankElement.java @@ -8,6 +8,7 @@ import net.minecraft.ChatFormatting; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BucketItem; import net.minecraft.world.item.ItemStack; @@ -24,7 +25,6 @@ import zone.moddev.mc.lib.gui.layout.ElementLayouts; 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.model.ElementSnapshot; import zone.moddev.mc.lib.gui.model.GaugeFill; import zone.moddev.mc.lib.gui.model.Interaction; @@ -32,23 +32,41 @@ import zone.moddev.mc.lib.gui.model.ResourceBinding; import zone.moddev.mc.lib.gui.runtime.ScreenClick; import zone.moddev.mc.lib.gui.runtime.ScreenHost; +import zone.moddev.mc.lib.gui.sync.ElementStateView; +import zone.moddev.mc.lib.gui.sync.ElementSync; +import zone.moddev.mc.lib.gui.sync.SynchronizedElement; +import zone.moddev.mc.lib.machine.neoforge.FluidStacks; /** * A complete tank UI component: binding, values, tooltip and cursor-container * interaction. All storage access runs on the server. The client draws its * snapshots with the glass gauge renderer. */ -public class FluidTankElement implements Element { +public class FluidTankElement implements SynchronizedElement { + private static final ElementSync DRAIN_OPEN = ElementSync + .field(ResourceLocation.parse("mmdlib:tank_drain_open"), + ByteBufCodecs.BOOL.cast(), 1, element -> false) + .sample(source -> source.machine() instanceof ScreenHost host + && ((FluidTankElement) source.element()).drainOpen(host)) + .immutable().build(); + private final Common common; private final int tank; private final Orientation orientation; private final int length; + private final boolean drainButton; + public static final int DRAIN_OPTION = 1; public static final ResourceLocation INTERACTION_ID = ResourceLocation .fromNamespaceAndPath("mmdlib", "fluid-container"); public FluidTankElement(Common common, int tank, Orientation orientation, int length) { + this(common, tank, orientation, length, true); + } + + public FluidTankElement(Common common, int tank, Orientation orientation, + int length, boolean drainButton) { Objects.requireNonNull(common); Objects.requireNonNull(orientation); if (tank < 0) @@ -62,6 +80,7 @@ public FluidTankElement(Common common, int tank, Orientation orientation, this.tank = tank; this.orientation = orientation; this.length = length; + this.drainButton = drainButton; } public boolean fills() { @@ -109,8 +128,33 @@ public Optional snapshot(ScreenHost host) { storage.getTankCapacity(tank))); } + @Override + public List> synchronizedValues() { + return drainButton() ? List.of(DRAIN_OPEN) : List.of(); + } + + private boolean drainOpen(ScreenHost host) { + return storage(host, tank).drainOpen(tank); + } + + public boolean drainOpen(ElementStateView state) { + return drainButton() && state.get(this, DRAIN_OPEN); + } + + @Override + public boolean validClickOption(int option) { + return option == 0 || drainButton() && option == DRAIN_OPTION; + } + @Override public boolean interact(ScreenClick click) { + if (click.option() == DRAIN_OPTION) { + if (!drainButton() || click.button() != 0 + || !(click.menu().blockEntity instanceof ScreenHost host)) + return false; + storage(host, tank).toggleDrain(tank); + return true; + } return transfer(click, tank); } @@ -218,8 +262,8 @@ public FluidStack drain(int amount, FluidAction action) { public List tooltip(ScreenHost host, ItemStack carried) { var storage = storage(host, tank); var current = storage.getFluidInTank(tank); - Component name = host.screenTankName(tank).orElseGet( - () -> Component.translatable("screen.mmdlib.tank.name", tank + 1)); + Component name = host.screenTankName(tank) + .orElseGet(this::defaultTankName); var accepted = BuiltInRegistries.FLUID.stream() .filter(fluid -> fluid != Fluids.EMPTY && fluid.isSource(fluid.defaultFluidState())) @@ -233,6 +277,17 @@ public List tooltip(ScreenHost host, ItemStack carried) { .withStyle(ChatFormatting.GRAY) : Component.translatable("screen.mmdlib.tank.contents", current.getAmount(), current.getHoverName())); + var plan = storage.plan(tank); + if (plan.take() > 0) + lines.add(Component + .translatable("screen.mmdlib.tank.reserved_input", plan.take()) + .withStyle(ChatFormatting.GOLD)); + if (!plan.add().isEmpty()) + lines.add(Component + .translatable("screen.mmdlib.tank.reserved_output", + plan.add().amount(), + FluidStacks.stack(plan.add()).getHoverName()) + .withStyle(ChatFormatting.AQUA)); var names = Component.empty(); for (var acceptedName : accepted) { if (!names.getSiblings().isEmpty()) @@ -300,6 +355,10 @@ public int tank() { return tank; } + public Component defaultTankName() { + return Component.translatable("screen.mmdlib.tank.name", tank + 1); + } + public Orientation orientation() { return orientation; } @@ -308,6 +367,10 @@ public int length() { return length; } + public boolean drainButton() { + return drainButton; + } + @Override public boolean equals(Object object) { if (this == object) @@ -318,7 +381,8 @@ public boolean equals(Object object) { return java.util.Objects.equals(common, other.common) && java.util.Objects.equals(tank, other.tank) && java.util.Objects.equals(orientation, other.orientation) - && java.util.Objects.equals(length, other.length); + && java.util.Objects.equals(length, other.length) + && drainButton == other.drainButton; } @Override @@ -328,12 +392,14 @@ public int hashCode() { hash = 31 * hash + java.util.Objects.hashCode(tank); hash = 31 * hash + java.util.Objects.hashCode(orientation); hash = 31 * hash + java.util.Objects.hashCode(length); + hash = 31 * hash + Boolean.hashCode(drainButton); return hash; } @Override public String toString() { return "FluidTankElement[common=" + common + ", tank=" + tank - + ", orientation=" + orientation + ", length=" + length + "]"; + + ", orientation=" + orientation + ", length=" + length + + ", drainButton=" + drainButton + "]"; } } diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/elements/ProgressElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/elements/ProgressElement.java index f9f8f9c4..6227963b 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/model/elements/ProgressElement.java +++ b/src/main/java/zone/moddev/mc/lib/gui/model/elements/ProgressElement.java @@ -2,17 +2,24 @@ import static zone.moddev.mc.lib.gui.model.ValueContract.NUMBERS; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.entity.BlockEntity; import zone.moddev.mc.lib.gui.WidgetTypes; 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.model.ProgressDirection; import zone.moddev.mc.lib.gui.model.ValueContract; +import zone.moddev.mc.lib.gui.runtime.ScreenHost; +import zone.moddev.mc.lib.gui.sync.ElementStateView; +import zone.moddev.mc.lib.gui.sync.ElementSync; +import zone.moddev.mc.lib.gui.sync.SynchronizedElement; import zone.moddev.mc.lib.gui.value.ValueType; /** @@ -22,16 +29,54 @@ * {@code icon}: the icon sprite; the default arrow when empty * {@code direction}: which way it fills */ -public class ProgressElement implements Element { +public class ProgressElement implements SynchronizedElement { + public static final ElementSync OUTPUT_BLOCKED = ElementSync + .field(ResourceLocation.parse("mmdlib:progress_output_blocked"), + ByteBufCodecs.BOOL.cast(), 1, element -> false) + .sample(source -> ((ProgressElement) source.element()) + .outputBlocked(source.machine())) + .immutable().build(); + private final Common common; private final Optional icon; private final ProgressDirection direction; + private final Optional processorKey; public ProgressElement(Common common, Optional icon, ProgressDirection direction) { + this(common, icon, direction, Optional.empty()); + } + + public ProgressElement(Common common, Optional icon, + ProgressDirection direction, Optional processorKey) { this.common = common; this.icon = icon; this.direction = direction; + this.processorKey = processorKey; + } + + private boolean outputBlocked(BlockEntity machine) { + return machine instanceof ScreenHost host + && host.screenFeatures() != null + && processorKey.flatMap(host.screenFeatures()::processor) + .map(processor -> processor.outputBlocked(machine.getLevel())) + .orElse(false); + } + + public boolean outputBlocked(ElementStateView state) { + return processorKey.isPresent() && state.get(this, OUTPUT_BLOCKED); + } + + public List> synchronizedValues() { + return processorKey.isPresent() ? List.of(OUTPUT_BLOCKED) : List.of(); + } + + public void validateBindings(Map> bindings) { + processorKey.ifPresent(key -> { + if (!bindings.getOrDefault("processors", Set.of()).contains(key)) + throw new IllegalArgumentException( + "Unknown processor-key: " + key); + }); } /** The processor arrow is a preset of the reusable progress sprite. */ @@ -54,8 +99,11 @@ public Set> valueKinds(WidgetTypes widgets) { } public void validate() { - Element.super.validate(); + SynchronizedElement.super.validate(); ValueContract.require(this, "a ", true); + if (processorKey.filter(String::isBlank).isPresent()) + throw new IllegalArgumentException( + "processor-key must not be blank"); } public Common common() { @@ -70,6 +118,10 @@ public ProgressDirection direction() { return direction; } + public Optional processorKey() { + return processorKey; + } + @Override public boolean equals(Object object) { if (this == object) @@ -79,7 +131,8 @@ public boolean equals(Object object) { var other = (ProgressElement) object; return java.util.Objects.equals(common, other.common) && java.util.Objects.equals(icon, other.icon) - && java.util.Objects.equals(direction, other.direction); + && java.util.Objects.equals(direction, other.direction) + && java.util.Objects.equals(processorKey, other.processorKey); } @Override @@ -88,12 +141,14 @@ public int hashCode() { hash = 31 * hash + java.util.Objects.hashCode(common); hash = 31 * hash + java.util.Objects.hashCode(icon); hash = 31 * hash + java.util.Objects.hashCode(direction); + hash = 31 * hash + java.util.Objects.hashCode(processorKey); return hash; } @Override public String toString() { return "ProgressElement[common=" + common + ", icon=" + icon - + ", direction=" + direction + "]"; + + ", direction=" + direction + ", processorKey=" + processorKey + + "]"; } } diff --git a/src/main/java/zone/moddev/mc/lib/gui/runtime/MachineMenu.java b/src/main/java/zone/moddev/mc/lib/gui/runtime/MachineMenu.java index 1dc38cad..2867baf2 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/runtime/MachineMenu.java +++ b/src/main/java/zone/moddev/mc/lib/gui/runtime/MachineMenu.java @@ -215,10 +215,9 @@ public MachineMenu(int id, Inventory inventory, BlockEntity entity) { /** * For tests only. * - * @param client - * whether the slots are the client's copy, as on a client; the - * menu still reads the level's side for layout, so this is only - * meaningful for running both against one server + * @param client whether the slots are the client's copy, as on a client; + * the menu still reads the level's side for layout, so this is + * only meaningful for running both against one server */ protected MachineMenu(int id, Inventory inventory, BlockEntity entity, boolean client) { @@ -368,8 +367,8 @@ public boolean visible(Element element) { if (visibility.isEmpty()) { for (var root : bound.screen().body()) cacheVisibility(root, true); - for (var root : bound.screen().tabs()) - cacheVisibility(root, true); + for (var drawer : layout.drawers()) + drawer.element().ifPresent(root -> cacheVisibility(root, true)); for (var root : bound.screen().implicitElements()) cacheVisibility(root, root.visibilityAnchor(bound.screen()).map( diff --git a/src/main/java/zone/moddev/mc/lib/gui/runtime/ScreenHost.java b/src/main/java/zone/moddev/mc/lib/gui/runtime/ScreenHost.java index b51716d8..8c44fd38 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/runtime/ScreenHost.java +++ b/src/main/java/zone/moddev/mc/lib/gui/runtime/ScreenHost.java @@ -17,6 +17,13 @@ * data-defined menu. */ public interface ScreenHost { + /** Feature ID is present for a drawer supplied by an installed feature. */ + default zone.moddev.mc.lib.gui.drawer.DrawerSettings screenDrawerSettings( + String featureId, + zone.moddev.mc.lib.gui.drawer.DrawerDefinition drawer) { + return zone.moddev.mc.lib.gui.drawer.DrawerSettings.DEFAULT; + } + default boolean screenStatsDrawer() { return true; } 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 cddf49dd..a3919178 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 @@ -45,8 +45,10 @@ private BuiltinMenuComponents() { } static void register(MenuComponentRegistry registry) { - registry.register(UPGRADES, 15, c -> c.menu().bound.screen().tabs() + registry.register(UPGRADES, 15, c -> c.menu().layout().drawers() .stream() + .filter(drawer -> drawer.type().equals(BuiltinDrawers.UPGRADES)) + .flatMap(drawer -> drawer.element().stream()) .filter( zone.moddev.mc.lib.gui.model.containers.UpgradesDrawerElement.class::isInstance) .map( @@ -61,22 +63,40 @@ static void register(MenuComponentRegistry registry) { InventoryMenuComponent.HINTS); registry.register(RESERVATIONS, -900, c -> new ReservationMenuComponent(c.menu().nativeSlots(), - c.client()), - ReservationMenuComponent.PLANS); + c.client(), c.host() == null ? null : c.host().screenFluids()), + ReservationMenuComponent.PLANS, + ReservationMenuComponent.TANK_PLANS); registry.register(AUTOMATION, 0, - c -> c.host() != null && c.host().screenAutomation() != null - ? new AutomationMenu(c.menu(), c.host().screenAutomation(), - c.inventory().player, c.client()) - : null); + c -> hasDrawer(c, BuiltinDrawers.SIDES) && c.host() != null + && c.host().screenAutomation() != null + ? new AutomationMenu(c.menu(), c.host().screenAutomation(), + c.inventory().player, c.client()) + : null); registry.register(REDSTONE, 10, - c -> c.host() != null && c.host().screenRedstone() != null - ? new RedstoneMenu(c.menu(), c.inventory().player, - c.host().screenRedstone(), c.client()) - : null); - registry.register(STATS, 20, StatsMenuComponent::new, + c -> hasDrawer(c, BuiltinDrawers.REDSTONE) && c.host() != null + && c.host().screenRedstone() != null + ? new RedstoneMenu(c.menu(), c.inventory().player, + c.host().screenRedstone(), c.client()) + : null); + registry.register(STATS, 20, + c -> hasDrawer(c, BuiltinDrawers.STATS) + ? new StatsMenuComponent(c) + : null, StatsMenuComponent.PAGES); - registry.register(BACKPACK, 30, c -> equipment(c, false)); - registry.register(CURIOS, 40, c -> equipment(c, true)); + registry.register(BACKPACK, 30, + c -> hasDrawer(c, BuiltinDrawers.BACKPACK) + ? equipment(c, false) + : null); + registry.register(CURIOS, 40, + c -> hasDrawer(c, BuiltinDrawers.CURIOS) + ? equipment(c, true) + : null); + } + + private static boolean hasDrawer(MenuComponentRegistry.Context context, + ResourceLocation type) { + return context.menu().layout().drawers().stream() + .anyMatch(drawer -> drawer.type().equals(type)); } private static ContainerDrawerMenu equipment( diff --git a/src/main/java/zone/moddev/mc/lib/gui/runtime/slot/ReservationMenuComponent.java b/src/main/java/zone/moddev/mc/lib/gui/runtime/slot/ReservationMenuComponent.java index dc58d914..e5110283 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/runtime/slot/ReservationMenuComponent.java +++ b/src/main/java/zone/moddev/mc/lib/gui/runtime/slot/ReservationMenuComponent.java @@ -1,24 +1,28 @@ package zone.moddev.mc.lib.gui.runtime.slot; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; +import zone.moddev.mc.lib.api.capabilities.FluidStorage; import zone.moddev.mc.lib.gui.runtime.component.ComponentSnapshot; import zone.moddev.mc.lib.gui.runtime.component.ComponentStateView; import zone.moddev.mc.lib.gui.runtime.component.ComponentSync; import zone.moddev.mc.lib.gui.runtime.component.MenuSnapshot; +import zone.moddev.mc.lib.machine.ingredient.FluidAmount; import zone.moddev.mc.lib.machine.inventory.SlotPlan; +import zone.moddev.mc.lib.machine.inventory.TankPlan; /** - * Owns reservation sampling, wire encoding and client slot adaptation for every - * contributor. + * Owns reservation sampling, wire encoding and client slot adaptation. */ public final class ReservationMenuComponent implements MenuSnapshot { private static final int MAX_SLOTS = 32767; @@ -59,12 +63,35 @@ public final class ReservationMenuComponent implements MenuSnapshot { .allMatch(e -> e.getKey() != null && e.getKey() >= 0 && e.getKey() < MAX_SLOTS && e.getValue() != null)); + // Resolve the fluid codec at packet time, after the registry boots. + public static final ComponentSync> TANK_PLANS = new ComponentSync<>( + ResourceLocation.parse("mmdlib:tank_reservation_plans"), 1, + ByteBufCodecs.map(LinkedHashMap::new, ByteBufCodecs.VAR_INT, StreamCodec + .of((buffer, plan) -> { + buffer.writeVarInt(plan.take()); + FluidAmount.STREAM_CODEC.encode(buffer, plan.add()); + }, buffer -> new TankPlan(buffer.readVarInt(), + FluidAmount.STREAM_CODEC.decode(buffer))), + MAX_SLOTS), + 65536, Map::of, + plans -> plans.size() <= MAX_SLOTS + && plans.entrySet().stream().allMatch(e -> e.getKey() >= 0 + && e.getKey() < MAX_SLOTS && e.getValue() != null)); + private final MenuSlots slots; private final boolean client; + private final FluidStorage fluids; + private Map tankPlans = Map.of(); public ReservationMenuComponent(MenuSlots slots, boolean client) { + this(slots, client, null); + } + + public ReservationMenuComponent(MenuSlots slots, boolean client, + FluidStorage fluids) { this.slots = Objects.requireNonNull(slots); this.client = client; + this.fluids = fluids; } public void snapshot(ComponentSnapshot values) { @@ -73,11 +100,22 @@ public void snapshot(ComponentSnapshot values) { if (entry.reservations()) plans.put(entry.slot().index, entry.plan()); values.put(PLANS, plans); + if (fluids != null) { + var tanks = new LinkedHashMap(); + for (int tank = 0; tank < fluids.getTanks(); tank++) { + var plan = fluids.plan(tank); + if (!plan.isNone()) + tanks.put(tank, plan); + } + values.put(TANK_PLANS, tanks); + } } public void applied(ComponentStateView values) { if (!client) return; + if (fluids != null) + tankPlans = Map.copyOf(values.get(TANK_PLANS)); var plans = values.get(PLANS); // This is a complete field snapshot. Omitted plans must clear any // previous client @@ -87,4 +125,8 @@ public void applied(ComponentStateView values) { ((SlotAdapter) entry.slot()).applyPlan( plans.getOrDefault(entry.slot().index, SlotPlan.NONE)); } + + public TankPlan tankPlan(int tank) { + return tankPlans.getOrDefault(tank, TankPlan.NONE); + } } 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 cffac47a..c443d22a 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 @@ -1,6 +1,9 @@ package zone.moddev.mc.lib.machine.definition; import java.util.List; +import java.util.Optional; + +import net.minecraft.resources.ResourceLocation; /** Optional physical/item policies and a mod-owned processor. */ public record MachineBehavior(ProcessorDeclaration processor, int stackSize, @@ -11,7 +14,26 @@ public record MachineBehavior(ProcessorDeclaration processor, int stackSize, zone.moddev.mc.lib.machine.presentation.VisualizerStyle visualizers, String gearboxSlot, String capacitorSlot, List rangeSlots, String legacyUpgradeStorage, MachineFacing facing, String comparatorSource, - List processors) { + List processors, + List features) { + public MachineBehavior(ProcessorDeclaration processor, int stackSize, + boolean noOcclusion, boolean immovable, boolean portable, + boolean drawers, List shapes, ResourceLocation secondaryAction, + 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) { + this(processor, stackSize, noOcclusion, immovable, portable, drawers, + shapes, secondaryAction, entityDisplay, itemDisplay, visualizers, + gearboxSlot, capacitorSlot, rangeSlots, legacyUpgradeStorage, + facing, comparatorSource, processors, List.of()); + } + + public Optional feature(ResourceLocation type) { + return features.stream().filter(feature -> feature.type().equals(type)) + .findFirst(); + } public MachineBehavior(ProcessorDeclaration processor, int stackSize, boolean noOcclusion, boolean immovable, boolean portable, boolean drawers, List shapes, @@ -57,6 +79,7 @@ public MachineBehavior(ProcessorDeclaration processor, int stackSize, java.util.Objects.requireNonNull(facing); rangeSlots = List.copyOf(rangeSlots); processors = List.copyOf(processors); + features = List.copyOf(features); if (rangeSlots.size() > 9 || new java.util.HashSet<>(rangeSlots).size() != rangeSlots.size()) throw new IllegalArgumentException( 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 82554929..2323261f 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 @@ -31,8 +31,8 @@ public record MachineDefinition(ResourceLocation id, String checksum, String itemStorageId, List slots, List groups, RecipeType recipeType, String processor, String processorName, boolean redstone, Node screen, RecipeSelection recipeSelection, - List ghosts, MachineBehavior behavior, Sounds sounds, - Events events) { + List ghosts, MachineBehavior behavior, Sounds sounds, Events events, + Node layout) { public record Ghost(String id, int count, ResourceLocation defaultItem, String name) { public Ghost(String id, int count, ResourceLocation defaultItem) { @@ -136,6 +136,29 @@ public MachineDefinition(ResourceLocation id, String checksum, String name, screen, recipeSelection, ghosts, behavior, sounds, Events.NONE); } + public MachineDefinition(ResourceLocation id, String checksum, String name, + float hardness, ResourceLocation mineable, boolean requiresTool, + Map textures, ResourceLocation baseModel, + List modelParts, + List faceTextures, Power power, Fluids fluids, + String itemStorageId, List slots, List groups, + RecipeType recipeType, String processor, String processorName, + boolean redstone, Node screen, RecipeSelection recipeSelection, + List ghosts, MachineBehavior behavior, Sounds sounds, + Events events) { + this(id, checksum, name, hardness, mineable, requiresTool, textures, + baseModel, modelParts, faceTextures, power, fluids, itemStorageId, + slots, groups, recipeType, processor, processorName, redstone, + screen, recipeSelection, ghosts, behavior, sounds, events, null); + } + + @Override + public Node screen() { + return layout == null || layout.children().isEmpty() + ? screen + : MachineScreenGenerators.withLayout(this, screen, layout); + } + public record RecipeSelection(ResourceLocation defaultRecipe) { } 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 740ad5e9..c3bda2d4 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 @@ -24,9 +24,13 @@ import zone.moddev.mc.lib.api.capabilities.RelativeFace; import zone.moddev.mc.lib.api.capabilities.Role; import zone.moddev.mc.lib.common.loading.DefinitionLoader.SourceRoot; +import zone.moddev.mc.lib.gui.drawer.BuiltinDrawers; +import zone.moddev.mc.lib.gui.drawer.DrawerPlacement; +import zone.moddev.mc.lib.gui.drawer.DrawerSettings; import zone.moddev.mc.lib.gui.load.ScreenException; import zone.moddev.mc.lib.gui.load.ScreenReader.Node; import zone.moddev.mc.lib.gui.load.ScreenReader; +import zone.moddev.mc.lib.gui.model.Edge; import zone.moddev.mc.lib.machine.definition.MachineDefinition.Fluids; import zone.moddev.mc.lib.machine.definition.MachineDefinition.Generator; import zone.moddev.mc.lib.machine.definition.MachineDefinition.Group; @@ -68,7 +72,6 @@ public static Map load( try (var stream = Files.newInputStream(path)) { var node = ScreenReader.parseMachine(path.toString(), stream); - validateTree(node); if (!node.name().equals("machine")) throw error(node, "Expected "); if (nodes.putIfAbsent(id, node) != null) @@ -195,13 +198,16 @@ private static Node resolve(ResourceLocation id, if (!visiting.add(id)) throw error(node, "Machine inheritance cycle " + visiting); var parent = node.attributes().get("extends"); - var result = node; + Node base = null; if (parent != null) { var parentId = resource(node, "extends"); if (!nodes.containsKey(parentId)) throw error(node, "Unknown base machine " + parent); - result = merge(resolve(parentId, nodes, resolved, visiting), node); + base = resolve(parentId, nodes, resolved, visiting); } + var expanded = MachineParts.expand(node, base); + validateTree(expanded); + var result = base == null ? expanded : merge(base, expanded); visiting.remove(id); resolved.put(id, result); return result; @@ -210,9 +216,11 @@ 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())) + if (parent.name().equals("machine") && Set + .of("processor", "recipe-type", "feature").contains(node.name())) return node.name() + ":" + required(node, "id"); + if (parent.name().equals("feature")) + return node.name(); if (Set.of("machine", "storage", "recipe-type").contains(parent.name())) return node.name(); if (parent.name().equals("appearance") && isDisplay(node)) @@ -230,8 +238,13 @@ private static boolean isDisplay(Node node) { } private static Node merge(Node base, Node child) { - if (child.name().equals("generator") || child.name().equals("fill")) + if (Set.of("generator", "fill", "layout").contains(child.name())) return child; + if (child.name().equals("feature") + && child.attributes().containsKey("type") + && base.attributes().containsKey("type") + && !resource(child, "type").equals(resource(base, "type"))) + throw error(child, "An inherited feature cannot change type"); var attrs = new LinkedHashMap<>(base.attributes()); // A new preset replaces the previous preset's base configuration, but // retains parts. @@ -330,18 +343,20 @@ private static Node merge(Node base, Node child) { "on-start", "on-finish", "bindings", "primary", "energy-per-tick")), Map.entry("redstone", Set.of("enabled", "pause", "comparator-source")), + Map.entry("drawer", Set.of("enabled", "edge", "anchor", "order")), 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", - "visualizers", "upgrades"), + "visualizers", "upgrades", "feature", "layout"), "storage", Set.of("energy", "items", "fluids"), "fluids", Set.of("tank", "tanks"), "items", Set.of("slot", "slots"), "groups", Set.of("group"), "appearance", Set.of("part", "face-texture", "face-overlay", "entity-display", "item-display"), - "recipe-type", Set.of("generator"), "shapes", Set.of("shape")); + "recipe-type", Set.of("generator"), "shapes", Set.of("shape"), + "feature", Set.of("drawer")); private static void validateTree(Node node) { if (node.name().equals("screen") @@ -350,7 +365,11 @@ private static void validateTree(Node node) { if (!node.namespace().equals(ScreenReader.NAMESPACE)) throw error(node, "Unknown machine XML namespace: " + node.namespace()); - if (!node.name().equals("generator")) { + if (node.name().equals("layout")) { + validateLayout(node); + return; + } + if (!Set.of("generator", "feature").contains(node.name())) { var allowed = ATTRIBUTES.get(node.name()); if (allowed == null) throw error(node, "Unknown machine element " + node.name()); @@ -363,6 +382,7 @@ private static void validateTree(Node node) { // source. var resources = switch (node.name()) { case "machine" -> List.of("extends"); + case "feature" -> List.of("type"); case "block" -> List.of("mineable"); case "appearance" -> List.of("front", "side", "top", "bottom", "model"); @@ -380,6 +400,8 @@ private static void validateTree(Node node) { for (var attribute : resources) if (node.attributes().containsKey(attribute)) resource(node, attribute); + if (node.name().equals("drawer")) + drawerSettings(node); if (node.name().equals("block") && node.attributes().containsKey("hardness")) hardness(node); @@ -405,11 +427,122 @@ private static void validateTree(Node node) { } } + private static final Map> LAYOUT_ENTRIES = Map.of( + "tank", Set.of("ref", "tooltip"), "processor", Set.of("ref"), + "inventory", Set.of("ref", "columns"), "energy", Set.of()); + + private static void validateLayout(Node node) { + if (!node.attributes().isEmpty()) + throw error(node, "A layout does not accept attributes"); + var seen = new HashSet(); + for (var entry : node.children()) { + var allowed = LAYOUT_ENTRIES.get(entry.name()); + if (allowed == null || !entry.namespace().equals(node.namespace())) + throw error(entry, "Unexpected layout entry " + entry.name()); + if (!entry.children().isEmpty()) + throw error(entry, "A layout entry cannot have children"); + for (var attr : entry.attributes().keySet()) + if (!allowed.contains(attr)) + throw error(entry, "Unknown layout attribute " + attr); + var key = allowed.contains("ref") + ? entry.name() + ":" + required(entry, "ref") + : entry.name(); + if (!seen.add(key)) + throw error(entry, "Duplicate layout entry " + key); + if (entry.attributes().containsKey("columns")) + number(entry, "columns", 1, 9); + } + } + + private static DrawerSettings drawerSettings(Node node) { + if (node == null) + return DrawerSettings.DEFAULT; + Edge edge = null; + DrawerPlacement.Anchor anchor = null; + Integer order = null; + if (node.attributes().containsKey("edge")) { + requireChoice(node, "edge", "left", "right"); + edge = Edge + .valueOf(required(node, "edge").toUpperCase(Locale.ROOT)); + } + if (node.attributes().containsKey("anchor")) { + requireChoice(node, "anchor", "top", "bottom"); + anchor = DrawerPlacement.Anchor + .valueOf(required(node, "anchor").toUpperCase(Locale.ROOT)); + } + if (node.attributes().containsKey("order")) + order = (int) number(node, "order", Integer.MIN_VALUE, + Integer.MAX_VALUE); + return new DrawerSettings(bool(node, "enabled", true), edge, anchor, + order); + } + + private record FeaturePlan(MachineFeatureDefinition definition, Node node) { + } + + private static List features(Node root) { + var features = new ArrayList(); + var builtins = new HashSet(); + for (var node : root.children()) { + if (!node.name().equals("feature")) + continue; + String id = required(node, "id"); + if (!id.matches("[a-z0-9_.-]+")) + throw error(node, "Invalid feature ID " + id); + var type = resource(node, "type"); + Set allowed; + try { + allowed = MachineFeatureTypes.options(type); + } catch (IllegalArgumentException ex) { + throw error(node, ex.getMessage()); + } + if (MachineFeatureTypes.builtin(type) && !builtins.add(type)) + throw error(node, + "Only one feature of type " + type + " is supported"); + var options = new LinkedHashMap<>(node.attributes()); + options.keySet().removeAll(Set.of("id", "type", "enabled")); + for (var key : options.keySet()) + if (!allowed.contains(key)) + throw error(node, + "Unknown feature option " + key + " for " + type); + if (type.equals(BuiltinDrawers.REDSTONE) + && options.containsKey("default-mode")) + requireChoice(node, "default-mode", "ignore", + "pause-while-powered"); + features.add(new FeaturePlan(new MachineFeatureDefinition(id, type, + bool(node, "enabled", true), options, + drawerSettings(optional(node, "drawer"))), node)); + } + return List.copyOf(features); + } + + /** Resolve built-in options alongside version-1 shorthand declarations. */ + private static Node featureOptions(Node root, String name, + ResourceLocation type, List features) { + var legacy = optional(root, name); + for (var feature : features) { + if (!feature.definition().type().equals(type)) + continue; + if (!feature.definition().enabled()) + return null; + var options = new LinkedHashMap<>(feature.definition().options()); + if (type.equals(BuiltinDrawers.REDSTONE)) + options.put("enabled", "true"); + if (legacy != null) + options.putAll(legacy.attributes()); + var source = legacy == null ? feature.node() : legacy; + return new Node(name, options, List.of(), source.source(), + source.line(), source.namespace()); + } + return legacy; + } + private static MachineDefinition plan(ResourceLocation id, Node root, Map loaders) { if (!"1".equals(root.attributes().get("version"))) throw error(root, "Expected machine version=1"); var block = one(root, "block"); + var features = features(root); requireChoice(block, "drop", "self"); var appearance = one(root, "appearance"); @@ -770,8 +903,9 @@ else if (prior != null) throw error(fluidNode, "Machines without a processor require storage/manual tank roles"); } - var redstone = optional(root, "redstone"); - if (redstone != null) + var redstone = featureOptions(root, "redstone", BuiltinDrawers.REDSTONE, + features); + if (redstone != null && redstone.attributes().containsKey("pause")) requireChoice(redstone, "pause", "processing-only"); var recovery = one(root, "recovery"); requireChoice(recovery, "policy", "capsule"); @@ -941,11 +1075,16 @@ else if (prior != null) "Energy provider must name a processor implementing ProcessorEnergy: " + provider); } - var upgrades = optional(root, "upgrades"); - String gearboxSlot = upgrades == null + var upgrades = featureOptions(root, "upgrades", BuiltinDrawers.UPGRADES, + features); + boolean gearboxEnabled = upgrades != null + && bool(upgrades, "gearbox", true); + boolean capacitorEnabled = upgrades != null + && bool(upgrades, "capacitor", true); + String gearboxSlot = !gearboxEnabled ? null : upgrades.attributes().get("gearbox-slot"); - String capacitorSlot = upgrades == null + String capacitorSlot = !capacitorEnabled ? null : upgrades.attributes().get("capacitor-slot"); // The library owns standard sockets; machine storage declares only @@ -957,10 +1096,11 @@ else if (prior != null) .anyMatch(ghost -> ghost.id().equals(reserved))) throw error(upgrades, "Reserved component storage: " + reserved); - if (gearboxSlot == null && processor != null) + if (gearboxEnabled && gearboxSlot == null && processor != null) gearboxSlot = componentSocket(root, slots, groups, ids, "gearbox"); - if (capacitorSlot == null && power != null && energyCapacitors) + if (capacitorEnabled && capacitorSlot == null && power != null + && energyCapacitors) capacitorSlot = componentSocket(root, slots, groups, ids, "capacitor"); if (itemId == null && !slots.isEmpty()) @@ -1022,6 +1162,9 @@ else if (prior != null) "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 + || (attribute.equals("gearbox-slot") + ? !gearboxEnabled + : !capacitorEnabled) || !upgrades.attributes().containsKey(attribute)) continue; var index = ids.get(required(upgrades, attribute)); @@ -1061,7 +1204,8 @@ else if (prior != null) && !processor.attributes().containsKey("bindings") && processorConfigs.getFirst().energyPerTick() == 0 ? List.of() - : processorConfigs); + : processorConfigs, + features.stream().map(FeaturePlan::definition).toList()); } catch (IllegalArgumentException ex) { throw error(block, ex.getMessage()); } @@ -1147,7 +1291,8 @@ else if (prior != null) ? MachineDefinition.Events.NONE : new MachineDefinition.Events( optionalResource(processor, "on-start"), - optionalResource(processor, "on-finish"))); + optionalResource(processor, "on-finish")), + optional(root, "layout")); var defaults = definition.visualDefaults(prototype); for (var part : appearanceRules) { try { @@ -1283,7 +1428,7 @@ private static void token(StringBuilder text, String value) { text.append(value.length()).append(':').append(value); } - private static Node optional(Node node, String name) { + static Node optional(Node node, String name) { var children = node.children().stream() .filter(n -> n.name().equals(name)).toList(); if (children.size() > 1) @@ -1356,7 +1501,7 @@ private static boolean bool(Node node, String key, boolean fallback) { return Boolean.parseBoolean(value); } - private static long number(Node node, String key, long min, long max) { + static long number(Node node, String key, long min, long max) { try { long value = Long.parseLong(required(node, key)); if (value >= min && value <= max) diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFeatureDefinition.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFeatureDefinition.java new file mode 100644 index 00000000..9e365086 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFeatureDefinition.java @@ -0,0 +1,19 @@ +package zone.moddev.mc.lib.machine.definition; + +import java.util.Map; + +import net.minecraft.resources.ResourceLocation; + +import zone.moddev.mc.lib.gui.drawer.DrawerSettings; + +/** Resolved, inherited configuration of one named machine feature. */ +public record MachineFeatureDefinition(String id, ResourceLocation type, + boolean enabled, Map options, DrawerSettings drawer) { + public MachineFeatureDefinition { + options = Map.copyOf(options); + } + + public DrawerSettings drawerSettings() { + return enabled ? drawer : DrawerSettings.HIDDEN; + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFeatureTypes.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFeatureTypes.java new file mode 100644 index 00000000..e0ed0c74 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFeatureTypes.java @@ -0,0 +1,87 @@ +package zone.moddev.mc.lib.machine.definition; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.BiFunction; + +import net.minecraft.resources.ResourceLocation; + +import zone.moddev.mc.lib.gui.drawer.BuiltinDrawers; +import zone.moddev.mc.lib.gui.runtime.ScreenHost; +import zone.moddev.mc.lib.machine.feature.MachineFeature; + +/** XML feature types. Register mod types during construction on both sides. */ +public final class MachineFeatureTypes { + private record Type(Set options, + BiFunction> factory) { + } + + private static final Map TYPES = new HashMap<>(); + + static { + builtin(BuiltinDrawers.REDSTONE, + Set.of("pause", "default-mode", "comparator-source")); + builtin(BuiltinDrawers.UPGRADES, + Set.of("gearbox", "capacitor", "gearbox-slot", "capacitor-slot", + "range-slots", "range-storage", "legacy-layout")); + for (var type : Set.of(BuiltinDrawers.SIDES, BuiltinDrawers.STATS, + BuiltinDrawers.INFO, BuiltinDrawers.CURIOS, BuiltinDrawers.BACKPACK, + BuiltinDrawers.POPOUT, BuiltinDrawers.SIDE_TAB)) + builtin(type, Set.of()); + } + + private MachineFeatureTypes() { + } + + private static void builtin(ResourceLocation id, Set options) { + TYPES.put(id, new Type(options, null)); + } + + /** + * Register a factory that creates a fresh feature per block entity. The + * feature's key must match the declaration ID used for persistence. + */ + public static synchronized void register(ResourceLocation id, + Set options, + BiFunction> factory) { + var type = new Type(Set.copyOf(options), + Objects.requireNonNull(factory)); + if (TYPES.putIfAbsent(Objects.requireNonNull(id), type) != null) + throw new IllegalArgumentException( + "Duplicate machine feature type: " + id); + } + + static synchronized Set options(ResourceLocation id) { + return type(id).options(); + } + + static synchronized boolean builtin(ResourceLocation id) { + return type(id).factory() == null; + } + + public static MachineFeature create(MachineFeatureDefinition definition, + ScreenHost host) { + Type type; + synchronized (MachineFeatureTypes.class) { + type = type(definition.type()); + } + if (!definition.enabled() || type.factory() == null) + return null; + var feature = Objects + .requireNonNull(type.factory().apply(definition, host)); + if (!definition.id().equals(feature.key())) + throw new IllegalArgumentException( + "Feature key must match its ID: " + definition.id()); + return feature; + } + + private static Type type(ResourceLocation id) { + var type = TYPES.get(id); + if (type == null) + throw new IllegalArgumentException( + "Unknown machine feature type: " + id); + return type; + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineParts.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineParts.java new file mode 100644 index 00000000..c0084a4a --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineParts.java @@ -0,0 +1,134 @@ +package zone.moddev.mc.lib.machine.definition; + +import static zone.moddev.mc.lib.machine.definition.MachineDefinitions.error; +import static zone.moddev.mc.lib.machine.definition.MachineDefinitions.number; +import static zone.moddev.mc.lib.machine.definition.MachineDefinitions.optional; +import static zone.moddev.mc.lib.machine.definition.MachineDefinitions.required; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import zone.moddev.mc.lib.gui.load.ScreenReader.Node; + +/** + * Lowers compact XML declarations into the existing storage and screen model. + */ +final class MachineParts { + private MachineParts() { + } + + static Node expand(Node machine, Node base) { + var parts = optional(machine, "parts"); + if (parts == null) + return machine; + if (!parts.namespace().equals(machine.namespace()) + || !parts.attributes().isEmpty()) + throw error(parts, "Expected with no attributes"); + if (optional(machine, "layout") != null) + throw error(parts, + "A machine cannot declare both parts and layout"); + + var children = new ArrayList<>(machine.children()); + int position = children.indexOf(parts); + children.remove(position); + var layout = new ArrayList(); + var items = new ArrayList(); + var tanks = new ArrayList(); + Node energy = null; + for (var part : parts.children()) { + if (!part.namespace().equals(parts.namespace()) + || !part.children().isEmpty()) + throw error(part, "Expected a machine part without children"); + switch (part.name()) { + case "inventory" -> { + var attrs = new LinkedHashMap<>(part.attributes()); + var columns = attrs.remove("columns"); + attrs.putIfAbsent("count", "1"); + items.add(node(part, "slots", attrs, List.of())); + layout.add(reference(part, required(part, "id"), "columns", + columns)); + } + case "tank", "tanks" -> { + var attrs = new LinkedHashMap<>(part.attributes()); + var tooltip = attrs.remove("tooltip"); + tanks.add(node(part, part.name(), attrs, List.of())); + String id = required(part, "id"); + if (part.name().equals("tanks")) { + int count = (int) number(part, "count", 1, 16); + for (int i = 0; i < count; i++) + layout.add(reference(part, id + "/" + i, "tooltip", + tooltip)); + } else + layout.add(reference(part, id, "tooltip", tooltip)); + } + case "processor" -> { + children.add(position++, part); + layout.add(node(part, "processor", + Map.of("ref", required(part, "id")), List.of())); + } + case "energy" -> { + if (!part.attributes().isEmpty()) { + var attrs = new LinkedHashMap<>(part.attributes()); + attrs.putIfAbsent("id", "energy"); + energy = node(part, "energy", attrs, List.of()); + } + layout.add(node(part, "energy", Map.of(), List.of())); + } + default -> + throw error(part, "Unknown machine part " + part.name()); + } + } + children.add(node(parts, "layout", Map.of(), layout)); + if (!items.isEmpty() || !tanks.isEmpty() || energy != null) { + var storage = optional(machine, "storage"); + var inherited = base == null ? null : optional(base, "storage"); + var groups = new ArrayList<>( + storage == null ? List.of() : storage.children()); + append(groups, storage, inherited, "items", items); + append(groups, storage, inherited, "fluids", tanks); + if (energy != null) + groups.add(energy); + if (storage != null) + children.remove(storage); + children.add(node(storage == null ? parts : storage, "storage", + storage == null ? Map.of() : storage.attributes(), groups)); + } + return node(machine, "machine", machine.attributes(), children); + } + + private static Node reference(Node part, String id, String option, + String value) { + var attrs = value == null + ? Map.of("ref", id) + : Map.of("ref", id, option, value); + return node(part, part.name().equals("tanks") ? "tank" : part.name(), + attrs, List.of()); + } + + private static void append(List groups, Node storage, Node base, + String name, List parts) { + if (parts.isEmpty()) + return; + var current = storage == null ? null : optional(storage, name); + if (current != null) { + var children = new ArrayList<>(current.children()); + children.addAll(parts); + groups.set(groups.indexOf(current), + node(current, name, current.attributes(), children)); + } else { + var inherited = base == null ? null : optional(base, name); + String id = inherited == null + ? name + : inherited.attributes().getOrDefault("id", name); + groups.add(node(parts.getFirst(), name, Map.of("id", id), parts)); + } + } + + private static Node node(Node origin, String name, + Map attrs, List children) { + return new Node(name, Map.copyOf(attrs), List.copyOf(children), + origin.source(), origin.line(), origin.namespace()); + } +} 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 c2b3da79..d147792a 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 @@ -63,6 +63,77 @@ public interface Generator { private MachineScreenGenerators() { } + /** An ordered layout owns the base screen's entire machine row. */ + static Node withLayout(MachineDefinition machine, Node screen, + Node layout) { + var claimed = upgradeSlots(machine, screen); + var controls = layout.children().stream() + .map(entry -> switch (entry.name()) { + case "tank" -> layoutTank(machine, entry); + case "inventory" -> layoutInventory(machine, entry, claimed); + case "processor" -> { + String ref = MachineDefinitions.required(entry, "ref"); + var processor = machine.processors().stream() + .filter(config -> config.id().equals(ref)).findFirst() + .orElseThrow(() -> MachineDefinitions.error(entry, + "Unknown layout processor " + ref)); + yield progress(machine, processor, entry); + } + case "energy" -> { + if (machine.power() == null) + throw MachineDefinitions.error(entry, + "A layout energy gauge requires energy storage"); + yield n(entry, "energy-gauge", + Map.of("id", "energy", "length", "3s"), List.of()); + } + default -> throw MachineDefinitions.error(entry, + "Unexpected layout entry " + entry.name()); + }).toList(); + var fills = new ArrayList(); + for (var child : screen.children()) + if (!child.name().equals("fill") + || !Set.of("machine", "tanks", "energy") + .contains(child.attributes().getOrDefault("name", ""))) + fills.add(child); + var row = n(layout, "hbox", Map.of("spacing", "6", "align", "center"), + controls); + fills.add(n(layout, "fill", Map.of("name", "machine"), + List.of(spacer(layout), row))); + fills.add(n(layout, "fill", Map.of("name", "tanks"), List.of())); + fills.add(n(layout, "fill", Map.of("name", "energy"), List.of())); + return n(screen, "screen", screen.attributes(), fills); + } + + private static Node layoutTank(MachineDefinition machine, Node entry) { + String ref = MachineDefinitions.required(entry, "ref"); + if (machine.fluids() != null) { + var tanks = machine.fluids().tanks(); + for (int i = 0; i < tanks.size(); i++) + if (tanks.get(i).id().equals(ref)) + return tank(entry, i); + } + throw MachineDefinitions.error(entry, "Unknown layout tank " + ref); + } + + private static Node layoutInventory(MachineDefinition machine, Node entry, + Set claimed) { + String ref = MachineDefinitions.required(entry, "ref"); + int columns = Integer + .parseInt(entry.attributes().getOrDefault("columns", "3")); + for (var ghost : machine.ghosts()) + if (ghost.id().equals(ref)) + return ghostInventory(machine, entry, ghost, columns); + var members = machine.inventorySlots(ref); + var visible = members.stream().filter(index -> !claimed.contains(index)) + .toList(); + if (visible.isEmpty()) + throw MachineDefinitions.error(entry, + "Layout inventory has no available slots: " + ref); + var group = machine.groups().stream() + .filter(config -> config.id().equals(ref)).findFirst().orElse(null); + return itemInventory(entry, ref, group, columns, members, visible); + } + /** * Machine context for generated fills and template-owned literal defaults. */ @@ -371,7 +442,7 @@ private static void options(Node node, Set allowed) { private static Node progress(MachineDefinition machine, ProcessorConfiguration config, Node node) { - return n(node, "progress", Map.of("id", + var attributes = new LinkedHashMap<>(Map.of("id", machine.processors().size() == 1 ? "generated_progress" : "generated_progress_" + config.id(), @@ -383,7 +454,10 @@ private static Node progress(MachineDefinition machine, machine.processors().size() == 1 ? "#getTime" : "#getTime(" + machine.processors().indexOf(config) + ")", - "jei-recipes", config.recipeType().id().toString()), List.of()); + "processor-key", config.id())); + if (config.recipeType() != null) + attributes.put("jei-recipes", config.recipeType().id().toString()); + return n(node, "progress", attributes, List.of()); } private static List processing(MachineDefinition machine, Node node) { @@ -453,59 +527,69 @@ private static List tanks(MachineDefinition machine, Node node) { if (machine.fluids() == null) return result; for (int index = 0; index < machine.fluids().tanks().size(); index++) - result.add(n(node, "fluid-tank", Map.of("id", "tank_" + index, - "length", "3s", "tank", Integer.toString(index)), List.of())); + result.add(tank(node, index)); return result; } + private static Node tank(Node node, int index) { + var attributes = new LinkedHashMap<>(Map.of("id", "tank_" + index, + "length", "3s", "tank", Integer.toString(index))); + if (node.attributes().containsKey("tooltip")) + attributes.put("tooltip", node.attributes().get("tooltip")); + return n(node, "fluid-tank", attributes, List.of()); + } + private static List groups(MachineDefinition machine, Node node, IoMode mode, int columns, Set claimed) { var result = new ArrayList(); if (mode == IoMode.INPUT) - for (var ghost : machine.ghosts()) { - var children = new ArrayList(); - for (int i = 0; i < ghost.count(); i++) - children.add(n(node, "ghost-slot", - Map.of("id", "ghost_" + ghost.id() + "_" + i, "index", - Integer.toString(i), "tooltip", - machine.groupTranslationKey(ghost.id())), - List.of())); - result.add(n(node, "inventory", Map.of("storage", ghost.id(), - "columns", Integer.toString(columns)), children)); - } + for (var ghost : machine.ghosts()) + result.add(ghostInventory(machine, node, ghost, columns)); 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 : unclaimed) - children.add(n(node, "item-slot", - Map.of("id", "slot_" + index, "index", - Integer.toString(members.indexOf(index))), - List.of())); - 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)); + var inventory = itemInventory(node, group.id(), group, columns, + machine.inventorySlots(group.id()), unclaimed); + result.add(n(node, "vbox", Map.of("spacing", "2"), + List.of(spacer(node), inventory, spacer(node)))); } } return result; } + private static Node ghostInventory(MachineDefinition machine, Node node, + MachineDefinition.Ghost ghost, int columns) { + var children = new ArrayList(); + for (int i = 0; i < ghost.count(); i++) + children.add(n(node, "ghost-slot", + Map.of("id", "ghost_" + ghost.id() + "_" + i, "index", + Integer.toString(i), "tooltip", + machine.groupTranslationKey(ghost.id())), + List.of())); + return n(node, "inventory", + Map.of("storage", ghost.id(), "columns", Integer.toString(columns)), + children); + } + + private static Node itemInventory(Node node, String id, + MachineDefinition.Group group, int columns, List members, + List visible) { + var children = new ArrayList(); + for (int index : visible) + children.add(n(node, "item-slot", Map.of("id", "slot_" + index, + "index", Integer.toString(members.indexOf(index))), List.of())); + var inventory = n(node, "inventory", Map.of("storage", id, "columns", + Integer.toString(columns), "spacing", "2"), children); + return group != null && group.automation() + ? n(node, "coloured-group", + Map.of("id", "inventory_" + id, "color", + String.format("#%06X", group.color() & 0xffffff)), + List.of(inventory)) + : inventory; + } + /** * Only upgrade layouts reserve slots; unrelated manual slots stay visible. */ diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java b/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java index 767e2f15..677a3f6e 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java @@ -98,6 +98,11 @@ public java.util.Optional> findProcessor(String key) { : java.util.Optional.empty(); } + public List contributors(Class contract) { + return features.values().stream().filter(contract::isInstance) + .map(contract::cast).toList(); + } + /** All processor kinds in stable declaration order. */ public List> allProcessors() { return features.values().stream().filter(Processor.class::isInstance) diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java index 00296067..5f5c52d1 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java @@ -236,6 +236,36 @@ public MatchResult recipeAvailability(MachineRecipeEntry entry) { return RecipeMatcher.check(entry.recipe(), inventory); } + private record OutputCheck(long recipes, ResourceLocation selected, + long[] storage, boolean blocked) { + } + + @Nullable + private OutputCheck outputCheck; + + /** An otherwise-ready recipe is waiting for space in its outputs. */ + public boolean outputBlocked(Level level) { + if (level == null || level.isClientSide || runner.active()) + return false; + long revision = recipeRevision(level); + var previous = outputCheck; + if (previous != null && previous.recipes() == revision + && java.util.Objects.equals(previous.selected(), selectedRecipe) + && inventory.unchanged(previous.storage())) + return previous.blocked(); + var result = selectionEnabled + ? selectedRecipe().flatMap(id -> selectedEntry(level, id)) + .map(holder -> recipeAvailability(holder.value())) + : lookup.explain(level, inventory) + .map(MachineRecipeLookup.Attempt::result); + boolean blocked = result + .filter(match -> match.reason() == MatchResult.Reason.NO_ROOM) + .isPresent(); + outputCheck = new OutputCheck(revision, selectedRecipe, + inventory.revisions(), blocked); + return blocked; + } + private final String key; private final String outputPrefix; private final MachineInventory inventory; diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/WorkingArea.java b/src/main/java/zone/moddev/mc/lib/machine/feature/WorkingArea.java index cd77947a..0325c1fc 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/WorkingArea.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/WorkingArea.java @@ -97,6 +97,20 @@ public BlockPos blockAt(BlockPos origin, Direction front, int index) { .relative(front, forward).immutable(); } + /** + * Snake traversal: left to right on even rows, right to left on odd rows. + * Row/layer order matches blockAt; each layer starts left to right again. + * The same index can still be passed to row for row-based processing. + */ + public BlockPos snakeBlockAt(BlockPos origin, Direction front, int index) { + int row = row(index); + int column = index % width(); + int ordered = (row & 1) == 0 + ? index + : index - column + width() - 1 - column; + return blockAt(origin, front, ordered); + } + /** * Lazy enumeration of coordinates; does not read a world or load chunks. */ diff --git a/src/main/java/zone/moddev/mc/lib/machine/multiblock/MultiblockDefinition.java b/src/main/java/zone/moddev/mc/lib/machine/multiblock/MultiblockDefinition.java index 0d4f4745..6fb2b258 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/multiblock/MultiblockDefinition.java +++ b/src/main/java/zone/moddev/mc/lib/machine/multiblock/MultiblockDefinition.java @@ -9,8 +9,7 @@ import net.minecraft.world.level.Level; /** - * Consumer-owned Java definition. No global registry or assembly-mode-specific - * catalog. + * Consumer-owned structure definition used by Java and fixed-layout XML. */ public record MultiblockDefinition(ResourceLocation id, int version, StructureResolver resolver, int maxMembers, int maxExtent, @@ -49,7 +48,10 @@ public void validate(ResolvedStructure structure) { } var bindings = new java.util.HashSet(); for (var port : ports) { - structure.member(port.member()); + if (structure.members().stream() + .noneMatch(member -> member.key().equals(port.member()))) + throw new IllegalArgumentException( + "Unknown port member " + port.member()); for (var face : DirectionKeys.of(port)) if (!bindings .add(port.member() + "/" + port.kind() + "/" + face)) diff --git a/src/main/java/zone/moddev/mc/lib/machine/multiblock/MultiblockDefinitions.java b/src/main/java/zone/moddev/mc/lib/machine/multiblock/MultiblockDefinitions.java new file mode 100644 index 00000000..bbce6cb7 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/multiblock/MultiblockDefinitions.java @@ -0,0 +1,200 @@ +package zone.moddev.mc.lib.machine.multiblock; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Locale; +import java.util.Set; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.exceptions.CommandSyntaxException; + +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; + +import zone.moddev.mc.lib.api.capabilities.RelativeFace; +import zone.moddev.mc.lib.gui.load.ScreenException; +import zone.moddev.mc.lib.gui.load.ScreenReader.Node; +import zone.moddev.mc.lib.gui.load.ScreenReader; + +/** Loads fixed multiblock definitions for Java-registered controllers. */ +public final class MultiblockDefinitions { + public static final String NAMESPACE = "https://moddev.zone/mmdlib/multiblock"; + + private MultiblockDefinitions() { + } + + /** + * Loads a bundled XML definition after the member blocks are registered. + */ + public static MultiblockDefinition load(ResourceLocation id, + Class owner) { + String path = "/data/" + id.getNamespace() + "/mmdlib/multiblock/" + + id.getPath() + ".xml"; + try (var input = owner.getResourceAsStream(path)) { + if (input == null) + throw new IllegalArgumentException( + "Missing multiblock " + path); + return read(id, path, input, BuiltInRegistries.BLOCK.asLookup()); + } catch (IOException ex) { + throw new UncheckedIOException("Cannot read multiblock " + path, + ex); + } + } + + /** + * Reads one fixed layout using the supplied lookup to resolve block states. + */ + public static MultiblockDefinition read(ResourceLocation id, String source, + InputStream input, HolderLookup blocks) throws IOException { + var root = ScreenReader.parseMachine(source, input); + if (!root.name().equals("structure") + || !root.namespace().equals(NAMESPACE)) + throw error(root, "Expected in " + NAMESPACE); + attributes(root, + Set.of("version", "max-members", "max-extent", "dismantling")); + + var members = new ArrayList(); + var requirements = new ArrayList(); + var ports = new ArrayList(); + var rules = new HashMap(); + for (var child : root.children()) { + if (!child.namespace().equals(NAMESPACE) + || !child.children().isEmpty()) + throw error(child, "Expected an empty multiblock entry"); + try { + switch (child.name()) { + case "member" -> { + attributes(child, + Set.of("id", "role", "offset", "state")); + members.add(new StructureMember(required(child, "id"), + required(child, "role"), offset(child), + state(child, blocks))); + } + case "rule" -> { + attributes(child, Set.of("id", "type")); + String key = required(child, "id"); + if (!required(child, "type").equals("air")) + throw error(child, + "Unknown rule type " + required(child, "type")); + if (rules.putIfAbsent(key, (level, pos) -> level + .getBlockState(pos).isAir()) != null) + throw error(child, "Duplicate rule " + key); + } + case "requirement" -> { + attributes(child, + Set.of("rule", "offset", "continuous")); + requirements.add( + new StructureRequirement(required(child, "rule"), + offset(child), bool(child, "continuous"))); + } + case "port" -> ports.add(port(child)); + default -> throw error(child, + "Unknown entry <" + child.name() + ">"); + } + } catch (ScreenException ex) { + throw ex; + } catch (IllegalArgumentException | CommandSyntaxException ex) { + throw new ScreenException(child.source(), child.line(), + ex.getMessage(), ex); + } + } + try { + var layout = new FixedLayout(members, requirements); + var definition = new MultiblockDefinition(id, + number(root, "version"), layout, number(root, "max-members"), + number(root, "max-extent"), enumValue(root, "dismantling", + MultiblockDefinition.Dismantling.class), + rules, ports); + definition.validate(layout.structure()); + return definition; + } catch (ScreenException ex) { + throw ex; + } catch (IllegalArgumentException ex) { + throw new ScreenException(root.source(), root.line(), + ex.getMessage(), ex); + } + } + + private static BlockState state(Node node, HolderLookup blocks) + throws CommandSyntaxException { + var reader = new StringReader(required(node, "state")); + var result = BlockStateParser.parseForBlock(blocks, reader, false); + if (reader.canRead()) + throw error(node, "Unexpected content after block state"); + return result.blockState(); + } + + private static StructurePort port(Node node) { + attributes(node, Set.of("member", "resource", "kind", "faces", + "unsided", "input", "output")); + var faces = EnumSet.noneOf(Direction.class); + for (String value : node.attributes().getOrDefault("faces", "").trim() + .split("\\s+")) { + if (value.isEmpty()) + continue; + var face = RelativeFace.valueOf(value.toUpperCase(Locale.ROOT)) + .toWorld(Direction.NORTH); + if (!faces.add(face)) + throw error(node, "Duplicate port face " + value); + } + return new StructurePort(required(node, "member"), + required(node, "resource"), + enumValue(node, "kind", StructurePort.Kind.class), faces, + bool(node, "unsided"), bool(node, "input"), bool(node, "output")); + } + + private static BlockPos offset(Node node) { + String[] axes = required(node, "offset").split("\\s+"); + if (axes.length != 3) + throw error(node, "Expected three integers for offset"); + return new BlockPos(Integer.parseInt(axes[0]), + Integer.parseInt(axes[1]), Integer.parseInt(axes[2])); + } + + private static int number(Node node, String attribute) { + return Integer.parseInt(required(node, attribute)); + } + + private static > E enumValue(Node node, String attribute, + Class type) { + return Enum.valueOf(type, required(node, attribute).replace('-', '_') + .toUpperCase(Locale.ROOT)); + } + + private static boolean bool(Node node, String attribute) { + return switch (node.attributes().getOrDefault(attribute, "false")) { + case "true" -> true; + case "false" -> false; + default -> + throw error(node, "Expected true or false for " + attribute); + }; + } + + private static String required(Node node, String attribute) { + String value = node.attributes().get(attribute); + if (value == null || value.isBlank()) + throw error(node, "Missing " + attribute); + return value.trim(); + } + + private static void attributes(Node node, Set allowed) { + for (String attribute : node.attributes().keySet()) + if (!allowed.contains(attribute)) + throw error(node, "Unknown attribute " + attribute); + } + + private static ScreenException error(Node node, String message) { + return new ScreenException(node.source(), node.line(), message); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java index 357b8479..656dca45 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java @@ -262,6 +262,9 @@ public final void serverTick() { && pausePolicy().processingEnabled(paused)); if (structureReady) afterMachineTick(); + var fluids = screenFluids(); + if (fluids != null) + fluids.tickDrains(); if (redstone != null) redstone.updateOutputs(); } @@ -385,10 +388,11 @@ protected final void loadAdditional(CompoundTag tag, if (redstone != null) { if (tag.contains("redstone_control")) redstone.load(tag.getCompound("redstone_control"), registries); - else { + else if (tag.contains("redstone_mode")) { int mode = tag.getInt("redstone_mode"); redstone.migrate(mode >= 0 && mode <= 2 ? mode : 0); - } + } else + redstone.load(new CompoundTag(), registries); } loadMachineData(tag, registries); if (multiblock() != null) { diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java index 3ed32d06..92633255 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java @@ -1,6 +1,7 @@ package zone.moddev.mc.lib.machine.neoforge; import java.util.List; +import java.util.Set; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; @@ -21,7 +22,12 @@ import zone.moddev.mc.lib.api.capabilities.SideConfig; import zone.moddev.mc.lib.api.redstone.RedstoneControl; import zone.moddev.mc.lib.common.types.SoundDefinition; +import zone.moddev.mc.lib.gui.drawer.BuiltinDrawers; +import zone.moddev.mc.lib.gui.drawer.DrawerDefinition; +import zone.moddev.mc.lib.gui.drawer.DrawerSettings; import zone.moddev.mc.lib.machine.definition.MachineDefinition; +import zone.moddev.mc.lib.machine.definition.MachineFeatureDefinition; +import zone.moddev.mc.lib.machine.definition.MachineFeatureTypes; import zone.moddev.mc.lib.machine.feature.RecipeProcessor; import zone.moddev.mc.lib.machine.presentation.BuiltinVisualVariables; import zone.moddev.mc.lib.machine.presentation.VisualVariables; @@ -34,6 +40,10 @@ public class DefinedMachineEntity extends BaseMachine implements zone.moddev.mc.lib.machine.feature.ProcessorMachine, zone.moddev.mc.lib.machine.presentation.VisualizerStyle.Provider { + private static final Set DECLARED_DRAWERS = Set.of( + BuiltinDrawers.SIDES, BuiltinDrawers.STATS, BuiltinDrawers.CURIOS, + BuiltinDrawers.BACKPACK); + public final MachineDefinition definition; private final List processorConfigurations; @@ -369,9 +379,20 @@ else if (value instanceof zone.moddev.mc.lib.machine.feature.StoredProcessor cus inventory.items(definition.itemStorageId(), items); if (definition.fluids() != null) inventory.fluids(definition.fluids().id(), fluids); + for (var declaration : definition.behavior().features()) { + var feature = MachineFeatureTypes.create(declaration, this); + if (feature != null) + features.add(feature); + } + var redstoneMode = definition.behavior() + .feature(BuiltinDrawers.REDSTONE) + .filter(feature -> "pause-while-powered" + .equals(feature.options().get("default-mode"))) + .map(feature -> RedstoneControl.Mode.READ) + .orElse(RedstoneControl.Mode.IGNORE); redstone = definition.redstone() || definition.behavior().comparatorSource() != null - ? new RedstoneControl(this, List.of(features)) + ? new RedstoneControl(this, List.of(features), redstoneMode) .comparatorSource(definition.behavior().comparatorSource()) : null; if (redstone != null && !definition.redstone()) @@ -776,6 +797,22 @@ public String screenDefinitionFingerprint() { return definition.checksum(); } + @Override + public DrawerSettings screenDrawerSettings(String featureId, + DrawerDefinition drawer) { + if (featureId != null) + return definition.behavior().features().stream() + .filter(feature -> feature.id().equals(featureId)).findFirst() + .map(MachineFeatureDefinition::drawerSettings) + .orElse(DrawerSettings.DEFAULT); + var type = BuiltinDrawers.featureType(drawer); + return definition.behavior().feature(type) + .map(MachineFeatureDefinition::drawerSettings) + .orElse(DECLARED_DRAWERS.contains(type) + ? DrawerSettings.HIDDEN + : DrawerSettings.DEFAULT); + } + @Override public ItemInventories screenItems() { return items; diff --git a/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java b/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java index 13705f9d..01b6ba33 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java +++ b/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java @@ -44,8 +44,7 @@ * @param time ticks the cycle takes * @param items item inputs, by slot * @param fluids fluid inputs, by tank - * @param products each product with where it lands; chance products are placed - * as if certain + * @param products each product with its reserved destination, if any * @param energy the energy each energy group must supply over the cycle */ public record CyclePlan(ResourceLocation recipe, int time, List items, @@ -136,7 +135,8 @@ public record Placed(String group, MachineProduct product, List at) { /** Copies the list. */ public Placed { - at = List.copyOf(at); + // Older saved plans included a placement for every chance item. + at = product.reservesOutput() ? List.copyOf(at) : List.of(); } } @@ -174,7 +174,7 @@ private record Plans(Map items, Map tanks) { /** * What running {@code recipe} would reserve now, ignoring energy; empty if - * it can't. Changes nothing. Chance products are placed as if certain. + * it can't. Changes nothing. */ public static Optional of(ResourceLocation id, MachineRecipe recipe, MachineInventory inventory) { @@ -244,16 +244,28 @@ else if (group instanceof FluidGroup tanks) if (group == null) return Optional.empty(); var list = entry.getValue(); - var placed = place(group, list, - taken.getOrDefault(key, new long[size(group)])); + var reserved = list.stream().filter(MachineProduct::reservesOutput) + .toList(); + var placed = reserved.isEmpty() + ? new int[0][] + : place(group, reserved, + taken.getOrDefault(key, new long[size(group)])); if (placed == null) return Optional.empty(); - for (int i = 0; i < list.size(); i++) { + int nextPlacement = 0; + for (var product : list) { + if (!product.reservesOutput()) { + if (!(group instanceof ItemGroup)) + return Optional.empty(); + products.add(new Placed(key, product, List.of())); + continue; + } + var row = placed[nextPlacement++]; var at = new ArrayList(); - for (int slot = 0; slot < placed[i].length; slot++) - if (placed[i][slot] > 0) - at.add(new At(slot, placed[i][slot])); - products.add(new Placed(key, list.get(i), at)); + for (int slot = 0; slot < row.length; slot++) + if (row[slot] > 0) + at.add(new At(slot, row[slot])); + products.add(new Placed(key, product, at)); } } return Optional.of( @@ -358,10 +370,8 @@ public void release(MachineInventory inventory) { } /** - * Rolls each product's chance, then in one transaction releases this plan, - * takes the consumed inputs and inserts the hits where they were placed. - * Retained inputs stay untouched. A product that misses leaves its space - * free, and nothing is kept of the roll, so a retry rolls again. + * Releases the plan, takes the consumed inputs and inserts rolled products + * in one transaction. Reserved outputs go in before optional item drops. * * @return false, with the plan still in place and nothing changed, if an * input is gone or a product no longer fits where it was placed @@ -385,8 +395,8 @@ public boolean finish(MachineInventory inventory, RandomSource random, return false; var hits = new ArrayList(); for (var placed : products) - if (placed.product.chance() >= 1 - || random.nextFloat() < placed.product.chance()) + if (placed.product.reservesOutput() + && RecipeMatcher.roll(placed.product, random)) hits.add(placed); if (!canFinish(inventory, hits)) return false; @@ -422,6 +432,11 @@ public boolean finish(MachineInventory inventory, RandomSource random, for (var at : placed.at) if (!insert(inventory, placed, at, tx)) return false; + for (var placed : products) + if (!placed.product.reservesOutput() + && placed.product instanceof ItemProduct item) + RecipeMatcher.bonus(items(inventory, placed.group), item, + random, tx); return true; } diff --git a/src/main/java/zone/moddev/mc/lib/machine/recipe/MachineProduct.java b/src/main/java/zone/moddev/mc/lib/machine/recipe/MachineProduct.java index 2e60bece..0e73d145 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/recipe/MachineProduct.java +++ b/src/main/java/zone/moddev/mc/lib/machine/recipe/MachineProduct.java @@ -31,6 +31,11 @@ public sealed interface MachineProduct /** The chance this product is made on a run, in (0, 1]. */ float chance(); + /** Chance-based item drops use available space at completion. */ + default boolean reservesOutput() { + return !(this instanceof ItemProduct) || chance() >= 1; + } + /** The JSON form: exactly one of {@code item} or {@code fluid}. */ Codec CODEC = new Dispatch().codec(); diff --git a/src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeMatcher.java b/src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeMatcher.java index 8a30d38c..b2b68cfd 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeMatcher.java +++ b/src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeMatcher.java @@ -41,9 +41,9 @@ private RecipeMatcher() { /** * Whether {@code recipe} can start: every input present and room for every - * product once the consumed inputs are gone, counting chance products as - * certain. A product may land in the slot or tank its own input empties. - * Changes nothing, and no storage's change callback runs. + * reserved product once the consumed inputs are gone. A product may land in + * the slot or tank its own input empties. Changes nothing, and no storage's + * change callback runs. */ public static MatchResult check(MachineRecipe recipe, MachineInventory inventory) { @@ -122,10 +122,10 @@ public static boolean consume(MachineRecipe recipe, } /** - * Rolls each product's chance and inserts the hits in one transaction, all - * or nothing. + * Inserts rolled products in one transaction. Reserved products must fit in + * full. Optional items use any space left after them. * - * @return whether everything rolled fitted; if not, nothing was inserted + * @return whether all rolled reserved products fitted */ public static boolean produce(MachineRecipe recipe, MachineInventory inventory, RandomSource random) { @@ -135,18 +135,36 @@ public static boolean produce(MachineRecipe recipe, if (group == null) return false; for (var product : entry.getValue()) { - if (product.chance() < 1 - && random.nextFloat() >= product.chance()) - continue; - if (!put(group, product, tx)) + if (product.reservesOutput() && roll(product, random) + && !put(group, product, tx)) return false; } } + for (var entry : recipe.outputs().entrySet()) { + var group = inventory.group(entry.getKey()).orElse(null); + for (var product : entry.getValue()) + if (!product.reservesOutput() + && product instanceof ItemProduct item) { + if (!(group instanceof ItemGroup items)) + return false; + bonus(items, item, random, tx); + } + } tx.commit(); return true; } } + static boolean roll(MachineProduct product, RandomSource random) { + return product.chance() >= 1 || random.nextFloat() < product.chance(); + } + + static void bonus(ItemGroup group, ItemProduct product, RandomSource random, + MachineTx tx) { + if (roll(product, random) && group != null) + group.insert(product.stack(), tx); + } + /** * Checks one group's inputs, and records what {@link #take} would take from * it. @@ -185,6 +203,8 @@ private static MatchResult checkOutputs(String key, SlotGroup group, boolean fits; if (products.get(i) instanceof ItemProduct item && group instanceof ItemGroup items) { + if (!item.reservesOutput()) + continue; stacks.add(item.stack()); fits = taken == null ? items.fits(stacks) diff --git a/src/main/resources/assets/mmdlib/lang/en_us.json b/src/main/resources/assets/mmdlib/lang/en_us.json index edc722e7..671f993c 100644 --- a/src/main/resources/assets/mmdlib/lang/en_us.json +++ b/src/main/resources/assets/mmdlib/lang/en_us.json @@ -20,7 +20,12 @@ "screen.mmdlib.face.unavailable": "Unavailable on this machine", "screen.mmdlib.tank.name": "Tank %s", "screen.mmdlib.tank.empty": "Empty", + "screen.mmdlib.tank.drain.open": "Click to drain", + "screen.mmdlib.tank.drain.close": "Click to stop draining", + "screen.mmdlib.tank.drain.empty": "Nothing to drain", "screen.mmdlib.tank.contents": "%s mB of %s", + "screen.mmdlib.tank.reserved_input": "%s mB reserved for processing", + "screen.mmdlib.tank.reserved_output": "Space reserved for %s mB of %s", "screen.mmdlib.tank.accepts": "Accepts: %s", "screen.mmdlib.tank.none": "None", "screen.mmdlib.tank.container_accepts": "Accepts %s in %s", @@ -29,6 +34,7 @@ "screen.mmdlib.machine.processor_warning": "%s: %s", "screen.mmdlib.machine.stalled": "Needs power", "screen.mmdlib.machine.blocked": "Recipe cannot finish", + "screen.mmdlib.progress.output_blocked": "Output blocked", "screen.mmdlib.machine.held": "Held by machine controls", "screen.mmdlib.processor.processing": "Working", "screen.mmdlib.processor.idle": "Idle", diff --git a/src/main/resources/assets/mmdlib/textures/gui/sprites/icon_tank_drain.png b/src/main/resources/assets/mmdlib/textures/gui/sprites/icon_tank_drain.png new file mode 100644 index 00000000..58ee48f1 Binary files /dev/null and b/src/main/resources/assets/mmdlib/textures/gui/sprites/icon_tank_drain.png differ diff --git a/src/main/resources/mmdlib/machine/base_machine.xml b/src/main/resources/mmdlib/machine/base_machine.xml index ec051d83..743ed367 100644 --- a/src/main/resources/mmdlib/machine/base_machine.xml +++ b/src/main/resources/mmdlib/machine/base_machine.xml @@ -1,9 +1,14 @@ - + + + + + + diff --git a/src/main/resources/mmdlib/machine/base_powered_machine.xml b/src/main/resources/mmdlib/machine/base_powered_machine.xml index 4532cfef..47fcf59d 100644 --- a/src/main/resources/mmdlib/machine/base_powered_machine.xml +++ b/src/main/resources/mmdlib/machine/base_powered_machine.xml @@ -1,6 +1,7 @@ - + + @@ -8,7 +9,5 @@ - - - + diff --git a/src/main/resources/mmdlib/schema/screen.xsd b/src/main/resources/mmdlib/schema/screen.xsd index c23a9912..e25a32e6 100644 --- a/src/main/resources/mmdlib/schema/screen.xsd +++ b/src/main/resources/mmdlib/schema/screen.xsd @@ -365,6 +365,7 @@ + @@ -378,6 +379,7 @@ + @@ -451,6 +453,7 @@ + diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CapabilitySmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CapabilitySmoke.java index 6d33d33a..665ccb8c 100644 --- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CapabilitySmoke.java +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CapabilitySmoke.java @@ -96,6 +96,24 @@ static void check(ServerLevel level) { fluidCopy.addTank(1000, Role.OUTPUT); fluidCopy.deserializeNBT(provider, fluids.serializeNBT(provider)); require(fluidCopy.getFluidInTank(in).getAmount() == 1000, "fluid NBT"); + require(!fluidCopy.drainOpen(in) && !fluidCopy.drainOpen(out), + "tanks without saved valve settings start closed"); + + fluids.tankId(in, "input").tankId(out, "output"); + fluids.toggleDrain(out); + require(!fluids.drainOpen(out), "empty tanks cannot start draining"); + fluids.tank(out).fill(new FluidStack(Fluids.LAVA, 3), + FluidAction.EXECUTE); + fluids.toggleDrain(out); + var reordered = new FluidStorage(); + reordered.tankId(reordered.addTank(1000, Role.OUTPUT), "output"); + reordered.tankId(reordered.addTank(1000, Role.INPUT), "input"); + reordered.deserializeNBT(provider, fluids.serializeNBT(provider)); + require(reordered.drainOpen(0) && !reordered.drainOpen(1), + "a nonempty tank's open valve follows its stable ID after loading"); + reordered.tickDrains(); + require(reordered.tank(0).isEmpty() && !reordered.drainOpen(0), + "an open valve discards the last few mB and closes"); var energy = new EnergyBuffer(10_000_000_000L, 1000); require(energy.insert(5_000_000_000L, false) == 5_000_000_000L, diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CyclePlanSmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CyclePlanSmoke.java index 4056b35b..e21e8ba2 100644 --- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CyclePlanSmoke.java +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CyclePlanSmoke.java @@ -128,10 +128,8 @@ static void check(ServerLevel level) { require(held.fluids.plan(0).take() == 250, "the water is locked"); require(held.items.plan(1).sameAs(new SlotPlan(0, rawCopper)), "the copper space is held"); - require( - held.items.plan(3) - .sameAs(new SlotPlan(0, new ItemStack(Items.GRAVEL))), - "the gravel space is held"); + require(held.items.plan(3).isNone(), + "the chance byproduct reserves no space"); var cramped = new Crusher(3, 1_000); cramped.items.setStackInSlot(1, new ItemStack(Items.RAW_COPPER, 62)); cramped.items.setStackInSlot(2, new ItemStack(Items.COBBLESTONE, 64)); @@ -285,27 +283,41 @@ static void check(ServerLevel level) { require(tanks.plan(0).isNone() && tanks.plan(1).isNone(), "tank plans gone"); - // Only a hit needs its space: a byproduct slot filled mid-cycle blocks - // a hit, not a miss. + // A full byproduct slot cannot block a hit, including after the cycle + // has already reserved its guaranteed products. var jammed = new Crusher(3, 1_000); var jammedPlan = CyclePlan.of(ID, crusher, jammed.inventory) .orElseThrow(); jammedPlan.reserve(jammed.inventory); jammed.items.setStackInSlot(3, new ItemStack(Items.COBBLESTONE, 64)); - require(!jammedPlan.finish(jammed.inventory, fixed(0F)), - "a hit has no room"); + require(jammedPlan.finish(jammed.inventory, fixed(0F)), + "A hit can be skipped without blocking the cycle"); require( - jammed.items.getStackInSlot(0).getCount() == 3 - && jammed.items.getStackInSlot(1).isEmpty() - && jammed.items.plan(0).sameAs(new SlotPlan(1, none)), - "a blocked finish changes nothing"); - require(jammedPlan.finish(jammed.inventory, fixed(.5F)), - "a miss needs no room"); + jammed.items.getStackInSlot(0).getCount() == 2 + && jammed.unplanned(), + "the cycle consumed inputs and released plans"); require(jammed.items.getStackInSlot(3).getCount() == 64, "the cobblestone stays"); require(ItemStack.matches(jammed.items.getStackInSlot(1), rawCopper), "the dust is made"); + var sameGroup = new zone.moddev.mc.lib.machine.recipe.MachineRecipe( + crusher.inputs(), + Map.of("output", + List.of(plan.products().get(1).product(), copper.product())), + crusher.time()); + var sharedOutput = new Crusher(3, 1_000); + sharedOutput.items.setStackInSlot(2, + new ItemStack(Items.COBBLESTONE, 64)); + var guaranteed = CyclePlan.of(ID, sameGroup, sharedOutput.inventory) + .orElseThrow(); + require( + guaranteed.reserve(sharedOutput.inventory) + && guaranteed.finish(sharedOutput.inventory, fixed(0F)) + && ItemStack.matches(sharedOutput.items.getStackInSlot(1), + rawCopper), + "A guaranteed output gets the last slot even with the chance item listed first"); + // release: this plan goes, another lane's plan on the same slot stays. var shared = new Crusher(3, 1_000); var other = new SlotPlan(1, none); @@ -332,10 +344,18 @@ static void check(ServerLevel level) { savedPlan.reserve(saved.inventory); var tag = (CompoundTag) CyclePlan.CODEC.encodeStart(nbt, savedPlan) .getOrThrow(); + var legacyPlacement = new CompoundTag(); + legacyPlacement.putInt("index", 0); + legacyPlacement.putInt("amount", 1); + var chancePlacement = new net.minecraft.nbt.ListTag(); + chancePlacement.add(legacyPlacement); + tag.getList("products", 10).getCompound(1).put("at", chancePlacement); var loaded = CyclePlan.CODEC.parse(nbt, tag).getOrThrow(); require(loaded.recipe().equals(ID) && loaded.time() == 200 && loaded.energy().equals(savedPlan.energy()) && loaded.products().size() == 2, "decoded plan"); + require(loaded.products().get(1).at().isEmpty(), + "an old saved chance byproduct releases its former placement"); var fresh = new Crusher(3, 1_000); require(loaded.restore(fresh.inventory), "restore on fresh storages"); for (int index = 0; index < 4; index++) diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MachineRecipeSmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MachineRecipeSmoke.java index 9b856311..d110810e 100644 --- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MachineRecipeSmoke.java +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MachineRecipeSmoke.java @@ -110,8 +110,8 @@ static void check(ServerLevel level) { var full = new Crusher(3, 1_000, 20, true); full.items.insertResult(3, new ItemStack(Items.COBBLESTONE, 64), false); int before = full.changes[0]; - expect(RecipeMatcher.check(crusher, full.inventory), Reason.NO_ROOM, - "byproduct", 0); + require(RecipeMatcher.check(crusher, full.inventory).ok(), + "A full byproduct slot does not prevent a match"); require(full.changes[0] == before, "check changed nothing"); var run = new Crusher(3, 1_000, 20, true); @@ -130,16 +130,8 @@ static void check(ServerLevel level) { require(partial.items.getStackInSlot(0).getCount() == 3, "ore put back when water is short"); - // A full byproduct slot and a hit on the 25%: nothing is produced at - // all. - full.items.setStackInSlot(3, new ItemStack(Items.COBBLESTONE, 64)); - require(!RecipeMatcher.produce(crusher, full.inventory, fixed(0F)), - "blocked"); - require(full.items.getStackInSlot(1).isEmpty() - && full.items.getStackInSlot(2).isEmpty(), "rolled back"); - // A miss: only the copper. - require(RecipeMatcher.produce(crusher, full.inventory, fixed(.99F)), - "produced on a miss"); + require(RecipeMatcher.produce(crusher, full.inventory, fixed(0F)), + "Guaranteed products survive a rolled byproduct with no room"); require(full.items.getStackInSlot(1).is(Items.RAW_COPPER) && full.items.getStackInSlot(1).getCount() == 2, "copper"); require(full.items.getStackInSlot(3).is(Items.COBBLESTONE), diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ProcessorSmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ProcessorSmoke.java index f4583c74..f8cf0d7f 100644 --- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ProcessorSmoke.java +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ProcessorSmoke.java @@ -276,8 +276,7 @@ static void twoLanes(ServerLevel level) { } /** - * The gravel byproduct's space is only held for the cycle: a miss leaves it - * free. + * The gravel byproduct leaves its capacity available throughout a cycle. */ static void chanceKeepsNothing(ServerLevel level) { var rig = ProcessorRig.crusher(16, 4_000, 1_000_000); @@ -288,7 +287,7 @@ static void chanceKeepsNothing(ServerLevel level) { rig.ticks(level, 1); require(rig.processor.status() == Status.RUNNING, "cycle " + cycle + " started"); - require(!rig.items.fits(3, rest), "gravel's space is held"); + require(rig.items.fits(3, rest), "the byproduct leaves space free"); rig.energy.setStored(1_000_000); rig.ticks(level, 200); require(rig.processor.status() == Status.IDLE, diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ReservationSyncSmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ReservationSyncSmoke.java index 2ad1e3c7..d14e1353 100644 --- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ReservationSyncSmoke.java +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/ReservationSyncSmoke.java @@ -17,7 +17,10 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.level.material.Fluids; +import zone.moddev.mc.lib.api.capabilities.FluidStorage; +import zone.moddev.mc.lib.api.capabilities.Role; import zone.moddev.mc.lib.gui.runtime.ScreenNetwork; import zone.moddev.mc.lib.gui.runtime.ScreenValues; import zone.moddev.mc.lib.gui.runtime.component.BuiltinMenuComponents; @@ -27,7 +30,9 @@ import zone.moddev.mc.lib.gui.runtime.slot.ReservationMenuComponent; import zone.moddev.mc.lib.gui.runtime.slot.SlotAdapter; import zone.moddev.mc.lib.gui.sync.ElementStateValue; +import zone.moddev.mc.lib.machine.ingredient.FluidAmount; import zone.moddev.mc.lib.machine.inventory.SlotPlan; +import zone.moddev.mc.lib.machine.inventory.TankPlan; /** * Registered reservation state supports any mod slot adapter, independent of @@ -57,6 +62,11 @@ private record Fixture(ReservationMenuComponent component, } private static Fixture fixture(RegistryAccess registries, boolean client) { + return fixture(registries, client, null); + } + + private static Fixture fixture(RegistryAccess registries, boolean client, + FluidStorage fluids) { var slots = new MenuSlots(); var registrar = slots .registrar(slot -> slot.index = slots.entries().size()); @@ -68,10 +78,11 @@ private static Fixture fixture(RegistryAccess registries, boolean client) { registrar.add(input, null, MenuSlots.Role.MACHINE); registrar.add(output, null, MenuSlots.Role.MACHINE); registrar.add(player, null, MenuSlots.Role.PLAYER_STORAGE); - var component = new ReservationMenuComponent(slots, client); + var component = new ReservationMenuComponent(slots, client, fluids); var registry = new MenuComponentRegistry(); registry.register(BuiltinMenuComponents.RESERVATIONS, 0, c -> null, - ReservationMenuComponent.PLANS); + ReservationMenuComponent.PLANS, + ReservationMenuComponent.TANK_PLANS); var state = new ComponentStates(registry.schema(), Map.of(BuiltinMenuComponents.RESERVATIONS, component), registries); return new Fixture(component, state, input, output, player); @@ -125,7 +136,10 @@ static void check(RegistryAccess registries) { field.encode(registries, reverse) .equals(field.encode(registries, plans)), "Map order changed reservation encoding"); - int address = before.keySet().iterator().next(); + int address = before.entrySet().stream() + .filter(entry -> entry.getValue() + .equals(field.encode(registries, plans))) + .findFirst().orElseThrow().getKey(); var saved = client.state.snapshot(); for (var malformed : List.of( encoded(registries, b -> b.writeVarInt(-1)), @@ -182,6 +196,38 @@ static void check(RegistryAccess registries) { Map.of(3, new SlotPlan(20, ItemStack.EMPTY), 20, SlotPlan.NONE)))); require(client.input.plan.isNone() && client.player.applied == 0, "Omitted plans or non-machine indexes were applied incorrectly"); + tankReservations(registries); + } + + private static void tankReservations(RegistryAccess registries) { + var fluids = new FluidStorage(); + fluids.addTank(4_000, Role.INPUT); + fluids.addTank(4_000, Role.OUTPUT); + var server = fixture(registries, false, fluids); + var client = fixture(registries, true, new FluidStorage()); + var take = new TankPlan(250, FluidAmount.EMPTY); + var add = new TankPlan(0, + new FluidAmount(Fluids.LAVA.builtInRegistryHolder(), + net.minecraft.core.component.DataComponentPatch.EMPTY, 200)); + fluids.setPlan(0, take); + fluids.setPlan(1, add); + var before = server.state.sample(List.of(server.component)); + client.state.apply(before); + require( + client.component.tankPlan(0).sameAs(take) + && client.component.tankPlan(1).sameAs(add), + "Tank reservation state lost input amount or output fluid and amount"); + fluids.setPlan(0, TankPlan.NONE); + fluids.setPlan(1, TankPlan.NONE); + var delta = ScreenValues.changed(before, + server.state.sample(List.of(server.component)), false); + require(delta.size() == 1, + "Clearing tank plans must send a complete tank field"); + client.state.apply(delta); + require( + client.component.tankPlan(0).isNone() + && client.component.tankPlan(1).isNone(), + "Tank reservation clearing left stale client state"); } private static ElementStateValue encoded(RegistryAccess registries, diff --git a/src/test/java/zone/moddev/mc/lib/gui/DrawerRegistryTest.java b/src/test/java/zone/moddev/mc/lib/gui/DrawerRegistryTest.java index e7460180..5b0a22b6 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/DrawerRegistryTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/DrawerRegistryTest.java @@ -7,14 +7,20 @@ import java.util.List; import java.util.Optional; +import com.mojang.serialization.Codec; + import net.minecraft.resources.ResourceLocation; +import net.neoforged.neoforge.items.IItemHandlerModifiable; + import org.junit.jupiter.api.Test; import zone.moddev.mc.lib.gui.client.DrawerFactories; import zone.moddev.mc.lib.gui.drawer.DrawerDefinition; import zone.moddev.mc.lib.gui.drawer.DrawerPlacement; import zone.moddev.mc.lib.gui.drawer.DrawerRegistry; +import zone.moddev.mc.lib.gui.drawer.DrawerSettings; +import zone.moddev.mc.lib.gui.drawer.MachineFeatureDrawers; import zone.moddev.mc.lib.gui.layout.DrawerTabs; import zone.moddev.mc.lib.gui.layout.Rect; import zone.moddev.mc.lib.gui.layout.ScreenLayout; @@ -29,7 +35,10 @@ import zone.moddev.mc.lib.gui.model.containers.PlayerInventoryElement; import zone.moddev.mc.lib.gui.model.containers.SideTabElement; import zone.moddev.mc.lib.gui.model.elements.PopoutElement; +import zone.moddev.mc.lib.gui.runtime.ScreenHost; import zone.moddev.mc.lib.gui.sync.ElementStateView; +import zone.moddev.mc.lib.machine.feature.FeatureHost; +import zone.moddev.mc.lib.machine.feature.MachineFeature; class DrawerRegistryTest { static final ResourceLocation TYPE = ResourceLocation.parse("test:drawer"); @@ -49,6 +58,63 @@ private static DrawerDefinition definition(String id, return new DrawerDefinition(TYPE, id, placement); } + private record Feature(String key) + implements MachineFeature, MachineFeatureDrawers { + public Codec codec() { + return Codec.INT; + } + + public Integer state() { + return 0; + } + + public void restore(Integer state) { + } + + public List drawers(DrawerRegistry.Context context) { + return List + .of(definition("provided", DrawerPlacement.top(Edge.LEFT, 0))); + } + } + + @Test + void installedFeatureSuppliesADrawerAndInheritsTheHostsPlacementPolicy() { + var features = new FeatureHost(() -> { + }).add(new Feature("provider")); + var host = new ScreenHost() { + @Override + public IItemHandlerModifiable screenItems() { + return null; + } + + @Override + public FeatureHost screenFeatures() { + return features; + } + + @Override + public DrawerSettings screenDrawerSettings(String featureId, + DrawerDefinition drawer) { + return "provider".equals(featureId) + ? new DrawerSettings(true, Edge.RIGHT, + DrawerPlacement.Anchor.BOTTOM, 15) + : DrawerSettings.HIDDEN; + } + }; + var popout = new PopoutElement(Common.empty(), PopoutKind.INFO, + Optional.empty(), Edge.LEFT, + Optional.of(new Text("test:info", Optional.empty()))); + var drawers = DrawerRegistry.builtins() + .resolve(new DrawerRegistry.Context(screen(List.of(popout)), + TextMeasure.NONE, host)); + assertEquals(1, drawers.size()); + var placement = drawers.getFirst().placement(); + assertEquals("provided", drawers.getFirst().id()); + assertEquals(Edge.RIGHT, placement.edge()); + assertEquals(DrawerPlacement.Anchor.BOTTOM, placement.anchor()); + assertEquals(15, placement.order()); + } + @Test void providersAreExplicitReplaceableAndRejectDuplicateIdentities() { var registry = new DrawerRegistry(); diff --git a/src/test/java/zone/moddev/mc/lib/gui/ElementBehaviorsTest.java b/src/test/java/zone/moddev/mc/lib/gui/ElementBehaviorsTest.java index 72e02af5..bc760e3d 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/ElementBehaviorsTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/ElementBehaviorsTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -46,6 +47,34 @@ * Mod types outside the implementation package exercise the public contracts. */ class ElementBehaviorsTest { + @Test + void foregroundHitDoesNotBecomeAModalOverlay() { + var tank = new ModElement(Common.empty()); + var other = new ModElement(Common.empty()); + var control = new ElementBehavior() { + public Optional additionalHitBounds() { + return Optional.of(new Rect(2, 20, 9, 7)); + } + + public Click mouseClicked(double x, double y, int button) { + return Click.CONSUME; + } + }; + var input = new ElementInput<>(List.of(tank, other), + e -> e == tank ? control : new ElementBehavior() { + }, e -> true, + e -> e == tank ? new Rect(0, 0, 18, 20) : new Rect(0, 20, 40, 20), + (x, y) -> x < 10, (e, entered) -> { + }); + input.update(); + assertNull(input.overlayOwner()); + assertSame(tank, input.hit(3, 23)); + assertTrue(input.click(3, 23, 0)); + assertSame(other, input.hit(3, 30)); + assertNull(input.hit(10, 23)); + assertFalse(input.click(10, 23, 0)); + } + @Test void foregroundChooserReceivesCoveredHitsButStillRespectsViewport() { var slot = new ModElement(Common.empty()); diff --git a/src/test/java/zone/moddev/mc/lib/gui/ElementInteractionTest.java b/src/test/java/zone/moddev/mc/lib/gui/ElementInteractionTest.java index 12e25ec2..b43446ab 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/ElementInteractionTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/ElementInteractionTest.java @@ -1,5 +1,6 @@ package zone.moddev.mc.lib.gui; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -60,6 +61,22 @@ void tankShorthandCreatesTheSameSelfContainedElement() throws Exception { assertFalse(gauge.common().clicks().any()); } + @Test + void drainButtonCanBeDisabledWithoutChangingTankSize() throws Exception { + var shown = (FluidTankElement) read( + "").body().getFirst(); + var hidden = (FluidTankElement) read( + "").body() + .getFirst(); + assertTrue(shown.validClickOption(FluidTankElement.DRAIN_OPTION)); + assertFalse(hidden.validClickOption(FluidTankElement.DRAIN_OPTION)); + assertTrue(hidden.validClickOption(0)); + var text = zone.moddev.mc.lib.gui.layout.TextMeasure.NONE; + assertArrayEquals(shown.measure(text), hidden.measure(text)); + assertThrows(ScreenException.class, () -> read( + "")); + } + @Test void sameInteractionCanBeAttachedToNonGaugeElementsAndAffectsFingerprint() throws Exception { diff --git a/src/test/java/zone/moddev/mc/lib/gui/TooltipCompositionTest.java b/src/test/java/zone/moddev/mc/lib/gui/TooltipCompositionTest.java index d7cc68a1..832aca40 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/TooltipCompositionTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/TooltipCompositionTest.java @@ -23,6 +23,7 @@ import zone.moddev.mc.lib.gui.client.ElementBehavior; import zone.moddev.mc.lib.gui.client.ElementRenderAccess; import zone.moddev.mc.lib.gui.client.ElementTooltips; +import zone.moddev.mc.lib.gui.layout.Rect; import zone.moddev.mc.lib.gui.model.Common; import zone.moddev.mc.lib.gui.model.Element; import zone.moddev.mc.lib.gui.model.Text; @@ -66,8 +67,8 @@ public Font font() { return null; } - public zone.moddev.mc.lib.gui.layout.Rect viewport() { - return new zone.moddev.mc.lib.gui.layout.Rect(0, 0, 100, 100); + public Rect viewport() { + return new Rect(0, 0, 100, 100); } public boolean visible(Element e) { @@ -113,6 +114,34 @@ public void appendChildTooltip(TooltipContext c, rows.stream().map(Component::getString).toList()); } + @Test + void foregroundControlShowsItsOwnTooltip() { + var leaf = new Leaf(authored("Gauge")); + var parent = new Parent(Common.empty(), leaf, "Parent"); + var access = new Access(); + access.parents.put(leaf, parent); + var drain = new ElementBehavior() { + public Optional additionalHitBounds() { + return Optional.of(new Rect(10, 30, 11, 10)); + } + + public List tooltip(int x, int y) { + return additionalHitBounds().orElseThrow().contains(x, y) + ? List.of(Component.literal("Drain")) + : List.of(); + } + }; + var rows = ElementTooltips.collect(leaf, access, e -> drain, 12, 34, + false, false, false); + assertEquals(List.of("Drain"), + rows.stream().map(Component::getString).toList()); + access.parents.clear(); + rows = ElementTooltips.collect(leaf, access, e -> drain, 12, 29, true, + false, false); + assertEquals(List.of("server", "Detailed 7/9"), + rows.stream().map(Component::getString).toList()); + } + @Test void elementCanReplaceDefaultContentAndParentsMustOptIn() { Element leaf = new Element() { diff --git a/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java b/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java index 072eaa54..dd5fe3d3 100644 --- a/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java +++ b/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java @@ -23,8 +23,13 @@ import org.junit.jupiter.api.io.TempDir; import zone.moddev.mc.lib.common.loading.DefinitionLoader.SourceRoot; +import zone.moddev.mc.lib.gui.drawer.BuiltinDrawers; +import zone.moddev.mc.lib.gui.drawer.DrawerPlacement; +import zone.moddev.mc.lib.gui.model.Edge; +import zone.moddev.mc.lib.machine.definition.MachineBehavior; import zone.moddev.mc.lib.machine.definition.MachineDefinition; import zone.moddev.mc.lib.machine.definition.MachineDefinitions; +import zone.moddev.mc.lib.machine.definition.MachineFeatureDefinition; import zone.moddev.mc.lib.machine.recipe.generation.GeneratorProperties; class MachineDefinitionsTest { @@ -48,6 +53,205 @@ private String crusher() throws Exception { .of("src/companion/resources/mmdlib/machine/simple_crusher.xml")); } + @Test + void machinePartsDefineStorageAndScreenOrderTogether() throws Exception { + write( + """ + + + + + + + + + + + """); + Files.writeString(directory.resolve("machine/base.xml"), """ + + + + """); + var machine = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")); + assertEquals("cargo", machine.itemStorageId()); + assertEquals("liquids", machine.fluids().id()); + assertEquals(List.of("water/0", "water/1"), + machine.fluids().tanks().stream().map(tank -> tank.id()).toList()); + assertEquals(4, machine.inventorySlots("solids").size()); + assertEquals("filter", machine.processors().getFirst().id()); + var row = machine.screen().children().stream() + .filter(fill -> "machine".equals(fill.attributes().get("name"))) + .findFirst().orElseThrow().children().getLast(); + assertEquals( + List.of("fluid-tank", "fluid-tank", "progress", "coloured-group", + "energy-gauge"), + row.children().stream().map(node -> node.name()).toList()); + assertEquals("test.water", + row.children().getFirst().attributes().get("tooltip")); + assertEquals("2", row.children().get(3).children().getFirst() + .attributes().get("columns")); + } + + @Test + void machinePartsRejectASecondRowDeclaration() throws Exception { + write(crusher().replace("", """ + + + + """)); + var failure = assertThrows( + zone.moddev.mc.lib.gui.load.ScreenException.class, + () -> MachineDefinitions.load(sources())); + assertTrue(failure.getMessage().contains("both parts and layout")); + } + + @Test + void orderedLayoutReplacesTheInheritedRow() throws Exception { + write(crusher().replace("mmdlib:base_powered_machine", "test:base") + .replace("", + """ + + + """)); + Files.writeString(directory.resolve("machine/base.xml"), """ + + + + """); + var id = ResourceLocation.parse("test:crusher"); + var screen = MachineDefinitions.load(sources()).get(id).screen(); + var row = screen.children().stream() + .filter(fill -> "machine".equals(fill.attributes().get("name"))) + .findFirst().orElseThrow().children().getLast(); + assertEquals(List.of("progress", "coloured-group"), + row.children().stream().map(node -> node.name()).toList()); + for (String region : List.of("tanks", "energy")) + assertTrue(screen.children().stream() + .anyMatch(fill -> region.equals(fill.attributes().get("name")) + && fill.children().isEmpty() + && !fill.attributes().containsKey("generator"))); + } + + @Test + void orderedLayoutReportsUnknownTankReference() throws Exception { + write(crusher().replace("", """ + + + """)); + var machine = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")); + var failure = assertThrows( + zone.moddev.mc.lib.gui.load.ScreenException.class, machine::screen); + assertTrue( + failure.getMessage().contains("Unknown layout tank missing")); + } + + @Test + void featureOverridesInheritTypeOptionsAndDrawerPlacementById() + throws Exception { + write(crusher().replace("mmdlib:base_powered_machine", "test:base") + .replace("", """ + + + + + """)); + Files.writeString(directory.resolve("machine/base.xml"), """ + + + + + + """); + var definition = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")); + var behavior = definition.behavior(); + var redstone = behavior.feature(BuiltinDrawers.REDSTONE).orElseThrow(); + assertTrue(definition.redstone()); + assertEquals("pause-while-powered", + redstone.options().get("default-mode")); + assertFalse(redstone.drawerSettings().enabled()); + assertEquals(Edge.LEFT, redstone.drawer().edge()); + assertEquals(DrawerPlacement.Anchor.BOTTOM, redstone.drawer().anchor()); + assertEquals(25, redstone.drawer().order()); + assertNull(behavior.gearboxSlot()); + assertEquals("mmdlib_capacitor/0", behavior.capacitorSlot()); + assertFalse(behavior.feature(BuiltinDrawers.STATS).orElseThrow() + .drawerSettings().enabled()); + assertTrue(behavior.feature(BuiltinDrawers.INFO).orElseThrow() + .drawerSettings().enabled()); + } + + @Test + void unpoweredMachineInheritsRedstoneWithIgnoreDefault() throws Exception { + String xml = """ + + + + + """; + write(xml); + var id = ResourceLocation.parse("test:crusher"); + var definition = MachineDefinitions.load(sources()).get(id); + assertNull(definition.power()); + assertTrue(definition.redstone()); + assertEquals("ignore", + definition.behavior().feature(BuiltinDrawers.REDSTONE).orElseThrow() + .options().get("default-mode")); + assertEquals( + List.of(BuiltinDrawers.INFO, BuiltinDrawers.STATS, + BuiltinDrawers.CURIOS, BuiltinDrawers.BACKPACK, + BuiltinDrawers.REDSTONE), + definition.behavior().features().stream() + .map(MachineFeatureDefinition::type).toList()); + + write(xml.replace("", + "")); + assertFalse(MachineDefinitions.load(sources()).get(id).redstone()); + } + + @Test + void standaloneLegacyRedstoneRequiresExplicitEnable() throws Exception { + String xml = """ + + + + + + + + + """; + var id = ResourceLocation.parse("test:crusher"); + write(xml); + assertFalse(MachineDefinitions.load(sources()).get(id).redstone()); + write(xml.replace("", + "", + "", + "")) { + write(crusher().replace("", override + "")); + var error = assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + assertTrue(error.getMessage().contains("crusher.xml")); + } + } + public static class Admission extends zone.moddev.mc.lib.machine.feature.StoredProcessor @@ -524,7 +728,8 @@ void originalConstructorRetainsAutomaticCubeDefaults() throws Exception { d.power(), d.fluids(), d.itemStorageId(), d.slots(), d.groups(), d.recipeType(), d.processor(), d.processorName(), d.redstone(), d.screen()); - assertEquals(d, compatible); + assertEquals(d.textures(), compatible.textures()); + assertEquals(MachineBehavior.DEFAULT, compatible.behavior()); assertNull(compatible.baseModel()); assertNull(compatible.recipeSelection()); assertTrue(compatible.ghosts().isEmpty()); diff --git a/src/test/java/zone/moddev/mc/lib/machine/WorkingAreaTest.java b/src/test/java/zone/moddev/mc/lib/machine/WorkingAreaTest.java index b6b0cf5a..ea97a7a5 100644 --- a/src/test/java/zone/moddev/mc/lib/machine/WorkingAreaTest.java +++ b/src/test/java/zone/moddev/mc/lib/machine/WorkingAreaTest.java @@ -13,6 +13,50 @@ import zone.moddev.mc.lib.machine.feature.WorkingArea; class WorkingAreaTest { + @Test + void snakeTraversalAlternatesRowsWithoutSkippingBlocksAtEveryFacingAndRange() { + var origin = new BlockPos(10, 64, 20); + for (int range = 0; range <= 9; range++) { + var area = new WorkingArea(-1, 0, -3, 1, 0, -1) + .expandHorizontal(range); + for (var front : Direction.Plane.HORIZONTAL) { + var visited = new java.util.HashSet(); + BlockPos previous = null; + for (int index = 0; index < area.size(); index++) { + var current = area.snakeBlockAt(origin, front, index); + assertTrue(visited.add(current)); + if (previous != null) + assertEquals(1, previous.distManhattan(current)); + int row = area.row(index); + if (index % area.width() == 0) + assertEquals( + origin.relative(front, -1 - row).relative( + front.getClockWise(), + row % 2 == 0 ? -1 - range : 1 + range), + current); + assertTrue(area.bounds(origin, front).contains( + net.minecraft.world.phys.Vec3.atCenterOf(current))); + previous = current; + } + assertEquals(area.size(), visited.size()); + } + } + } + + @Test + void snakeRowsResetPerLayerAndRejectInvalidIndexes() { + var area = new WorkingArea(0, 0, 0, 2, 1, 2); + int[] columns = {0, 1, 2, 2, 1, 0, 0, 1, 2}; + for (int index = 0; index < area.size(); index++) + assertEquals( + new BlockPos(columns[index % 9], index / 9, -(index / 3 % 3)), + area.snakeBlockAt(BlockPos.ZERO, Direction.NORTH, index)); + assertThrows(IndexOutOfBoundsException.class, + () -> area.snakeBlockAt(BlockPos.ZERO, Direction.NORTH, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> area + .snakeBlockAt(BlockPos.ZERO, Direction.NORTH, area.size())); + } + @Test void rearExpansionAndTraversalAgreeForEveryFacingAndRange() { var base = new WorkingArea(-1, 0, -3, 1, 0, -1);