From 72c9fa53e0e60c5ead7d24c444011497f90f02f5 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Sun, 15 Nov 2026 17:53:07 +0200 Subject: [PATCH 1/3] Add recipe chains, shared recipe drawers, and machine displays --- CHANGELOG.md | 11 + docs/gauge-textures.md | 11 +- docs/gui-screens.md | 58 ++- docs/mod-author-guide.md | 3 + docs/recipe-chains.md | 222 +++++++++ docs/xml-machines.md | 77 +++- scripts/generate_gauge_textures.py | 2 +- .../test/GroupPresentationClientSmoke.java | 27 +- .../mc/lib/api/capabilities/ItemStorage.java | 23 +- .../mc/lib/api/capabilities/ItemStore.java | 17 + .../api/capabilities/PlannedItemHandler.java | 54 ++- .../client/jei/PresentedRecipeCategory.java | 61 +++ .../lib/gui/client/BuiltinElementClients.java | 13 +- .../lib/gui/client/ColouredGroupBehavior.java | 9 +- .../lib/gui/client/ContainerCellRenderer.java | 3 +- .../zone/moddev/mc/lib/gui/client/Drawer.java | 17 + .../mc/lib/gui/client/DrawerOpener.java | 9 + .../moddev/mc/lib/gui/client/Drawers.java | 30 ++ .../mc/lib/gui/client/ElementDrawing.java | 15 + .../mc/lib/gui/client/ElementHighlight.java | 6 +- .../mc/lib/gui/client/ElementInput.java | 18 +- .../lib/gui/client/ElementRenderAccess.java | 22 + .../lib/gui/client/EnergyGaugeRenderer.java | 7 +- .../lib/gui/client/FilterSamplesBehavior.java | 2 +- .../mc/lib/gui/client/GaugeRenderer.java | 51 ++- .../lib/gui/client/GroupColourProvider.java | 6 + .../mc/lib/gui/client/MachineScreen.java | 38 +- .../mc/lib/gui/client/SideConfigDrawer.java | 19 +- .../mc/lib/gui/client/SideDrawerRenderer.java | 15 +- .../mc/lib/gui/client/SlotRenderer.java | 6 +- .../lib/gui/client/recipe/RecipeCatalog.java | 35 ++ .../lib/gui/client/recipe/RecipeDrawer.java | 275 +++++++++++ .../gui/client/recipe/RecipePresentation.java | 83 ++++ .../mc/lib/gui/layout/RecipeDrawerLayout.java | 49 ++ .../mc/lib/gui/layout/SideDrawerLayout.java | 7 + .../containers/ColouredGroupElement.java | 7 +- .../lib/machine/definition/ItemDisplay.java | 48 ++ .../machine/definition/MachineBehavior.java | 10 +- .../definition/MachineDefinitions.java | 115 ++++- .../mc/lib/machine/feature/FeatureHost.java | 9 +- .../lib/machine/feature/MachineFeature.java | 10 +- .../mc/lib/machine/feature/RecipeChain.java | 405 +++++++++++++++++ .../mc/lib/machine/feature/RecipeCycle.java | 191 ++++++++ .../lib/machine/feature/RecipeProcessor.java | 155 ++----- .../neoforge/MachineInventoryLifecycle.java | 1 + .../machine/neoforge/MachineResourcePack.java | 11 +- .../machine/neoforge/RecipeOperations.java | 141 ++++++ .../lib/machine/neoforge/StorageGroups.java | 8 +- .../client/ConditionalMachineModel.java | 44 +- .../client/MachineEntityDisplays.java | 27 +- .../neoforge/client/MachineItemDisplay.java | 63 +++ .../presentation/ConditionalModelPart.java | 6 +- .../lib/machine/presentation/FaceOverlay.java | 90 ++++ .../mc/lib/machine/recipe/RecipeGraph.java | 190 ++++++++ .../resources/assets/mmdlib/lang/en_us.json | 4 + .../textures/gui/sprites/icon_recipes.png | Bin 0 -> 506 bytes .../moddev/mc/lib/smoke/MMDLibGameTests.java | 24 + .../moddev/mc/lib/smoke/RecipeChainSmoke.java | 427 ++++++++++++++++++ .../mc/lib/gui/ElementBehaviorsTest.java | 46 ++ .../mc/lib/gui/GroupPresentationTest.java | 66 ++- .../mc/lib/gui/RecipeDrawerLayoutTest.java | 77 ++++ .../moddev/mc/lib/gui/SpriteElementsTest.java | 4 +- .../mc/lib/gui/client/SlotRendererTest.java | 23 + .../mc/lib/machine/EntityDisplayTest.java | 5 +- .../mc/lib/machine/FaceOverlayTest.java | 111 +++++ .../mc/lib/machine/ItemDisplayTest.java | 175 +++++++ 66 files changed, 3576 insertions(+), 218 deletions(-) create mode 100644 docs/recipe-chains.md create mode 100644 src/main/java/zone/moddev/mc/lib/client/jei/PresentedRecipeCategory.java create mode 100644 src/main/java/zone/moddev/mc/lib/gui/client/DrawerOpener.java create mode 100644 src/main/java/zone/moddev/mc/lib/gui/client/GroupColourProvider.java create mode 100644 src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeCatalog.java create mode 100644 src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java create mode 100644 src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipePresentation.java create mode 100644 src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java create mode 100644 src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java create mode 100644 src/main/java/zone/moddev/mc/lib/machine/feature/RecipeChain.java create mode 100644 src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java create mode 100644 src/main/java/zone/moddev/mc/lib/machine/neoforge/RecipeOperations.java create mode 100644 src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java create mode 100644 src/main/java/zone/moddev/mc/lib/machine/presentation/FaceOverlay.java create mode 100644 src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeGraph.java create mode 100644 src/main/resources/assets/mmdlib/textures/gui/sprites/icon_recipes.png create mode 100644 src/runtimeTest/java/zone/moddev/mc/lib/smoke/RecipeChainSmoke.java create mode 100644 src/test/java/zone/moddev/mc/lib/gui/RecipeDrawerLayoutTest.java create mode 100644 src/test/java/zone/moddev/mc/lib/gui/client/SlotRendererTest.java create mode 100644 src/test/java/zone/moddev/mc/lib/machine/FaceOverlayTest.java create mode 100644 src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index c72317a1..d78aab34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased — 2.0.2 +- Add Java recipe-chain helpers for concurrent stages, stock targets, pending + input protection, saved cycles and bounded recipe-path discovery. See + [recipe chains](docs/recipe-chains.md). +- Add a shared recipe drawer and optional JEI presentation adapter. Narrow + layouts open inward without covering recipe content with the tab rail; + foreground element popups retain input priority over the drawer. +- Add front-face item displays and rectangular, optionally emissive frame + overlays to machine appearances. Both `` and `` + belong inside ``; move existing root-level entity displays there. +- Tint grouped slot and gauge backgrounds while preserving item/fluid colours; + reserve group outlines for hover and selection. - Update NeoForge to 21.1.265 (from 21.1.247); it is now the minimum NeoForge version MMDLib requires. Update the Gradle wrapper to 9.9.1 (from 9.8.2). - Machines (#105): diff --git a/docs/gauge-textures.md b/docs/gauge-textures.md index 86f03f3e..e78edb2f 100644 --- a/docs/gauge-textures.md +++ b/docs/gauge-textures.md @@ -8,7 +8,8 @@ Textures for the planned GUI fill gauge, styled as a glass graduated cylinder. T These textures supply `` and the matching slim background of ``. The energy renderer draws thin red charge bars with a soft reflection, without a terminal or graduations. Bars are at most four pixels thick, separated by one-pixel gaps. -Both empty interiors use neutral dark grey `#555555`. +Both empty interiors use neutral dark grey `#555555` as their base. Glass tanks add +subtle cylindrical shading and reflection over the empty portion. ## Files @@ -37,7 +38,9 @@ For a gauge of length *L* (≥ 10) at (*x*, *y*): 3. **Glass**: flush preceding buffered GUI draws, enable source-alpha blending, then draw the three `glass_*` pieces in the same arrangement as the body. The renderer restores the caller's blend enable/function, depth-test state and shader color after drawing the gauge. - The overlay is clipped to the filled portion, leaving the empty interior flat medium grey. + The overlay uses full strength over the filled portion and 35% strength over the empty + portion, with separate clips meeting at the fluid level. This keeps partially filled and + completely empty tanks rounded without changing the lighting over their contents. Fluid textures remain visible beneath it; the cylinder effect comes from lighting, not a new outline. The energy gauge uses only the body textures, without this glass overlay. 4. **Graduations**, drawn in code: colour `#EEF3F6` at 85% opacity, with a 35% black shadow @@ -115,3 +118,7 @@ under 12 px. Thicker gauges keep a 1 px gap-coloured margin on each side. - Segments are flat. Only segments at least 4 px in both directions get a bevel (top/left edge 35% toward white, bottom/right edge at 70%; 12% and 85% when unlit). Smaller segments drawn with a bevel blur into the gaps and their proportions read wrong. + +Gauge body textures receive the same subtle group-colour background wash as item slots. +The fluid, glass and charged energy bars retain their original colours. Group outlines +appear when the associated automation button is highlighted, not continuously. diff --git a/docs/gui-screens.md b/docs/gui-screens.md index 6cc3dde2..3cc78838 100644 --- a/docs/gui-screens.md +++ b/docs/gui-screens.md @@ -459,10 +459,10 @@ provider, a rectangular outline uses the request's colour and outset. Highlights targets and run with viewport clipping and isolated pose/colour state. `ElementHighlight` distinguishes persistent `DECORATION`, `EMPHASIS` of an existing decoration, -and a control's `SELECTION` marker. Factory methods supply the usual zero/one-pixel outsets; +and a control's `SELECTION` marker. Factory methods supply a two-pixel outset; providers may reuse `request.outline(bounds)` or `request.render(graphics, bounds)`. -`GroupBehavior` supplies panel captions. `ColouredGroupBehavior` suppresses duplicate persistent -decoration, emphasizes its own coloured outline, and retains the requesting control's selection +`GroupBehavior` supplies panel captions. `ColouredGroupBehavior` suppresses persistent +decoration, draws its coloured outline on emphasis, and retains the requesting control's selection style. The inline side-config renderer and side-config drawer depend only on these contracts; they do not recognize concrete group classes or construct temporary group wrappers. @@ -2167,12 +2167,25 @@ processor arrow composes a `ProgressSpriteElement`, retaining its default arrow darkened custom-icon background. `ColouredGroupElement` decorates exactly one inner element, which can itself contain any number -of children. It preserves that child's dimensions and stretching and paints its outline after -the child backgrounds. Generated resource-group inventories use this wrapper; automation +of children. It preserves that child's dimensions and stretching. Group outlines appear only +when the corresponding group control is hovered or selected, without covering the original casing. +Hover and selection outlines extend two pixels beyond the element bounds. Outlines clip to the +viewport rather than the child rectangle; layout and hit areas remain unchanged, so leave +room between neighbouring groups for their decoration. Generated resource-group inventories +use this wrapper; automation selection highlights the whole inventory once. Older hand-authored highlight targets still work through the generic highlight service's outline fallback; mod targets can provide their own `HighlightPresentation`. +Grouped slot backgrounds and fluid/energy gauge casings receive a 40% group-colour +wash, preserving their original shading and any explicit slot tint. Fluid contents, energy +bars, items, empty icons, ghost previews and stack counts retain their colours. Automation +no longer draws persistent identification outlines; hovering a group button or selecting it +in the open drawer emphasizes its associated elements. The nearest group wins without stacking tints: registered behaviors can provide +`GroupColourProvider`, and host resource associations supply colours for older screens without +wrappers. `ElementRenderAccess.groupColour` resolves these through ordinary parent traversal, +including in fragments. Ungrouped slots retain their original appearance. + ```xml @@ -2694,3 +2707,38 @@ client preview is cached per open screen and rebuilt only when the data or clien level changes. It never spawns, ticks or searches for a live world entity, and does not load passenger trees. The preview cache is discarded when the screen closes. Entity data should be updated by the processor when its occupant changes. + +## Shared recipe drawer + +`RecipeDrawer` in `gui.client.recipe` hosts a `RecipeCatalog` with named groups +and paged choices. Register a `DrawerDefinition` using `DrawerRegistry` on both +sides, then register its `DrawerFactories` client factory: + +```java +DrawerFactories.GLOBAL.register(RECIPE_DRAWER_TYPE, (screen, definition) -> + new RecipeDrawer(screen, definition, new MyRecipeCatalog(screen))); +``` + +The catalog returns a stable list until recipes change and implements `select` +by submitting a server-validated element action. `initialGroup()` can select the +machine's current source. Opening and paging are client presentation only. +An element behavior opens it through +`access.service(DrawerOpener.class).map(opener -> opener.open(drawerId))`. + +Each choice has a `RecipePresentation`: dimensions, item positions and roles, +extra item tooltips, indexed fluid requirements, tooltip areas and background +drawing. Its coordinates are local; background drawing must not draw the items. +The drawer supplies native item rendering. An optional JEI category extends +`PresentedRecipeCategory` and returns the same presentation from +`presentation(T recipe)`; its adapter creates JEI ingredient slots and tooltip +areas, preserving ingredient lookup without duplicating layout/artwork. + +The recipe API itself has no JEI dependency. Consumers keep machine-specific +recipe policy, catalog construction and action validation. Refresh cached catalogs +when synchronized recipes/tags change. Drawer choices are previews, never authority. +The drawer keeps native GUI scale and uses the side margin when available. At narrow +widths it opens inward over the machine, keeping recipe content clear of the tab rail. +Its body reserves space in JEI and blocks underlying slot/control hover. Foreground +element popups retain input priority above the drawer and remain clipped to the viewport. +Existing drawers can opt into the same behavior through +`Drawer.renderForeground` and `Drawer.covers`. diff --git a/docs/mod-author-guide.md b/docs/mod-author-guide.md index b9bb1d92..fe32a7c4 100644 --- a/docs/mod-author-guide.md +++ b/docs/mod-author-guide.md @@ -24,6 +24,9 @@ including inherited storage, generated screens and dynamic recipes. More special machines and custom world entities use their dedicated typed factory APIs. The manual wiring below remains an alternative; do not queue objects twice. +Machines with a selected material path can use [recipe chains](recipe-chains.md) +for concurrent stages, per-stage stock targets and processing-first extraction. + Java machines spanning several blocks can use [multiblock placement and lifecycle](multiblocks.md), with one controller, linked physical parts and guarded resource ports. diff --git a/docs/recipe-chains.md b/docs/recipe-chains.md new file mode 100644 index 00000000..d5be490c --- /dev/null +++ b/docs/recipe-chains.md @@ -0,0 +1,222 @@ +# Recipe chains + +`RecipeCycle`, `RecipeChain` and `RecipeGraph` support machines that select a +material path and run its stages concurrently. They are Java runtime helpers; +the consuming mod supplies its processor/controller, recipe policy, storage, +save/sync integration and screen. They do not register a machine or recipe type. + +## Execute a selected recipe + +`machine.feature.RecipeCycle` executes a supplied `MachineRecipe` against a +`MachineInventory`. The ordinary `RecipeProcessor` uses this same runner while +retaining its automatic lookup, selection, pause and saved-state format. + +- `start(id, recipe)` reserves inputs and output space. It neither advances + time nor spends FE, and refuses to replace active work. Admission can succeed + without power; automatic `RecipeProcessor` still applies its usual matcher. +- `advance(random)` advances at most one tick, transactionally charging that + tick's share of every energy input. Results distinguish idle, running, + energy-stalled, completion-blocked and completed work. +- A blocked completion retains paid progress and retries without charging it + again. `CyclePlan` remains responsible for reservations, atomic consumption, + output insertion and rollback. +- `state()` / `State.CODEC` persist the active plan and progress. Load storage + first, then `restore(state)`. Restoring twice replaces this runner's claims. + A failed restore returns false, leaves this runner idle and preserves items. +- `release()` releases claims while keeping progress. A caller using + `resume(id, recipe, paidProgress, previousTime)` must retain the recipe ID and + previous duration itself. A changed duration resets paid progress. `reset()` + also clears progress. Neither is appropriate for a finish-before-switch policy. + +Use the runner only on the owning server thread. Do not call `restore` on a +client mirror: it installs authoritative storage reservations. + +## Bind a path + +`machine.feature.RecipeChain` accepts 1–64 `Step` bindings. Stage zero generates +an item without item inputs; its recipe can require fluids and energy. Every +later stage consumes one ingredient, possibly several copies, from the previous +stage. Every stage produces one deterministic item stack into one output slot. +Chance products, multiple item ingredients and item catalysts are outside this +coordinator's scope. + +Recipe item keys are `input` and `output`. Other keys can map shared energy or +fluids. Create each physical stage output group **once**, then reuse that exact +`ItemGroup` instance as the next stage's input. Distinct stage outputs must not +overlap physically, even through different group wrappers. These bindings and +their reservations are exclusive to the chain. + +For example, given two valid recipes (`generation` and `grinding`) and their +IDs, a host binds its resources as follows: + +```java +var items = new ItemStorage(2).role(Role.OUTPUT, 0, 1); +var generated = StorageGroups.items(items, 0); +var ground = StorageGroups.items(items, 1); +var power = StorageGroups.energy(energy); +var sourceInventory = MachineInventory.builder() + .group("output", generated) + .group("energy", power) + .group("water", StorageGroups.fluids(fluids, 0)) + .group("lava", StorageGroups.fluids(fluids, 1)) + .build(); +var grindingInventory = MachineInventory.builder() + .group("input", generated) + .group("output", ground) + .group("energy", power) + .build(); +var chain = new RecipeChain(List.of( + new RecipeChain.Step(generationId, generation, sourceInventory), + new RecipeChain.Step(grindingId, grinding, grindingInventory))); +items.pendingClaims(chain::pendingTake); +chain.target(1, chain.step(1).product().getMaxStackSize()); +``` + +The types above are `api.capabilities.ItemStorage` / `Role`, +`machine.neoforge.StorageGroups`, `machine.inventory.MachineInventory` and +`machine.feature.RecipeChain`. The host owns `energy` and the two-tank `fluids` +storage. Recipe group names must match the bindings. + +Call `chain.tick(random)` once per server tick and mark the host changed when it +returns true. Settings changes also need the host's usual save/sync notification. +`cycle(index)` exposes a detached state snapshot; `result(index)` is the last +attempted advancement/admission result, not a promise that the stage advanced +on the current tick. + +Stages active at tick entry advance before new work is admitted. With enough +FE, they all advance in the same tick. The first stage rotates between funded +passes. An energy-stalled stage keeps first turn and ends the advancement pass +until its charge can be funded, so cheaper stages cannot keep spending that +charge. Configure the energy buffer to hold each stage's largest per-tick share. + +## Stock and extraction + +`target(index, amount)` takes a number from zero through the product's normal +stack size. A mod can map None / One / Stack to 0 / 1 / maximum. Targets are +refill goals, not protected minimum reserves. Zero-stock intermediates still +supply downstream demand. Planning works backward through the path, counting +active outputs and subtracting active consumption to avoid double-ordering. +A host can call `bufferLimit(index, amount)` to cap a stage's planned stock even +when downstream demand is larger. For One Run, set both target and buffer limit +to the following step's input count (the terminal stage uses its own output +batch). Default limits are a normal stack, preserving ordinary concurrent bulk +planning. Buffer limits are host policy: reapply them after binding/restoring the +chain, alongside the host's saved mode. Existing stock and active work are never +removed. Limits must allow at least the next step's input batch; full output +batches may overshoot the limit. As a downstream cycle reserves the ready batch, +a replacement can run concurrently. + +A stage whose output cannot accept a complete batch does not propagate unmet +stock demand upstream. This prevents a blocked/incompatible intermediate from +filling every preceding None stage. Independent stock targets still apply on +those stages, and active cycles keep their reservations and finish normally. +Removing the blockage allows downstream demand to propagate again. + +Full recipe batches are retained. A target of one pane can produce sixteen. +If sixteen panes cannot fit in the destination slot, the batch waits; there is +no overflow deletion or additional hidden buffer. Inputs and products larger +than a normal stack are unsupported in this one-slot model. + +Output slots use three availability quantities: + +1. Actual `CyclePlan` claims protect active work. +2. `pendingTake(stage)` protects up to the next demanded downstream batch, + including a partial batch while it accumulates. +3. Everything else remains extractable, including stock below its refill target. + +Bind the pure pending-claim projection to **physical** `ItemStorage` owners with +`pendingClaims`. In the example, local slot and stage indexes coincide. For +combined/named inventories, explicitly map each owner's local slots to stage +indexes and return zero for unrelated slots. Use a callback referencing the +host's current chain when bindings can change. Pending claims apply only to +`Role.OUTPUT` slots. + +External extraction, hopper views and menu `SlotPlan` snapshots see the same +combined protection. Simulation changes neither items nor reservations. Internal +`StorageGroups` use `ItemStore.processingPlan`, `freeForProcessing` and +`extractForProcessing`, which respect active claims but can consume the pending +batch. Storage subclass extraction limits and rollback behavior still apply. +Internal insertion capacity uses actual reservations, not pending demand. + +Pending protection releases immediately when demand disappears, downstream +output space is unavailable, a pause/host hold applies, or draining starts. +Power loss alone retains it so the batch can resume. It also releases when the +next cycle takes over with an actual reservation. No pending claim is persisted. + +## Pause, switching and loading + +`paused(true)` and `held(true)` stop advancement and admission while preserving +active work and its claims. The former is persisted; the latter is transient +host/redstone state. This is deliberately different from ordinary +`RecipeProcessor.pause()`, which retains its existing release-and-resume behavior. + +For a route switch, the host validates and saves a pending selection, then calls +`drain()`. This stops every new old-route cycle, including generation, and +releases pending batch protection. Keep ticking until `drained()` is true. +Pause, power loss or blocked completion may delay it. `cancelDrain()` resumes +admission without replacing any active plan. + +Once drained, the host preserves accessible leftovers and changes bindings only +when that can be done without losing or relabeling items. The library does not +move leftovers, choose recovery slots or apply the pending route. + +Persist `RecipeChain.State` alongside storage and the host's source, active +bindings, pending route and recovery metadata. Reconstruct the same bindings, +load storage, then call `restore`. It validates route IDs, targets and shape; +false means at least one active reservation could not be restored. Other valid +cycles can remain active. The host must handle that recovery result explicitly. +Retain binding descriptions needed to drain saved work if a recipe disappears; +the chain state is not a recipe catalog. Current recipe lookup is not needed to +finish an already-restored `CyclePlan`. + +For a `StoredProcessor`, decode registry-dependent bindings and restore claims in +`MachineFeature.restoreResources(registries)`. The defined-machine lifecycle calls +this hook after both storage and feature state have loaded, before automation can +extract anything on the first tick. `FeatureHost` forwards it to every feature. +The ordinary `restore` callback has no registry provider and must not install +claims against the old inventory. Override `reset()` to call `chain.reset()` and +release any previous runner claims before reloading or destroying the host. +Reinstall pending-claim projections during resource restoration as well. + +Use state snapshots for the host's bounded client presentation data, alongside +the existing menu reservation synchronization. Recompute host hold after load. + +## Discover transformations + +`machine.recipe.RecipeGraph.discover(root, resolver, limits)` expands concrete +item-and-component identities. The resolver returns admitted `Operation` values +with recipe ID, operation kind, input count, output and executable recipe. +Each identity is expanded once; cycles remain edges. `pathTo(node)` chooses a +shortest path, breaking ties by recipe ID and operation kind. Alternative edges +remain available through `edges()`. Duplicate IDs for one source are rejected. + +Default bounds are 512 nodes, 2,048 edges and depth 32. `truncated()` reports +incomplete discovery. The resolver must also bound/index its own catalog work. +Discovery belongs outside processing ticks. + +`RecipeGraph.Cache` caches one source per owner and recipe/policy snapshot. +Use a fresh snapshot identity or call `invalidate()` on recipe **and tag** +reload, or when admission/cost policy changes. Changing source components or +limits also rebuilds. This helper does not subscribe to loader reload events. +Before starting a client-selected route, the server must resolve its exact IDs +against the current admitted graph. On reload, drain an invalid active route +before rebuilding it; changing the cache alone does not stop an existing chain. + +`machine.neoforge.RecipeOperations` supplies conservative adapters: + +- `smelting(holder, source, level, cost)` supports ordinary vanilla smelting. +- `crafting(...)` supports ordinary shaped/shapeless recipes whose occupied + cells all accept the same source. It preserves empty shaped cells and batch + quantities, such as six glass producing sixteen panes. +- Both exclude special subclasses, remainder-bearing recipes and batches that + cannot fit one normal stack. Their generated ingredients bind exact source + components. Sources that cannot be represented by the standard strict + component ingredient are excluded. +- `machine(id, kind, recipe, source)` admits an existing deterministic + single-item transformation with optional energy. It retains its ingredient + and recipe semantics; extra fluids/materials, catalysts and chance outputs + are excluded. A chain additionally checks its concrete parent product. + +The mod decides allowed operations and supplies positive time/FE costs for +vanilla adapters. The graph is independent of the NeoForge adapter and can use +other explicitly supported operation resolvers. diff --git a/docs/xml-machines.md b/docs/xml-machines.md index 87e06073..c5df619a 100644 --- a/docs/xml-machines.md +++ b/docs/xml-machines.md @@ -1196,16 +1196,54 @@ entities; discard the preview if it returns false, since a failed load or hook m have partially changed it. Portable ownership and world placement stay with the caller, who must retain the snapshot until placement succeeds. +### Front item displays + +Bind a synchronized processor variable to an item preview on the front of a machine: + +```xml + + + +``` + +The variable must be a synchronized `ItemStack` or a string containing an item ID +such as `minecraft:stone`. An empty stack or empty string displays nothing. Invalid +or unregistered live item IDs also display nothing; the loader validates the +binding and default value without looking up the item registry during schema loading. +Use `.synced()` when declaring the processor variable so tracking players receive +updates without opening a menu. The processor owns when that value changes. + +`x` and `y` position the center on the front face in block units (0..1), with x +increasing toward the viewer's right and y upward. Width and height are in (0, 1]. +All four default to 0.5. The display follows horizontal machine facing and uses +the lighting outside that face. It renders one native item GUI model flattened +just outside the face, over the normal/conditional texture, without a count label. + +One `` is supported inside ``. It follows normal machine +XML inheritance: children override supplied attributes and inherit the rest. It can +coexist with an ``; MMDLib registers a combined +block-entity renderer. No consumer renderer registration or portable-machine policy +is needed. This displays an item on a placed block; it does not alter the machine's +inventory item model. + ### Entity displays on blocks and items -Declare a detached living-entity overlay beside the machine's appearance: +Declare a detached living-entity overlay inside the machine's ``: ```xml - + + + ``` +One `` is supported per ``, with the same attribute +inheritance as ``. Neither display is accepted at the machine root. +They coexist with parts and face overlays and do not count toward the 64 conditional +appearance-rule limit. Changing the appearance preset preserves inherited displays. + MMDLib registers the block renderer, item renderer and model wrapper. The variable must be a synchronized `EntitySnapshot`. Item displays additionally require a portable machine and a `PortableVariable.entity(...)` declaration using the same @@ -1366,3 +1404,34 @@ type from its XML definition. Java integrations can access them through needed. Call these after the corresponding registry event (for example, in creative tab contents or client setup), not while initializing a mod's static fields. Unknown or not-yet-registered IDs fail explicitly instead of returning air. + +### Rectangular face overlays + +Use independent `` children of `` for lamps, status +indicators and other dynamic surface regions. Multiple overlays coexist on the +same face; the base face and `` are retained. + +```xml + +``` + +Coordinates use a 16 by 16 face, measured from its top-left as seen from outside. +For top and bottom, the north-facing machine's model UV orientation applies; +overlays rotate with the block. Bounds must fit on the face. `face` accepts front, +back, left, right, top and bottom. Each overlay is a cutout plane just outside the +face, so transparent pixels expose the casing. Keep independent rectangles or +opaque pixels disjoint to avoid overlapping coplanar surfaces. + +A static overlay needs only its rectangle and texture. `frames` defaults to 1; +for multiple frames (maximum 32), supply a numeric visual processor `variable`. +The texture is a vertical strip of equally sized frames, without animation +`.mcmeta`. The value selects a zero-based frame, rounded down and clamped to the +strip's range. Optional `when` uses the normal visual conditions; it defaults to +true. `emissive="true"` makes opaque pixels full-bright without making the block +emit world light. Default is false. Use transparency around glowing pixels. + +MMDLib expands the declaration into conditional model parts, reusing tracking +snapshots and model invalidation when the selected frame changes. No per-machine +renderer or full-face variants are needed. Inventory models keep the base casing. diff --git a/scripts/generate_gauge_textures.py b/scripts/generate_gauge_textures.py index 6b0a4f88..51cfa3f7 100644 --- a/scripts/generate_gauge_textures.py +++ b/scripts/generate_gauge_textures.py @@ -3,7 +3,7 @@ Writes to src/main/resources/assets/mmdlib/textures/gui/gauge/: body_top.png, body_middle.png, body_bottom.png shared casing: outline + medium grey interior - glass_top.png, glass_middle.png, glass_bottom.png translucent highlight drawn over the contents + glass_top.png, glass_middle.png, glass_bottom.png translucent glass lighting (softer above contents) and prints the per-row content clip table for the caps (see docs/gauge-textures.md). The textures are vertical; horizontal gauges draw them rotated 90 degrees clockwise. diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/GroupPresentationClientSmoke.java b/src/companionTest/java/zone/moddev/mc/companion/test/GroupPresentationClientSmoke.java index 7afbda51..08333f42 100644 --- a/src/companionTest/java/zone/moddev/mc/companion/test/GroupPresentationClientSmoke.java +++ b/src/companionTest/java/zone/moddev/mc/companion/test/GroupPresentationClientSmoke.java @@ -189,12 +189,28 @@ static boolean run(MachineScreen screen) { .contains(ElementHighlight.Kind.SELECTION), "Inline side config reads the mod caption and invokes its highlight capability"); require( - customRequests.contains(ElementHighlight.Kind.DECORATION), - "Drawer identification reaches the custom highlight capability"); + !customRequests.contains(ElementHighlight.Kind.DECORATION), + "Idle groups use background tints without persistent outlines"); assertLabel(screen, "tank_1", "Mod tank"); assertLabel(screen, "labelled_group", "Panel"); assertLabel(screen, "tank_2", "Coloured"); assertLabel(screen, "tank_3", "Plain"); + for (String id : List.of("tank_1", "tank_3")) { + var target = menu.bound.screen().find(id).orElseThrow(); + var group = automation.inventory.groups().stream() + .filter(candidate -> candidate.id().equals("tank_3")) + .findFirst().orElseThrow(); + require( + screen.presentation().groupColour(target) + .equals(Optional.of(group.colour())), + "Legacy targets respect the element's group association order for background colour"); + } + var owned = (ColouredGroupElement) menu.bound.screen() + .find("tank_2").orElseThrow(); + require( + screen.presentation().groupColour(owned.child()) + .equals(Optional.of(owned.colour())), + "Descendants inherit the wrapper colour through real screen presentation"); select(automation, "tank_1"); } case 1 -> { @@ -209,9 +225,10 @@ static boolean run(MachineScreen screen) { } case 3 -> { require( - colouredRequests.containsAll( - EnumSet.allOf(ElementHighlight.Kind.class)), - "Coloured wrapper handles decoration, emphasis and inline selection through its" + colouredRequests + .containsAll(EnumSet.of(ElementHighlight.Kind.EMPHASIS, + ElementHighlight.Kind.SELECTION)), + "Coloured wrapper handles emphasis and inline selection through its" + " contract"); capture("groups-coloured.png"); click(screen, selector); diff --git a/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStorage.java b/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStorage.java index a12779cd..6e195411 100644 --- a/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStorage.java +++ b/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStorage.java @@ -3,6 +3,7 @@ import java.util.Arrays; import java.util.function.Consumer; import java.util.function.IntFunction; +import java.util.function.IntUnaryOperator; import java.util.function.Predicate; import java.util.function.Supplier; @@ -69,10 +70,29 @@ public String slotId(int slot) { private Runnable onChange = () -> { }; private boolean bypass; + private IntUnaryOperator pendingClaims = slot -> 0; private long revision; private final String[] slotIds; private final ListTag recovery = new ListTag(); + /** + * Installs a pure pending-batch quantity projection for output slots. + * Publish changed policy state through the host's normal menu snapshots. + * Replacing it does not alter active reservations or item contents. + */ + public ItemStorage pendingClaims(IntUnaryOperator claims) { + pendingClaims = java.util.Objects.requireNonNull(claims); + markChanged(); + return this; + } + + @Override + protected int pendingTake(int slot) { + return roles[checked(slot)] == Role.OUTPUT + ? pendingClaims.applyAsInt(slot) + : 0; + } + /** * Optional stable identity for save migration; legacy saves still load by * index. @@ -245,8 +265,7 @@ public ItemStorage onChange(Runnable onChange) { /** * Sets the role of these slots. * - * @throws IndexOutOfBoundsException - * if a slot does not exist + * @throws IndexOutOfBoundsException if a slot does not exist */ public ItemStorage role(Role role, int... slots) { revision++; diff --git a/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStore.java b/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStore.java index e371f804..1b363113 100644 --- a/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStore.java +++ b/src/main/java/zone/moddev/mc/lib/api/capabilities/ItemStore.java @@ -14,6 +14,8 @@ import net.neoforged.neoforge.items.IItemHandler; import net.neoforged.neoforge.items.IItemHandlerModifiable; +import zone.moddev.mc.lib.machine.inventory.SlotPlan; + /** * Item storage access, including a combined view over independently owned * inventories. @@ -27,6 +29,21 @@ public interface ItemStore extends IItemHandlerModifiable, ReservedSlots { int localSlot(int slot); + /** Actual cycle claims, excluding external pending-batch protection. */ + default SlotPlan processingPlan(int slot) { + return storage(slot).reservationPlans().get(localSlot(slot)); + } + + default int freeForProcessing(int slot) { + return processingPlan(slot).free(getStackInSlot(slot)); + } + + default ItemStack extractForProcessing(int slot, int amount, + boolean simulate) { + return storage(slot).extractForProcessing(localSlot(slot), amount, + simulate); + } + Role role(int slot); ItemStore restrict(Predicate filter, int... slots); diff --git a/src/main/java/zone/moddev/mc/lib/api/capabilities/PlannedItemHandler.java b/src/main/java/zone/moddev/mc/lib/api/capabilities/PlannedItemHandler.java index 0312e2b7..33251430 100644 --- a/src/main/java/zone/moddev/mc/lib/api/capabilities/PlannedItemHandler.java +++ b/src/main/java/zone/moddev/mc/lib/api/capabilities/PlannedItemHandler.java @@ -14,6 +14,7 @@ public class PlannedItemHandler extends ItemStackHandler implements ReservedSlots { private final ReservationPlans plans; + private boolean processingExtraction; public PlannedItemHandler(int size) { super(size); @@ -32,7 +33,35 @@ public final ReservationPlans reservationPlans() { @Override public SlotPlan plan(int slot) { - return plans.get(slot); + var active = plans.get(slot); + int pending = Math.clamp(pendingTake(slot), 0, + active.free(getStackInSlot(slot))); + return pending == 0 + ? active + : new SlotPlan(active.take() + pending, active.add()); + } + + /** + * Additional items protected from external extraction while preparing a + * batch. Must be pure: simulation and menu snapshots call this too. + * Processing groups use the actual reservation table, not this projection. + */ + protected int pendingTake(int slot) { + return 0; + } + + /** Internal access still respects active cycles, but not pending demand. */ + public final ItemStack extractForProcessing(int slot, int amount, + boolean simulate) { + validateSlotIndex(slot); + boolean previous = processingExtraction; + processingExtraction = true; + try { + // Preserve subclass extraction limits and failure behavior. + return extractItem(slot, amount, simulate); + } finally { + processingExtraction = previous; + } } /** Replaces a plan for synchronization or restoring state. */ @@ -60,24 +89,33 @@ public int freeToTake(int slot) { @Override public int maxHeld(int slot, ItemStack stack) { - if (!hasPlan(slot)) + var active = plans.get(slot); + if (active.isNone()) return Math.min(getSlotLimit(slot), stack.getMaxStackSize()); var held = getStackInSlot(slot); - return held.getCount() - + plan(slot).room(held, stack, getSlotLimit(slot)); + return held.getCount() + active.room(held, stack, getSlotLimit(slot)); } @Override public boolean isItemValid(int slot, ItemStack stack) { - return !hasPlan(slot) - || plan(slot).accepts(getStackInSlot(slot), stack); + var active = plans.get(slot); + return active.isNone() || active.accepts(getStackInSlot(slot), stack); } @Override public ItemStack extractItem(int slot, int amount, boolean simulate) { validateSlotIndex(slot); - return super.extractItem(slot, Math.min(amount, freeToTake(slot)), - simulate); + boolean processing = processingExtraction; + // Content-change callbacks still observe normal external protection. + processingExtraction = false; + try { + int free = processing + ? plans.get(slot).free(getStackInSlot(slot)) + : freeToTake(slot); + return super.extractItem(slot, Math.min(amount, free), simulate); + } finally { + processingExtraction = processing; + } } @Override diff --git a/src/main/java/zone/moddev/mc/lib/client/jei/PresentedRecipeCategory.java b/src/main/java/zone/moddev/mc/lib/client/jei/PresentedRecipeCategory.java new file mode 100644 index 00000000..4820b200 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/client/jei/PresentedRecipeCategory.java @@ -0,0 +1,61 @@ +package zone.moddev.mc.lib.client.jei; + +import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; +import mezz.jei.api.gui.drawable.IDrawable; +import mezz.jei.api.gui.ingredient.IRecipeSlotsView; +import mezz.jei.api.gui.widgets.IRecipeExtrasBuilder; +import mezz.jei.api.neoforge.NeoForgeTypes; +import mezz.jei.api.recipe.IFocusGroup; +import mezz.jei.api.recipe.RecipeIngredientRole; +import mezz.jei.api.recipe.RecipeType; +import mezz.jei.api.recipe.category.AbstractRecipeCategory; + +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; + +import zone.moddev.mc.lib.gui.client.recipe.RecipePresentation; + +/** Optional JEI adapter for the same presentations used by recipe drawers. */ +public abstract class PresentedRecipeCategory + extends + AbstractRecipeCategory { + protected PresentedRecipeCategory(RecipeType type, Component title, + IDrawable icon, int width, int height) { + super(type, title, icon, width, height); + } + + public abstract RecipePresentation presentation(T recipe); + + private static RecipeIngredientRole role(RecipePresentation.Role role) { + return RecipeIngredientRole.valueOf(role.name()); + } + + @Override + public void setRecipe(IRecipeLayoutBuilder builder, T recipe, + IFocusGroup focuses) { + var view = presentation(recipe); + for (var item : view.items()) + builder.addSlot(role(item.role()), item.x(), item.y()) + .addItemStack(item.stack()).addRichTooltipCallback( + (slot, tooltip) -> item.tooltip().forEach(tooltip::add)); + for (var fluid : view.fluids()) + builder.addInvisibleIngredients(role(fluid.role())) + .addIngredient(NeoForgeTypes.FLUID_STACK, fluid.stack()); + } + + @Override + public void draw(T recipe, IRecipeSlotsView slots, GuiGraphics graphics, + double x, double y) { + presentation(recipe).drawBackground(graphics); + } + + @Override + public void createRecipeExtras(IRecipeExtrasBuilder builder, T recipe, + IFocusGroup focuses) { + for (var tooltip : presentation(recipe).tooltips()) { + var r = tooltip.bounds(); + builder.addTooltipArea(r.x(), r.y(), r.width(), r.height()) + .setTooltip(tooltip.lines()); + } + } +} 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 d747e908..3636c71b 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 @@ -82,9 +82,7 @@ private static List> declarations() { .renderer((element, c) -> SpriteRenderer .draw(element.spriteElement(), c)), ElementClient.of(COLOURED_GROUP).renderer((element, c) -> { - }).overlay((element, c) -> ColouredGroupRenderer.draw(element, - c.graphics(), c.bounds(), false)) - .behavior(ColouredGroupBehavior::new), + }).behavior(ColouredGroupBehavior::new), ElementClient.of(BOX).renderer((element, c) -> { }), ElementClient.of(SPACER).renderer((element, c) -> { }), ElementClient.of(INVENTORY_CONTROLS).renderer((element, c) -> { @@ -125,19 +123,20 @@ private static List> declarations() { ElementClient.of(SLOT) .renderer((element, c) -> slots.draw(c.graphics(), c.bounds(), element, c.access().contents(element), - c.access().hint(element))) + c.access().hint(element), c.access().groupColour(element))) .behavior(SlotBehavior::new), ElementClient.of(GAUGE) .renderer((element, c) -> GaugeRenderer.draw(c.graphics(), c.bounds(), element.orientation(), element.fill(c.value()), - c.ratio())), + c.ratio(), c.access().groupColour(element))), ElementClient.of(FLUID_TANK) .renderer((element, c) -> GaugeRenderer.draw(c.graphics(), c.bounds(), element.orientation(), element.fill(c.value()), - c.ratio())), + c.ratio(), c.access().groupColour(element))), ElementClient.of(ENERGY_GAUGE) .renderer((element, c) -> EnergyGaugeRenderer.draw(c.graphics(), - c.bounds(), element, c.ratio())), + c.bounds(), element, c.ratio(), + c.access().groupColour(element))), ElementClient.of(METER).renderer(MeterRenderer::draw), ElementClient.of(SIDE_CONFIG).renderer(SideConfigRenderer::draw) .renderer(ElementRenderers.Pass.OVERLAY, diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ColouredGroupBehavior.java b/src/main/java/zone/moddev/mc/lib/gui/client/ColouredGroupBehavior.java index 5f14c0f4..eba628b8 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ColouredGroupBehavior.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ColouredGroupBehavior.java @@ -9,7 +9,7 @@ * The wrapper owns its existing outline and how external controls emphasize it. */ public class ColouredGroupBehavior extends DefaultElementBehavior - implements HighlightPresentation { + implements HighlightPresentation, GroupColourProvider { private final ColouredGroupElement group; public ColouredGroupBehavior(ColouredGroupElement group, @@ -18,10 +18,13 @@ public ColouredGroupBehavior(ColouredGroupElement group, this.group = group; } + public int groupColour() { + return group.colour(); + } + public void highlight(GuiGraphics graphics, Rect bounds, ElementHighlight request) { - // Its registered overlay renderer already supplies the persistent - // decoration. + // Backgrounds identify the group; outlines are reserved for emphasis. if (request.kind() == ElementHighlight.Kind.DECORATION) return; if (request.kind() == ElementHighlight.Kind.EMPHASIS) diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ContainerCellRenderer.java b/src/main/java/zone/moddev/mc/lib/gui/client/ContainerCellRenderer.java index 804e1d06..82be5437 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ContainerCellRenderer.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ContainerCellRenderer.java @@ -42,7 +42,8 @@ static void slot(ContainerSlotElement element, ElementRenderers.Context c) { return; } var contents = c.access().contents(element); - SLOTS.draw(g, b, element, contents, c.access().hint(element)); + SLOTS.draw(g, b, element, contents, c.access().hint(element), + c.access().groupColour(element)); int[] xy = element.itemPosition(b); var original = new Rect(xy[0], xy[1], 16, 16); var item = element.nativeBounds(original); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java index 33dcee78..16eeb072 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/Drawer.java @@ -104,6 +104,12 @@ public java.util.Optional presentation(Class type) { return java.util.Optional.empty(); } + /** Optional resource-group colour for an element on the host screen. */ + public java.util.Optional groupColour( + zone.moddev.mc.lib.gui.model.Element element) { + return java.util.Optional.empty(); + } + public abstract void close(); /** Close purely local presentation when a server-owned drawer is opened. */ @@ -163,6 +169,17 @@ public void renderTab(GuiGraphics graphics) { public void render(GuiGraphics graphics, int mouseX, int mouseY) { } + /** Content that may cover the main panel, drawn above its native slots. */ + public void renderForeground(GuiGraphics graphics, int mouseX, int mouseY) { + } + + /** + * Prevent underlying machine controls and slots from claiming hover/input. + */ + public boolean covers(double x, double y) { + return false; + } + public void tooltip(GuiGraphics graphics, int mouseX, int mouseY) { } diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/DrawerOpener.java b/src/main/java/zone/moddev/mc/lib/gui/client/DrawerOpener.java new file mode 100644 index 00000000..079ad503 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/client/DrawerOpener.java @@ -0,0 +1,9 @@ +package zone.moddev.mc.lib.gui.client; + +/** + * Behavior service for opening a declared drawer without exposing the screen. + */ +@FunctionalInterface +public interface DrawerOpener { + boolean open(String id); +} diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/Drawers.java b/src/main/java/zone/moddev/mc/lib/gui/client/Drawers.java index c48da79f..7a6e943e 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/Drawers.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/Drawers.java @@ -47,6 +47,28 @@ public List entries() { return List.copyOf(entries); } + /** + * Opens a declared, available drawer through its normal + * restoration/arbitration path. + */ + public boolean open(String id) { + for (var drawer : entries) + if (drawer.id().equals(id) && drawer.available() + && !pending(drawer.edge())) { + userInput(); + if (!drawer.restore(drawer.selection())) + return false; + remember(drawer, true, drawer.selection()); + return true; + } + return false; + } + + public Optional groupColour(Element element) { + return entries.stream().map(drawer -> drawer.groupColour(element)) + .flatMap(Optional::stream).findFirst(); + } + public Optional presentation(Element element, Class type) { var drawer = elements.get(element); return drawer == null ? Optional.empty() : drawer.presentation(type); @@ -109,6 +131,14 @@ public void render(GuiGraphics graphics, int x, int y) { entries.forEach(d -> d.render(graphics, x, y)); } + public void renderForeground(GuiGraphics graphics, int x, int y) { + entries.forEach(d -> d.renderForeground(graphics, x, y)); + } + + public boolean covers(double x, double y) { + return entries.stream().anyMatch(d -> d.covers(x, y)); + } + /** * Navigation tabs stay visible above every drawer body, including XML * foreground popouts. diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ElementDrawing.java b/src/main/java/zone/moddev/mc/lib/gui/client/ElementDrawing.java index c97a5fef..62a9a940 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ElementDrawing.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ElementDrawing.java @@ -17,6 +17,21 @@ public final class ElementDrawing { private ElementDrawing() { } + /** Multiply the existing shading by a 40% group-colour wash. */ + public static int backgroundTint(int tint, + java.util.Optional groupColour) { + if (groupColour.isEmpty()) + return tint; + int colour = groupColour.get(); + int result = 0; + for (int shift = 0; shift <= 16; shift += 8) { + int base = tint >> shift & 255; + int channel = colour >> shift & 255; + result |= (base * (765 + 2 * channel) / 1275) << shift; + } + return result; + } + public static void blit(GuiGraphics g, ResourceLocation icon, int x, int y, int width, int height) { RenderSystem.enableBlend(); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/ElementHighlight.java b/src/main/java/zone/moddev/mc/lib/gui/client/ElementHighlight.java index 193a9631..790b2599 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/ElementHighlight.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/ElementHighlight.java @@ -33,15 +33,15 @@ public enum Kind { } public static ElementHighlight decoration(int colour) { - return new ElementHighlight(Kind.DECORATION, colour, 0); + return new ElementHighlight(Kind.DECORATION, colour, 2); } public static ElementHighlight emphasis(int colour) { - return new ElementHighlight(Kind.EMPHASIS, colour, 1); + return new ElementHighlight(Kind.EMPHASIS, colour, 2); } public static ElementHighlight selection(int colour) { - return new ElementHighlight(Kind.SELECTION, colour, 0); + return new ElementHighlight(Kind.SELECTION, colour, 2); } public Rect outline(Rect bounds) { 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 b2f1d2a7..1d33634e 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 @@ -25,6 +25,7 @@ public class ElementInput { private final Predicate visible; private final Function bounds; private final BiPredicate hitArea; + private final BiPredicate overlayHitArea; private final BiConsumer hoverListener; private E focused, captured, hovered; private double mouseX, mouseY; @@ -43,10 +44,25 @@ public ElementInput(List elements, Function factory, Predicate visible, Function bounds, BiPredicate hitArea, BiConsumer hoverListener) { + this(elements, factory, visible, bounds, hitArea, hitArea, + hoverListener); + } + + /** + * Separate hit regions let foreground overlays receive input above a + * surface that occludes ordinary controls. Both regions include the host's + * viewport constraints. + */ + public ElementInput(List elements, Function factory, + Predicate visible, Function bounds, + BiPredicate hitArea, + BiPredicate overlayHitArea, + BiConsumer hoverListener) { order = List.copyOf(elements); this.visible = visible; this.bounds = bounds; this.hitArea = Objects.requireNonNull(hitArea); + this.overlayHitArea = Objects.requireNonNull(overlayHitArea); this.hoverListener = Objects.requireNonNull(hoverListener); for (var element : order) instances.put(element, @@ -106,7 +122,7 @@ private void refreshHover() { public E hit(double x, double y) { var overlay = overlayOwner(); if (overlay != null) - return hitArea.test(x, y) + return overlayHitArea.test(x, y) && (bounds.apply(overlay).contains(x, y) || instances .get(overlay).overlayBounds().orElseThrow().contains(x, y)) ? overlay 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 42da5483..7663d460 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 @@ -62,6 +62,28 @@ default Optional capability(Element element, Class type) { return Optional.empty(); } + /** Direct host-owned resource association, without ancestor inheritance. */ + default Optional associatedGroupColour(Element element) { + return Optional.empty(); + } + + /** + * Nearest group wins; an element-owned colour precedes its host + * association. + */ + default Optional groupColour(Element element) { + for (Element current = element; current != null; current = parent( + current).orElse(null)) { + var colour = capability(current, GroupColourProvider.class) + .map(GroupColourProvider::groupColour); + if (colour.isEmpty()) + colour = associatedGroupColour(current); + if (colour.isPresent()) + return colour; + } + return Optional.empty(); + } + /** * A registered group caption, or the ordinary tooltip for elements without * that capability. diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/EnergyGaugeRenderer.java b/src/main/java/zone/moddev/mc/lib/gui/client/EnergyGaugeRenderer.java index 3a03e69e..987a9b99 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/EnergyGaugeRenderer.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/EnergyGaugeRenderer.java @@ -21,9 +21,14 @@ private EnergyGaugeRenderer() { static void draw(GuiGraphics g, Rect r, EnergyGaugeElement gauge, double ratio) { + draw(g, r, gauge, ratio, java.util.Optional.empty()); + } + + static void draw(GuiGraphics g, Rect r, EnergyGaugeElement gauge, + double ratio, java.util.Optional groupColour) { boolean vertical = gauge.orientation() == Orientation.VERTICAL; int length = vertical ? r.height() : r.width(); - GaugeRenderer.background(g, r, vertical); + GaugeRenderer.background(g, r, vertical, groupColour); int inside = length - 4; // Clip the last charged bar to the actual level, keeping empty and full diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/FilterSamplesBehavior.java b/src/main/java/zone/moddev/mc/lib/gui/client/FilterSamplesBehavior.java index 80e853ef..e70d4180 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/FilterSamplesBehavior.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/FilterSamplesBehavior.java @@ -45,6 +45,6 @@ static void render(FilterControl.Samples element, RENDERER.draw(c.graphics(), element.sampleBounds(r, i), element.sampleSlot(i), element .sampleDisplay(FilterDrawing.configuration(c.value()), i), - ItemStack.EMPTY); + ItemStack.EMPTY, c.access().groupColour(element)); } } 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 1e2003bf..6dd571be 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 @@ -32,10 +32,16 @@ private GaugeRenderer() { * gauges. */ static void background(GuiGraphics g, Rect r, boolean vertical) { + background(g, r, vertical, java.util.Optional.empty()); + } + + static void background(GuiGraphics g, Rect r, boolean vertical, + java.util.Optional groupColour) { var state = RenderState.capture(); try { int length = vertical ? r.height() : r.width(); - shell(g, r, vertical, length, "body"); + shell(g, r, vertical, length, "body", 1, + ElementDrawing.backgroundTint(0xffffff, groupColour)); } finally { try { g.flush(); @@ -47,11 +53,16 @@ static void background(GuiGraphics g, Rect r, boolean vertical) { static void draw(GuiGraphics g, Rect r, Orientation orientation, GaugeFill fill, double ratio) { + draw(g, r, orientation, fill, ratio, java.util.Optional.empty()); + } + + static void draw(GuiGraphics g, Rect r, Orientation orientation, + GaugeFill fill, double ratio, java.util.Optional groupColour) { var state = RenderState.capture(); try { g.flush(); g.setColor(1, 1, 1, 1); - drawGauge(g, r, orientation, fill, ratio); + drawGauge(g, r, orientation, fill, ratio, groupColour); } finally { try { g.flush(); @@ -62,10 +73,12 @@ static void draw(GuiGraphics g, Rect r, Orientation orientation, } private static void drawGauge(GuiGraphics g, Rect r, - Orientation orientation, GaugeFill fill, double ratio) { + Orientation orientation, GaugeFill fill, double ratio, + java.util.Optional groupColour) { boolean vertical = orientation == Orientation.VERTICAL; int length = vertical ? r.height() : r.width(); - shell(g, r, vertical, length, "body"); + 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 @@ -86,8 +99,22 @@ private static void drawGauge(GuiGraphics g, Rect r, g.fill(strip.x(), strip.y(), strip.right(), strip.bottom(), 0x4dffffff); } - // Keep the shared empty background flat. Only the contents get curved + // Continue the same curvature above the fluid with a softer reflection. + // Clip the two strengths separately so filled pixels keep their // lighting. + if (filled < length - 2) { + if (vertical) + g.enableScissor(r.x(), r.y(), r.right(), + r.bottom() - 1 - filled); + else + g.enableScissor(r.x() + 1 + filled, r.y(), r.right(), + r.bottom()); + try { + shell(g, r, vertical, length, "glass", .35f); + } finally { + g.disableScissor(); + } + } if (filled > 0) { if (vertical) g.enableScissor(r.x(), r.bottom() - 1 - filled, r.right(), @@ -119,12 +146,23 @@ private static void drawGauge(GuiGraphics g, Rect r, private static void shell(GuiGraphics g, Rect r, boolean vertical, int length, String layer) { + shell(g, r, vertical, length, layer, 1); + } + + private static void shell(GuiGraphics g, Rect r, boolean vertical, + int length, String layer, float alpha) { + shell(g, r, vertical, length, layer, alpha, 0xffffff); + } + + private static void shell(GuiGraphics g, Rect r, boolean vertical, + int length, String layer, float alpha, int tint) { // GuiGraphics fills may be buffered, and flushing them can disable // blending. // Drain them before configuring the immediate texture draws (especially // translucent glass). g.flush(); - g.setColor(1, 1, 1, 1); + g.setColor((tint >> 16 & 255) / 255f, (tint >> 8 & 255) / 255f, + (tint & 255) / 255f, alpha); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); g.pose().pushPose(); @@ -153,6 +191,7 @@ private static void shell(GuiGraphics g, Rect r, boolean vertical, } finally { g.pose().popPose(); RenderSystem.disableBlend(); + g.setColor(1, 1, 1, 1); } } diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/GroupColourProvider.java b/src/main/java/zone/moddev/mc/lib/gui/client/GroupColourProvider.java new file mode 100644 index 00000000..2c55ce86 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/client/GroupColourProvider.java @@ -0,0 +1,6 @@ +package zone.moddev.mc.lib.gui.client; + +/** Optional group colour inherited by descendant slot backgrounds. */ +public interface GroupColourProvider { + int groupColour(); +} 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 edbb367f..ff31ebb1 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 @@ -59,6 +59,10 @@ public Optional parent(Element element) { return Optional.ofNullable(renderParents.get(element)); } + public Optional associatedGroupColour(Element element) { + return drawers.groupColour(element); + } + public Object value(Element element, boolean maximum) { return menu.value(element, maximum); } @@ -180,6 +184,9 @@ public ElementRenderAccess presentation() { } public java.util.Optional service(Class type) { + if (type == DrawerOpener.class) + return java.util.Optional + .of(type.cast((DrawerOpener) drawers::open)); return type == EntityPreviewPolicies.class && menu.blockEntity instanceof zone.moddev.mc.lib.gui.runtime.ScreenHost host ? java.util.Optional.of( @@ -221,6 +228,8 @@ public boolean showRecipes() { return recipes.test(MachineScreen.this, element); } }), this::visible, this::bounds, + (x, y) -> renderAccess.viewport().contains(x, y) + && !drawers.covers(x, y), (x, y) -> renderAccess.viewport().contains(x, y), (element, entered) -> ElementHover.dispatch(menu, element, entered)); } @@ -369,14 +378,29 @@ public void render(GuiGraphics g, int mx, int my, float partial) { ElementHover.preview(elementInput.hovered(), renderAccess, e -> draw(g, e, bounds(e), mx, my, partial)); renderElements(ElementRenderers.Pass.FOREGROUND, g, partial, mx, my); + g.pose().pushPose(); + g.pose().translate(0, 0, 200); + drawers.renderForeground(g, mx, my); + g.pose().translate(0, 0, 10); drawers.renderTabs(g); + // XML tabs use the TOP pass; keep them above foreground drawer rails + // too. renderElements(ElementRenderers.Pass.TOP, g, partial, mx, my); - if (elementInput.overlayOwner() == null) - renderTooltip(g, mx, my); - if (elementInput.hovered() != null) - tooltip(g, elementInput.hovered(), mx, my); - if (elementInput.overlayOwner() == null) - drawers.tooltip(g, mx, my); + g.pose().popPose(); + g.pose().pushPose(); + // Item decorations add 200 to the drawer's 200; tooltips must clear + // that layer. + g.pose().translate(0, 0, 200); + try { + if (elementInput.overlayOwner() == null && !drawers.covers(mx, my)) + renderTooltip(g, mx, my); + if (elementInput.hovered() != null) + tooltip(g, elementInput.hovered(), mx, my); + if (elementInput.overlayOwner() == null) + drawers.tooltip(g, mx, my); + } finally { + g.pose().popPose(); + } } private void tooltip(GuiGraphics g, Element e, int mx, int my) { @@ -589,6 +613,8 @@ public net.minecraft.world.inventory.Slot nativeSlotAt(double x, double y, @Override protected boolean isHovering(int x, int y, int w, int h, double mx, double my) { + if (drawers.covers(mx, my)) + return false; var bounds = nativeSlots.hitBounds(menu.nativeSlots(), x, y, w, h); return super.isHovering(bounds.x(), bounds.y(), bounds.width(), bounds.height(), mx, my); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java index 9e7aac43..a6cd56d1 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/SideConfigDrawer.java @@ -3,6 +3,7 @@ import static zone.moddev.mc.lib.api.automation.AutomationInventory.COLUMNS; import java.util.ArrayList; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -22,6 +23,7 @@ import zone.moddev.mc.lib.gui.layout.GroupOrder; import zone.moddev.mc.lib.gui.layout.Rect; import zone.moddev.mc.lib.gui.layout.SideDrawerLayout; +import zone.moddev.mc.lib.gui.model.Element; import zone.moddev.mc.lib.gui.model.ElementGroup; import zone.moddev.mc.lib.gui.model.containers.PlayerInventoryElement; import zone.moddev.mc.lib.gui.runtime.AutomationMenu; @@ -44,6 +46,7 @@ public final class SideConfigDrawer extends Drawer { private final ColourButtonBar colourBar; private final List displayOrder; private final Map> groupHighlights; + private final Map groupColours = new IdentityHashMap<>(); private String editorKey = ""; private FilterControl root; private ElementFragment editor; @@ -70,6 +73,11 @@ public SideConfigDrawer(MachineScreen screen, indices.put(groups.get(i).id(), i); var definitionModel = screen.getMenu().bound.screen(); groupHighlights = GroupHighlights.of(definitionModel, associations); + for (var element : definitionModel.elements()) + element.associatedGroups(definitionModel, associations).stream() + .filter(indices::containsKey).findFirst() + .ifPresent(id -> groupColours.put(element, + groups.get(indices.get(id)).colour())); displayOrder = GroupOrder.of(definitionModel, associations.stream().map(ElementGroup::id).toList(), element -> element.associatedGroups(definitionModel, associations)) @@ -95,6 +103,11 @@ else if (kind.equals("select")) { return true; } + @Override + public Optional groupColour(Element element) { + return Optional.ofNullable(groupColours.get(element)); + } + private Rect panel() { return screen.panelBounds(); } @@ -365,12 +378,6 @@ public void render(GuiGraphics g, int mx, int my) { tooltip = null; faceTooltip = List.of(); drawFrame(g, tab, body, model.open()); - for (int index = 0; index < count(); index++) { - var group = model.inventory.group(index); - for (var element : groupHighlights.get(group.id())) - screen.presentation().highlight(g, element, - ElementHighlight.decoration(0xff000000 | group.colour())); - } if (tab.contains(mx, my)) tooltip = Component.translatable("screen.mmdlib.automation.open"); int hoveredGroup = colourBar.render(g, mx, my, model.open()).orElse(-1); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/SideDrawerRenderer.java b/src/main/java/zone/moddev/mc/lib/gui/client/SideDrawerRenderer.java index 69a88b23..0f4f8186 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/SideDrawerRenderer.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/SideDrawerRenderer.java @@ -35,11 +35,18 @@ public static void tab(GuiGraphics graphics, Rect tab, int color) { sprite(graphics, TAB, tab, color); } + /** + * A detached panel, also suitable for drawers overlapping their host at + * narrow GUI widths. + */ + public static void panel(GuiGraphics graphics, Rect body, int color) { + sprite(graphics, PANEL, body, color); + } + public static void open(GuiGraphics graphics, Rect tab, Rect body, Edge edge, int color) { - int x = Math.min(tab.x(), body.x()); - var whole = new Rect(x, body.y(), body.width() + tab.width(), - body.height()); + var whole = zone.moddev.mc.lib.gui.layout.SideDrawerLayout.frame(tab, + body); sprite(graphics, PANEL, whole, color); // The narrow, darker rail retains the active icon beside the main // machine panel. @@ -47,7 +54,7 @@ public static void open(GuiGraphics graphics, Rect tab, Rect body, | (((color & 0xfefefe) >> 1) + ((color & 0xfcfcfc) >> 2)); graphics.fill(tab.x() + 2, body.y() + 2, tab.right() - 2, body.bottom() - 2, rail); - int seam = edge == Edge.LEFT ? tab.x() : tab.right() - 1; + int seam = body.x() >= tab.right() ? tab.right() - 1 : tab.x(); graphics.fill(seam, body.y() + 2, seam + 1, body.bottom() - 2, 0xff000000 | ((color & 0xfefefe) >> 1)); tab(graphics, tab, color); diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/SlotRenderer.java b/src/main/java/zone/moddev/mc/lib/gui/client/SlotRenderer.java index 80140293..5aaa5002 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/client/SlotRenderer.java +++ b/src/main/java/zone/moddev/mc/lib/gui/client/SlotRenderer.java @@ -1,5 +1,7 @@ package zone.moddev.mc.lib.gui.client; +import java.util.Optional; + import net.minecraft.client.gui.GuiGraphics; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; @@ -15,10 +17,11 @@ final class SlotRenderer { private final GhostItems ghosts = new GhostItems(); void draw(GuiGraphics graphics, Rect bounds, SlotElement element, - ItemStack contents, ItemStack hint) { + ItemStack contents, ItemStack hint, Optional groupColour) { int[] item = element.itemPosition(bounds); element.render(new SlotElement.Painter() { public void background(ResourceLocation sprite, int tint) { + tint = ElementDrawing.backgroundTint(tint, groupColour); graphics.setColor((tint >> 16 & 255) / 255f, (tint >> 8 & 255) / 255f, (tint & 255) / 255f, 1); graphics.blitSprite(sprite, bounds.x(), bounds.y(), @@ -47,4 +50,5 @@ public void ghost(ItemStack stack, float alpha) { } }, contents, hint); } + } diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeCatalog.java b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeCatalog.java new file mode 100644 index 00000000..c4a8b4c8 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeCatalog.java @@ -0,0 +1,35 @@ +package zone.moddev.mc.lib.gui.client.recipe; + +import java.util.List; + +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; + +/** + * Client recipe choices. Selection implementations must submit a + * server-validated action. + */ +public interface RecipeCatalog { + record Choice(String key, RecipePresentation presentation) { + } + record Group(String key, Component title, ItemStack icon, + List choices) { + public Group { + icon = icon.copy(); + choices = List.copyOf(choices); + } + } + + /** Return a stable immutable list until the recipe catalog changes. */ + List groups(); + + /** Initial group when the drawer has no remembered selection. */ + default String initialGroup() { + return ""; + } + + /** + * True only if selection was submitted; the server remains authoritative. + */ + boolean select(Group group, Choice choice); +} diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java new file mode 100644 index 00000000..492e02a7 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipeDrawer.java @@ -0,0 +1,275 @@ +package zone.moddev.mc.lib.gui.client.recipe; + +import java.util.List; +import java.util.Objects; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +import zone.moddev.mc.lib.gui.client.Drawer; +import zone.moddev.mc.lib.gui.client.IconSprite; +import zone.moddev.mc.lib.gui.client.MachineScreen; +import zone.moddev.mc.lib.gui.drawer.DrawerDefinition; +import zone.moddev.mc.lib.gui.layout.Rect; +import zone.moddev.mc.lib.gui.layout.SideDrawerLayout; + +/** + * Native-scale paged recipe drawer; has no JEI dependency or machine-specific + * policy. + */ +public final class RecipeDrawer extends Drawer { + private final RecipeCatalog catalog; + private boolean open; + private String groupKey = ""; + private int page; + private RecipeCatalog.Group group; + private List groups = List.of(); + private Rect body = new Rect(0, 0, 0, 0); + private int rowHeight = 24, pageSize = 1; + + public RecipeDrawer(MachineScreen screen, DrawerDefinition definition, + RecipeCatalog catalog) { + super(screen, definition, IconSprite.gui( + ResourceLocation.fromNamespaceAndPath("mmdlib", "icon_recipes")), + 0x96b9a5); + this.catalog = Objects.requireNonNull(catalog); + } + + public boolean open() { + return open; + } + public void close() { + open = false; + } + public void closeLocal() { + close(); + } + public Selection selection() { + return new Selection(groupKey, page); + } + + public boolean restore(Selection selection) { + if (screen.drawers().pending(edge())) + return false; + groupKey = selection.key().isEmpty() + ? catalog.initialGroup() + : selection.key(); + page = selection.offset(); + openLocal(); + open = true; + layout(); + return true; + } + + private void layout() { + groups = catalog.groups(); + group = groups.stream().filter(g -> g.key().equals(groupKey)) + .findFirst().orElse(groups.isEmpty() ? null : groups.getFirst()); + String next = group == null ? "" : group.key(); + if (!next.equals(groupKey)) + page = 0; + groupKey = next; + int width = 160; + rowHeight = 24; + if (group != null) + for (var choice : group.choices()) { + width = Math.max(width, choice.presentation().width()); + rowHeight = Math.max(rowHeight, choice.presentation().height()); + } + body = zone.moddev.mc.lib.gui.layout.RecipeDrawerLayout.body(edge(), + tabBounds(), screen.panelBounds(), screen.width, + screen.drawerBottom(), width, rowHeight); + pageSize = zone.moddev.mc.lib.gui.layout.RecipeDrawerLayout + .pageSize(body, rowHeight); + page = Math.clamp(page, 0, pages() - 1); + } + + private int pages() { + return Math.max(1, + Math.ceilDiv(group == null ? 0 : group.choices().size(), pageSize)); + } + public Rect bodyBounds() { + layout(); + return body; + } + public List visibleRecipes() { + layout(); + if (group == null) + return List.of(); + int start = page * pageSize; + return group.choices().subList(start, + Math.min(group.choices().size(), start + pageSize)); + } + + private Rect previousGroup() { + return new Rect(body.x() + 5, body.y() + 4, 16, 18); + } + private Rect nextGroup() { + return new Rect(body.right() - 21, body.y() + 4, 16, 18); + } + private Rect previousPage() { + return new Rect(body.x() + 5, body.bottom() - 20, 16, 16); + } + private Rect nextPage() { + return new Rect(body.right() - 21, body.bottom() - 20, 16, 16); + } + private Rect content() { + return zone.moddev.mc.lib.gui.layout.RecipeDrawerLayout.content(body); + } + + public void renderForeground(GuiGraphics g, int mx, int my) { + if (!open) + return; + var choices = visibleRecipes(); + drawFrame(g, tabBounds(), body, true); + var font = Minecraft.getInstance().font; + g.enableScissor(body.x() + 4, body.y() + 4, body.right() - 4, + body.bottom() - 4); + try { + if (group != null) { + g.renderItem(group.icon(), body.x() + 24, body.y() + 5); + g.drawString(font, + font.plainSubstrByWidth(group.title().getString(), + Math.max(0, body.width() - 68)), + body.x() + 44, body.y() + 9, 0xff263e35, false); + } + arrow(g, previousGroup(), "<", groups.size() > 1); + arrow(g, nextGroup(), ">", groups.size() > 1); + arrow(g, previousPage(), "<", page > 0); + arrow(g, nextPage(), ">", page + 1 < pages()); + var label = Component.translatable("screen.mmdlib.recipes.page", + page + 1, pages()); + g.drawString(font, label, + body.x() + (body.width() - font.width(label)) / 2, + body.bottom() - 16, 0xff263e35, false); + var content = content(); + g.enableScissor(content.x(), content.y(), content.right(), + content.bottom()); + try { + if (choices.isEmpty()) + g.drawString(font, + Component.translatable("screen.mmdlib.recipes.empty"), + content.x(), content.y(), 0xff555555, false); + for (int i = 0; i < choices.size(); i++) { + var row = new Rect(content.x(), content.y() + i * rowHeight, + content.width(), rowHeight); + if (row.contains(mx, my)) + g.fill(row.x(), row.y(), row.right(), row.bottom(), + 0x3058bd98); + g.pose().pushPose(); + try { + g.pose().translate(row.x(), row.y(), 0); + choices.get(i).presentation().draw(g); + } finally { + g.pose().popPose(); + } + } + } finally { + g.disableScissor(); + } + } finally { + g.disableScissor(); + } + } + + private static void arrow(GuiGraphics g, Rect r, String text, + boolean enabled) { + g.drawString(Minecraft.getInstance().font, text, r.x() + 5, r.y() + 4, + enabled ? 0xff263e35 : 0xff999999, false); + } + + public List exclusions() { + if (!open) + return List.of(tabBounds()); + layout(); + return List.of(tabBounds(), body, + SideDrawerLayout.rail(tabBounds(), body)); + } + public boolean contains(double x, double y) { + if (!open) + return tabContains(x, y); + layout(); + return tabContains(x, y) || body.contains(x, y) + || SideDrawerLayout.rail(tabBounds(), body).contains(x, y) + && !otherTab(x, y); + } + public boolean covers(double x, double y) { + if (!open) + return false; + layout(); + return body.contains(x, y) + || SideDrawerLayout.rail(tabBounds(), body).contains(x, y); + } + public boolean click(double x, double y, int button) { + if (!contains(x, y)) + return false; + if (button != 0) + return true; + if (tabContains(x, y)) { + if (open) + close(); + else + restore(selection()); + } else if (open) { + if (previousGroup().contains(x, y)) + changeGroup(-1); + else if (nextGroup().contains(x, y)) + changeGroup(1); + else if (previousPage().contains(x, y)) + page = Math.max(0, page - 1); + else if (nextPage().contains(x, y)) + page = Math.min(pages() - 1, page + 1); + else if (content().contains(x, y)) { + var choices = visibleRecipes(); + int row = (int) (y - content().y()) / rowHeight; + if (row < choices.size() + && catalog.select(group, choices.get(row))) + close(); + } + } + remember(open, selection()); + return true; + } + private void changeGroup(int delta) { + if (groups.isEmpty()) + return; + groupKey = groups + .get(Math.floorMod(groups.indexOf(group) + delta, groups.size())) + .key(); + page = 0; + } + public boolean scroll(double x, double y, double amount) { + if (!open) + return false; + layout(); + if (!open || !body.contains(x, y)) + return false; + page = Math.clamp(page + (amount > 0 ? -1 : amount < 0 ? 1 : 0), 0, + pages() - 1); + remember(true, selection()); + return true; + } + public void tooltip(GuiGraphics g, int x, int y) { + if (open) + layout(); + List lines = List.of(); + if (tabContains(x, y)) + lines = List + .of(Component.translatable("screen.mmdlib.recipes.title")); + else if (open && content().contains(x, y)) { + var choices = visibleRecipes(); + int row = (y - content().y()) / rowHeight; + if (row < choices.size()) + lines = choices.get(row).presentation().tooltip( + x - content().x(), y - content().y() - row * rowHeight); + } else if (open + && (previousGroup().contains(x, y) || nextGroup().contains(x, y))) { + lines = List + .of(Component.translatable("screen.mmdlib.recipes.group")); + } + if (!lines.isEmpty()) + g.renderComponentTooltip(Minecraft.getInstance().font, lines, x, y); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipePresentation.java b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipePresentation.java new file mode 100644 index 00000000..2e17e30b --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/client/recipe/RecipePresentation.java @@ -0,0 +1,83 @@ +package zone.moddev.mc.lib.gui.client.recipe; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; + +import net.neoforged.neoforge.fluids.FluidStack; + +import zone.moddev.mc.lib.gui.layout.Rect; + +/** + * Viewer-independent recipe drawing. JEI supplies native ingredient slots; + * drawers draw them here. + */ +public interface RecipePresentation { + enum Role { + INPUT, OUTPUT, CATALYST, RENDER_ONLY + } + + record Item(int x, int y, ItemStack stack, Role role, + List tooltip) { + public Item { + stack = stack.copy(); + tooltip = List.copyOf(tooltip); + } + } + + /** + * Searchable fluids, including catalysts; their custom drawing belongs to + * the background. + */ + record Fluid(FluidStack stack, Role role) { + public Fluid { + stack = stack.copy(); + } + } + + record Tooltip(Rect bounds, List lines) { + public Tooltip { + lines = List.copyOf(lines); + } + } + + int width(); + int height(); + List items(); + default List fluids() { + return List.of(); + } + default List tooltips() { + return List.of(); + } + + /** Coordinates are local to this presentation; excludes item rendering. */ + void drawBackground(GuiGraphics graphics); + + default void draw(GuiGraphics graphics) { + drawBackground(graphics); + for (var item : items()) { + graphics.renderItem(item.stack(), item.x(), item.y()); + graphics.renderItemDecorations(Minecraft.getInstance().font, + item.stack(), item.x(), item.y()); + } + } + + default List tooltip(double x, double y) { + for (var area : tooltips()) + if (area.bounds().contains(x, y)) + return area.lines(); + for (var item : items()) + if (new Rect(item.x(), item.y(), 16, 16).contains(x, y)) { + var lines = new ArrayList(); + lines.add(item.stack().getHoverName()); + lines.addAll(item.tooltip()); + return List.copyOf(lines); + } + return List.of(); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java b/src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java new file mode 100644 index 00000000..5a043498 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/gui/layout/RecipeDrawerLayout.java @@ -0,0 +1,49 @@ +package zone.moddev.mc.lib.gui.layout; + +import zone.moddev.mc.lib.gui.model.Edge; + +/** + * Keeps complete recipe rows at native scale, overlapping the host when the + * side margin is narrow. + */ +public final class RecipeDrawerLayout { + public static final int HEADER = 24, FOOTER = 22, INSET = 6; + + private RecipeDrawerLayout() { + } + + public static Rect body(Edge edge, Rect tab, Rect panel, int screenWidth, + int screenBottom, int recipeWidth, int rowHeight) { + int width = Math.max(160, recipeWidth) + 2 * INSET; + int right = Math.max(SideDrawerLayout.MARGIN, + screenWidth - SideDrawerLayout.MARGIN); + int leftEnd = Math.clamp(tab.x(), SideDrawerLayout.MARGIN, right); + int rightStart = Math.clamp(tab.right(), SideDrawerLayout.MARGIN, + right); + int leftRoom = leftEnd - SideDrawerLayout.MARGIN; + int rightRoom = right - rightStart; + boolean left = edge == Edge.LEFT; + // Open inward when the outer margin cannot fit the recipes. Never + // clamp the body across the fixed navigation rail. + if ((left ? leftRoom : rightRoom) < width + && (left ? rightRoom > leftRoom : leftRoom > rightRoom)) + left = !left; + width = Math.min(width, left ? leftRoom : rightRoom); + int x = left ? leftEnd - width : rightStart; + return SideDrawerLayout.body(panel, screenBottom, x, + SideDrawerLayout.top(panel), width, panel.height()); + } + + public static Rect content(Rect body) { + return new Rect(body.x() + INSET, body.y() + HEADER, + Math.max(0, body.width() - 2 * INSET), + Math.max(0, body.height() - HEADER - FOOTER)); + } + + public static int pageSize(Rect body, int rowHeight) { + if (rowHeight <= 0) + throw new IllegalArgumentException( + "Recipe row height must be positive"); + return Math.max(1, content(body).height() / rowHeight); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java b/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java index 27d85aae..c4f1c0ac 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java +++ b/src/main/java/zone/moddev/mc/lib/gui/layout/SideDrawerLayout.java @@ -66,4 +66,11 @@ public static Rect body(Rect panel, int screenBottom, int x, int y, public static Rect rail(Rect tab, Rect body) { return new Rect(tab.x(), body.y(), tab.width(), body.height()); } + + /** Shared background beneath the content and the whole column of tabs. */ + public static Rect frame(Rect tab, Rect body) { + int left = Math.min(tab.x(), body.x()); + return new Rect(left, body.y(), + Math.max(tab.right(), body.right()) - left, body.height()); + } } diff --git a/src/main/java/zone/moddev/mc/lib/gui/model/containers/ColouredGroupElement.java b/src/main/java/zone/moddev/mc/lib/gui/model/containers/ColouredGroupElement.java index 9b84f977..c1d61372 100644 --- a/src/main/java/zone/moddev/mc/lib/gui/model/containers/ColouredGroupElement.java +++ b/src/main/java/zone/moddev/mc/lib/gui/model/containers/ColouredGroupElement.java @@ -77,10 +77,9 @@ public boolean replacesChildHighlight(Screen screen, Element descendant, } public Rect outline(Rect bounds, boolean highlighted) { - return highlighted - ? new Rect(bounds.x() - 1, bounds.y() - 1, bounds.width() + 2, - bounds.height() + 2) - : bounds; + int outset = 2; + return new Rect(bounds.x() - outset, bounds.y() - outset, + bounds.width() + 2 * outset, bounds.height() + 2 * outset); } public boolean verticalChildren(boolean verticalParent) { diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java b/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java new file mode 100644 index 00000000..b7c5f039 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java @@ -0,0 +1,48 @@ +package zone.moddev.mc.lib.machine.definition; + +import java.util.Map; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; + +import zone.moddev.mc.lib.gui.model.ProcessorVariable; +import zone.moddev.mc.lib.machine.feature.Processor; + +/** A flat item preview on the front face, measured in block units. */ +public record ItemDisplay(ProcessorVariable variable, double x, double y, + float width, float height) { + public ItemDisplay { + if (variable == null || !Double.isFinite(x) || !Double.isFinite(y) + || x < 0 || x > 1 || y < 0 || y > 1 || !Float.isFinite(width) + || !Float.isFinite(height) || width <= 0 || width > 1 || height <= 0 + || height > 1) + throw new IllegalArgumentException( + "Item display requires a position in 0..1 and dimensions in (0, 1]"); + } + + public void validate(Map> processors) { + var value = variable.defaultValue(processors); + if (!(value instanceof ItemStack) && !(value instanceof String)) + throw new IllegalArgumentException( + "Item display requires a synchronized ItemStack or item-ID string variable"); + if (value instanceof String id && !id.isEmpty() + && ResourceLocation.tryParse(id) == null) + throw new IllegalArgumentException( + "Invalid default item display ID: " + id); + } + + /** + * Position just outside the front face; x increases to the viewer's right. + */ + public net.minecraft.world.phys.Vec3 offset( + net.minecraft.core.Direction facing) { + return switch (facing) { + case SOUTH -> new net.minecraft.world.phys.Vec3(x, y, 1.002); + case NORTH -> new net.minecraft.world.phys.Vec3(1 - x, y, -.002); + case EAST -> new net.minecraft.world.phys.Vec3(1.002, y, 1 - x); + case WEST -> new net.minecraft.world.phys.Vec3(-.002, y, x); + default -> throw new IllegalArgumentException( + "Item display requires horizontal facing"); + }; + } +} 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 988f240d..0f0e7f2b 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java @@ -7,7 +7,15 @@ public record MachineBehavior(ProcessorDeclaration processor, int stackSize, boolean noOcclusion, boolean immovable, boolean portable, boolean drawers, List shapes, net.minecraft.resources.ResourceLocation secondaryAction, - EntityDisplay entityDisplay) { + EntityDisplay entityDisplay, ItemDisplay itemDisplay) { + public MachineBehavior(ProcessorDeclaration processor, int stackSize, + boolean noOcclusion, boolean immovable, boolean portable, + boolean drawers, List shapes, + net.minecraft.resources.ResourceLocation secondaryAction, + EntityDisplay entityDisplay) { + this(processor, stackSize, noOcclusion, immovable, portable, drawers, + shapes, secondaryAction, entityDisplay, null); + } public MachineBehavior(ProcessorDeclaration processor, int stackSize, boolean noOcclusion, boolean immovable, boolean portable, boolean drawers, List shapes, 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 6e7e8a53..17c74cf6 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 @@ -37,6 +37,7 @@ import zone.moddev.mc.lib.machine.inventory.MachineStorageKeys; import zone.moddev.mc.lib.machine.presentation.ConditionalFaceTexture; import zone.moddev.mc.lib.machine.presentation.ConditionalModelPart; +import zone.moddev.mc.lib.machine.presentation.FaceOverlay; import zone.moddev.mc.lib.machine.presentation.VisualCondition; /** @@ -117,6 +118,8 @@ private static String key(Node parent, Node node) { // merge identity. if (Set.of("machine", "storage", "recipe-type").contains(parent.name())) return node.name(); + if (parent.name().equals("appearance") && isDisplay(node)) + return node.name(); var id = node.attributes().getOrDefault("id", node.attributes().get("name")); // Ordinary unnamed screen siblings are ordered content, never implicit @@ -124,6 +127,11 @@ private static String key(Node parent, Node node) { return id == null ? null : node.name() + ":" + id; } + private static boolean isDisplay(Node node) { + return node.name().equals("item-display") + || node.name().equals("entity-display"); + } + private static Node merge(Node base, Node child) { if (child.name().equals("generator") || child.name().equals("fill")) return child; @@ -173,9 +181,14 @@ private static Node merge(Node base, Node child) { Map.entry("entity-display", Set.of("variable", "offset", "width", "height", "yaw", "item-yaw", "block", "item", "item-property")), + Map.entry("item-display", + Set.of("variable", "x", "y", "width", "height")), Map.entry("part", Set.of("id", "model", "when")), Map.entry("face-texture", Set.of("id", "face", "texture", "when", "emissive-mask")), + Map.entry("face-overlay", + Set.of("id", "face", "texture", "x", "y", "width", "height", + "frames", "variable", "emissive", "when")), Map.entry("storage", Set.of()), Map.entry("items", Set.of("id")), Map.entry("fluids", Set.of("id")), Map.entry("tank", @@ -206,11 +219,12 @@ private static Node merge(Node base, Node child) { 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", - "entity-display"), + "processor", "redstone", "recovery", "screen", "shapes"), "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"), + Set.of("group"), "appearance", + Set.of("part", "face-texture", "face-overlay", "entity-display", + "item-display"), "recipe-type", Set.of("generator"), "shapes", Set.of("shape")); private static void validateTree(Node node) { @@ -239,6 +253,7 @@ private static void validateTree(Node node) { case "part" -> List.of("model"); case "entity-display" -> List.of("item-property"); case "face-texture" -> List.of("texture", "emissive-mask"); + case "face-overlay" -> List.of("texture"); case "recipe-type" -> List.of("id"); case "processor" -> List.of("recipe-type", "default-recipe", "running-sound", "finish-sound", "on-start", "on-finish"); @@ -610,10 +625,16 @@ else if (prior != null) float hardness = hardness(block); var modelParts = new ArrayList(); var faceTextures = new ArrayList(); - if (appearance.children().size() > 64) + var appearanceRules = appearance.children().stream() + .filter(part -> !isDisplay(part)).toList(); + if (appearanceRules.size() > 64) throw error(appearance, "At most 64 conditional parts and face-texture rules are supported"); - for (var part : appearance.children()) { + for (var part : appearanceRules) { + if (part.name().equals("face-overlay")) { + modelParts.addAll(overlayParts(part)); + continue; + } if (part.name().equals("face-texture")) { if (baseModel != null) throw error(part, @@ -663,7 +684,7 @@ else if (prior != null) throw error(shape, ex.getMessage()); } } - var displayNode = optional(root, "entity-display"); + var displayNode = optional(appearance, "entity-display"); EntityDisplay display = null; if (displayNode != null) { var offset = displayNode.attributes() @@ -695,6 +716,25 @@ else if (prior != null) throw error(displayNode, ex.getMessage()); } } + var itemDisplayNode = optional(appearance, "item-display"); + ItemDisplay itemDisplay = null; + if (itemDisplayNode != null) { + try { + itemDisplay = new ItemDisplay( + zone.moddev.mc.lib.gui.model.ProcessorVariable + .parse(required(itemDisplayNode, "variable")), + Double.parseDouble( + itemDisplayNode.attributes().getOrDefault("x", "0.5")), + Double.parseDouble( + itemDisplayNode.attributes().getOrDefault("y", "0.5")), + Float.parseFloat(itemDisplayNode.attributes() + .getOrDefault("width", "0.5")), + Float.parseFloat(itemDisplayNode.attributes() + .getOrDefault("height", "0.5"))); + } catch (IllegalArgumentException ex) { + throw error(itemDisplayNode, ex.getMessage()); + } + } ProcessorDeclaration declaration = null; zone.moddev.mc.lib.machine.feature.Processor prototype = null; if (custom) { @@ -719,7 +759,7 @@ else if (prior != null) block.attributes().containsKey("on-secondary-use") ? resource(block, "on-secondary-use") : null, - display); + display, itemDisplay); } catch (IllegalArgumentException ex) { throw error(block, ex.getMessage()); } @@ -737,6 +777,17 @@ else if (prior != null) throw error(displayNode, ex.getMessage()); } } + if (itemDisplay != null) { + if (prototype == null) + throw error(itemDisplayNode, + "Item displays require a custom processor with a synchronized variable"); + try { + itemDisplay + .validate(Map.of(required(processor, "id"), prototype)); + } catch (IllegalArgumentException ex) { + throw error(itemDisplayNode, ex.getMessage()); + } + } var definition = new MachineDefinition(id, checksum(root), required(root, "name"), hardness, resource(block, "mineable"), bool(block, "requires-tool", false), textures, baseModel, @@ -779,9 +830,13 @@ else if (prior != null) optionalResource(processor, "on-start"), optionalResource(processor, "on-finish"))); var defaults = definition.visualDefaults(prototype); - for (var part : appearance.children()) { + for (var part : appearanceRules) { try { - VisualCondition.compile(required(part, "when"), defaults); + if (part.name().equals("face-overlay")) { + for (var frame : overlayParts(part)) + VisualCondition.compile(frame.when(), defaults); + } else + VisualCondition.compile(required(part, "when"), defaults); } catch (IllegalArgumentException ex) { throw error(part, ex.getMessage()); } @@ -931,6 +986,48 @@ private static void requireChoice(Node node, String name, "Supported " + name + ": " + String.join(", ", values)); } + private static List overlayParts(Node node) { + try { + String id = required(node, "id"); + if (id.equals("base")) + throw new IllegalArgumentException( + "The model part ID 'base' is reserved"); + var face = RelativeFace + .valueOf(required(node, "face").toUpperCase(Locale.ROOT)); + int frames = node.attributes().containsKey("frames") + ? (int) number(node, "frames", 1, 32) + : 1; + String variable = frames > 1 + ? required(node, "variable") + : node.attributes().get("variable"); + if (variable != null) + zone.moddev.mc.lib.gui.model.ProcessorVariable.parse(variable); + var result = new ArrayList(); + for (int frame = 0; frame < frames; frame++) { + String when = node.attributes().getOrDefault("when", "true"); + if (frames > 1) + when = "(" + when + ") && " + + (frame == 0 + ? variable + " < 1" + : frame == frames - 1 + ? variable + " >= " + frame + : variable + " >= " + frame + " && " + variable + + " < " + (frame + 1)); + var overlay = new FaceOverlay(face, resource(node, "texture"), + Double.parseDouble(required(node, "x")), + Double.parseDouble(required(node, "y")), + Double.parseDouble(required(node, "width")), + Double.parseDouble(required(node, "height")), frame, frames, + bool(node, "emissive", false)); + result.add(new ConditionalModelPart(id + "/frame_" + frame, + null, when, overlay)); + } + return result; + } catch (IllegalArgumentException ex) { + throw error(node, ex.getMessage()); + } + } + private static boolean bool(Node node, String key, boolean fallback) { var value = node.attributes().get(key); if (value == null) 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 9f8ec5d0..86fb90be 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 @@ -58,8 +58,7 @@ public FeatureHost(Runnable onChange, Runnable onSync) { /** * Adds {@code feature}; features tick in the order added. * - * @throws IllegalArgumentException - * if another feature has the same key + * @throws IllegalArgumentException if another feature has the same key */ public FeatureHost add(MachineFeature feature) { if (variables != null || variableSource != null) @@ -144,6 +143,12 @@ public void reset() { features.values().forEach(MachineFeature::reset); } + public void restoreResources( + net.minecraft.core.HolderLookup.Provider registries) { + features.values() + .forEach(feature -> feature.restoreResources(registries)); + } + /** Finds a recipe processor by its stable feature/persistence key. */ public java.util.Optional processor(String key) { return features.get(key) instanceof RecipeProcessor processor diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/MachineFeature.java b/src/main/java/zone/moddev/mc/lib/machine/feature/MachineFeature.java index bb62fdae..3d51dcab 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/MachineFeature.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/MachineFeature.java @@ -7,8 +7,7 @@ * {@link RecipeProcessor}. A {@link FeatureHost} runs a machine's features and * saves each one under its key. * - * @param - * the state that is saved + * @param the state that is saved */ public interface MachineFeature { /** The name this feature's state is saved under; unique within a host. */ @@ -23,6 +22,13 @@ public interface MachineFeature { /** Takes on loaded state. */ void restore(S state); + /** + * Rebinds saved resource claims after storage and feature state are loaded. + */ + default void restoreResources( + net.minecraft.core.HolderLookup.Provider registries) { + } + /** * Releases transient ownership before replacing storage contents or * destroying the host. diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeChain.java b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeChain.java new file mode 100644 index 00000000..8108cc02 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeChain.java @@ -0,0 +1,405 @@ +package zone.moddev.mc.lib.machine.feature; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemStack; + +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient.ItemPart; +import zone.moddev.mc.lib.machine.inventory.ItemGroup; +import zone.moddev.mc.lib.machine.inventory.MachineInventory; +import zone.moddev.mc.lib.machine.recipe.MachineProduct.ItemProduct; +import zone.moddev.mc.lib.machine.recipe.MachineRecipe; + +/** + * Bounded concurrent execution of a selected linear recipe path. The host owns + * selection, storage, saving and synchronization. All methods run on its server + * thread; quantity queries are pure and safe during extraction simulation. Item + * groups must be exclusive to this chain. Recipes use "input"/"output" for + * stage items, with other names available for fluids and shared energy. + */ +public final class RecipeChain { + public static final int MAX_STAGES = 64; + + public record Step(ResourceLocation id, MachineRecipe recipe, + MachineInventory inventory) { + public Step { + Objects.requireNonNull(id); + Objects.requireNonNull(recipe); + Objects.requireNonNull(inventory); + var products = recipe.outputs().get("output"); + if (recipe.time() < 1 || recipe.outputs().size() != 1 + || products == null || products.size() != 1 + || !(products.getFirst() instanceof ItemProduct item) + || item.chance() != 1 || item.stack().isEmpty() + || item.stack().getCount() > item.stack().getMaxStackSize() + || !(inventory.group("output") + .orElse(null) instanceof ItemGroup output) + || output.size() != 1) + throw new IllegalArgumentException( + "Chain steps require one deterministic item output slot"); + var input = recipe.inputs().getOrDefault("input", List.of()); + if (!input.isEmpty() && (input.size() != 1 + || !(input.getFirst() instanceof ItemPart))) + throw new IllegalArgumentException( + "The input group is for stage items only"); + for (var entry : recipe.inputs().entrySet()) + for (var part : entry.getValue()) + if (part instanceof ItemPart + && (!entry.getKey().equals("input") + || entry.getValue().size() != 1 || !part.consumed() + || part.amount() < 1)) + throw new IllegalArgumentException( + "Chain steps consume one item ingredient group"); + } + + public ItemStack product() { + return ((ItemProduct) recipe.outputs().get("output").getFirst()) + .stack(); + } + + public ItemGroup output() { + return (ItemGroup) inventory.group("output").orElseThrow(); + } + + public int inputCount() { + return recipe.inputs().getOrDefault("input", List.of()).stream() + .filter(ItemPart.class::isInstance).map(ItemPart.class::cast) + .mapToInt(ItemPart::count).sum(); + } + } + + public record StageState(ResourceLocation recipe, int target, + RecipeCycle.State cycle) { + public static final Codec CODEC = RecordCodecBuilder + .create( + i -> i + .group( + ResourceLocation.CODEC.fieldOf("recipe") + .forGetter(StageState::recipe), + Codec.intRange(0, Integer.MAX_VALUE).fieldOf("target") + .forGetter(StageState::target), + RecipeCycle.State.CODEC.fieldOf("cycle") + .forGetter(StageState::cycle)) + .apply(i, StageState::new)); + } + + public record State(List stages, boolean paused, + boolean draining, int first) { + public static final Codec CODEC = RecordCodecBuilder + .create(i -> i.group( + StageState.CODEC.listOf(1, MAX_STAGES).fieldOf("stages") + .forGetter(State::stages), + Codec.BOOL.optionalFieldOf("paused", false) + .forGetter(State::paused), + Codec.BOOL.optionalFieldOf("draining", false) + .forGetter(State::draining), + Codec.intRange(0, MAX_STAGES - 1).optionalFieldOf("first", 0) + .forGetter(State::first)) + .apply(i, State::new)); + + public State { + stages = List.copyOf(stages); + } + } + + private final List steps; + private final List cycles; + private final int[] targets; + private final int[] bufferLimits; + private final RecipeCycle.Result[] results; + private boolean paused; + private boolean held; + private boolean draining; + private int first; + + public RecipeChain(List steps) { + if (steps.isEmpty() || steps.size() > MAX_STAGES) + throw new IllegalArgumentException("Invalid chain length"); + this.steps = List.copyOf(steps); + var outputs = java.util.Collections + .newSetFromMap(new java.util.IdentityHashMap()); + for (int i = 0; i < steps.size(); i++) { + var step = steps.get(i); + if (!outputs.add(step.output())) + throw new IllegalArgumentException("Aliased stage outputs"); + if (i == 0 && step.inputCount() != 0) + throw new IllegalArgumentException( + "Root must generate its item"); + if (i > 0) { + var previous = steps.get(i - 1); + if (step.inputCount() == 0 + || step.inputCount() > previous.product().getMaxStackSize() + || step.inventory().group("input").orElse(null) != previous + .output() + || !((ItemPart) step.recipe().inputs().get("input") + .getFirst()).items().test(previous.product())) + throw new IllegalArgumentException( + "Each input must be the preceding output group"); + } + } + cycles = steps.stream().map(s -> new RecipeCycle(s.inventory())) + .toList(); + targets = new int[steps.size()]; + bufferLimits = steps.stream() + .mapToInt(s -> s.product().getMaxStackSize()).toArray(); + results = new RecipeCycle.Result[steps.size()]; + java.util.Arrays.fill(results, RecipeCycle.Result.IDLE); + } + + public int size() { + return steps.size(); + } + + public Step step(int index) { + return steps.get(index); + } + + public RecipeCycle.State cycle(int index) { + return cycles.get(index).state(); + } + + public RecipeCycle.Result result(int index) { + return results[index]; + } + + public int target(int index) { + return targets[index]; + } + + /** Numeric policy; a consumer maps its None/One/Stack controls here. */ + public void target(int index, int amount) { + if (amount < 0 || amount > steps.get(index).product().getMaxStackSize()) + throw new IllegalArgumentException( + "Target outside one normal stack"); + targets[index] = amount; + } + + /** + * Host-owned buffer policy, reapplied when binding/restoring a chain. + * Limits future admissions, not existing stock or active work. Full output + * batches can exceed this threshold. Allow at least the following step's + * input batch to avoid starving that step. Defaults to a normal stack. + */ + public void bufferLimit(int index, int amount) { + int minimum = index + 1 < size() + ? steps.get(index + 1).inputCount() + : 1; + if (amount < minimum + || amount > steps.get(index).product().getMaxStackSize()) + throw new IllegalArgumentException( + "Buffer limit must fit the next input batch and one normal stack"); + bufferLimits[index] = amount; + } + + public boolean paused() { + return paused; + } + + /** Pause keeps active work intact, releasing only pending batch claims. */ + public void paused(boolean value) { + paused = value; + } + + /** Redstone/host hold, not persisted as a player's pause preference. */ + public void held(boolean value) { + held = value; + } + + /** Stops all admissions; existing cycles finish normally when powered. */ + public void drain() { + draining = true; + } + + public boolean draining() { + return draining; + } + + public void cancelDrain() { + draining = false; + } + + public boolean drained() { + return draining && cycles.stream().noneMatch(RecipeCycle::active); + } + + /** + * Tick once per world tick. Advance only cycles active at entry, then admit + * new work. Rotate the first advancing stage after a funded pass. An energy + * stall keeps that stage first and ends the pass, allowing its next tick's + * charge to accumulate instead of being spent by cheaper work. Returns + * whether state changed; stock/extraction can change separately. + */ + public boolean tick(RandomSource random) { + return tick(random, stage -> true); + } + + /** + * Host-owned start conditions, evaluated immediately before each admission + * after active cycles advance. Rejecting a stage never stops its active + * work or prevents other stages from starting. + */ + public boolean tick(RandomSource random, + java.util.function.IntPredicate canStart) { + Objects.requireNonNull(random); + Objects.requireNonNull(canStart); + if (paused || held) + return false; + boolean changed = false; + int nextFirst = cycles.stream().anyMatch(RecipeCycle::active) + ? (first + 1) % size() + : first; + for (int offset = 0; offset < size(); offset++) { + int i = (first + offset) % size(); + var cycle = cycles.get(i); + int before = cycle.progress(); + var result = cycle.advance(random); + changed |= results[i] != result || before != cycle.progress() + || result == RecipeCycle.Result.COMPLETED; + results[i] = result; + if (result == RecipeCycle.Result.STALLED) { + nextFirst = i; + break; + } + } + changed |= first != nextFirst; + first = nextFirst; + if (!draining) + for (int i = size() - 1; i >= 0; i--) { + var step = steps.get(i); + if (!cycles.get(i).active() && needed()[i] && matchingInput(i) + && canStart.test(i) + && cycles.get(i).start(step.id(), step.recipe())) { + results[i] = RecipeCycle.Result.RUNNING; + changed = true; + } + } + // first is part of saved scheduling state even when energy stalled. + return changed || cycles.stream().anyMatch(RecipeCycle::active); + } + + /** + * Extra claim beyond active reservations, for the next demanded batch. Bind + * this pure projection to each physical output slot's pendingClaims. It + * sees current contents even if an extractor ticks before this machine. + */ + public int pendingTake(int stage) { + steps.get(stage); + int next = stage + 1; + if (paused || held || draining || next == size() + || cycles.get(next).active() || !needed()[next] + || !matchingInput(next)) + return 0; + var step = steps.get(next); + if (!step.output().fits(List.of(step.product()))) + return 0; + return Math.min(step.inputCount(), steps.get(stage).output().free(0)); + } + + private boolean[] needed() { + var needs = new boolean[size()]; + long upstream = 0; + for (int i = size() - 1; i >= 0; i--) { + var step = steps.get(i); + var held = step.output().peek(0); + long available = ItemStack.isSameItemSameComponents(held, + step.product()) ? held.getCount() : 0; + if (cycles.get(i).active()) + available += plannedOutput(i); + if (i + 1 < size() && cycles.get(i + 1).active()) + available -= plannedInput(i + 1); + long missing = Math.max(0, + Math.min(bufferLimits[i], Math.max(targets[i], upstream)) + - available); + needs[i] = missing > 0; + long batches = (missing + step.product().getCount() - 1) + / step.product().getCount(); + // A blocked output cannot consume more inputs. Independent upstream + // targets still refill, subject to their own buffer limits. + upstream = missing > 0 + && step.output().fits(List.of(step.product())) + ? batches * step.inputCount() + : 0; + } + return needs; + } + + private boolean matchingInput(int stage) { + if (stage == 0) + return true; + var previous = steps.get(stage - 1); + return ItemStack.isSameItemSameComponents(previous.output().peek(0), + previous.product()); + } + + private long plannedOutput(int stage) { + return cycles.get(stage).plan().stream() + .flatMap(p -> p.products().stream()) + .filter(p -> p.group().equals("output")) + .flatMap(p -> p.at().stream()).mapToLong(a -> a.amount()).sum(); + } + + private long plannedInput(int stage) { + return cycles.get(stage).plan().stream() + .flatMap(p -> p.items().stream()) + .filter(t -> t.group().equals("input")) + .mapToLong(t -> t.stack().getCount() - t.retained()).sum(); + } + + public State state() { + var saved = new ArrayList(); + for (int i = 0; i < size(); i++) + saved.add(new StageState(steps.get(i).id(), targets[i], + cycles.get(i).state())); + return new State(saved, paused, draining, first); + } + + /** + * Release ownership before storage reload/destruction, never for path + * switching. + */ + public void reset() { + cycles.forEach(RecipeCycle::reset); + java.util.Arrays.fill(results, RecipeCycle.Result.IDLE); + } + + /** + * Restore only into the same storage bindings, after loading their items. + * Returns false if any active plan could not be restored. No lost plan + * consumes items; the host must retain/recover incompatible path contents. + */ + public boolean restore(State saved) { + if (saved.stages().size() != size() || saved.first() < 0 + || saved.first() >= size()) + throw new IllegalArgumentException("Saved chain shape differs"); + for (int i = 0; i < size(); i++) { + var stage = saved.stages().get(i); + if (!stage.recipe().equals(steps.get(i).id()) || stage.target() < 0 + || stage.target() > steps.get(i).product().getMaxStackSize() + || stage.cycle().plan() + .filter(p -> !p.recipe().equals(stage.recipe())) + .isPresent()) + throw new IllegalArgumentException("Saved chain route differs"); + } + cycles.forEach(RecipeCycle::reset); + boolean restored = true; + for (int i = 0; i < size(); i++) { + var stage = saved.stages().get(i); + targets[i] = stage.target(); + restored &= cycles.get(i).restore(stage.cycle()); + results[i] = cycles.get(i).active() + ? RecipeCycle.Result.RUNNING + : RecipeCycle.Result.IDLE; + } + paused = saved.paused(); + draining = saved.draining(); + first = saved.first(); + return restored; + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java new file mode 100644 index 00000000..aad4f0fc --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java @@ -0,0 +1,191 @@ +package zone.moddev.mc.lib.machine.feature; + +import java.util.Objects; +import java.util.Optional; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.RandomSource; + +import zone.moddev.mc.lib.machine.inventory.EnergyGroup; +import zone.moddev.mc.lib.machine.inventory.MachineInventory; +import zone.moddev.mc.lib.machine.recipe.CyclePlan; +import zone.moddev.mc.lib.machine.recipe.MachineRecipe; + +/** + * Executes one explicitly supplied recipe against stable inventory groups. + * Selection, demand, pause and tick ordering belong to the caller. Reserving + * never advances time or spends energy; only {@link #advance} does that. + */ +public final class RecipeCycle { + public record State(Optional plan, int progress) { + public static final Codec CODEC = RecordCodecBuilder + .create(i -> i.group( + CyclePlan.CODEC.lenientOptionalFieldOf("cycle") + .forGetter(State::plan), + Codec.intRange(0, Integer.MAX_VALUE) + .optionalFieldOf("progress", 0).forGetter(State::progress)) + .apply(i, State::new)); + + public State { + Objects.requireNonNull(plan); + if (progress < 0) + throw new IllegalArgumentException("Negative cycle progress"); + } + } + + public enum Result { + IDLE, RUNNING, STALLED, BLOCKED, COMPLETED + } + + private final MachineInventory inventory; + private CyclePlan plan; + private int progress; + + public RecipeCycle(MachineInventory inventory) { + this.inventory = Objects.requireNonNull(inventory); + } + + public Optional plan() { + return Optional.ofNullable(plan); + } + + public boolean active() { + return plan != null; + } + + public int progress() { + return progress; + } + + public int time() { + return plan == null ? 0 : plan.time(); + } + + public State state() { + return new State(plan(), progress); + } + + /** + * Claims inputs/output space, even without power. Callers that require + * power before admission can first use RecipeMatcher. Active work is never + * replaced. On failure, neither storage nor runner state changes. + */ + public boolean start(ResourceLocation id, MachineRecipe recipe) { + return start(id, recipe, false, 0, 0); + } + + /** Reclaims interrupted work; changed duration discards paid progress. */ + public boolean resume(ResourceLocation id, MachineRecipe recipe, + int paidProgress, int previousTime) { + return start(id, recipe, true, paidProgress, previousTime); + } + + private boolean start(ResourceLocation id, MachineRecipe recipe, + boolean resuming, int paidProgress, int previousTime) { + Objects.requireNonNull(id); + Objects.requireNonNull(recipe); + if (recipe.time() < 1 || paidProgress < 0) + throw new IllegalArgumentException("Invalid cycle time/progress"); + if (active()) + return false; + var next = CyclePlan.of(id, recipe, inventory, resuming).orElse(null); + if (next == null || !next.reserve(inventory)) + return false; + plan = next; + progress = resuming && previousTime == next.time() + ? Math.min(paidProgress, next.time()) + : 0; + return true; + } + + /** + * Advances at most one processing tick. A completed cycle releases its + * claims and commits its products atomically through CyclePlan. A blocked + * completion retries without charging energy again. + */ + public Result advance(RandomSource random) { + Objects.requireNonNull(random); + if (plan == null) + return Result.IDLE; + if (progress < plan.time()) { + if (!draw()) + return Result.STALLED; + progress++; + } + if (progress < plan.time()) + return Result.RUNNING; + if (!plan.finish(inventory, random)) + return Result.BLOCKED; + plan = null; + progress = 0; + return Result.COMPLETED; + } + + private boolean draw() { + for (var need : plan.energy().entrySet()) { + long share = EnergySchedule.share(need.getValue(), plan.time(), + progress); + if (!(inventory.group(need.getKey()) + .orElse(null) instanceof EnergyGroup group) + || group.stored() < share) + return false; + } + try (var tx = inventory.begin()) { + for (var need : plan.energy().entrySet()) { + long share = EnergySchedule.share(need.getValue(), plan.time(), + progress); + if (!(inventory.group(need.getKey()) + .orElse(null) instanceof EnergyGroup group) + || group.consume(share, tx) < share) + return false; + } + tx.commit(); + return true; + } + } + + /** Release claims while retaining paid progress for an explicit resume. */ + public void release() { + if (plan != null) + plan.release(inventory); + plan = null; + } + + public void reset() { + release(); + progress = 0; + } + + /** + * Loads after storage. Repeated restores never accumulate claims. Failed + * restores release old work and leave an idle runner, preserving items. + */ + public boolean restore(State saved) { + Objects.requireNonNull(saved); + reset(); + var next = saved.plan().orElse(null); + if (next == null) { + progress = saved.progress(); + return true; + } + if (next.time() < 1 || next.energy().entrySet().stream() + .anyMatch(e -> e.getValue() < 0 || !(inventory.group(e.getKey()) + .orElse(null) instanceof EnergyGroup))) + return false; + if (!next.restore(inventory)) + return false; + plan = next; + progress = Math.min(saved.progress(), next.time()); + return true; + } + + /** Client/paused progress without installing any server reservation. */ + void idleProgress(int value) { + if (active() || value < 0) + throw new IllegalStateException("Expected idle cycle progress"); + progress = value; + } +} 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 aee29ebb..5020879c 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 @@ -179,8 +179,8 @@ public Optional selectedRecipe() { return Optional.ofNullable(selectedRecipe); } public Optional activeRecipe() { - return Optional.ofNullable(cycle != null - ? cycle.recipe() + return Optional.ofNullable(activePlan() != null + ? activePlan().recipe() : resumeRecipe != null ? resumeRecipe : clientActiveRecipe); } @@ -241,9 +241,7 @@ public MatchResult recipeAvailability(MachineRecipeEntry entry) { private final MachineInventory inventory; private final MachineRecipeType type; private final MachineRecipeLookup lookup; - @Nullable - private CyclePlan cycle; - private int progress; + private final RecipeCycle runner; private boolean redstoneRunning; private final List redstoneOutputs; @Nullable @@ -274,7 +272,7 @@ public long startedCycles() { /** The running cycle, if any. */ public Optional cycle() { - return Optional.ofNullable(cycle); + return runner.plan(); } /** The cycle finished on the latest tick, if one was. */ @@ -315,6 +313,7 @@ public RecipeProcessor(String key, MachineRecipeType type, outputPrefix = outputPrefix(key); this.displayName = displayName.copy(); this.inventory = inventory; + runner = new RecipeCycle(inventory); this.type = type; lookup = type.lookup(); redstoneOutputs = List.of( @@ -362,11 +361,11 @@ public List redstoneOutputs() { private int redstoneProgress() { if (justFinished != null) return 15; - int duration = cycle != null - ? cycle.time() + int duration = activePlan() != null + ? activePlan().time() : resumeRecipe != null ? resumeTime : 0; return duration > 0 - ? RedstoneControl.level((double) progress / duration) + ? RedstoneControl.level((double) progress() / duration) : 0; } @@ -398,8 +397,8 @@ public Codec codec() { @Override public State state() { - return new State(paused, progress, Optional.ofNullable(resumeRecipe), - resumeTime, Optional.ofNullable(cycle), Optional.of(status), + return new State(paused, progress(), Optional.ofNullable(resumeRecipe), + resumeTime, runner.plan(), Optional.of(status), selectionEnabled ? Optional.of(new Selection(selectedRecipe())) : Optional.empty()); @@ -425,7 +424,7 @@ public void restoreOnClient(State state) { clientActiveRecipe = state.cycle().map(CyclePlan::recipe) .orElse(state.resumeRecipe().orElse(null)); paused = state.paused(); - progress = state.progress(); + runner.idleProgress(state.progress()); state.status().ifPresent(sent -> status = sent); syncedTime = state.cycle().map(CyclePlan::time).orElse(0); } @@ -445,9 +444,7 @@ public void restore(State state) { if (selectionEnabled) state.selection().ifPresent( value -> selectedRecipe = value.recipe().orElse(null)); - if (cycle != null) - cycle.release(inventory); - cycle = null; + runner.reset(); syncedTime = 0; justFinished = null; redstoneRunning = false; @@ -455,29 +452,20 @@ public void restore(State state) { searchDelay = 0; resumeRecipe = state.resumeRecipe().orElse(null); resumeTime = state.resumeTime(); - progress = resumeRecipe == null ? 0 : state.progress(); - var saved = state.cycle().filter(plan -> !paused && holds(plan)) - .orElse(null); - if (saved != null) { - cycle = saved; - progress = Math.min(state.progress(), saved.time()); - } + runner.idleProgress(resumeRecipe == null ? 0 : state.progress()); + if (!paused && state.cycle().isPresent() && !runner + .restore(new RecipeCycle.State(state.cycle(), state.progress()))) + runner.idleProgress(resumeRecipe == null ? 0 : state.progress()); status = paused ? Status.PAUSED - : cycle == null ? Status.IDLE : Status.RUNNING; + : runner.active() ? Status.RUNNING : Status.IDLE; activityChanges.changed(); progressChanges.changed(); } - /** - * Whether the plan's energy groups are there and its reservations can be - * put back. - */ - private boolean holds(CyclePlan plan) { - for (var key : plan.energy().keySet()) - if (!(inventory.group(key).orElse(null) instanceof EnergyGroup)) - return false; - return plan.restore(inventory); + @Nullable + private CyclePlan activePlan() { + return runner.plan().orElse(null); } /** Whether an interrupt holds the processor. */ @@ -515,11 +503,10 @@ public void interrupt() { public void pause() { if (paused) return; - if (cycle != null) { - cycle.release(inventory); - resumeRecipe = cycle.recipe(); - resumeTime = cycle.time(); - cycle = null; + if (runner.active()) { + resumeRecipe = activePlan().recipe(); + resumeTime = activePlan().time(); + runner.release(); } paused = true; redstoneRunning = false; @@ -562,12 +549,9 @@ public void setPaused(boolean value) { * Cancels work, releases reservations and forgets progress and pause state. */ public void reset() { - if (cycle != null) - cycle.release(inventory); - cycle = null; + runner.reset(); resumeRecipe = null; resumeTime = 0; - progress = 0; syncedTime = 0; justFinished = null; paused = false; @@ -581,7 +565,7 @@ public void reset() { @Override public Statistics statistics() { - var plan = cycle != null ? cycle : justFinished; + var plan = runner.active() ? activePlan() : justFinished; var maximum = plan == null ? new Statistics.Text(Statistics.label("no_recipe")) : (Statistics.Value) new Statistics.Rate(java.math.BigInteger.ONE, @@ -618,7 +602,7 @@ public Status status() { /** Ticks of the running cycle done. */ public int progress() { - return progress; + return runner.progress(); } /** @@ -628,7 +612,7 @@ public int progress() { * progress} is as of the last status change. */ public int time() { - return cycle == null ? syncedTime : cycle.time(); + return runner.active() ? runner.time() : syncedTime; } /** @@ -687,33 +671,28 @@ private void run(FeatureHost host) { return; } var level = host.level(); - if (cycle == null + if (!runner.active() && (resumeRecipe == null || !reserveAgain(level, host))) { start(level, host); return; } - if (progress < cycle.time()) { - if (!draw()) { - status = Status.STALLED; - return; - } - progress++; + var active = activePlan(); + int before = progress(); + var result = runner.advance(level.getRandom()); + status = switch (result) { + case IDLE, COMPLETED -> Status.IDLE; + case RUNNING -> Status.RUNNING; + case STALLED -> Status.STALLED; + case BLOCKED -> Status.BLOCKED; + }; + if (result == RecipeCycle.Result.COMPLETED) { + completedCycles = completedCycles.add(java.math.BigInteger.ONE); + justFinished = active; + } + if (progress() != before || result == RecipeCycle.Result.COMPLETED) { progressChanges.changed(); - status = Status.RUNNING; host.markChanged(); } - if (progress >= cycle.time()) { - if (cycle.finish(inventory, level.getRandom())) { - completedCycles = completedCycles.add(java.math.BigInteger.ONE); - justFinished = cycle; - cycle = null; - progress = 0; - status = Status.IDLE; - host.markChanged(); - } else { - status = Status.BLOCKED; - } - } } /** @@ -725,21 +704,15 @@ private boolean reserveAgain(Level level, FeatureHost host) { var id = resumeRecipe; resumeRecipe = null; host.markChanged(); - CyclePlan plan = null; var holder = level.getRecipeManager().byKey(id).orElse(null); - if (holder != null && holder.value() instanceof MachineRecipeEntry entry - && entry.type() == type) { - plan = CyclePlan.of(id, entry.recipe(), inventory, true) - .filter(found -> found.reserve(inventory)).orElse(null); - } - if (plan == null) { - progress = 0; + if (!(holder != null + && holder.value() instanceof MachineRecipeEntry entry + && entry.type() == type + && runner.resume(id, entry.recipe(), progress(), resumeTime))) { + runner.idleProgress(0); progressChanges.changed(); return false; } - cycle = plan; - if (plan.time() != resumeTime) - progress = 0; progressChanges.changed(); return true; } @@ -760,45 +733,17 @@ private void start(Level level, FeatureHost host) { if (selectionEnabled && found != null && !recipeAvailability(found.value()).ok()) found = null; - var plan = found == null - ? null - : CyclePlan.of(found.id(), found.value().recipe(), inventory) - .orElse(null); - if (plan == null || !plan.reserve(inventory)) { + if (found == null + || !runner.start(found.id(), found.value().recipe())) { searchDelay = SEARCH_RETRY_INTERVAL - 1; searchedRevisions = inventory.revisions(); return; } - cycle = plan; searchDelay = 0; - progress = 0; status = Status.RUNNING; progressChanges.changed(); startedCycles++; host.markChanged(); } - /** Draws this tick's energy from every energy group, or none of it. */ - private boolean draw() { - for (var need : cycle.energy().entrySet()) { - long share = EnergySchedule.share(need.getValue(), cycle.time(), - progress); - if (!(inventory.group(need.getKey()) - .orElse(null) instanceof EnergyGroup group) - || group.stored() < share) - return false; - } - try (var tx = inventory.begin()) { - for (var need : cycle.energy().entrySet()) { - long share = EnergySchedule.share(need.getValue(), cycle.time(), - progress); - if (!(inventory.group(need.getKey()) - .orElse(null) instanceof EnergyGroup group) - || group.consume(share, tx) < share) - return false; - } - tx.commit(); - return true; - } - } } diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineInventoryLifecycle.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineInventoryLifecycle.java index 8a80088e..ed8ab8d8 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineInventoryLifecycle.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineInventoryLifecycle.java @@ -142,6 +142,7 @@ else if (tag.contains(key)) features.load( registries.createSerializationContext(NbtOps.INSTANCE), tag.get("features")); + features.restoreResources(registries); } public void tick(boolean processingAllowed, boolean paused, diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java index 7d24af78..db7603dd 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java @@ -119,8 +119,15 @@ else if (value instanceof Number number) var json = new JsonObject(); json.addProperty("id", part.id()); json.addProperty("when", part.when()); - var child = new JsonObject(); - child.addProperty("parent", part.model().toString()); + var child = part.overlay() == null + ? new JsonObject() + : part.overlay().model(); + if (part.overlay() == null) + child.addProperty("parent", + part.model().toString()); + else + json.addProperty("emissive", + part.overlay().emissive()); json.add("model", child); parts.add(json); } diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/RecipeOperations.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/RecipeOperations.java new file mode 100644 index 00000000..3879ca29 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/RecipeOperations.java @@ -0,0 +1,141 @@ +package zone.moddev.mc.lib.machine.neoforge; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import net.minecraft.core.NonNullList; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; +import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.ShapedRecipe; +import net.minecraft.world.item.crafting.ShapelessRecipe; +import net.minecraft.world.item.crafting.SingleRecipeInput; +import net.minecraft.world.item.crafting.SmeltingRecipe; +import net.minecraft.world.level.Level; + +import net.neoforged.neoforge.common.crafting.DataComponentIngredient; + +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient.EnergyPart; +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient.ItemPart; +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient; +import zone.moddev.mc.lib.machine.recipe.MachineProduct.ItemProduct; +import zone.moddev.mc.lib.machine.recipe.MachineProduct; +import zone.moddev.mc.lib.machine.recipe.MachineRecipe; +import zone.moddev.mc.lib.machine.recipe.RecipeGraph.Operation; + +/** + * Conservative adapters for concrete source stacks. Mods decide which recipe + * types to offer and supply costs; the library does not register new recipes. + */ +public final class RecipeOperations { + private RecipeOperations() { + } + + public record Cost(int ticks, long energy) { + public Cost { + if (ticks < 1 || energy < 1) + throw new IllegalArgumentException("Invalid operation cost"); + } + } + + public static Optional smelting(RecipeHolder holder, + ItemStack source, Level level, Cost cost) { + if (source.isEmpty() + || holder.value().getClass() != SmeltingRecipe.class) + return Optional.empty(); + var recipe = (SmeltingRecipe) holder.value(); + var input = new SingleRecipeInput(source.copyWithCount(1)); + if (!recipe.matches(input, level) || recipe.getRemainingItems(input) + .stream().anyMatch(s -> !s.isEmpty())) + return Optional.empty(); + return operation(holder.id(), "smelt", source, 1, + recipe.assemble(input, level.registryAccess()), cost); + } + + /** + * Supports ordinary shaped/shapeless recipes filled with repeated copies of + * this concrete source. Special subclasses and remainder recipes are + * excluded instead of guessing their semantics. Empty shaped cells stay + * empty, so a 3x2 glass-pane recipe still consumes exactly six glass. + */ + public static Optional crafting(RecipeHolder holder, + ItemStack source, Level level, Cost cost) { + if (source.isEmpty() + || !(holder.value() instanceof CraftingRecipe recipe) + || (recipe.getClass() != ShapedRecipe.class + && recipe.getClass() != ShapelessRecipe.class)) + return Optional.empty(); + var ingredients = recipe.getIngredients(); + int width = recipe instanceof ShapedRecipe shaped + ? shaped.getWidth() + : 3; + int height = recipe instanceof ShapedRecipe shaped + ? shaped.getHeight() + : 3; + var slots = NonNullList.withSize(width * height, ItemStack.EMPTY); + int count = 0; + for (int i = 0; i < ingredients.size(); i++) { + var ingredient = ingredients.get(i); + if (ingredient.isEmpty()) + continue; + if (i >= slots.size() || !ingredient.test(source)) + return Optional.empty(); + slots.set(i, source.copyWithCount(1)); + count++; + } + var input = CraftingInput.of(width, height, slots); + if (count == 0 || !recipe.matches(input, level) || recipe + .getRemainingItems(input).stream().anyMatch(s -> !s.isEmpty())) + return Optional.empty(); + return operation(holder.id(), "craft", source, count, + recipe.assemble(input, level.registryAccess()), cost); + } + + /** Adapter for deterministic item transformations supplied by a mod. */ + public static Optional machine(ResourceLocation id, + ResourceLocation kind, MachineRecipe recipe, ItemStack source) { + if (source.isEmpty() || recipe.time() < 1 + || recipe.outputs().size() != 1 + || recipe.outputs().getOrDefault("output", List.of()).size() != 1 + || !(recipe.outputs().get("output") + .getFirst() instanceof ItemProduct product) + || product.chance() != 1 || product.stack().isEmpty() + || product.stack().getCount() > product.stack().getMaxStackSize()) + return Optional.empty(); + var input = recipe.inputs().getOrDefault("input", List.of()); + if (input.size() != 1 || !(input.getFirst() instanceof ItemPart item) + || !item.consumed() || item.count() < 1 + || item.count() > source.getMaxStackSize() + || !item.items().test(source)) + return Optional.empty(); + for (var entry : recipe.inputs().entrySet()) + if (!entry.getKey().equals("input") && entry.getValue().stream() + .anyMatch(p -> !(p instanceof EnergyPart))) + return Optional.empty(); + return Optional + .of(new Operation(id, kind, item.count(), product.stack(), recipe)); + } + + private static Optional operation(ResourceLocation id, + String kind, ItemStack source, int count, ItemStack output, Cost cost) { + if (output.isEmpty() || output.getCount() > output.getMaxStackSize() + || count > source.getMaxStackSize()) + return Optional.empty(); + var ingredient = DataComponentIngredient.of(true, source); + // A source with removed default components may not be representable + // by the standard strict ingredient; exclude it rather than broaden it. + if (!ingredient.test(source)) + return Optional.empty(); + Map> inputs = Map.of("input", + List.of(new ItemPart(ingredient, count)), "energy", + List.of(new EnergyPart(cost.energy()))); + Map> outputs = Map.of("output", + List.of(new ItemProduct(output, 1))); + return Optional.of(new Operation(id, + ResourceLocation.fromNamespaceAndPath("mmdlib", kind), count, + output, new MachineRecipe(inputs, outputs, cost.ticks()))); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/StorageGroups.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/StorageGroups.java index 92d74281..d7314fca 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/StorageGroups.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/StorageGroups.java @@ -84,7 +84,7 @@ public ItemStack peek(int slot) { @Override public int free(int slot) { - return valid(slot) ? storage.freeToTake(slots[slot]) : 0; + return valid(slot) ? storage.freeForProcessing(slots[slot]) : 0; } @Override @@ -95,7 +95,7 @@ public int extract(int slot, int count, MachineTx tx) { if (storage.getStackInSlot(index).isEmpty()) return 0; track(index, tx); - return storage.extractItem(index, count, false).getCount(); + return storage.extractForProcessing(index, count, false).getCount(); } @Override @@ -157,7 +157,7 @@ public int[][] place(List stacks, long[] taken) { var usable = new boolean[slots.length]; for (int i = 0; i < slots.length; i++) { var stack = storage.getStackInSlot(slots[i]); - var plan = storage.plan(slots[i]); + var plan = storage.processingPlan(slots[i]); var asked = new SlotPlan(plan.take() + (int) taken[i], plan.add()); usable[i] = asked.legal(stack, storage.getSlotLimit(slots[i])); @@ -172,7 +172,7 @@ public int[][] place(List stacks, long[] taken) { for (boolean merging : new boolean[]{true, false}) for (int i = 0; i < slots.length && left > 0; i++) { var slot = held.get(i); - var plan = storage.plan(slots[i]); + var plan = storage.processingPlan(slots[i]); if (!usable[i] || merging == plan.endState(slot).isEmpty()) continue; diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/ConditionalMachineModel.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/ConditionalMachineModel.java index abfac1ee..22f8d976 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/ConditionalMachineModel.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/ConditionalMachineModel.java @@ -56,8 +56,8 @@ @EventBusSubscriber(modid = "mmdlib", bus = EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public final class ConditionalMachineModel implements IUnbakedGeometry { - private record Part(String id, BlockModel model, - VisualCondition condition) { + private record Part(String id, BlockModel model, VisualCondition condition, + boolean emissive) { } private record FaceTexture(RelativeFace face, String texture, VisualCondition condition, String emissiveMask) { @@ -108,7 +108,9 @@ private static ConditionalMachineModel read(JsonObject json, parts.add(new Part(id, context.deserialize(part.get("model"), BlockModel.class), VisualCondition.compile(part.get("when").getAsString(), - defaults))); + defaults), + part.has("emissive") + && part.get("emissive").getAsBoolean())); } var faceTextures = new ArrayList(); if (json.has("face_textures")) @@ -165,9 +167,11 @@ public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, ? baseModel : new FaceTextureModel(baseModel, textureRules)); for (var part : parts) - children.put(part.id(), new ConditionalPart( - part.model().bake(baker, part.model(), sprites, state, true), - part.condition())); + children + .put(part.id(), + new ConditionalPart(part.model().bake(baker, part.model(), + sprites, state, true), part.condition(), + part.emissive())); // Inventory items intentionally show the base appearance, independent // of world state. return new CompositeModel.Baked(context.isGui3d(), @@ -203,10 +207,27 @@ private static final class ConditionalPart extends BakedModelWrapper { private final VisualCondition condition; + private final boolean emissive; + private final com.google.common.cache.LoadingCache lit = com.google.common.cache.CacheBuilder + .newBuilder().maximumSize(64) + .build(com.google.common.cache.CacheLoader + .from(ConditionalPart::light)); - private ConditionalPart(BakedModel model, VisualCondition condition) { + private ConditionalPart(BakedModel model, VisualCondition condition, + boolean emissive) { super(model); this.condition = condition; + this.emissive = emissive; + } + + private static BakedQuad light(BakedQuad quad) { + int[] vertices = quad.getVertices().clone(); + for (int i = 0; i < 4; i++) + vertices[i + * net.neoforged.neoforge.client.model.IQuadTransformer.STRIDE + + net.neoforged.neoforge.client.model.IQuadTransformer.UV2] = net.minecraft.client.renderer.LightTexture.FULL_BRIGHT; + return new BakedQuad(vertices, quad.getTintIndex(), + quad.getDirection(), quad.getSprite(), false, false); } private boolean visible(ModelData data) { @@ -228,9 +249,12 @@ public ModelData getModelData(BlockAndTintGetter level, BlockPos pos, @Override public List getQuads(BlockState state, Direction side, RandomSource random, ModelData data, RenderType type) { - return visible(data) - ? originalModel.getQuads(state, side, random, data, type) - : List.of(); + if (!visible(data)) + return List.of(); + var quads = originalModel.getQuads(state, side, random, data, type); + return emissive + ? quads.stream().map(lit::getUnchecked).toList() + : quads; } @Override diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java index 890b6c41..7373245d 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java @@ -96,12 +96,29 @@ public static void setup(FMLClientSetupEvent event) { @SubscribeEvent public static void renderers(EntityRenderersEvent.RegisterRenderers event) { - for (var definition : MachineContent.definitions().values()) - if (definition.behavior().entityDisplay() != null - && definition.behavior().entityDisplay().block()) + for (var definition : MachineContent.definitions().values()) { + var entity = definition.behavior().entityDisplay(); + var item = definition.behavior().itemDisplay(); + if (entity != null && entity.block() || item != null) event.registerBlockEntityRenderer( - MachineContent.entityType(definition.id()), - context -> new BlockDisplay(Binding.of(definition))); + MachineContent.entityType(definition.id()), context -> { + var entityRenderer = entity != null && entity.block() + ? new BlockDisplay(Binding.of(definition)) + : null; + var itemRenderer = item == null + ? null + : new MachineItemDisplay(item); + return (machine, partial, pose, buffers, light, + overlay) -> { + if (entityRenderer != null) + entityRenderer.render(machine, partial, pose, + buffers, light, overlay); + if (itemRenderer != null) + itemRenderer.render(machine, partial, pose, + buffers, light, overlay); + }; + }); + } } @SubscribeEvent diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java new file mode 100644 index 00000000..a656107c --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java @@ -0,0 +1,63 @@ +package zone.moddev.mc.lib.machine.neoforge.client; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; + +import zone.moddev.mc.lib.machine.definition.ItemDisplay; +import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity; + +/** Shared front-face overlay driven by a declared tracking-player variable. */ +final class MachineItemDisplay + implements BlockEntityRenderer { + private final ItemDisplay display; + + MachineItemDisplay(ItemDisplay display) { + this.display = display; + } + + static ItemStack item(Object value) { + if (value instanceof ItemStack stack) + return stack.copyWithCount(1); + if (value instanceof String name && !name.isEmpty()) { + var id = ResourceLocation.tryParse(name); + if (id != null && BuiltInRegistries.ITEM.containsKey(id)) + return new ItemStack(BuiltInRegistries.ITEM.get(id)); + } + return ItemStack.EMPTY; + } + + @Override + public void render(DefinedMachineEntity machine, float partialTick, + PoseStack pose, MultiBufferSource buffers, int light, int overlay) { + var stack = item(display.variable().read(machine)); + if (stack.isEmpty()) + return; + var facing = machine.getBlockState() + .getValue(BlockStateProperties.HORIZONTAL_FACING); + if (machine.getLevel() != null) + light = LevelRenderer.getLightColor(machine.getLevel(), + machine.getBlockPos().relative(facing)); + pose.pushPose(); + try { + var offset = display.offset(facing); + pose.translate(offset.x, offset.y, offset.z); + pose.mulPose(Axis.YP.rotationDegrees(-facing.toYRot())); + pose.scale(display.width(), display.height(), .001f); + Minecraft.getInstance().getItemRenderer().renderStatic(stack, + ItemDisplayContext.GUI, light, overlay, pose, buffers, + machine.getLevel(), 0); + } finally { + pose.popPose(); + } + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/presentation/ConditionalModelPart.java b/src/main/java/zone/moddev/mc/lib/machine/presentation/ConditionalModelPart.java index d6b815e0..79e93ab8 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/presentation/ConditionalModelPart.java +++ b/src/main/java/zone/moddev/mc/lib/machine/presentation/ConditionalModelPart.java @@ -4,5 +4,9 @@ /** A static child model included when its typed condition is true. */ public record ConditionalModelPart(String id, ResourceLocation model, - String when) { + String when, FaceOverlay overlay) { + public ConditionalModelPart(String id, ResourceLocation model, + String when) { + this(id, model, when, null); + } } diff --git a/src/main/java/zone/moddev/mc/lib/machine/presentation/FaceOverlay.java b/src/main/java/zone/moddev/mc/lib/machine/presentation/FaceOverlay.java new file mode 100644 index 00000000..b93f5814 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/presentation/FaceOverlay.java @@ -0,0 +1,90 @@ +package zone.moddev.mc.lib.machine.presentation; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; + +import zone.moddev.mc.lib.api.capabilities.RelativeFace; + +/** One frame of a vertical texture strip on a rectangular face region. */ +public record FaceOverlay(RelativeFace face, ResourceLocation texture, double x, + double y, double width, double height, int frame, int frames, + boolean emissive) { + public FaceOverlay { + if (face == null || texture == null || !Double.isFinite(x) + || !Double.isFinite(y) || !Double.isFinite(width) + || !Double.isFinite(height) || x < 0 || y < 0 || width <= 0 + || height <= 0 || x + width > 16 || y + height > 16) + throw new IllegalArgumentException( + "Overlay region must fit within a 16 by 16 face"); + if (frames < 1 || frames > 32 || frame < 0 || frame >= frames) + throw new IllegalArgumentException( + "Overlay requires 1 to 32 frames and a valid frame index"); + } + + /** + * Pixel coordinates measured from the top left when looking at the face. + */ + public JsonObject model() { + var direction = face.toWorld(Direction.NORTH); + double left = x, right = x + width, top = 16 - y, bottom = top - height; + double[] from, to; + switch (direction) { + case NORTH -> { + from = new double[]{16 - right, bottom, -0.01}; + to = new double[]{16 - left, top, -0.01}; + } + case SOUTH -> { + from = new double[]{left, bottom, 16.01}; + to = new double[]{right, top, 16.01}; + } + case WEST -> { + from = new double[]{-0.01, bottom, left}; + to = new double[]{-0.01, top, right}; + } + case EAST -> { + from = new double[]{16.01, bottom, 16 - right}; + to = new double[]{16.01, top, 16 - left}; + } + case UP -> { + from = new double[]{left, 16.01, y}; + to = new double[]{right, 16.01, y + height}; + } + case DOWN -> { + from = new double[]{left, -0.01, 16 - y - height}; + to = new double[]{right, -0.01, 16 - y}; + } + default -> throw new IllegalStateException(); + } + var model = new JsonObject(); + model.addProperty("render_type", "minecraft:cutout"); + var textures = new JsonObject(); + textures.addProperty("overlay", texture.toString()); + textures.addProperty("particle", texture.toString()); + model.add("textures", textures); + var element = new JsonObject(); + element.add("from", array(from)); + element.add("to", array(to)); + element.addProperty("shade", !emissive); + var surface = new JsonObject(); + surface.addProperty("texture", "#overlay"); + surface.add("uv", + array(0, 16.0 * frame / frames, 16, 16.0 * (frame + 1) / frames)); + var faces = new JsonObject(); + faces.add(direction.getName(), surface); + element.add("faces", faces); + var elements = new JsonArray(); + elements.add(element); + model.add("elements", elements); + return model; + } + + private static JsonArray array(double... values) { + var result = new JsonArray(); + for (double value : values) + result.add(value); + return result; + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeGraph.java b/src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeGraph.java new file mode 100644 index 00000000..fb2063ae --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/recipe/RecipeGraph.java @@ -0,0 +1,190 @@ +package zone.moddev.mc.lib.machine.recipe; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; + +/** + * A bounded, deterministic graph of single-material transformations. Build from + * a recipe snapshot, cache in the owning catalog and rebuild on reload. + * Contains no machine state and never scans recipes during processing. + */ +public final class RecipeGraph { + public record Operation(ResourceLocation id, ResourceLocation kind, + int inputCount, ItemStack output, MachineRecipe recipe) { + public Operation { + Objects.requireNonNull(id); + Objects.requireNonNull(kind); + Objects.requireNonNull(recipe); + output = output.copy(); + if (inputCount < 1 || output.isEmpty() || recipe.time() < 1) + throw new IllegalArgumentException("Invalid recipe operation"); + } + + @Override + public ItemStack output() { + return output.copy(); + } + } + + public record Edge(int from, int to, Operation operation) { + } + + public record Limits(int nodes, int edges, int depth) { + public Limits { + if (nodes < 1 || nodes > 4096 || edges < 1 || edges > 16384 + || depth < 1 || depth > 63) + throw new IllegalArgumentException( + "Invalid recipe graph limits"); + } + + public static Limits defaults() { + return new Limits(512, 2048, 32); + } + } + + private final List nodes; + private final List edges; + private final List parents; + private final boolean truncated; + + private RecipeGraph(List nodes, List edges, + List parents, boolean truncated) { + this.nodes = nodes.stream().map(ItemStack::copy).toList(); + this.edges = List.copyOf(edges); + // Root has no parent. + this.parents = java.util.Collections + .unmodifiableList(new ArrayList<>(parents)); + this.truncated = truncated; + } + + /** + * The resolver returns admitted operations for a concrete source stack. + * Each node is expanded once; cycles remain edges without recursive work. + * Prefer shortest paths, then recipe ID order. Callers must also bound + * resolver work for their recipe catalog. + */ + public static RecipeGraph discover(ItemStack root, + Function> resolver, Limits limits) { + if (root.isEmpty()) + throw new IllegalArgumentException("Empty recipe root"); + Objects.requireNonNull(resolver); + Objects.requireNonNull(limits); + var nodes = new ArrayList(); + var edges = new ArrayList(); + var parents = new ArrayList(); + var depths = new ArrayList(); + nodes.add(root.copyWithCount(1)); + parents.add(null); + depths.add(0); + boolean truncated = false; + outer : for (int from = 0; from < nodes.size(); from++) { + var operations = resolver + .apply(nodes.get(from).copy()).stream().sorted(Comparator + .comparing(Operation::id).thenComparing(Operation::kind)) + .toList(); + if (depths.get(from) == limits.depth()) { + truncated |= !operations.isEmpty(); + continue; + } + var seen = new java.util.HashSet(); + for (var operation : operations) { + if (!seen.add(operation.id())) + throw new IllegalArgumentException( + "Duplicate operation ID: " + operation.id()); + if (edges.size() == limits.edges()) { + truncated = true; + break outer; + } + int to = indexOf(nodes, operation.output()); + if (to < 0 && nodes.size() == limits.nodes()) { + truncated = true; + continue; + } + boolean fresh = to < 0; + if (fresh) + to = nodes.size(); + var edge = new Edge(from, to, operation); + edges.add(edge); + if (fresh) { + nodes.add(operation.output().copyWithCount(1)); + parents.add(edge); + depths.add(depths.get(from) + 1); + } + } + } + return new RecipeGraph(nodes, edges, parents, truncated); + } + + private static int indexOf(List nodes, ItemStack item) { + for (int i = 0; i < nodes.size(); i++) + if (ItemStack.isSameItemSameComponents(nodes.get(i), item)) + return i; + return -1; + } + + public int size() { + return nodes.size(); + } + + public int indexOf(ItemStack item) { + return indexOf(nodes, item); + } + + public ItemStack item(int node) { + return nodes.get(node).copy(); + } + + public List edges() { + return edges; + } + + public boolean truncated() { + return truncated; + } + + public List pathTo(int node) { + nodes.get(node); + var path = new ArrayList(); + while (node != 0) { + var parent = parents.get(node); + path.add(parent.operation()); + node = parent.from(); + } + java.util.Collections.reverse(path); + return List.copyOf(path); + } + + /** + * One graph per owner/source; a new recipe or policy snapshot invalidates + * it. + */ + public static final class Cache { + private Object revision; + private RecipeGraph graph; + private Limits bounds; + + public RecipeGraph get(Object snapshot, ItemStack root, + Function> resolver, Limits limits) { + Objects.requireNonNull(snapshot); + if (graph == null || revision != snapshot || !limits.equals(bounds) + || !ItemStack.isSameItemSameComponents(graph.item(0), root)) { + graph = discover(root, resolver, limits); + revision = snapshot; + bounds = limits; + } + return graph; + } + + public void invalidate() { + revision = null; + graph = null; + bounds = null; + } + } +} diff --git a/src/main/resources/assets/mmdlib/lang/en_us.json b/src/main/resources/assets/mmdlib/lang/en_us.json index e6bbaafa..b9afe963 100644 --- a/src/main/resources/assets/mmdlib/lang/en_us.json +++ b/src/main/resources/assets/mmdlib/lang/en_us.json @@ -124,6 +124,10 @@ "screen.mmdlib.stats.cycles_unit": "cycles", "screen.mmdlib.stats.no_recipe": "No recipe", "screen.mmdlib.stats.title": "Statistics", + "screen.mmdlib.recipes.title": "Recipes", + "screen.mmdlib.recipes.empty": "No recipes available", + "screen.mmdlib.recipes.page": "%s / %s", + "screen.mmdlib.recipes.group": "Change recipe group", "screen.mmdlib.stats.tick": "t", "screen.mmdlib.stats.second": "s", "screen.mmdlib.stats.minute": "min", diff --git a/src/main/resources/assets/mmdlib/textures/gui/sprites/icon_recipes.png b/src/main/resources/assets/mmdlib/textures/gui/sprites/icon_recipes.png new file mode 100644 index 0000000000000000000000000000000000000000..fc71c797ed5fe42689981910106329b208d22139 GIT binary patch literal 506 zcmeAS@N?(olHy`uVBq!ia0vp^B0wy}!3-pG`1q876k~CayA#8@b22Z19F}xPUq=Rp zjs4tz5?O(Kl>na*R~}XdF#%R-Gij|zt?1}z+bUc4KKHP-VKZmW+`fJLwQJXa3h#Q| zEd^3MB|(0{{}F&e=>EBLKyl6jkH}&M2EM}}%y>M1MG8<*ti&~}{Yndic#fH=f&ooa@Ed~xChm}E!k(GfF$npYWX($`yCk;ksus9Qt zZOF*Pzz3wGfHz_bIHB``?@RX`w=b=f50vZdE1W$?L5bu5+Kabn}FRSZj~ zHR_ayFOI6IT_HSUZ_statC`cx=WfwU;_SL@`Qm@+ME1jJ+?THP9@!4E+|$+1Wt~$( F69A!>f`$M9 literal 0 HcmV?d00001 diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MMDLibGameTests.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MMDLibGameTests.java index 7e83f598..8731d028 100644 --- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MMDLibGameTests.java +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/MMDLibGameTests.java @@ -324,6 +324,30 @@ public static void cyclePlan(GameTestHelper helper) { helper.succeed(); } + @GameTest(template = EMPTY) + public static void recipeCycleRunner(GameTestHelper helper) { + RecipeChainSmoke.runner(helper.getLevel()); + helper.succeed(); + } + + @GameTest(template = EMPTY) + public static void recipeChainPriority(GameTestHelper helper) { + RecipeChainSmoke.priority(helper.getLevel()); + helper.succeed(); + } + + @GameTest(template = EMPTY) + public static void recipeChainConcurrent(GameTestHelper helper) { + RecipeChainSmoke.concurrent(helper.getLevel()); + helper.succeed(); + } + + @GameTest(template = EMPTY) + public static void recipeChainDiscovery(GameTestHelper helper) { + RecipeChainSmoke.discovery(helper.getLevel()); + helper.succeed(); + } + @GameTest(template = EMPTY) public static void processorWorkedRun(GameTestHelper helper) { ProcessorSmoke.workedRun(helper.getLevel()); diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/RecipeChainSmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/RecipeChainSmoke.java new file mode 100644 index 00000000..90f9a8a4 --- /dev/null +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/RecipeChainSmoke.java @@ -0,0 +1,427 @@ +package zone.moddev.mc.lib.smoke; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import net.minecraft.core.component.DataComponents; +import net.minecraft.nbt.NbtOps; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.Ingredient; + +import zone.moddev.mc.lib.api.capabilities.EnergyBuffer; +import zone.moddev.mc.lib.api.capabilities.IoMode; +import zone.moddev.mc.lib.api.capabilities.ItemStorage; +import zone.moddev.mc.lib.api.capabilities.Role; +import zone.moddev.mc.lib.gui.runtime.ClientMenuItems; +import zone.moddev.mc.lib.machine.feature.RecipeChain; +import zone.moddev.mc.lib.machine.feature.RecipeCycle; +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient.EnergyPart; +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient.ItemPart; +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient; +import zone.moddev.mc.lib.machine.inventory.MachineInventory; +import zone.moddev.mc.lib.machine.neoforge.RecipeOperations; +import zone.moddev.mc.lib.machine.neoforge.StorageGroups; +import zone.moddev.mc.lib.machine.recipe.MachineProduct.ItemProduct; +import zone.moddev.mc.lib.machine.recipe.MachineRecipe; +import zone.moddev.mc.lib.machine.recipe.RecipeGraph; + +/** Shared runner, priority, concurrent demand and discovery integration. */ +final class RecipeChainSmoke { + private RecipeChainSmoke() { + } + + private static ResourceLocation id(String value) { + return ResourceLocation.fromNamespaceAndPath("mmdlib_test", value); + } + + private static MachineRecipe recipe(Item input, int count, Item output, + int produced, int ticks, long energy) { + var inputs = new LinkedHashMap>(); + if (input != null) + inputs.put("input", + List.of(new ItemPart(Ingredient.of(input), count))); + inputs.put("energy", List.of(new EnergyPart(energy))); + return new MachineRecipe(inputs, + Map.of("output", + List.of(new ItemProduct(new ItemStack(output, produced), 1))), + ticks); + } + + private static final class Rig { + final Item[] products = {Items.COBBLESTONE, Items.GRAVEL, Items.SAND, + Items.GLASS, Items.GLASS_PANE}; + final ItemStorage items = new ItemStorage(5).role(Role.OUTPUT, 0, 1, 2, + 3, 4); + final EnergyBuffer energy = new EnergyBuffer(100000, 100000); + final RecipeChain chain; + + Rig() { + var groups = java.util.stream.IntStream.range(0, 5) + .mapToObj(i -> StorageGroups.items(items, i)).toList(); + var steps = new ArrayList(); + for (int i = 0; i < 5; i++) { + var inventory = MachineInventory.builder() + .group("output", groups.get(i)) + .group("energy", StorageGroups.energy(energy)); + if (i > 0) + inventory.group("input", groups.get(i - 1)); + steps.add(new RecipeChain.Step(id("stage_" + i), + recipe(i == 0 ? null : products[i - 1], i == 4 ? 6 : 1, + products[i], i == 4 ? 16 : 1, 3, 7), + inventory.build())); + } + chain = new RecipeChain(steps); + items.pendingClaims(chain::pendingTake); + energy.setStored(100000); + } + } + + static void runner(ServerLevel level) { + var rig = new Rig(); + var step = rig.chain.step(1); + var runner = new RecipeCycle(step.inventory()); + rig.items.restoreStack(0, new ItemStack(Items.COBBLESTONE, 2)); + rig.energy.setStored(0); + require(runner.start(step.id(), step.recipe()), + "reserve without power"); + require(runner.progress() == 0 && rig.energy.stored() == 0, + "reserving does not process or charge"); + require(runner.advance(level.random) == RecipeCycle.Result.STALLED, + "no power retains active work"); + require(rig.items.extractItem(0, 64, true).getCount() == 1, + "only unreserved surplus is extractable"); + rig.energy.setStored(7); + runner.advance(level.random); + var saved = runner.state(); + var ops = RegistryOps.create(NbtOps.INSTANCE, level.registryAccess()); + var encoded = RecipeCycle.State.CODEC.encodeStart(ops, saved) + .getOrThrow(); + require( + runner.restore( + RecipeCycle.State.CODEC.parse(ops, encoded).getOrThrow()), + "saved runner restores"); + require(runner.restore(saved) && rig.items.plan(0).take() == 1, + "repeated restore does not accumulate claims"); + require(!runner.start(id("replacement"), step.recipe()), + "active work cannot be replaced"); + runner.advance(level.random); + require( + runner.advance(level.random) == RecipeCycle.Result.COMPLETED + && rig.energy.stored() == 0 + && rig.items.getStackInSlot(1).is(Items.GRAVEL), + "exact total energy and one output after three paid ticks"); + require(runner.advance(level.random) == RecipeCycle.Result.IDLE, + "completion is never repeated"); + blockedCompletion(level); + } + + private static void blockedCompletion(ServerLevel level) { + var items = new CrusherSmoke.Capped(2); + items.role(Role.INPUT, 0).role(Role.OUTPUT, 1); + items.restoreStack(0, new ItemStack(Items.COBBLESTONE)); + var energy = new EnergyBuffer(10, 10); + energy.setStored(3); + var inventory = MachineInventory.builder() + .group("input", StorageGroups.items(items, 0)) + .group("output", StorageGroups.items(items, 1)) + .group("energy", StorageGroups.energy(energy)).build(); + var runner = new RecipeCycle(inventory); + require( + runner.start(id("blocked"), + recipe(Items.COBBLESTONE, 1, Items.GRAVEL, 1, 1, 3)), + "blocked-completion fixture reserves"); + items.cap = 0; + require(runner.advance(level.random) == RecipeCycle.Result.BLOCKED + && runner.progress() == 1 && energy.stored() == 0 + && items.getStackInSlot(0).getCount() == 1 + && items.getStackInSlot(1).isEmpty() && items.plan(0).take() == 1, + "subclass extraction failures roll back contents and reservations"); + items.cap = Integer.MAX_VALUE; + require(runner.advance(level.random) == RecipeCycle.Result.COMPLETED + && energy.stored() == 0 && items.getStackInSlot(1).is(Items.GRAVEL), + "blocked completion retries without charging twice"); + } + + static void priority(ServerLevel level) { + var rig = new Rig(); + rig.chain.target(4, 64); + rig.items.restoreStack(3, new ItemStack(Items.GLASS, 3)); + var before = rig.items.getStackInSlot(3).copy(); + var hopper = rig.items.view(i -> IoMode.OUTPUT); + require( + hopper.extractItem(3, 64, true).isEmpty() + && hopper.extractItem(3, 64, false).isEmpty(), + "partial crafting batch protected before machine tick"); + require( + ItemStack.matches(before, rig.items.getStackInSlot(3)) + && rig.items.reservationPlans().get(3).isNone(), + "simulation creates neither mutations nor active reservations"); + require(rig.items.plan(3).take() == 3, + "menu snapshot includes batch claim"); + var mirror = new ClientMenuItems(5, rig.items); + mirror.setStackInSlot(3, before.copy()); + mirror.setPlan(3, rig.items.plan(3)); + require(mirror.extractItem(3, 64, true).isEmpty(), + "client click prediction observes the same pending claim"); + rig.chain.target(4, 0); + require(hopper.extractItem(3, 64, true).getCount() == 3, + "removed demand immediately releases pending claims"); + rig.chain.target(4, 64); + rig.chain.paused(true); + require(hopper.extractItem(3, 64, true).getCount() == 3, + "manual pause releases pending batch protection"); + rig.chain.paused(false); + rig.chain.held(true); + require(hopper.extractItem(3, 64, true).getCount() == 3, + "host suspension releases pending claims"); + rig.chain.held(false); + rig.chain.drain(); + require(hopper.extractItem(3, 64, true).getCount() == 3, + "switch request releases pending claims before ticking"); + rig.chain.cancelDrain(); + rig.items.restoreStack(3, new ItemStack(Items.GLASS, 8)); + require(hopper.extractItem(3, 64, true).getCount() == 2, + "only the next batch is protected, surplus stays free"); + rig.chain.tick(level.random); + require( + rig.chain.cycle(4).plan().isPresent() + && rig.items.reservationPlans().get(3).take() == 6, + "processor can consume its own pending batch"); + rig.chain.drain(); + require(!rig.chain.drained(), "drain waits for active cycles"); + rig.chain.paused(true); + rig.chain.tick(level.random); + require(!rig.chain.drained() && rig.items.plan(3).take() == 6, + "pause does not abandon active work during switch"); + rig.chain.paused(false); + for (int i = 0; i < 10; i++) + rig.chain.tick(level.random); + require( + rig.chain.drained() && rig.items.getStackInSlot(4).getCount() == 16, + "drain completes existing work without admitting new batches"); + require(rig.items.getStackInSlot(3).getCount() == 2, + "old path leftovers are preserved"); + } + + static void concurrent(ServerLevel level) { + var rig = new Rig(); + rig.chain.target(4, 64); + boolean concurrent = false; + for (int tick = 0; tick < 800; tick++) { + rig.chain.tick(level.random); + int active = 0; + for (int i = 0; i < 5; i++) + if (rig.chain.cycle(i).plan().isPresent()) + active++; + concurrent |= active > 1; + } + require(concurrent, "multiple stages run together"); + require(rig.items.getStackInSlot(4).getCount() == 64, + "None intermediates still supply six-item crafting batches"); + require(rig.energy.stored() == 99300, + "24 four-stage glass cycles and four pane batches pay exactly 700 FE"); + long energy = rig.energy.stored(); + for (int tick = 0; tick < 30; tick++) + rig.chain.tick(level.random); + require(rig.energy.stored() == energy, "satisfied targets stop work"); + rig.items.extractItem(4, 1, false); + // A sixteen-item recipe cannot fit in a slot holding 63. Do not void + // overflow or lock its inputs while the final output is blocked. + rig.items.restoreStack(3, new ItemStack(Items.GLASS, 6)); + require(rig.chain.pendingTake(3) == 0, + "blocked output releases pending claims"); + + rig.items.restoreStack(3, ItemStack.EMPTY); + rig.items.restoreStack(4, new ItemStack(Items.DIRT)); + for (int tick = 0; tick < 30; tick++) + rig.chain.tick(level.random); + require( + rig.energy.stored() == energy + && rig.items.getStackInSlot(0).isEmpty(), + "blocked final output does not propagate unfillable demand to None stages"); + rig.chain.target(0, 1); + for (int tick = 0; tick < 30; tick++) + rig.chain.tick(level.random); + require( + rig.items.getStackInSlot(0).getCount() == 1 + && rig.chain.cycle(0).plan().isEmpty(), + "independent source target still refills while downstream output is blocked"); + + var buffered = new Rig(); + buffered.chain.target(3, 6); // One downstream pane batch. + buffered.chain.bufferLimit(3, 6); + buffered.chain.target(4, 64); + buffered.items.restoreStack(2, new ItemStack(Items.SAND, 64)); + buffered.items.restoreStack(3, new ItemStack(Items.GLASS, 6)); + require(buffered.chain.pendingTake(2) == 0, + "a ready One Run buffer does not reserve more input for a distant Full Stack target"); + buffered.chain.tick(level.random); + require( + buffered.chain.cycle(4).plan().isPresent() + && buffered.chain.cycle(3).plan().isPresent(), + "consuming the ready batch allows its replacement to run concurrently"); + + var saved = new Rig(); + saved.chain.target(4, 64); + for (int i = 0; i < 12; i++) + saved.chain.tick(level.random); + saved.chain.drain(); + var ops = RegistryOps.create(NbtOps.INSTANCE, level.registryAccess()); + var encoded = RecipeChain.State.CODEC + .encodeStart(ops, saved.chain.state()).getOrThrow(); + var copy = new Rig(); + for (int i = 0; i < 5; i++) + copy.items.restoreStack(i, saved.items.getStackInSlot(i)); + copy.energy.setStored(saved.energy.stored()); + require( + copy.chain.restore( + RecipeChain.State.CODEC.parse(ops, encoded).getOrThrow()), + "concurrent saved plans restore against shared stage storage"); + for (int i = 0; i < 10; i++) { + saved.chain.tick(level.random); + copy.chain.tick(level.random); + } + require( + copy.chain.drained() + && copy.energy.stored() == saved.energy.stored(), + "pending drain and paid progress survive save/load"); + for (int i = 0; i < 5; i++) + require( + ItemStack.matches(copy.items.getStackInSlot(i), + saved.items.getStackInSlot(i)), + "save/load preserves every stage output"); + fairness(level); + admission(level); + } + + private static void admission(ServerLevel level) { + var rig = new Rig(); + rig.chain.target(0, 64); + rig.chain.target(1, 64); + rig.chain.tick(level.random); + require(rig.chain.cycle(0).plan().isPresent(), + "source starts while admitted"); + for (int tick = 0; tick < 10; tick++) + rig.chain.tick(level.random, stage -> stage != 0); + require( + rig.items.getStackInSlot(1).getCount() == 1 + && rig.chain.cycle(0).plan().isEmpty(), + "closing source admission lets active work finish and downstream work run"); + rig.chain.tick(level.random); + require(rig.chain.cycle(0).plan().isPresent(), + "reopening admission resumes source work"); + } + + private static void fairness(ServerLevel level) { + var items = new ItemStorage(2).role(Role.OUTPUT, 0, 1); + var energy = new EnergyBuffer(100, 100); + var power = StorageGroups.energy(energy); + var source = StorageGroups.items(items, 0); + var output = StorageGroups.items(items, 1); + var chain = new RecipeChain(List.of( + new RecipeChain.Step(id("costly_source"), + recipe(null, 0, Items.COBBLESTONE, 1, 1, 10), + MachineInventory.builder().group("output", source) + .group("energy", power).build()), + new RecipeChain.Step(id("cheap_grind"), + recipe(Items.COBBLESTONE, 1, Items.GRAVEL, 1, 1, 1), + MachineInventory.builder().group("input", source) + .group("output", output).group("energy", power).build()))); + items.restoreStack(0, new ItemStack(Items.COBBLESTONE, 32)); + chain.target(0, 64); + chain.target(1, 64); + chain.tick(level.random); + for (int i = 0; i < 11; i++) { + energy.setStored(energy.stored() + 1); + chain.tick(level.random); + } + require(items.getStackInSlot(0).getCount() == 32 + && items.getStackInSlot(1).getCount() == 1 && energy.stored() == 0, + "scarce FE funds both stages without cheaper work draining the waiting charge"); + } + + static void discovery(ServerLevel level) { + var cost = new RecipeOperations.Cost(5, 20); + var panes = level.getRecipeManager() + .byKey(ResourceLocation.parse("minecraft:glass_pane")) + .orElseThrow(); + var op = RecipeOperations + .crafting(panes, new ItemStack(Items.GLASS), level, cost) + .orElseThrow(); + require(op.inputCount() == 6 && op.output().getCount() == 16, + "craft adapter preserves the shaped six-glass batch"); + require(RecipeOperations + .crafting(panes, new ItemStack(Items.SAND), level, cost).isEmpty(), + "unrelated materials are not invented"); + var named = new ItemStack(Items.GLASS); + named.set(DataComponents.CUSTOM_NAME, Component.literal("Named glass")); + var exact = RecipeOperations.crafting(panes, named, level, cost) + .orElseThrow(); + var ingredient = ((ItemPart) exact.recipe().inputs().get("input") + .getFirst()).items(); + require( + ingredient.test(named) + && !ingredient.test(new ItemStack(Items.GLASS)), + "adapted recipes preserve the concrete source components"); + var mixed = level.getRecipeManager() + .byKey(ResourceLocation.parse("minecraft:stone_pickaxe")) + .orElseThrow(); + require(RecipeOperations + .crafting(mixed, new ItemStack(Items.COBBLESTONE), level, cost) + .isEmpty(), "mixed-material recipes are excluded"); + var furnace = level.getRecipeManager() + .byKey(ResourceLocation.parse("minecraft:glass")).orElseThrow(); + require( + RecipeOperations + .smelting(furnace, new ItemStack(Items.SAND), level, cost) + .orElseThrow().output().is(Items.GLASS), + "ordinary smelting is discoverable"); + var calls = new AtomicInteger(); + java.util.function.Function> resolver = source -> { + calls.incrementAndGet(); + Item next = source.is(Items.COBBLESTONE) + ? Items.GRAVEL + : Items.COBBLESTONE; + var recipe = recipe(source.getItem(), 1, next, 1, 5, 20); + return List.of(RecipeOperations + .machine(id(next == Items.GRAVEL ? "forward" : "back"), + id("grind"), recipe, source) + .orElseThrow()); + }; + var cache = new RecipeGraph.Cache(); + var snapshot = new Object(); + var root = new ItemStack(Items.COBBLESTONE); + var graph = cache.get(snapshot, root, resolver, + RecipeGraph.Limits.defaults()); + require( + graph.size() == 2 && graph.edges().size() == 2 + && graph.pathTo(1).size() == 1 && calls.get() == 2, + "cycles are edges, never infinite expansion"); + cache.get(snapshot, root, resolver, RecipeGraph.Limits.defaults()); + require(calls.get() == 2, "same snapshot reuses discovery"); + cache.get(new Object(), root, resolver, RecipeGraph.Limits.defaults()); + require(calls.get() == 4, "reload invalidates discovery"); + cache.get(snapshot, root, resolver, RecipeGraph.Limits.defaults()); + require( + cache.get(snapshot, root, resolver, new RecipeGraph.Limits(1, 2, 2)) + .truncated(), + "changed limits invalidate the cached graph"); + require(RecipeGraph + .discover(root, resolver, new RecipeGraph.Limits(1, 2, 2)) + .truncated(), "catalog limits report truncation"); + } + + private static void require(boolean condition, String message) { + if (!condition) + throw new AssertionError(message); + } +} 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 38051dd3..72e02af5 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/ElementBehaviorsTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/ElementBehaviorsTest.java @@ -1,6 +1,7 @@ package zone.moddev.mc.lib.gui; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; @@ -45,6 +46,51 @@ * Mod types outside the implementation package exercise the public contracts. */ class ElementBehaviorsTest { + @Test + void foregroundChooserReceivesCoveredHitsButStillRespectsViewport() { + var slot = new ModElement(Common.empty()); + var viewport = new Rect(0, 0, 80, 60); + var drawer = new Rect(20, 0, 60, 60); + boolean[] open = {true}; + int[] clicks = {0}; + var chooser = new ElementBehavior() { + public Optional overlayBounds() { + return open[0] + ? Optional.of(new Rect(0, 20, 100, 22)) + : Optional.empty(); + } + public void dismissOverlay() { + open[0] = false; + } + public Click mouseClicked(double x, double y, int button) { + clicks[0]++; + return Click.CONSUME; + } + }; + var input = new ElementInput<>(List.of(slot), e -> chooser, e -> true, + e -> new Rect(0, 0, 60, 40), + (x, y) -> viewport.contains(x, y) && !drawer.contains(x, y), + viewport::contains, (e, entered) -> { + }); + input.update(); + input.hover(30, 25); + assertEquals(slot, input.hovered()); + assertTrue(input.click(30, 25, 0)); + assertEquals(1, clicks[0]); + assertTrue(open[0], "Clicking the chooser must not dismiss it"); + assertNull(input.hit(90, 25), + "Overlay remains clipped to the viewport"); + assertTrue(input.click(90, 25, 0)); + assertFalse(open[0]); + input.update(); + assertNull(input.hovered(), "Covered ordinary controls remain blocked"); + assertFalse(input.click(30, 25, 0)); + assertFalse(input.scroll(30, 25, 0, 1)); + assertEquals(1, clicks[0]); + assertTrue(input.click(5, 5, 0)); + assertEquals(2, clicks[0]); + } + @Test void transientChooserOwnsHitsOutsideItsSlotAndConsumesDismissal() { var slot = new ModElement(Common.empty()); diff --git a/src/test/java/zone/moddev/mc/lib/gui/GroupPresentationTest.java b/src/test/java/zone/moddev/mc/lib/gui/GroupPresentationTest.java index cfc16cfb..2da2926e 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/GroupPresentationTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/GroupPresentationTest.java @@ -6,7 +6,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.util.IdentityHashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import net.minecraft.client.gui.Font; @@ -19,6 +21,7 @@ import zone.moddev.mc.lib.gui.client.ElementBehaviors; import zone.moddev.mc.lib.gui.client.ElementHighlight; import zone.moddev.mc.lib.gui.client.ElementRenderAccess; +import zone.moddev.mc.lib.gui.client.GroupColourProvider; import zone.moddev.mc.lib.gui.client.GroupLabelProvider; import zone.moddev.mc.lib.gui.client.HighlightPresentation; import zone.moddev.mc.lib.gui.layout.Rect; @@ -110,11 +113,11 @@ public Optional capability(Class type) { @Test void fallbackGeometryAndOwnedDecorationRemainDistinct() { var bounds = new Rect(10, 20, 30, 40); - assertEquals(bounds, + assertEquals(new Rect(8, 18, 34, 44), ElementHighlight.decoration(0xff123456).outline(bounds)); - assertEquals(bounds, + assertEquals(new Rect(8, 18, 34, 44), ElementHighlight.selection(0xff123456).outline(bounds)); - assertEquals(new Rect(9, 19, 32, 42), + assertEquals(new Rect(8, 18, 34, 44), ElementHighlight.emphasis(0xff123456).outline(bounds)); assertThrows(IllegalArgumentException.class, () -> new ElementHighlight(ElementHighlight.Kind.EMPHASIS, 0, -1)); @@ -122,6 +125,9 @@ void fallbackGeometryAndOwnedDecorationRemainDistinct() { new LabelElement(Common.empty(), CAPTION)); var behavior = ElementBehaviors.builtins() .create(new ElementBehaviorsTest.Access(group)); + assertEquals(0xffabcdef, + BehaviorCapabilities.find(behavior, GroupColourProvider.class) + .orElseThrow().groupColour()); var presentation = BehaviorCapabilities .find(behavior, HighlightPresentation.class).orElseThrow(); assertDoesNotThrow( @@ -129,4 +135,58 @@ void fallbackGeometryAndOwnedDecorationRemainDistinct() { ElementHighlight.decoration(0xff123456)), "Owned overlay decoration must not be drawn again by another feature"); } + + @Test + void nearestGroupColourCrossesPlainContainersAndSupportsHostAssociations() { + var leaf = new LabelElement(Common.empty(), CAPTION); + var inner = new ColouredGroupElement(Common.empty(), 0xff55ff88, leaf); + var plain = new GroupElement(Common.empty(), Optional.empty(), + Optional.empty(), 2, List.of(inner)); + var outer = new ColouredGroupElement(Common.empty(), 0xff4488cc, plain); + Map parents = new IdentityHashMap<>(); + parents.put(leaf, inner); + parents.put(inner, plain); + parents.put(plain, outer); + var registry = ElementBehaviors.builtins(); + Map behaviors = new IdentityHashMap<>(); + for (var element : List.of(leaf, inner, plain, outer)) + behaviors.put(element, + registry.create(new ElementBehaviorsTest.Access(element))); + Map associations = new IdentityHashMap<>(); + var access = new ElementRenderAccess() { + public Font font() { + return null; + } + + public Rect viewport() { + return new Rect(0, 0, 100, 100); + } + + public Optional parent(Element element) { + return Optional.ofNullable(parents.get(element)); + } + + public Optional capability(Element element, Class type) { + var behavior = behaviors.get(element); + return behavior == null + ? Optional.empty() + : BehaviorCapabilities.find(behavior, type); + } + + public Optional associatedGroupColour(Element element) { + return Optional.ofNullable(associations.get(element)); + } + }; + assertEquals(Optional.of(0xff55ff88), access.groupColour(leaf)); + assertEquals(Optional.of(0xff4488cc), access.groupColour(plain)); + associations.put(inner, 0xffabcdef); + assertEquals(Optional.of(0xff55ff88), access.groupColour(leaf), + "The wrapper owns its colour even when associated with another group"); + behaviors.remove(inner); + assertEquals(Optional.of(0xffabcdef), access.groupColour(leaf), + "Legacy group anchors also supply inherited colour"); + parents.remove(leaf); + assertTrue(access.groupColour(leaf).isEmpty(), + "Ungrouped elements keep their original appearance"); + } } diff --git a/src/test/java/zone/moddev/mc/lib/gui/RecipeDrawerLayoutTest.java b/src/test/java/zone/moddev/mc/lib/gui/RecipeDrawerLayoutTest.java new file mode 100644 index 00000000..6968084f --- /dev/null +++ b/src/test/java/zone/moddev/mc/lib/gui/RecipeDrawerLayoutTest.java @@ -0,0 +1,77 @@ +package zone.moddev.mc.lib.gui; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import zone.moddev.mc.lib.gui.layout.RecipeDrawerLayout; +import zone.moddev.mc.lib.gui.layout.Rect; +import zone.moddev.mc.lib.gui.model.Edge; + +class RecipeDrawerLayoutTest { + @Test + void backgroundIncludesTabRailWithoutOvershootingOverlappingPanels() { + var tab = new Rect(200, 60, 22, 24); + var body = new Rect(20, 34, 180, 166); + assertEquals(new Rect(20, 34, 202, 166), + zone.moddev.mc.lib.gui.layout.SideDrawerLayout.frame(tab, body)); + assertEquals(new Rect(200, 34, 22, 166), + zone.moddev.mc.lib.gui.layout.SideDrawerLayout.rail(tab, body)); + var overlapping = new Rect(100, 34, 180, 166); + assertEquals(overlapping, zone.moddev.mc.lib.gui.layout.SideDrawerLayout + .frame(tab, overlapping)); + } + @Test + void narrowMarginsOverlapInsteadOfShrinkingRecipeRows() { + var panel = new Rect(70, 30, 220, 190); + var left = RecipeDrawerLayout.body(Edge.LEFT, new Rect(48, 54, 22, 24), + panel, 360, 236, 168, 24); + var right = RecipeDrawerLayout.body(Edge.RIGHT, + new Rect(290, 54, 22, 24), panel, 360, 236, 168, 24); + assertEquals(168, RecipeDrawerLayout.content(left).width()); + assertEquals(168, RecipeDrawerLayout.content(right).width()); + assertTrue(left.right() > panel.x()); + assertTrue(right.x() < panel.right()); + assertEquals(70, left.x()); + assertEquals(290, right.right()); + assertTrue(left.x() >= 4 && right.right() <= 356); + assertEquals(panel.y() + 4, left.y()); + assertEquals(panel.bottom() - 4, left.bottom()); + assertEquals(panel.y() + 4, right.y()); + assertEquals(panel.bottom() - 4, right.bottom()); + assertEquals(5, RecipeDrawerLayout.pageSize(left, 24)); + } + + @Test + void constrainedViewportsKeepContentOnOneSideOfTheRail() { + for (int screenWidth : new int[]{180, 240, 360, 900}) + for (var edge : Edge.values()) { + var panel = new Rect((screenWidth - 140) / 2, 30, 140, 190); + var tab = new Rect( + edge == Edge.LEFT ? panel.x() - 22 : panel.right(), 54, 22, + 24); + var body = RecipeDrawerLayout.body(edge, tab, panel, + screenWidth, 236, 168, 24); + var content = RecipeDrawerLayout.content(body); + assertTrue(body.right() <= tab.x() || body.x() >= tab.right(), + "Recipe body must not cross the navigation rail"); + assertTrue(body.x() >= 4 && body.right() <= screenWidth - 4); + assertTrue(content.width() >= 0); + } + } + + @Test + void wideScreensUseTheSideMarginAndShortScreensPageCompleteRows() { + var panel = new Rect(300, 30, 220, 190); + var tab = new Rect(278, 54, 22, 24); + var body = RecipeDrawerLayout.body(Edge.LEFT, tab, panel, 900, 150, 168, + 24); + assertEquals(tab.x(), body.right()); + assertTrue(body.bottom() <= 150); + assertEquals(2, RecipeDrawerLayout.pageSize(body, 24)); + var content = RecipeDrawerLayout.content(body); + assertTrue( + content.bottom() <= body.bottom() - RecipeDrawerLayout.FOOTER); + } +} diff --git a/src/test/java/zone/moddev/mc/lib/gui/SpriteElementsTest.java b/src/test/java/zone/moddev/mc/lib/gui/SpriteElementsTest.java index 16d7e561..91099609 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/SpriteElementsTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/SpriteElementsTest.java @@ -158,7 +158,9 @@ void outlineWrapsExactlyOneChildAndPreservesItsGeometry() throws Exception { assertEquals(18, bounds.height()); assertEquals(bounds.x() + 20, layout.bounds(screen.find("two").orElseThrow()).x()); - assertEquals(new Rect(bounds.x() - 1, bounds.y() - 1, 40, 20), + assertEquals(new Rect(bounds.x() - 2, bounds.y() - 2, 42, 22), + outline.outline(bounds, false)); + assertEquals(new Rect(bounds.x() - 2, bounds.y() - 2, 42, 22), outline.outline(bounds, true)); assertThrows(ScreenException.class, () -> read("")); diff --git a/src/test/java/zone/moddev/mc/lib/gui/client/SlotRendererTest.java b/src/test/java/zone/moddev/mc/lib/gui/client/SlotRendererTest.java new file mode 100644 index 00000000..6e00bd3b --- /dev/null +++ b/src/test/java/zone/moddev/mc/lib/gui/client/SlotRendererTest.java @@ -0,0 +1,23 @@ +package zone.moddev.mc.lib.gui.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +class SlotRendererTest { + @Test + void groupWashPreservesNeutralAndExistingSlotShading() { + assertEquals(0xf0cd82, + ElementDrawing.backgroundTint(0xf0cd82, Optional.empty())); + assertEquals(0xf0cd82, + ElementDrawing.backgroundTint(0xf0cd82, Optional.of(0xffffffff))); + assertEquals(0xff9999, + ElementDrawing.backgroundTint(0xffffff, Optional.of(0xffff0000))); + assertEquals(0x804c4c, + ElementDrawing.backgroundTint(0x808080, Optional.of(0xffff0000))); + assertEquals(0, + ElementDrawing.backgroundTint(0, Optional.of(0xffff0000))); + } +} diff --git a/src/test/java/zone/moddev/mc/lib/machine/EntityDisplayTest.java b/src/test/java/zone/moddev/mc/lib/machine/EntityDisplayTest.java index 6abfd846..e9102777 100644 --- a/src/test/java/zone/moddev/mc/lib/machine/EntityDisplayTest.java +++ b/src/test/java/zone/moddev/mc/lib/machine/EntityDisplayTest.java @@ -61,9 +61,10 @@ private MachineDefinition load(String attributes, boolean portable) """ - + + + - diff --git a/src/test/java/zone/moddev/mc/lib/machine/FaceOverlayTest.java b/src/test/java/zone/moddev/mc/lib/machine/FaceOverlayTest.java new file mode 100644 index 00000000..5678a7df --- /dev/null +++ b/src/test/java/zone/moddev/mc/lib/machine/FaceOverlayTest.java @@ -0,0 +1,111 @@ +package zone.moddev.mc.lib.machine; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; + +import java.util.List; +import java.util.Map; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.PackType; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import zone.moddev.mc.lib.api.capabilities.RelativeFace; +import zone.moddev.mc.lib.common.loading.DefinitionLoader.SourceRoot; +import zone.moddev.mc.lib.machine.definition.MachineDefinitions; +import zone.moddev.mc.lib.machine.neoforge.MachineResourcePack; +import zone.moddev.mc.lib.machine.presentation.FaceOverlay; +import zone.moddev.mc.lib.machine.presentation.VisualCondition; + +class FaceOverlayTest { + @TempDir + Path directory; + + private zone.moddev.mc.lib.machine.definition.MachineDefinition load( + String settings) throws Exception { + Files.createDirectories(directory.resolve("machine")); + Files.writeString(directory.resolve("machine/overlay.xml"), + """ + + + + + + + + + """ + .formatted(settings)); + return MachineDefinitions + .load(List.of( + new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"), + getClass().getClassLoader()), + new SourceRoot("test", directory, getClass().getClassLoader()))) + .get(ResourceLocation.parse("test:overlay")); + } + + @Test + void framesCoexistAndOnlyCoverTheirOwnRegion() throws Exception { + var definition = load( + "x='5' y='13.5' width='6' height='1' frames='4' variable='$processors.crusher.progress' emissive='true'"); + assertEquals(5, definition.modelParts().size()); + assertTrue(definition.faceTextures().isEmpty()); + for (double value : new double[]{-2, 0, 0.9, 1, 1.9, 2, 3, 9}) { + int selected = (int) Math.max(0, Math.min(3, value)); + for (int frame = 0; frame < 4; frame++) + assertEquals(frame == selected, + VisualCondition + .compile(definition.modelParts().get(frame).when(), + definition.visualDefaults()) + .test(Map.of("processors.crusher.progress", value))); + } + var assets = MachineResourcePack.build(PackType.CLIENT_RESOURCES, + Map.of(definition.id(), definition)); + var model = com.google.gson.JsonParser.parseString(new String( + assets + .get(ResourceLocation.parse("test:models/block/overlay.json")), + java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject(); + var part = model.getAsJsonArray("parts").get(2).getAsJsonObject(); + assertTrue(part.get("emissive").getAsBoolean()); + var child = part.getAsJsonObject("model"); + assertEquals("minecraft:cutout", + child.get("render_type").getAsString()); + var element = child.getAsJsonArray("elements").get(0).getAsJsonObject(); + assertEquals("[5.0,1.5,-0.01]", element.get("from").toString()); + assertEquals("[11.0,2.5,-0.01]", element.get("to").toString()); + var face = element.getAsJsonObject("faces").getAsJsonObject("north"); + assertEquals("[0.0,8.0,16.0,12.0]", face.get("uv").toString()); + assertFalse(face.has("cullface")); + } + + @Test + void validatesBoundsAndNumericBindings() { + for (String settings : List.of("x='NaN' y='0' width='1' height='1'", + "x='15' y='0' width='2' height='1'", + "x='0' y='0' width='1' height='1' frames='33' variable='$processors.crusher.progress'", + "x='0' y='0' width='1' height='1' frames='4'", + "x='0' y='0' width='1' height='1' frames='4' variable='$processors.crusher.running'", + "x='0' y='0' width='1' height='1' frames='4' variable='$processors.crusher.missing'")) + assertThrows(IllegalArgumentException.class, () -> load(settings)); + } + + @Test + void supportsEveryRelativeFace() { + for (var side : RelativeFace.values()) { + var overlay = new FaceOverlay(side, + ResourceLocation.parse("test:block/lights"), 2, 3, 4, 5, 0, 1, + false); + var element = overlay.model().getAsJsonArray("elements").get(0) + .getAsJsonObject(); + assertTrue(element.getAsJsonObject("faces").has( + side.toWorld(net.minecraft.core.Direction.NORTH).getName())); + } + } +} diff --git a/src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java b/src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java new file mode 100644 index 00000000..dd5b9934 --- /dev/null +++ b/src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java @@ -0,0 +1,175 @@ +package zone.moddev.mc.lib.machine; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; + +import java.util.List; + +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.phys.Vec3; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import zone.moddev.mc.lib.common.loading.DefinitionLoader.SourceRoot; +import zone.moddev.mc.lib.machine.definition.MachineDefinition; +import zone.moddev.mc.lib.machine.definition.MachineDefinitions; +import zone.moddev.mc.lib.machine.feature.ProcessorMachine; +import zone.moddev.mc.lib.machine.feature.ProcessorState; +import zone.moddev.mc.lib.machine.feature.StoredProcessor; + +class ItemDisplayTest { + @TempDir + Path directory; + + public static final class Fixture extends StoredProcessor { + public Fixture() { + variables.string("product", "").synced().define(); + variables.string("private_product", "").define(); + variables.string("invalid", "not an item id").synced().define(); + variables.bool("flag", false).visual().define(); + variables.entity("occupant").synced().define(); + } + public boolean canStart(ProcessorState state, + ProcessorMachine machine) { + return false; + } + public ProcessState process(ProcessorState state, + ProcessorMachine machine, int delta) { + return ProcessState.IDLE; + } + } + + private MachineDefinition load(String attributes, String extra) + throws Exception { + Files.createDirectories(directory.resolve("machine")); + Files.writeString(directory.resolve("machine/display.xml"), + """ + + + + %s + + + + + + """ + .formatted(attributes, extra)); + return loadMachine("display"); + } + + private MachineDefinition loadMachine(String name) { + return MachineDefinitions + .load(List.of( + new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"), + getClass().getClassLoader()), + new SourceRoot("test", directory, getClass().getClassLoader()))) + .get(ResourceLocation.parse("test:" + name)); + } + + @Test + void bindsWithoutItemRegistryLookupAndCoexistsWithEntityDisplays() + throws Exception { + var definition = load( + "variable='$processors.test.product' x='0.25' y='0.7' width='0.4' height='0.6'", + ""); + var display = definition.behavior().itemDisplay(); + assertNotNull(definition.behavior().entityDisplay()); + assertEquals("product", display.variable().name()); + assertEquals(.4f, display.width()); + assertEquals(.6f, display.height()); + assertEquals(new Vec3(.75, .7, -.002), display.offset(Direction.NORTH)); + assertEquals(new Vec3(1.002, .7, .75), display.offset(Direction.EAST)); + assertEquals(new Vec3(.25, .7, 1.002), display.offset(Direction.SOUTH)); + assertEquals(new Vec3(-.002, .7, .25), display.offset(Direction.WEST)); + assertThrows(IllegalArgumentException.class, + () -> display.offset(Direction.UP)); + var defaults = load("variable='$processors.test.product'", "") + .behavior().itemDisplay(); + assertEquals(.5, defaults.x()); + assertEquals(.5, defaults.y()); + assertEquals(.5f, defaults.width()); + } + + @Test + void nestedDisplaysInheritAndOverrideAlongsideConditionalParts() + throws Exception { + load("variable='$processors.test.product' width='0.4' height='0.6'", + "" + + ""); + Files.writeString(directory.resolve("machine/child.xml"), + """ + + + + + + + """); + var child = loadMachine("child"); + assertEquals(.8f, child.behavior().itemDisplay().width()); + assertEquals(.6f, child.behavior().itemDisplay().height()); + assertEquals("product", + child.behavior().itemDisplay().variable().name()); + assertEquals(.7f, child.behavior().entityDisplay().width()); + assertEquals(.9f, child.behavior().entityDisplay().height()); + assertEquals(1, child.modelParts().size()); + Files.writeString(directory.resolve("machine/grandchild.xml"), + """ + + + + """); + var grandchild = loadMachine("grandchild"); + assertEquals(child.behavior().itemDisplay(), + grandchild.behavior().itemDisplay()); + assertEquals(child.behavior().entityDisplay(), + grandchild.behavior().entityDisplay()); + assertEquals(child.modelParts(), grandchild.modelParts()); + } + + @Test + void displaysAreOnlyAllowedInsideAppearance() throws Exception { + for (var display : List.of( + "", + "")) { + load("variable='$processors.test.product'", ""); + var file = directory.resolve("machine/display.xml"); + Files.writeString(file, Files.readString(file).replace("", + display + "")); + var error = assertThrows(IllegalArgumentException.class, + () -> loadMachine("display")); + assertTrue( + error.getMessage().contains("Unexpected child of machine")); + } + } + + @Test + void invalidBindingsBoundsAndDuplicatesFailAtLoad() { + for (var attrs : List.of("variable='$processors.test.flag'", + "variable='$processors.test.private_product'", + "variable='$processors.test.missing'", + "variable='$processors.missing.product'", "variable='product'", + "variable='$processors.test.invalid'", + "variable='$processors.test.product' width='0'", + "variable='$processors.test.product' height='Infinity'", + "variable='$processors.test.product' x='NaN'", + "variable='$processors.test.product' y='-0.1'", + "variable='$processors.test.product' width='2'")) + assertThrows(IllegalArgumentException.class, () -> load(attrs, "")); + assertThrows(IllegalArgumentException.class, + () -> load("variable='$processors.test.product'", + "")); + assertThrows(IllegalArgumentException.class, () -> load( + "variable='$processors.test.product'", + "" + .repeat(2))); + } +} From 4ed0123c8faedbf98f2d0a8f160f107aeb1b945a Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Sun, 15 Nov 2026 18:28:57 +0200 Subject: [PATCH 2/3] Preserve standalone gauge rendering without presentation services --- .../lib/gui/client/BuiltinElementClients.java | 9 +++---- .../mc/lib/gui/client/ElementRenderers.java | 7 +++++ .../mc/lib/gui/ElementRenderersTest.java | 26 +++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) 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 3636c71b..3a5a6049 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 @@ -123,20 +123,19 @@ private static List> declarations() { ElementClient.of(SLOT) .renderer((element, c) -> slots.draw(c.graphics(), c.bounds(), element, c.access().contents(element), - c.access().hint(element), c.access().groupColour(element))) + c.access().hint(element), c.groupColour())) .behavior(SlotBehavior::new), ElementClient.of(GAUGE) .renderer((element, c) -> GaugeRenderer.draw(c.graphics(), c.bounds(), element.orientation(), element.fill(c.value()), - c.ratio(), c.access().groupColour(element))), + 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.access().groupColour(element))), + c.ratio(), c.groupColour())), ElementClient.of(ENERGY_GAUGE) .renderer((element, c) -> EnergyGaugeRenderer.draw(c.graphics(), - c.bounds(), element, c.ratio(), - c.access().groupColour(element))), + c.bounds(), element, c.ratio(), c.groupColour())), ElementClient.of(METER).renderer(MeterRenderer::draw), ElementClient.of(SIDE_CONFIG).renderer(SideConfigRenderer::draw) .renderer(ElementRenderers.Pass.OVERLAY, 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 2eb7df18..dd6a0958 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 @@ -103,6 +103,13 @@ public double ratio() { return element.fillRatio(value, maximum); } + /** Standalone contexts retain the default, untinted background. */ + public Optional groupColour() { + return access == null + ? Optional.empty() + : access.groupColour(element); + } + public ElementRenderAccess access() { return Objects.requireNonNull(access, "This render context has no presentation services"); diff --git a/src/test/java/zone/moddev/mc/lib/gui/ElementRenderersTest.java b/src/test/java/zone/moddev/mc/lib/gui/ElementRenderersTest.java index 223c3548..1a6e775b 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/ElementRenderersTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/ElementRenderersTest.java @@ -87,6 +87,32 @@ private ElementRenderers.Context context(Element element) { new Rect(0, 0, 20, 10), null, null, 0, 0, 0); } + @Test + void backgroundTintIsOptionalForStandaloneContexts() { + var element = new ModElement(Common.empty()); + assertTrue(context(element).groupColour().isEmpty()); + assertTrue( + new ElementRenderers.Context(null, element, new Rect(0, 0, 20, 10), + null, null, 0, 0, 0, 5).groupColour().isEmpty()); + var access = new ElementRenderAccess() { + public net.minecraft.client.gui.Font font() { + return null; + } + + public Rect viewport() { + return new Rect(0, 0, 20, 10); + } + + public Optional associatedGroupColour(Element target) { + assertSame(element, target); + return Optional.of(0x123456); + } + }; + assertEquals(Optional.of(0x123456), + new ElementRenderers.Context(null, element, new Rect(0, 0, 20, 10), + null, null, 0, 0, 0, 5, access).groupColour()); + } + @Test void mostSpecificFamilyAndExactOverrideAreIndependentOfRegistrationOrder() { for (boolean reverse : new boolean[]{false, true}) { From 269c5cb828538e1b81fa18f9d6eef3ebacb40241 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Sun, 15 Nov 2026 18:39:49 +0200 Subject: [PATCH 3/3] Keep foreground drawers above native slot contents --- .../java/zone/moddev/mc/lib/gui/client/MachineScreen.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) 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 ff31ebb1..c3290736 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 @@ -379,7 +379,9 @@ public void render(GuiGraphics g, int mx, int my, float partial) { e -> draw(g, e, bounds(e), mx, my, partial)); renderElements(ElementRenderers.Pass.FOREGROUND, g, partial, mx, my); g.pose().pushPose(); - g.pose().translate(0, 0, 200); + // Native slot items and decorations can reach z=200. Keep the whole + // foreground drawer above them, including its opaque background. + g.pose().translate(0, 0, 400); drawers.renderForeground(g, mx, my); g.pose().translate(0, 0, 10); drawers.renderTabs(g); @@ -388,9 +390,9 @@ public void render(GuiGraphics g, int mx, int my, float partial) { renderElements(ElementRenderers.Pass.TOP, g, partial, mx, my); g.pose().popPose(); g.pose().pushPose(); - // Item decorations add 200 to the drawer's 200; tooltips must clear + // Item decorations add 200 to the drawer's 400; tooltips must clear // that layer. - g.pose().translate(0, 0, 200); + g.pose().translate(0, 0, 400); try { if (elementInput.overlayOwner() == null && !drawers.covers(mx, my)) renderTooltip(g, mx, my);