Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
4678f6d
Support configurable machine facing and placement preferences
faceofcat Nov 17, 2026
332143b
Add fluid tags and mod-owned machine admission rules
faceofcat Nov 17, 2026
ed3f5ae
Expose transactional typed resources to machine processors
faceofcat Nov 17, 2026
5d073c6
Add processor placement preferences and accepted-placement callbacks
faceofcat Nov 17, 2026
20c724c
Expose existing machine redstone sources to comparators
faceofcat Nov 17, 2026
fa05158
Compose independent processors over shared machine resources
faceofcat Nov 17, 2026
a82ec44
Deliver Java callbacks for every recipe cycle transition
faceofcat Nov 17, 2026
6089113
Delegate machine energy ownership to a selected processor
faceofcat Nov 17, 2026
56d340f
Charge transactional operating energy per successful processor step
faceofcat Nov 17, 2026
63a3782
Preserve aliased energy and authored controls in processor composition
faceofcat Nov 17, 2026
49572c9
Explain the purpose and manual checks for every companion machine
faceofcat Nov 17, 2026
16039b9
Validate recipe diagnostics across shared machine consumers
faceofcat Nov 17, 2026
1c8457f
Update display and working-area tests for vertical facing
faceofcat Nov 17, 2026
5680ebc
Merge branch 'codex/machine-upgrades-displays' into codex/machine-por…
faceofcat Nov 17, 2026
bfd5564
Validate comparator source IDs while loading machine definitions
faceofcat Nov 17, 2026
2943c27
Honor the primary processor in keyless lookups and controls
faceofcat Nov 17, 2026
8ea8eef
Avoid neighbour updates during load-time facing repair
faceofcat Nov 17, 2026
d6b2b40
Reuse processor configurations in client sound ticks
faceofcat Nov 17, 2026
270f8fa
Share recipe input admission across Java resources and XML lanes
faceofcat Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 193 additions & 0 deletions docs/xml-machines.md
Original file line number Diff line number Diff line change
Expand Up @@ -1639,3 +1639,196 @@ emit world light. Default is false. Use transparency around glowing pixels.
MMDLib expands the declaration into conditional model parts, reusing tracking
snapshots and model invalidation when the selected frame changes. No per-machine
renderer or full-face variants are needed. Inventory models keep the base casing.

## Allowed facing and placement

`<block facing="horizontal" placement-facing="toward-player"/>` is the default.
`facing="all"` allows all six directions. A space-separated list allows any
nonempty subset, such as `up`, `down`, `up down`, or `north east up`.
`placement-facing="away-from-player"` reverses the placement preference.
Placement picks the nearest allowed look direction (opposite the look direction
for toward-player); a fixed direction always wins. Rotation/mirroring retains
its old direction when the transformed front is forbidden. Loaded states outside
the declared set normalize to north if allowed, otherwise the first allowed
Minecraft direction (down, up, north, south, west, east).

Vertical fronts use north as local top. Shapes, models, displays and working
areas share that orientation. Range upgrades expand the area's local plane.
The companion's Facing Demo machines illustrate all, away, up-only, down-only,
vertical and asymmetric sets; the existing crushers show horizontal defaults.

## Dynamic storage admission

Real slots accept `filter-class="your.ModAdmission"` or
`filter-processor="processor_id"`, alongside existing `item-tag` restrictions.
Tanks accept the same hooks and `fluid-tag="namespace:tag"` alongside exact `fluid`.
All applicable rules must pass. Recipe admission still accepts the union of linked
recipe inputs. Rules do not delete contents when tags, recipes or configuration change.

Implement `StorageAdmission` with `acceptsItem(ProcessorMachine, memberId, ItemStack)`
and/or `acceptsFluid(ProcessorMachine, memberId, FluidAmount)`. Unimplemented kinds
refuse insertion. A class needs a public no-argument constructor and is instantiated
per machine; a processor binding names a custom processor implementing that interface.
The member ID is the stable storage slot/tank ID, such as `fuel/0`. Values are detached;
the host can have a null level during construction/loading. Queries must not mutate
storage and must handle simulated operations. Read live config/recipes or invalidate
any private caches on reload. These hooks govern external admission; machine-product
transactions retain their existing internal insertion semantics.

The companion Admission Demo shows furnace fuel, vanilla smelting, item/fluid tags,
a mod-config-selected fluid tag and recipe-based fluid admission. Its custom processor
supplies rules without a recipe processor. `AdmissionDemo.fuelTag` illustrates the
mod-owned configuration value; the fixture itself is an inspection/storage machine.

## Typed processor storage

`ProcessorMachine.resources()` exposes the host's existing `MachineInventory`.
Use `items("group")`, `fluids("group")` and `energy("group")` for typed access;
missing or wrong-kind names fail explicitly. Indexes are local to that group.
Use `try (var tx = resources.begin())` and commit only when every operation succeeds.
Closing without commit rolls all changes back. These are internal processing
operations: they honor reservations but bypass external roles and item admission.
Use copied `peek` values for inspection. Declaration prototypes have no live host.

The companion Porting Workshop converts one cobblestone and 25 mB water into stone
using one transaction. A blocked output leaves both inputs unchanged. Its processor
uses only the common host API, with no cast to the XML block entity.

## Placement callbacks

Custom processors can override `placementFacing(BlockPlaceContext, Direction)`.
This pure preference hook runs on the declaration prototype (no live host), on
both sides. Its result must be allowed by the machine's `facing` declaration.
`placed(MachinePlacement)` runs on live processors once after successful server
item placement and portable payload restoration. `StoredProcessor` subclasses override
`onPlaced(MachinePlacement)` inside the supplied state-update scope. It receives the final state,
position, nullable placer, level and a copied placing stack. It does not run when
loading a chunk or when a placement event cancels. Direct world `setBlock` calls
are not item placement and do not initialize ownership.

The Porting Workshop records the placing player's UUID/team in processor state.
Sneak placement chooses the clicked face; ordinary placement faces the player.

## Comparator readout

`<redstone comparator-source="workshop/output"/>` selects one existing
`IRedstoneOutput` descriptor by its stable ID. The source is sampled together
with per-face outputs, once per selected source per tick. Comparator readout is
block-wide and independent of Emit faces and their inversion. Unknown source
IDs fail during definition loading with the source file and line. Custom processors
contribute descriptors through `redstoneOutputs()`; their IDs must be available
on the host-free schema prototype. Loading reads the IDs without sampling their
live value suppliers. No second provider is needed.
The Porting Workshop exposes output fullness to both the redstone drawer and
comparators, including comparators reading through an adjacent solid block.

## Several processors per machine

Declare repeated `<processor id="...">` elements with unique stable IDs. They tick
in declaration order and persist separately. Recipe and custom processors can run
together. Repeated `<recipe-type>` declarations provide the types used by recipe
lanes. The first processor is the default primary unless one declares `primary="true"`;
portable or secondary-use machines with several processors require an explicit primary.
Primary selection controls item/placement behavior, keyless processor controls,
and the no-argument progress/time/pause getters. It does not change tick order or
explicitly indexed lane bindings.

Recipe lanes can declare `bindings="input=left_input output=left_output"` to map
recipe group names to the machine's physical groups. A binding list defines the
lane's view; `energy=energy` is included automatically when available. Without a
list, all resource groups retain their names. Custom processors use named host
resources directly. Shared targets retain common reservation/transaction identity.
Recipe admission unions participating lanes by physical slot/tank, then intersects
that union with authored admission rules. `filter-inputs` names recipe-side aliases;
omitting it filters all bound input groups.

Generated progress displays and default processor buttons address each lane.
Per-lane sounds, visuals, statistics and persistence use the same stable IDs.
JEI registers every used recipe type and routes transfer to its bound inputs.
Default selection by legacy keyless runtime APIs remains first-in-registration-order;
use explicit processor keys when choosing a particular lane.

Inheritance merges repeated processors/types by ID. For compatibility, when both
parent and child declare exactly one processor (or one recipe type), that child
still overrides the parent singleton even when renaming it. To append to such a
parent, repeat its existing ID alongside the new declaration.

The companion Parallel Workshop runs two crushing lanes plus a custom water-powered
Charge Pump (one mB supplies 100 FE). The Shared Workshop rebinds the second lane
to the first lane's input to demonstrate contention without duplicate products.


### Java recipe cycle callbacks

`on-start` and `on-finish` use the ordinary `MaterialExtensions.GLOBAL.events()`
registry. Mods can register Java callbacks with `MaterialEventTypes.MACHINE_CYCLE_START`
and `MACHINE_CYCLE_FINISH`; CraftTweaker is optional. `MachineCycle.processor()`
identifies the lane. Callbacks fire for every actual transition, including multiple
transitions in one accelerated tick. Loading or resuming a cycle does not replay
its start, and interruption/failed output does not report a finish. A finish sees
the committed recipe resources. Java-created recipe processors can use
`RecipeProcessor.cycleCallbacks(start, finish)` directly.

The companion Parallel Workshop registers both Java callbacks in `CompanionMod`
and records their counts and lane identity in its charge pump's saved state.


### Processor-owned energy

An energy declaration uses the built-in buffer by default (`provider="builtin"`).
To give ownership to a custom processor, set `provider` to its stable processor ID:

```xml
<storage>
<energy id="energy" provider="battery" capacitors="true"
capacity="200000" input-rate="2000" output-rate="2000"/>
</storage>
<processor id="battery" class="example.BatteryBank"/>
```

The processor implements `ProcessorEnergy.createEnergyStorage(capacity, inputRate,
outputRate)` and returns its authoritative `EnergyBuffer` (or subclass). This runs
once during construction, before host resources are available. The same store
backs recipe transactions, energy gauges, statistics, visual values, saving and
the library's single NeoForge capability registration. Do not separately register
another energy capability or save a second copy. A subclass backed by another
storage must implement the buffer's transactional checkpoint, consumption,
telemetry and serialization contracts consistently.

`energyMode(side)` adds live restrictions to ordinary side configuration; null
means unsided access. Cached views query it on every transfer, so temporary
unavailability can return `IoMode.DISABLED` without swapping storage or invalidating
capabilities. The source itself stays stable for the machine's lifetime.

Custom sources default to `capacitors="false"`; their automatic capacitor socket
is omitted and explicit incompatible sockets are rejected. Opt in only when the
source supports the standard capacity/rate upgrades. Built-in buffers retain the
existing capacitor behavior. Machines without an energy declaration expose no
energy capability. The companion Battery Workshop reuses the two recipe lanes
and supplies their energy through its BatteryBank processor, including live side
restrictions and capacitor support.


### Per-processor operating energy

`<processor energy-per-tick="5" .../>` adds a nonnegative FE cost per successful
work step. It defaults to zero and requires the machine's `energy` resource.
Recipe lanes add it to the recipe's scheduled energy; different machines or lanes
can reuse the same recipe with different operating costs. Gearbox-accelerated
steps each pay their cost. Starting, idle, paused, held, stalled and blocked steps
do not charge. Recipe and operating charges commit together: insufficient power
leaves both energy and progress unchanged. For a costed recipe, a blocked final
step also rolls back that step's charges and progress until completion succeeds.

Custom `StoredProcessor` implementations use the same option. The cost is reserved
before `process` runs and retained only when `performedWork(result)` returns true
(default: `RUNNING`). Override that hook if a successful completion reports `IDLE`.
Use resource transactions for custom work; return a failure status without committing
partial resource mutations. On failure, the reserved energy and its telemetry roll
back. The custom processor sees the remaining energy after its operating reservation.
Java machines can configure `operatingCost(amount)` directly on either processor type.

The companion Paid Workshop runs the Parallel Workshop's unchanged recipes at 5
and 9 FE/step overhead, alongside a custom charge pump costing 3 FE/step. Its focused
tests cover combined-cost starvation, accelerated work, pause/idle, failed final
output, successful completion and custom-processor refunds.
5 changes: 4 additions & 1 deletion scripts/companion.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ sourceSets {
}
}

// Unit definition tests load the real companion XML and its mod-owned processors.
sourceSets.test.runtimeClasspath += sourceSets.companion.output

neoForge.addModdingDependenciesTo(sourceSets.companion)
neoForge.addModdingDependenciesTo(sourceSets.companionTest)
neoForge.addModdingDependenciesTo(sourceSets.companionServerTest)
Expand Down Expand Up @@ -94,7 +97,7 @@ neoForge {
gameDirectory = layout.buildDirectory.dir('companion-gametest')
sourceSet = sourceSets.companionServerTest
loadedMods = [neoForge.mods.named(mod_id).get(), neoForge.mods.mmdlib_companion_test]
systemProperty 'neoforge.enabledGameTestNamespaces', 'mmdlib_companion'
systemProperty 'neoforge.enabledGameTestNamespaces', project.hasProperty('portingHooksOnly') ? 'mmdlib_porting' : 'mmdlib_companion,mmdlib_porting'
}
multiblockClientSmoke {
client()
Expand Down
63 changes: 63 additions & 0 deletions src/companion/java/zone/moddev/mc/companion/AdmissionDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package zone.moddev.mc.companion;

import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.item.crafting.SingleRecipeInput;

import zone.moddev.mc.lib.machine.feature.ProcessorMachine;
import zone.moddev.mc.lib.machine.feature.ProcessorState;
import zone.moddev.mc.lib.machine.feature.StorageAdmission;
import zone.moddev.mc.lib.machine.feature.StoredProcessor;
import zone.moddev.mc.lib.machine.ingredient.FluidAmount;
import zone.moddev.mc.lib.machine.ingredient.MachineIngredient;
import zone.moddev.mc.lib.machine.recipe.MachineRecipeEntry;

/** A custom processor can also supply live insertion rules without casts. */
public final class AdmissionDemo extends StoredProcessor
implements StorageAdmission {
/** A consuming mod can supply this value from its own reloadable config. */
public static volatile ResourceLocation fuelTag = ResourceLocation
.parse("minecraft:lava");

@Override
public boolean acceptsItem(ProcessorMachine host, String member,
ItemStack stack) {
if (member.startsWith("fuel/"))
return stack.getBurnTime(RecipeType.SMELTING) > 0;
return host.level() != null
&& host.level().getRecipeManager().getRecipeFor(RecipeType.SMELTING,
new SingleRecipeInput(stack), host.level()).isPresent();
}

@Override
public boolean acceptsFluid(ProcessorMachine host, String member,
FluidAmount fluid) {
if (member.equals("oil"))
return fluid.fluid().is(TagKey.create(Registries.FLUID, fuelTag));
if (host.level() == null)
return false;
return host.level().getRecipeManager().getRecipes().stream().anyMatch(
holder -> holder.value() instanceof MachineRecipeEntry entry
&& entry.type().id().equals(
ResourceLocation.parse("mmdlib_companion:lava_smelting"))
&& entry.recipe().inputs()
.getOrDefault("fuel", java.util.List.of()).stream()
.anyMatch(
part -> part instanceof MachineIngredient.FluidPart input
&& input.fluids().contains(fluid.fluid())));
}

@Override
public boolean canStart(ProcessorState state, ProcessorMachine context) {
return false;
}

@Override
public ProcessState process(ProcessorState state, ProcessorMachine context,
int ticks) {
return ProcessState.IDLE;
}
}
43 changes: 43 additions & 0 deletions src/companion/java/zone/moddev/mc/companion/BatteryBank.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package zone.moddev.mc.companion;

import net.minecraft.core.Direction;

import zone.moddev.mc.lib.api.capabilities.EnergyBuffer;
import zone.moddev.mc.lib.api.capabilities.IoMode;
import zone.moddev.mc.lib.machine.feature.ProcessorEnergy;
import zone.moddev.mc.lib.machine.feature.ProcessorMachine;
import zone.moddev.mc.lib.machine.feature.ProcessorState;
import zone.moddev.mc.lib.machine.feature.StoredProcessor;

/**
* Processor-owned energy, with side policy applied to cached capability views.
*/
public final class BatteryBank extends StoredProcessor
implements ProcessorEnergy {
private EnergyBuffer buffer;
public EnergyBuffer createEnergyStorage(long capacity, long input,
long output) {
if (buffer != null)
throw new IllegalStateException("Already bound");
return buffer = new EnergyBuffer(capacity, input, output);
}
public EnergyBuffer buffer() {
return buffer;
}
public IoMode energyMode(Direction side) {
if (paused())
return IoMode.DISABLED;
return side == null
? IoMode.BOTH
: side == Direction.UP
? IoMode.INPUT
: side == Direction.DOWN ? IoMode.OUTPUT : IoMode.DISABLED;
}
public boolean canStart(ProcessorState state, ProcessorMachine machine) {
return false;
}
public ProcessState process(ProcessorState state, ProcessorMachine machine,
int ticks) {
return ProcessState.IDLE;
}
}
45 changes: 45 additions & 0 deletions src/companion/java/zone/moddev/mc/companion/ChargePump.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package zone.moddev.mc.companion;

import zone.moddev.mc.lib.machine.feature.ProcessorMachine;
import zone.moddev.mc.lib.machine.feature.ProcessorState;
import zone.moddev.mc.lib.machine.feature.StoredProcessor;

/** Example charging alongside recipe lanes: one mB water supplies 100 FE. */
public final class ChargePump extends StoredProcessor {
private final ProcessorState.Key<Integer> starts = variables.define(
"starts", com.mojang.serialization.Codec.INT, 0,
java.util.function.UnaryOperator.identity(), false, true);
private final ProcessorState.Key<Integer> finishes = variables.define(
"finishes", com.mojang.serialization.Codec.INT, 0,
java.util.function.UnaryOperator.identity(), false, true);
private final ProcessorState.Key<String> lastLane = variables.define(
"last_lane", com.mojang.serialization.Codec.STRING, "",
java.util.function.UnaryOperator.identity(), false, true);

public void recordCycle(String lane, boolean finished) {
variables.update(() -> {
var counter = finished ? finishes : starts;
variables.set(counter, variables.get(counter) + 1);
variables.set(lastLane, lane);
});
}

@Override
public boolean canStart(ProcessorState state, ProcessorMachine host) {
return host.resources().fluids("coolant").free(0) > 0;
}

@Override
public ProcessState process(ProcessorState state, ProcessorMachine host,
int ticks) {
var resources = host.resources();
try (var tx = resources.begin()) {
if (resources.energy("energy").insert(100, tx) != 100)
return ProcessState.BLOCKED;
if (resources.fluids("coolant").extract(0, 1, tx) != 1)
return ProcessState.IDLE;
tx.commit();
}
return ProcessState.RUNNING;
}
}
Loading
Loading