Repository navigation
2 ‐ Dev Guide
This guide targets contributors who build, extend, or review TradeShuffler.
tradeshuffler-mod/
├─ common/ # loader-neutral logic: client/server config models and stores, shuffle rules, facades, i18n, update service (no Minecraft classes)
├─ shared/ # Minecraft-dependent runtime for both sides (server services, client screen logic, payloads, mixins, textures), bundled into both loader jars
├─ fabric/ # Fabric entrypoints (common + client) and loader glue
├─ neoforge/ # NeoForge entrypoints (common + client) and loader glue
├─ config/ # matrix-targets.json (versions SSOT), mod.properties (mod id/name/group)
├─ gradle/ # wrapper + shared build scripts (matrix defaults, Java conventions, mod info, TurtleLib dependency)
├─ settings.gradle, build.gradle, gradlew # standalone build + repo-level tasks
├─ version.properties # mod version + required TurtleLib version
├─ update-sources.properties
└─ README.md
Base package: net.kroet.tradeshuffler. Mod id: tradeshuffler.
TradeShuffler depends on TurtleLib. It compiles against the TurtleLib core jar attached to the TurtleLib GitHub release, whose version is turtlelib_dependency_version in version.properties. The same value is the minimum TurtleLib version in the mod metadata. Players install TurtleLib as its own mod; TradeShuffler jars do not bundle it.
- A JDK 17+ to start Gradle. The compile toolchain (the
javavalue of the selected matrix target, currently Java 25) is detected automatically or downloaded. - Source of truth for versions:
config/matrix-targets.json. Builds without parameters use the first target. - Use this repository's own wrapper:
./gradlew. It is a standalone build.
Use test tasks for normal validation/debugging:
./gradlew testTradeShuffler
Other tasks:
-
./gradlew buildbuilds both loader jars intodist/. -
./gradlew verifyMatrixTargetsvalidates the build matrix. -
./gradlew releaseTradeShufflerruns the clean release build for all matrix targets.
Code formatting:
- Java formatting is enforced with Spotless (Eclipse JDT formatter, settings in
config/spotless-eclipse-formatter.properties).spotlessCheckruns withbuild,testTradeShufflerandreleaseTradeShufflerand fails on unformatted code;./gradlew spotlessApplyfixes it. - Null safety is checked with JSpecify: every package is
@NullMarked(package-info.java), and values that may be null are marked@Nullable.nullCheckruns the Eclipse compiler with the rules inconfig/jdt_null_analysis.prefs(the same ones VS Code uses) on every source set; it runs withcheck,buildandtestTradeShufflerand fails on any null warning. - All text files use LF line endings, only
*.batuses CRLF (.gitattributes,.editorconfig).
-
./gradlew gameTestTradeShufflerstarts a Fabric and then a NeoForge game test server and runs the server-side tests: zombie conversion keeps the trade plan and the traded flag, level-up unlocks exactly the planned trades, a profession change discards the plan, plan and flag survive saving, a shuffle request rerolls until the first trade, a trade without XP locks shuffling too (also after a restock), and rapid shuffles at a cartographer roll the plan (with its exploration maps) only once shuffling pauses. A failing test ends the task with an error. - The test functions live once in
shared/src/gametest/java;fabric/src/gametest(@GameTestmethods, entrypointfabric-gametest) andneoforge/src/gametest(RegisterGameTestsEvent, own empty structure) only register them. These source sets never end up in a mod jar, andbuilddoes not run them. - The test servers install the TurtleLib loader jar, so the task needs the hrobasti-mods workspace; in a lone clone it stops with a hint.
- Test villagers run with
NoAI: without a registered job site POI, their brain would reset the profession at once. - Run directories:
fabric/build/run/gameTestandneoforge/build/run/gameTest.
To develop TradeShuffler and TurtleLib together, clone TurtleLib next to this repository (../turtle-lib-mod) and add -PuseLocalTurtleLib=true. The build then uses the local TurtleLib sources instead of the release jar. Inside the hrobasti-mods workspace this is the default.
- Fabric:
./gradlew :tradeshuffler-fabric:runClient/runServer(run directoryfabric/run). - NeoForge:
./gradlew :tradeshuffler-neoforge:runClient/runServer(run directoryneoforge/run). - TurtleLib is a separate mod at runtime: put the matching TurtleLib loader jar into
fabric/run/modsorneoforge/run/mods. - For a dedicated dev server, add
eula=truetorun/eula.txt. Therun/directories are not versioned.
TradeShuffler is a client and server mod: the server validates requests and generates trades; the client only requests and renders. Anything that decides about trades runs on the server.
-
sharedcontains code for both sides. Client-only code (screens, rendering) must only be reached from client entrypoints or client mixins. - The Fabric metadata uses
"environment": "*"with amainand acliententrypoint; NeoForge uses one@Modclass for both sides and one withdist = Dist.CLIENT. - Loader modules declare
evaluationDependsOn(':tradeshuffler-common')/(':tradeshuffler-shared'), because their jars bundle the outputs of these modules.
TurtleLib is used only through UpdateFacade in common; feature, UI and entrypoint code never import TurtleLib. Add a facade only when TradeShuffler starts using another TurtleLib part. Translations use Minecraft's lang files, not TurtleLib.
Private Minecraft members are reached through compile-checked accessor/invoker mixins in shared, never through reflection by name.
Mixins live in shared and are loader-neutral (Minecraft 26.x ships unobfuscated, so no refmap is needed). Both configs are listed in fabric.mod.json and neoforge.mods.toml.
tradeshuffler.mixins.json (both sides, package net.kroet.tradeshuffler.shared.mixin):
| Mixin | Target | Purpose |
|---|---|---|
MerchantMenuAccessor |
MerchantMenu |
Accessors for trader and tradeContainer. |
AbstractVillagerInvoker |
AbstractVillager |
Invoker for addOffersFromTradeSet and accessor for the raw offers field (trade plan generation and consumption). |
VillagerInvoker |
Villager |
Invoker for updateSpecialPrices(Player). |
VillagerTradePlanMixin |
Villager |
Implements TradeShufflerVillager (traded flag, trade plan, PlanPacer); saves/loads flag and plan; startTrading TAIL schedules the plan and sends the trade state; updateTrades HEAD consumes a planned batch; tick TAIL generates the plan. |
AbstractVillagerNotifyTradeMixin |
AbstractVillager |
notifyTrade TAIL, villagers on the server only: sets the traded flag on the first trade and resends the state. |
ZombieVillagerTradePlanMixin |
ZombieVillager |
Implements TradeShufflerZombieVillager; keeps traded flag and plan (same save keys) while the villager is a zombie. |
MobConversionMixin |
Mob |
convertTo RETURN: ZombieConversion carries flag and plan through infection and cure. |
tradeshuffler.client.mixins.json (client only, package net.kroet.tradeshuffler.shared.mixin.client):
| Mixin | Target | Purpose |
|---|---|---|
MerchantScreenMixin |
MerchantScreen |
Constructor: forgets the trade state and a pending shuffle of the previous screen. Adds the shuffle button in init and implements ShuffleButtonHost; @WrapOperation on the getOffers() call sites (preview list); locks and decorates preview rows; guards postButtonClick. |
AbstractContainerScreenMixin |
AbstractContainerScreen |
containerTick and keyPressed for screens implementing ShuffleButtonHost; MerchantScreen declares neither method. |
MerchantScreenTradeOfferButtonMixin |
MerchantScreen$TradeOfferButton |
Implements PreviewRowButton (row index) and sets the tooltip of preview rows. |
MerchantScreenAccessor |
MerchantScreen |
Accessor for scrollOff. |
Payloads are vanilla CustomPacketPayload records with StreamCodecs in shared/network; the loader modules only register them.
| Payload | Direction | Id | Fields |
|---|---|---|---|
ShuffleRequestPayload |
client → server | tradeshuffler:shuffle_request |
containerId |
TradeStatePayload |
server → client | tradeshuffler:trade_state |
containerId, shuffleBlockReason (ShuffleEligibility.Verdict name, empty = allowed), preview (up to 4 PreviewBatch(level, offers)) |
-
TradeShufflerNetworkBindingsholds two small interfaces installed by the loader entrypoints:Server(canReceive,sendTradeState) andClient(serverSupportsShuffle,sendShuffleRequest). They are separate so a dedicated server never loads client networking classes. Until a loader installs them, no-op bindings apply. - Fabric:
PayloadTypeRegistry.serverboundPlay()/clientboundPlay(),ServerPlayNetworkingandClientPlayNetworking(canSendchecks). - NeoForge:
RegisterPayloadHandlersEventwith anoptional()registrar (playToServerwith handler,playToClientwithout); the client handler is registered viaRegisterClientPayloadHandlersEventin the client entrypoint.hasChannelchecks,PacketDistributor/ClientPacketDistributor. - The server only sends to players whose client registered the channels. With optional channels, NeoForge accepts vanilla connections.
- On the client,
ClientTradeStatekeeps the latest state for the open merchant menu; it is cleared when a merchant screen opens and on disconnect.
-
ShuffleEligibility(common/rules) decides from plain facts whether a shuffle is allowed and returns the first failing rule as aVerdict: shuffle enabled, matching container, trader is aVillager, alive and trading with the player, traded flag not set, XP 0, novice level, profession has novice trades, job site (ifrequireJobSite), cooldown elapsed.ShuffleFactsinsharedcollects these facts from the game. -
ShuffleCooldowntracks the last accepted shuffle per player in server ticks (shuffleCooldownTicks); a player's entry is removed when they leave, and all entries on server start. - The traded flag is stored in the villager's save data under
tradeshuffler:traded(only written whentrue) and is never cleared. Vanilla ignores unknown keys, so removing the mod leaves villagers intact. -
TradeStateServicesendsTradeStatePayloadwhen trading starts and after the first completed trade. Container and cooldown are not part of that check; they only apply to requests (ShuffleRequestHandler).
-
LevelPlan<T>(common/rules) holds pre-generated batches for the levels above the current one (fromLevel()to 5), with a stamp of profession and villager type. Operations:isValidFor(stamp, level),nextMissingLevel(),put,take(level)(returns the batch and drops all levels up to it),dropUpTo(level),isComplete(). -
TradePlanService(shared/server) uses it asLevelPlan<MerchantOffers>, stored per villager throughTradeShufflerVillagerand saved undertradeshuffler:trade_plan(TradePlanCodec: profession, type,from_level, list of{level, offers}in vanilla's offer format). -
Generation: scheduled when a player who can receive TradeShuffler payloads opens the screen without a complete plan, and after a shuffle. Pacing lives in
PlanPacerandGenerationBudget(common/rules): after a shuffle generation waits until shuffling has paused for 40 ticks (every shuffle restarts the wait), and server-wide at most one level is generated per server tick. Reason: generating runs vanilla trade functions such asminecraft:exploration_map, which search for structures, create map data and claim the structure. TheVillager#tickhook asks the pacer and generates viaaddOffersFromTradeSet(vanilla's trade set path, so data packs apply). When the plan is complete, the trading player gets a new trade state. -
Consumption: the
Villager#updateTradesHEAD hook. Empty offers (new profession, reset, shuffle) clear the plan and let vanilla roll the novice batch. A batch for the new level is appended instead of vanilla's roll, then prices are updated and the state is resent. Without a batch, vanilla rolls the level and the plan is regenerated; the client never saw that level, so the preview stays binding. - Invalidation: a stamp mismatch or a lower level discards the plan; batches up to the current level are dropped (a level set by commands brings no trades of the skipped levels, as in vanilla). A master keeps no plan.
-
Zombie infection and cure: vanilla only copies offers and XP;
MobConversionMixin+ZombieConversioncarry the plan and the traded flag over, so the preview stays binding and a villager nobody traded with can still be shuffled after the cure. -
Preview:
TradeStatePayloadcarries the batches only when the plan is complete andpreviewEnabledis on; batches are copied, empty ones are left out. - In 26.3, a villager levels up immediately during the trade, also while the trading screen is open.
-
ClientTradeStatekeeps the last trade state for the open merchant screen;PreviewViewfilters its batches to levels abovegetTraderLevel()(so a batch never shows twice after a level-up) and respects the client configpreviewEnabled. - Without real offers no preview is shown, so the screen never treats a preview row as the selected trade.
- The combined list (real offers + preview offers) exists only at
MerchantScreen's owngetOffers()call sites inextractContents,mouseScrolled,mouseDraggedandmouseClicked, rebuilt on every access.MerchantMenuis never changed, so server logic, auto-fill and other mods see the real offers. Vanilla scrolling and scroll bounds work for the longer list unchanged. - At
extractContentsTAIL, rows beyond the real offers getactive = false(disabled sprite, not clickable), a translucent black overlay (previewDimAlpha) and a 2 px stripe in the level badge color (previewLevelStripe).graphics.nextStratum()puts the overlay above the row items.postButtonClickadditionally ignores indices beyond the real offers. - Preview row tooltips combine the hovered item's own tooltip with "Unlocks at " and a base-price note (
tradeshuffler.screen.preview.*); item zones match vanilla's trade offer button.
-
ShuffleServiceruns on the server thread after a request was accepted:setOffers(null)+getOffers()(vanilla regenerates the novice batch through the trade set path),updateSpecialPrices,sendMerchantOffers,MerchantMenu#slotsChanged(recomputes the result slot, so a previously selected offer cannot be taken for free), then a newTradeStatePayload. -
ShuffleButtonController(client) creates the 20×20SpriteIconButtonwith thetradeshuffler:shuffle/shuffle_disabledsprites atleftPos - 22 + offsetX(at least 2),topPos + 18 + offsetY. State is updated in the screen tick, never while rendering. Visible: config enabled, server accepts shuffle requests, a trade state for this container arrived, andshowProgressBar(). Active: no block reason and the local checkgetTraderXp() == 0. Otherwise the button is greyed out and its tooltip adds the reason (tradeshuffler.screen.shuffle.tooltip.unavailable.<reason>, unknown reasons fall back to…unavailable.other). The server never sends text, only the reason name. - After a request the button stays disabled until the next trade state arrives, or for at most 20 ticks (a rejected request gets no answer).
- Key mapping
key.tradeshuffler.shuffle(TradeShufflerKeyMappings), unbound by default, in the categorytradeshuffler:tradeshuffler. Fabric registers it viaKeyMapping.Category.register+KeyMappingHelper, NeoForge viaRegisterKeyMappingsEvent. Vanilla key mappings do not fire while a screen is open, soAbstractContainerScreenMixinchecks the key inkeyPressed.
-
Client config (
TradeShufflerClientConfig, fileconfig/tradeshuffler.json): shuffle button visibility and offset, preview settings, update controls (updateCheckEnabled,UpdateChannel). Loaded by the client entrypoints viaClientConfigHolder. Edited inTradeShufflerConfigScreen(shared/client, one screen for both loaders), registered viaTradeShufflerModMenuApi(Fabric, Mod Menu entrypoint) andIConfigScreenFactory(NeoForge client entrypoint); saving applies the values immediately. -
Server config (
TradeShufflerServerConfig, fileconfig/tradeshuffler-server.json):shuffleEnabled,previewEnabled,requireJobSite,shuffleCooldownTicks. Loaded on server start (dedicated and integrated) viaServerConfigHolder. - Both stores normalize values on load and write the file back, so a missing file is created with defaults.
- New config fields are additive: missing values in an existing file fall back to their defaults, so no
configVersionbump is needed.
TradeShuffler is licensed under MIT. The jars bundle no third-party code or assets; THIRD_PARTY_NOTICES.md records that, the platform and test dependencies ("Not shipped") and the Minecraft depictions ("Trademarks"). A bundled third-party component would need a permissive license, a table row in the notices and its license text under src/main/resources/licenses/; the workspace check command verifies this.
- The mod icon (256×256) lives once in
common/src/main/resources/assets/tradeshuffler/icon.pngand is referenced asiconinfabric.mod.jsonandiconFileinneoforge.mods.toml. It shows a Minecraft villager (Mojang), recorded under "Trademarks" inTHIRD_PARTY_NOTICES.mdas not covered by the MIT license. - Button textures live in
shared/src/main/resources/assets/tradeshuffler/textures/gui/sprites/(shuffle.png,shuffle_disabled.png, 18×18 with the symbol centered for a 20×20 button).
Update provider metadata is maintained in update-sources.properties (flat key/value). Empty project ids disable the update check.
During common:processResources, it is copied into resources as:
tradeshuffler-update-sources.properties
TradeShufflerUpdateService loads this bundled resource via java.util.Properties.
Before publishing to GitHub/Modrinth/CurseForge:
- run all relevant
testtasks - build loader artifacts (clean-first):
./gradlew releaseTradeShuffler
- verify generated jars in
dist - confirm
commonandsharedclasses and resources are bundled in both loader jars - confirm README and wiki reflect current behavior
- GitHub releases are immutable: create the release as a draft, attach all assets, then publish
- keep code changes loader-safe and minimal
- run
./gradlew spotlessApplybefore committing - add/update tests for behavior changes
- keep user-facing text in docs and locale keys aligned
- update the User Guide whenever player-visible behavior or configuration changes
Locale keys must be grouped by feature/setting and use dot-separated segments.
-
Labels / fixed texts:
tradeshuffler.<area>.<setting>[.<detail>] -
Tooltips:
tradeshuffler.<area>.<setting>.tooltip.<variant>.<kind> -
Key bindings:
key.tradeshuffler.<action>; key-binds section:key.category.tradeshuffler.tradeshuffler
Where:
-
<area>is typicallyscreen,configorupdate -
<setting>is the exact setting path -
<variant>identifies option/state -
<kind>is usuallydesc(description) orlabel
- Keep all 14 language files structurally identical and in the same order.
LocaleFilesConsistencyTestenforces this. - Place keys in thematic blocks: base strings first, then one block per feature/setting.
- The server never sends literal text; all UI text is resolved on the client.
For translation file naming, language-code mapping, and contribution workflow, see:
- the GitHub wiki's Translations page