diff --git a/AGENTS.md b/AGENTS.md index 81b875b..50915ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,8 +40,8 @@ Read [[🧠 Philosophy]] before changing the vault. The Bookshelf Principle, Pre ## Code -The first slice is in code and has been played (ADRs 012–016): [[▢️ Create Goal]], [[πŸ”Œ Recipe Provider]] via `RecipeManager`, overlay HUD, capture = tooltip + rebindable Add key. +The first slice is in code and has been played (ADRs 012–017): [[▢️ Create Goal]], [[πŸ”Œ Recipe Provider]] via `RecipeManager`, overlay HUD, capture = tooltip + rebindable Add key, player world save. -Do not start EMI/JEI/REI. Recipe source is `RecipeManager` (ADR-016). Persistence and Project wait until settled. Do not rewrite the overlay as a `Screen` unless the HUD path fails. +Do not start EMI/JEI/REI. Recipe source is `RecipeManager` (ADR-016). Persistence is the player in this world (ADR-017). Project waits until settled. Do not rewrite the overlay as a `Screen` unless the HUD path fails. The NeoForge template example block/item is gone. Do not put it back. diff --git a/README.md b/README.md index 394b415..2db87df 100644 --- a/README.md +++ b/README.md @@ -47,9 +47,9 @@ Those may be integrated with later. They are not owned by Satistaskory. ## Status -First slice is in `src/` and has been played: domain, `VanillaRecipeProvider` (`RecipeManager`, one level), in-memory plan, overlay on the right, hover + Add key (default `=`). +First slice is in `src/` and has been played: domain, `VanillaRecipeProvider` (`RecipeManager`, one level), player world save, overlay on the right, hover + Add key (default `=`). -`/satistaskory add minecraft:furnace` is a debug command. The plan is RAM-only. Not EMI. Template example block/item is gone. +`/satistaskory add minecraft:furnace` is a debug command. Not EMI. Template example block/item is gone. --- diff --git a/docs/03-Architecture/▢️ Create Goal.md b/docs/03-Architecture/▢️ Create Goal.md index 1f48105..7ddef57 100644 --- a/docs/03-Architecture/▢️ Create Goal.md +++ b/docs/03-Architecture/▢️ Create Goal.md @@ -37,7 +37,7 @@ RefreshProgress missing = required βˆ’ available ``` -Persistence: none in this slice. The list lives in memory. +Persistence: the player in this world's save (ADR-017). Leave the world and the overlay unloads; come back and the goals load. --- @@ -76,6 +76,8 @@ Do not start EMI. Do not start a planner menu. [[πŸ”Œ Recipe Provider]] +[[πŸ’Ύ Persistence]] + [[πŸ“ˆ Progress Calculation]] [[πŸ–₯️ Experience]] diff --git a/docs/03-Architecture/πŸ›οΈ Architecture.md b/docs/03-Architecture/πŸ›οΈ Architecture.md index 8f17e04..bb4d105 100644 --- a/docs/03-Architecture/πŸ›οΈ Architecture.md +++ b/docs/03-Architecture/πŸ›οΈ Architecture.md @@ -100,7 +100,7 @@ First use case: [[▢️ Create Goal]]. In code this slice is one `Planner` faca Mark Goal Complete is named. It is not in the first slice. -The application layer calls infrastructure through ports (`RecipeProvider`, inventory snapshot). It does not contain domain rules. It loads what the use case needs, asks the domain to decide, and presents the result. Persistence is in-memory for this slice. +The application layer calls infrastructure through ports (`RecipeProvider`, inventory snapshot, `GoalStore`). It does not contain domain rules. It loads what the use case needs, asks the domain to decide, and presents the result. Persistence is the player in this world's save (ADR-017). Packages: [[πŸ“¦ Packages]]. @@ -119,7 +119,7 @@ Examples: - Save data storage - Inventory scanning -Shipped this slice: `VanillaRecipeProvider` (`RecipeManager`, all types, one level), player-inventory snapshot, HUD overlay, tooltip+key capture. `StubRecipeProvider` is unit tests only. No save adapter yet. EMI/JEI/REI are not dependencies. +Shipped this slice: `VanillaRecipeProvider` (`RecipeManager`, all types, one level), player-inventory snapshot, HUD overlay, tooltip+key capture, player world save. `StubRecipeProvider` is unit tests only. EMI/JEI/REI are not dependencies. Infrastructure is never the source of domain truth. @@ -147,7 +147,7 @@ Possible implementations: - Server Save - Future Cloud Sync -First slice: in-memory. No save adapter yet. +Shipped: player attachment in this world's save. Survives quit and death. Remote multiplayer stays RAM-only until a server adapter exists. See [[πŸ’Ύ Persistence]] and ADR-017. --- @@ -215,6 +215,10 @@ See [[🎯 Success Metrics]]. [[🧾 Recipe Resolution]] +[[πŸ’Ύ Persistence]] + +[[πŸ”Œ Recipe Provider]] + [[πŸ–₯️ Experience]] [[🚢 Day in the Life]] diff --git a/docs/03-Architecture/πŸ’Ύ Persistence.md b/docs/03-Architecture/πŸ’Ύ Persistence.md new file mode 100644 index 0000000..e29179f --- /dev/null +++ b/docs/03-Architecture/πŸ’Ύ Persistence.md @@ -0,0 +1,49 @@ +# πŸ’Ύ Persistence + +Port used by [[▢️ Create Goal]] (and the sibling quantity / clear paths). + +The domain does not know where the plan is stored (ADR-004). Infrastructure answers. + +--- + +## Shape + +```text +GoalStore + all() / find / put / remove / clear +``` + +Play uses `PersistingGoalStore`: RAM plus a write after each change. + +`InMemoryGoalStore` remains for unit tests. + +--- + +## Shipped implementation + +Player attachment in **this world's save** (ADR-017). + +| Event | Result | +|-------|--------| +| Join world | Load this player's goals | +| Create / + / βˆ’ / Clear | Write the attachment | +| Leave world | Unload RAM. Do not write empty (that would wipe the save) | +| Death | Plan is copied. It is not loot | + +Singleplayer and LAN host. Remote dedicated server: RAM-only this slice. + +Server save and cloud remain possible later. They do not change `GoalStore`. + +--- + +## Related Documents + +[[πŸ›οΈ Architecture]] + +[[πŸ“¦ Packages]] + +[[πŸ“ Decisions]] + +[[▢️ Create Goal]] + +[[🎯 Goal]] diff --git a/docs/03-Architecture/πŸ“ Decisions.md b/docs/03-Architecture/πŸ“ Decisions.md index 571a9e2..1f6bb4a 100644 --- a/docs/03-Architecture/πŸ“ Decisions.md +++ b/docs/03-Architecture/πŸ“ Decisions.md @@ -282,6 +282,27 @@ The port remains. The **order** was wrong. --- +### ADR-017 β€” First persistence is the player in this world + +**Date:** 2026-09-08 + +**Decision:** Active goals persist as a NeoForge player attachment in the current world's save. + +- Per player, not one list for the whole world +- Copy on death: dying does not wipe the plan +- Load on join, write after each change, unload RAM on leave so worlds do not leak +- Singleplayer and LAN host. A remote dedicated server has no integrated world save on the client; that session stays RAM-only until a server adapter exists + +**Reason:** + +The first slice is a prosthetic the player can quit and resume. ADR-004 named world save, server save, and cloud. World save is the one they play. + +**Status:** βœ… Accepted + +**Refines:** ADR-004. **Supersedes** ADR-013’s β€œPersistence: in-memory” freeze for this slice. + +--- + ## Related Documents [[πŸ›οΈ Architecture]] diff --git a/docs/03-Architecture/πŸ“¦ Packages.md b/docs/03-Architecture/πŸ“¦ Packages.md index c01b908..d9a1bf3 100644 --- a/docs/03-Architecture/πŸ“¦ Packages.md +++ b/docs/03-Architecture/πŸ“¦ Packages.md @@ -2,7 +2,7 @@ Java packages for the first slice. Root: `com.sufficient.satistaskory`. -Rule #9: do not add a package until the slice needs it. No `project`, `emi`, or `persistence` until those are in the slice. +Rule #9: do not add a package until the slice needs it. No `project` or `emi` until those are in the slice. --- @@ -25,7 +25,8 @@ com.sufficient.satistaskory application/ Planner # create / increment / decrement / clear / snapshot - InMemoryGoalStore + GoalStore # port + InMemoryGoalStore # unit tests; inner store for persist infrastructure/ recipe/ @@ -33,6 +34,10 @@ com.sufficient.satistaskory StubRecipeProvider # unit tests only inventory/ PlayerInventoryAdapter # player inventory β†’ InventoryState + persistence/ + GoalPlan # NBT codec + PersistingGoalStore + PlayerGoalPersistence # player attachment in this world client/ PlayOverlay # Screen 2 HUD (not a Screen) CaptureHook # tooltip + KeyMapping ADD_GOAL @@ -50,7 +55,6 @@ Dependencies point inward: `infrastructure` and `application` may import `domain |---------|-----| | `Project` | Organizational only; not in the slice | | Completion strategy | Ready β‰  complete; complete is not in the slice | -| Persistence | In-memory goals. ADR-004 still holds; no save adapter yet | | Full-screen planner | Not discovered | The NeoForge template example block/item is gone. Do not put it back. @@ -65,6 +69,8 @@ The NeoForge template example block/item is gone. Do not put it back. [[πŸ”Œ Recipe Provider]] +[[πŸ’Ύ Persistence]] + [[🎯 Goal]] [[πŸ“ Decisions]] diff --git a/docs/04-Planning/πŸ—ΊοΈ Roadmap.md b/docs/04-Planning/πŸ—ΊοΈ Roadmap.md index eb1c3a1..d92c982 100644 --- a/docs/04-Planning/πŸ—ΊοΈ Roadmap.md +++ b/docs/04-Planning/πŸ—ΊοΈ Roadmap.md @@ -6,19 +6,19 @@ What exists, and what is next. Implementation detail will live in an Implementat ## βœ… Now (docs) -- Philosophy Rules #1–#10; ADRs **001–016** +- Philosophy Rules #1–#10; ADRs **001–017** - Vision, ubiquitous language, bounded context (one: Goal Planning) - Goal invariants: one per ItemId, quantity β‰₯ 1, create at 1 / +1, `[-]` at 1 removes - Packages named; [[πŸ”Œ Recipe Provider]] sketched; [[▢️ Create Goal]] written - Experience: capture in place; overlay on the right (goals + aggregated needed counts) -First slice **code exists** and has been played: domain, `VanillaRecipeProvider` (`RecipeManager`, all types, one level), in-memory `Planner`, player inventory, play overlay, hover + Add key. Plan does not survive restart. +First slice **code exists** and has been played: domain, `VanillaRecipeProvider` (`RecipeManager`, all types, one level), player world save, player inventory, play overlay, hover + Add key. --- ## πŸ”² Next -1. World-save persistence +The frozen first slice is in play. Listen. Do not open Project, completion, or a Screen rewrite because the list is empty. EMI is not a dependency. See ADR-016. @@ -26,7 +26,9 @@ EMI is not a dependency. See ADR-016. ## ⏸ Not opened -- World save +- Project +- Completion +- Full-screen planner --- @@ -35,7 +37,7 @@ EMI is not a dependency. See ADR-016. Not a queue. See [[🚧 Future Ideas]]. - Viewer-only recipe adapter if `RecipeManager` is not enough -- Persistence (world / server / cloud) +- Persistence (server / cloud) - Projects packaged - Completion - Full-screen planner diff --git a/docs/04-Planning/🧭 Notes for the Wayfinder.md b/docs/04-Planning/🧭 Notes for the Wayfinder.md index d56f189..5a81a23 100644 --- a/docs/04-Planning/🧭 Notes for the Wayfinder.md +++ b/docs/04-Planning/🧭 Notes for the Wayfinder.md @@ -367,6 +367,20 @@ Next is still world save. Not EMI. Not a Screen rewrite. --- +## πŸ“œ 2026-09-08 (player world save) + +Greetings, Wayfinder. + +Recipes worked in play: spruce fence gate β†’ sticks + spruce planks. The first slice's last freeze was persistence. + +ADR-017: the plan lives on the player in this world's save. Copy on death. Unload RAM when leaving so World B does not inherit World A. Remote dedicated server is still RAM-only. + +The frozen slice is now: name a goal, see missing materials, quit, come back, still see them. + +Do not open Project because that feels like "what's next." Listen. + +--- + ## Related Documents [[🌟 Project Vision]] diff --git a/docs/99-backlog/🚧 Future Ideas.md b/docs/99-backlog/🚧 Future Ideas.md index 5a8cb79..a56ae12 100644 --- a/docs/99-backlog/🚧 Future Ideas.md +++ b/docs/99-backlog/🚧 Future Ideas.md @@ -7,7 +7,7 @@ Not a build queue. --- - Viewer-only recipe adapter (EMI/JEI/REI) **if** a recipe never appears in `RecipeManager` -- Persistence (world save / server / cloud) +- Persistence (server save / cloud) - Inventory-detection completion (alongside manual) - Ender chest / later storage in the inventory snapshot - Projects packaged diff --git a/src/main/java/com/sufficient/satistaskory/Satistaskory.java b/src/main/java/com/sufficient/satistaskory/Satistaskory.java index a05717e..29a0e3d 100644 --- a/src/main/java/com/sufficient/satistaskory/Satistaskory.java +++ b/src/main/java/com/sufficient/satistaskory/Satistaskory.java @@ -4,16 +4,32 @@ import org.slf4j.Logger; import com.mojang.logging.LogUtils; +import com.sufficient.satistaskory.infrastructure.persistence.GoalPlan; + import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.ModContainer; import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.attachment.AttachmentType; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; @Mod(Satistaskory.MODID) public class Satistaskory { public static final String MODID = "satistaskory"; public static final Logger LOGGER = LogUtils.getLogger(); + public static final DeferredRegister> ATTACHMENT_TYPES = + DeferredRegister.create(NeoForgeRegistries.Keys.ATTACHMENT_TYPES, MODID); + + public static final DeferredHolder, AttachmentType> PLAYER_GOALS = + ATTACHMENT_TYPES.register("player_goals", () -> AttachmentType.builder(GoalPlan::empty) + .serialize(GoalPlan.CODEC) + .copyOnDeath() + .build()); + public Satistaskory(IEventBus modEventBus, ModContainer modContainer) { + ATTACHMENT_TYPES.register(modEventBus); LOGGER.info("Satistaskory loaded. Goals are the domain."); } } diff --git a/src/main/java/com/sufficient/satistaskory/SatistaskoryClient.java b/src/main/java/com/sufficient/satistaskory/SatistaskoryClient.java index caf4901..6546963 100644 --- a/src/main/java/com/sufficient/satistaskory/SatistaskoryClient.java +++ b/src/main/java/com/sufficient/satistaskory/SatistaskoryClient.java @@ -15,6 +15,7 @@ import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.ModContainer; import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; import net.neoforged.neoforge.client.event.InputEvent; import net.neoforged.neoforge.client.event.RegisterClientCommandsEvent; import net.neoforged.neoforge.client.event.RegisterGuiLayersEvent; @@ -39,6 +40,16 @@ public class SatistaskoryClient { @EventBusSubscriber(modid = Satistaskory.MODID, value = Dist.CLIENT) public static class GameEvents { + @SubscribeEvent + public static void onJoinWorld(ClientPlayerNetworkEvent.LoggingIn event) { + PlannerSession.onJoinWorld(); + } + + @SubscribeEvent + public static void onLeaveWorld(ClientPlayerNetworkEvent.LoggingOut event) { + PlannerSession.onLeaveWorld(); + } + @SubscribeEvent public static void onClientCommands(RegisterClientCommandsEvent event) { ClientCommands.register(event.getDispatcher()); diff --git a/src/main/java/com/sufficient/satistaskory/application/GoalStore.java b/src/main/java/com/sufficient/satistaskory/application/GoalStore.java new file mode 100644 index 0000000..6081289 --- /dev/null +++ b/src/main/java/com/sufficient/satistaskory/application/GoalStore.java @@ -0,0 +1,22 @@ +package com.sufficient.satistaskory.application; + +import java.util.List; +import java.util.Optional; + +import com.sufficient.satistaskory.domain.Goal; +import com.sufficient.satistaskory.domain.ItemId; + +/** + * Where active goals live. Domain does not know the backing store (ADR-004). + */ +public interface GoalStore { + List all(); + + Optional find(ItemId item); + + void put(Goal goal); + + void remove(ItemId item); + + void clear(); +} diff --git a/src/main/java/com/sufficient/satistaskory/application/InMemoryGoalStore.java b/src/main/java/com/sufficient/satistaskory/application/InMemoryGoalStore.java index 6450e7f..ef849eb 100644 --- a/src/main/java/com/sufficient/satistaskory/application/InMemoryGoalStore.java +++ b/src/main/java/com/sufficient/satistaskory/application/InMemoryGoalStore.java @@ -7,7 +7,7 @@ import java.util.Optional; import com.sufficient.satistaskory.domain.Goal; import com.sufficient.satistaskory.domain.ItemId; -public final class InMemoryGoalStore { +public final class InMemoryGoalStore implements GoalStore { private final List goals = new ArrayList<>(); public List all() { diff --git a/src/main/java/com/sufficient/satistaskory/application/Planner.java b/src/main/java/com/sufficient/satistaskory/application/Planner.java index 0c48b70..099426a 100644 --- a/src/main/java/com/sufficient/satistaskory/application/Planner.java +++ b/src/main/java/com/sufficient/satistaskory/application/Planner.java @@ -10,14 +10,14 @@ import com.sufficient.satistaskory.domain.ProgressCalculation; import com.sufficient.satistaskory.domain.ProgressSnapshot; /** - * Application facade for the first slice. Persistence is this store, in RAM. + * Application facade for the first slice. Persistence is the store's job. */ public final class Planner { - private final InMemoryGoalStore store; + private final GoalStore store; private final ProgressCalculation progress; private final Supplier inventory; - public Planner(InMemoryGoalStore store, ProgressCalculation progress, Supplier inventory) { + public Planner(GoalStore store, ProgressCalculation progress, Supplier inventory) { this.store = Objects.requireNonNull(store, "store"); this.progress = Objects.requireNonNull(progress, "progress"); this.inventory = Objects.requireNonNull(inventory, "inventory"); diff --git a/src/main/java/com/sufficient/satistaskory/infrastructure/client/PlannerSession.java b/src/main/java/com/sufficient/satistaskory/infrastructure/client/PlannerSession.java index 6ca4daf..1ded872 100644 --- a/src/main/java/com/sufficient/satistaskory/infrastructure/client/PlannerSession.java +++ b/src/main/java/com/sufficient/satistaskory/infrastructure/client/PlannerSession.java @@ -1,21 +1,23 @@ package com.sufficient.satistaskory.infrastructure.client; -import com.sufficient.satistaskory.application.InMemoryGoalStore; import com.sufficient.satistaskory.application.Planner; import com.sufficient.satistaskory.domain.InventoryState; import com.sufficient.satistaskory.domain.MaterialAggregation; import com.sufficient.satistaskory.domain.ProgressCalculation; import com.sufficient.satistaskory.domain.RecipeResolution; import com.sufficient.satistaskory.infrastructure.inventory.PlayerInventoryAdapter; +import com.sufficient.satistaskory.infrastructure.persistence.PersistingGoalStore; +import com.sufficient.satistaskory.infrastructure.persistence.PlayerGoalPersistence; import com.sufficient.satistaskory.infrastructure.recipe.VanillaRecipeProvider; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; /** - * Client-side in-memory plan. Gone when the game restarts. + * Client plan for the current world. Written to the player in this world's save. */ public final class PlannerSession { + private static PersistingGoalStore store; private static Planner planner; private PlannerSession() {} @@ -26,7 +28,8 @@ public final class PlannerSession { } RecipeResolution resolution = new RecipeResolution(new VanillaRecipeProvider()); ProgressCalculation progress = new ProgressCalculation(resolution, new MaterialAggregation()); - planner = new Planner(new InMemoryGoalStore(), progress, PlannerSession::currentInventory); + store = new PersistingGoalStore(); + planner = new Planner(store, progress, PlannerSession::currentInventory); } public static Planner get() { @@ -36,6 +39,17 @@ public final class PlannerSession { return planner; } + public static void onJoinWorld() { + bootstrap(); + store.loadFromWorld(PlayerGoalPersistence.load()); + } + + public static void onLeaveWorld() { + if (store != null) { + store.unload(); + } + } + private static InventoryState currentInventory() { LocalPlayer player = Minecraft.getInstance().player; if (player == null) { diff --git a/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/GoalPlan.java b/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/GoalPlan.java new file mode 100644 index 0000000..0e60799 --- /dev/null +++ b/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/GoalPlan.java @@ -0,0 +1,59 @@ +package com.sufficient.satistaskory.infrastructure.persistence; + +import java.util.ArrayList; +import java.util.List; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +import com.sufficient.satistaskory.domain.Goal; +import com.sufficient.satistaskory.domain.ItemId; + +/** + * NBT shape for the player's goal list. Not a domain type. + */ +public record GoalPlan(List goals) { + public static final GoalPlan EMPTY = new GoalPlan(List.of()); + + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + GoalEntry.CODEC.listOf().fieldOf("goals").forGetter(GoalPlan::goals) + ).apply(instance, GoalPlan::new)); + + public GoalPlan { + goals = List.copyOf(goals); + } + + public static GoalPlan empty() { + return EMPTY; + } + + public static GoalPlan fromGoals(List goals) { + List entries = new ArrayList<>(goals.size()); + for (Goal goal : goals) { + entries.add(new GoalEntry(goal.targetItem().toString(), goal.quantity())); + } + return new GoalPlan(entries); + } + + public List toGoals() { + List result = new ArrayList<>(); + for (GoalEntry entry : goals) { + if (entry.quantity() < 1) { + continue; + } + try { + result.add(new Goal(ItemId.parse(entry.item()), entry.quantity())); + } catch (IllegalArgumentException ignored) { + // skip a corrupt row; do not fail the world + } + } + return result; + } + + public record GoalEntry(String item, int quantity) { + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.STRING.fieldOf("item").forGetter(GoalEntry::item), + Codec.INT.fieldOf("quantity").forGetter(GoalEntry::quantity) + ).apply(instance, GoalEntry::new)); + } +} diff --git a/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/PersistingGoalStore.java b/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/PersistingGoalStore.java new file mode 100644 index 0000000..8844a4d --- /dev/null +++ b/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/PersistingGoalStore.java @@ -0,0 +1,67 @@ +package com.sufficient.satistaskory.infrastructure.persistence; + +import java.util.List; +import java.util.Optional; + +import com.sufficient.satistaskory.application.GoalStore; +import com.sufficient.satistaskory.application.InMemoryGoalStore; +import com.sufficient.satistaskory.domain.Goal; +import com.sufficient.satistaskory.domain.ItemId; + +/** + * RAM store that writes the player's world save after each change. + * Load and leave-world must not write; otherwise logout would wipe the save. + */ +public final class PersistingGoalStore implements GoalStore { + private final InMemoryGoalStore inner = new InMemoryGoalStore(); + private boolean persist = true; + + @Override + public List all() { + return inner.all(); + } + + @Override + public Optional find(ItemId item) { + return inner.find(item); + } + + @Override + public void put(Goal goal) { + inner.put(goal); + persist(); + } + + @Override + public void remove(ItemId item) { + inner.remove(item); + persist(); + } + + @Override + public void clear() { + inner.clear(); + persist(); + } + + public void loadFromWorld(List goals) { + persist = false; + inner.clear(); + for (Goal goal : goals) { + inner.put(goal); + } + persist = true; + } + + public void unload() { + persist = false; + inner.clear(); + persist = true; + } + + private void persist() { + if (persist) { + PlayerGoalPersistence.save(inner.all()); + } + } +} diff --git a/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/PlayerGoalPersistence.java b/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/PlayerGoalPersistence.java new file mode 100644 index 0000000..ad9168f --- /dev/null +++ b/src/main/java/com/sufficient/satistaskory/infrastructure/persistence/PlayerGoalPersistence.java @@ -0,0 +1,49 @@ +package com.sufficient.satistaskory.infrastructure.persistence; + +import java.util.List; +import java.util.UUID; + +import com.sufficient.satistaskory.Satistaskory; +import com.sufficient.satistaskory.domain.Goal; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.server.IntegratedServer; +import net.minecraft.server.level.ServerPlayer; + +/** + * Player attachment in this world's save. Singleplayer and LAN host. + * A remote server has no integrated save; the session stays RAM-only there. + */ +public final class PlayerGoalPersistence { + private PlayerGoalPersistence() {} + + public static List load() { + Minecraft minecraft = Minecraft.getInstance(); + IntegratedServer server = minecraft.getSingleplayerServer(); + if (server == null || minecraft.player == null) { + return List.of(); + } + ServerPlayer player = server.getPlayerList().getPlayer(minecraft.player.getUUID()); + if (player == null) { + return List.of(); + } + return player.getData(Satistaskory.PLAYER_GOALS).toGoals(); + } + + public static void save(List goals) { + Minecraft minecraft = Minecraft.getInstance(); + IntegratedServer server = minecraft.getSingleplayerServer(); + if (server == null || minecraft.player == null) { + return; + } + UUID id = minecraft.player.getUUID(); + GoalPlan plan = GoalPlan.fromGoals(goals); + server.execute(() -> { + ServerPlayer player = server.getPlayerList().getPlayer(id); + if (player == null) { + return; + } + player.setData(Satistaskory.PLAYER_GOALS, plan); + }); + } +} diff --git a/src/test/java/com/sufficient/satistaskory/infrastructure/persistence/GoalPlanTest.java b/src/test/java/com/sufficient/satistaskory/infrastructure/persistence/GoalPlanTest.java new file mode 100644 index 0000000..dfeceea --- /dev/null +++ b/src/test/java/com/sufficient/satistaskory/infrastructure/persistence/GoalPlanTest.java @@ -0,0 +1,42 @@ +package com.sufficient.satistaskory.infrastructure.persistence; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.sufficient.satistaskory.domain.Goal; +import com.sufficient.satistaskory.domain.ItemId; +import com.sufficient.satistaskory.infrastructure.persistence.GoalPlan.GoalEntry; + +class GoalPlanTest { + private static final ItemId FURNACE = ItemId.parse("minecraft:furnace"); + + @Test + void roundTripKeepsItemAndQuantity() { + GoalPlan plan = GoalPlan.fromGoals(List.of(new Goal(FURNACE, 3))); + List goals = plan.toGoals(); + assertEquals(1, goals.size()); + assertEquals(FURNACE, goals.getFirst().targetItem()); + assertEquals(3, goals.getFirst().quantity()); + } + + @Test + void skipsCorruptRows() { + GoalPlan plan = new GoalPlan(List.of( + new GoalEntry("minecraft:furnace", 2), + new GoalEntry("not-an-id", 1), + new GoalEntry("minecraft:chest", 0))); + List goals = plan.toGoals(); + assertEquals(1, goals.size()); + assertEquals(FURNACE, goals.getFirst().targetItem()); + assertEquals(2, goals.getFirst().quantity()); + } + + @Test + void emptyPlanIsEmpty() { + assertTrue(GoalPlan.empty().toGoals().isEmpty()); + } +}