diff --git a/CHANGELOG.md b/CHANGELOG.md index cc5f1c56..32a314e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ Releases are numbered **2.x.yy**: `x` is the major version and `yy` a two-digit [Versioning](README.md#versioning)). Every version needs a section here before it can be merged; CI publishes the section as the GitHub release notes. +## [2.0.07] - 2026-10-09 + +### Added +- The survival campaign picks its build plot. Starting on rough ground no longer means building + into a hill or a tree and pausing at the first blocked placement: the campaign looks up to 16 + blocks around the start, once, for the nearest clear, level plot that fits every building of the + chosen tier, and keeps the old spot two blocks east of the start whenever that already fits. When + nothing fits it pauses straight away and says so; `.grind resume` builds at the old spot anyway. + The search reads each column once from loaded chunks and took at most 10 ms in the game tests, + where a test arena with a pillar on every third column is refused until a clean patch is opened. + ## [2.0.06] - 2026-10-09 ### Added diff --git a/README.md b/README.md index 6a677f44..727f13b9 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ AI contributors: read [handover.md](handover.md) for current progress, architect 1. Install Fabric Loader for Minecraft 26.2. 2. Put Fabric API and `agalarhack-*.jar` in `.minecraft/mods/`. -3. Launch the Fabric profile. The HUD should report **Agalar Hack 2.0.06**. +3. Launch the Fabric profile. The HUD should report **Agalar Hack 2.0.07**. ## Versioning diff --git a/docs/ADDONS.md b/docs/ADDONS.md index 71e5c3be..59e4cf6f 100644 --- a/docs/ADDONS.md +++ b/docs/ADDONS.md @@ -60,7 +60,7 @@ This client is not on a Maven repository, so depend on the jar you have: ```gradle dependencies { - modImplementation files("libs/agalarhack-2.0.06.jar") + modImplementation files("libs/agalarhack-2.0.07.jar") } ``` diff --git a/docs/AUTOGRIND.md b/docs/AUTOGRIND.md index cf705de6..f0559cea 100644 --- a/docs/AUTOGRIND.md +++ b/docs/AUTOGRIND.md @@ -1,10 +1,17 @@ # AutoGrind -`.grind survival` starts the full survival campaign. Choose a flat, empty plot in the Overworld before starting; -its southwest floor corner is two blocks east of the starting position. `.grind status` reports the -current milestone or actionable pause, `.grind stop` cancels it, and `.grind resume` continues the -same task after a pause. A new campaign in the same loaded world reuses its base location and checks -live inventory again. Disconnecting or loading an unrelated world clears the base. +`.grind survival` starts the full survival campaign in the Overworld. Its buildings go on the +nearest clear, level plot: on open level ground that is the spot two blocks east of the start, as +before; otherwise the campaign searches up to 16 blocks around it once, in loaded chunks, for a plot +that fits every building the chosen tier will put up (the iron house, the diamond annex and walkway, +the max portal and enchanting area). A plot fits when nothing but grass-like blocks stands in the +build volume, the ground is solid rather than water, at most two blocks low anywhere, and level under +at least 80% of the floor. When nothing fits, the campaign pauses at once and says so: move to +open, level ground and start again, or `.grind resume` to build at the default corner anyway. +`.grind status` reports the current milestone or actionable pause, `.grind stop` cancels it, and +`.grind resume` continues the same task after a pause. A new campaign in the same loaded world +reuses its base location and checks live inventory again; a base chosen for a lower tier is not +re-checked for a higher one. Disconnecting or loading an unrelated world clears the base. | Command | Result | | --- | --- | @@ -102,7 +109,8 @@ Unit tests cover all campaign item prerequisite chains, gear tiers, crafting lay ordering, building/portal geometry, storage reserves, station slot arithmetic and owned Baritone process cancellation. Real-client scenarios cover ordinary resource breaking and pickup, crafting, station placement, cooking, diamond/iron equipment recipes, Netherite smithing, survival startup and -stop, exact building placements, chest transfers, storage withdrawal and automatic equipment. +stop, exact building placements, build plot choice on rough ground, chest transfers, storage +withdrawal and automatic equipment. The regular client suite verifies Baritone absence; bridge unit tests also use API-shaped stubs. `tools/test-baritone.sh` runs a separate installed-Baritone 1.19.0 / Minecraft 26.2 fixture with a @@ -115,6 +123,6 @@ test-only cleanup does not fix or establish clean shutdown for a normal installe suite also exercises pressure storage, full-chest stack merging and near-broken tool replacement. A complete randomly generated survival world from empty inventory through the Nether and all enchants is not a deterministic integration-test fixture. Baritone availability, terrain access, animal/resource availability and server interaction rules -can require manual intervention. Build footprints need clear supports; existing blocks are not -removed. Full chests, unrelated station contents, and server-rejected placements remain resumable +can require manual intervention. Existing blocks are never removed: rough ground with no level plot +in reach pauses the campaign at its start rather than later at a blocked placement. Full chests, unrelated station contents, and server-rejected placements remain resumable pauses or specific failures. Eight-item smelting batches can exceed the requested minimum. diff --git a/docs/MAJOR_GELISTIRME_PLANI.md b/docs/MAJOR_GELISTIRME_PLANI.md index 13f3c33d..5a3b9146 100644 --- a/docs/MAJOR_GELISTIRME_PLANI.md +++ b/docs/MAJOR_GELISTIRME_PLANI.md @@ -129,8 +129,14 @@ kalır ve özel pathfinder yazılmaz. külçe, taşınan cevheri eritmeye tercih ediliyor. Adı değiştirilmiş, büyülü ve kırılmak üzere olan eşyalar alınmıyor, iki boş yuva korunuyor, ulaşılamayan sandık kampanyayı duraklatmıyor. Kampanya deposu ve içerik kaydı `GrindStorage`'da. -3. **İnşaat alanı seçimi.** Oyuncunun durduğu yerde düz alan yoksa tarayıcı bütçesiyle yakında - uygun bir alan aransın. Bulunamazsa net bir duraklatma mesajı verilsin. +3. ✅ **İnşaat alanı seçimi (2.0.07).** Kampanya yeni bir dünyada başlarken, kademenin bütün + binalarının (ev, depo eki, portal, büyü alanı) taban alanına uyan en yakın temiz ve düz alanı + 16 blok içinde, yalnızca yüklü chunk'larda bir kez arıyor. Her sütunun üst bloğu bir kez okunuyor + ve sonuç tekrar kullanılıyor; arama süresi günlüğe yazılıyor (game testlerinde en fazla 10 ms). + Düz zeminde konum eskisiyle aynı. + Alan yoksa kampanya baştan, net bir mesajla duraklıyor; `.grind resume` varsayılan köşeyi kabul + ediyor. Not: "tarayıcı bütçesi" yerine tek seferlik, sınırlı bir okuma seçildi (en fazla birkaç + bin sütun), çünkü kampanyanın görev listesi tabanın konumu belli olmadan kurulamıyor. 4. **Avlanmada keşif.** Yüklü hayvan yoksa Baritone ile sınırlı bir keşif yapılsın. Baritone yoksa bugünkü duraklatma kalır. 5. **İlk şablon.** Bastion bulma ve yağmalama güvenilir biçimde test edilemiyor. Bu madde ancak @@ -187,7 +193,8 @@ E (kanıt) her adımda paralel | 2.0.04 | ✅ D1 ilk adım: AutoGrind görev sınıfları ayrıldı (davranış değişmeden) | | 2.0.05 | ✅ D1 devamı (seyahat, istasyon, erişim yardımcıları) ve C2 overlay kare süreleri | | 2.0.06 | ✅ D1 son adım (envanter yardımcıları) ve D2 depodan geri alma | -| 2.0.07+ | D3–D4 AutoGrind 2 adımları, ESP kutu maliyeti, C3 (ölçüm sonucuna göre) | +| 2.0.07 | ✅ D3 inşaat alanı seçimi | +| 2.0.08+ | D4 avlanmada keşif, ESP kutu maliyeti, C3 (ölçüm sonucuna göre) | | 2.1.00 | B: Addon API 2 ve sürüm sözleşmesi, A4 güncelleme denetleyicisi | ## Riskler diff --git a/gradle.properties b/gradle.properties index 8b9c0578..a3eb9a85 100644 --- a/gradle.properties +++ b/gradle.properties @@ -16,6 +16,6 @@ fabric_api_version=0.157.0+26.2 # Version scheme 2.x.yy: x is the major line, yy a two-digit minor update (00-99). Raise yy for each # release; raise x (and reset yy to 00) for a major one. The Minecraft version above is separate. # The build rejects anything else. -mod_version=2.0.06 +mod_version=2.0.07 maven_group=me.mrhakan archives_base_name=agalarhack diff --git a/handover.md b/handover.md index ddb74e68..a753f1e3 100644 --- a/handover.md +++ b/handover.md @@ -65,6 +65,13 @@ recomputes `GrindWithdrawal.plan` (pure, top-down: carried, then stored, then ingredients) from live contents after opening, skips unreachable chests, and has its own 2,400-tick budget because its goal ticks it directly. `EnchantTask`'s XP coal sets `useStorage = false`. +- 2.0.07 (D3): `startSurvival` in a new world (or after a no-plot pause that was not resumed) calls + `GrindPlot.choose` (pure) over `SurvivalBlueprint.footprint(tier)` with a cached `LoadedTerrain` + that reads each column's top non-replaceable block in feet-10..feet+8 once. The default corner is + tried first. No plot: the base is the default corner, `provisionalBase` is set, and the runner is + paused with a "No clear, level spot" reason; `resume()` clears the flag, a restart searches again. + Structure offsets (`PORTAL_X`, `ENCHANTING_X/Z`) and the enchanting layout now live in + `SurvivalBlueprint` so the footprint and the tasks cannot drift apart. - 2.0.05: `OverlayTimings` is the frame-based counterpart of `ModuleTimings` (a `ModuleTimings` with a 120-frame window and 180-frame expiry). `WorldOverlays.collect` opens a frame each time it runs, which also closes the previous one; an overlay's labels and deferred lines add into one slot, so diff --git a/src/gametest/java/me/mrhakan/agalarhack/services/SurvivalTasksGameTest.java b/src/gametest/java/me/mrhakan/agalarhack/services/SurvivalTasksGameTest.java index 685b1ed9..121f5516 100644 --- a/src/gametest/java/me/mrhakan/agalarhack/services/SurvivalTasksGameTest.java +++ b/src/gametest/java/me/mrhakan/agalarhack/services/SurvivalTasksGameTest.java @@ -98,6 +98,9 @@ public final class SurvivalTasksGameTest implements FabricClientGameTest { g.stop(); // Restarting in the same loaded world must retain completed base storage. g.startSurvival(SurvivalProgression.Tier.MAX); + // Should no plot fit the MAX buildings around this arena, the campaign starts paused; + // resuming accepts the default corner, which is all this scenario needs. + g.resume(); g.useBaritone(false); }); for (int i = 0; i < 300; i++) { @@ -159,7 +162,8 @@ public final class SurvivalTasksGameTest implements FabricClientGameTest { })) throw new AssertionError("Level-30 enchanting did not return enchanted gear and consume three levels"); context.runOnClient(c -> g.stop()); storedSuppliesAreTakenBack(context, world, g, base, chest); - org.slf4j.LoggerFactory.getLogger("agalarhack-gametest").info("Survival placement, storage, equipment, template duplication, enchanting and storage withdrawal passed"); + buildPlotSearch(context, world, g, base.offset(0, 0, 96)); + org.slf4j.LoggerFactory.getLogger("agalarhack-gametest").info("Survival placement, storage, equipment, template duplication, enchanting, storage withdrawal and build plot search passed"); } } /** @@ -211,6 +215,55 @@ private static void storedSuppliesAreTakenBack(ClientGameTestContext context, Te context.runOnClient(c -> g.stop()); } + /** + * D3: on rough ground the campaign finds a level plot nearby instead of building where it + * stands, and says so plainly when there is none. The arena is level stone with a two-high + * pillar on every third column, so no house footprint fits anywhere in reach, until a clean + * patch is opened a few blocks east. + */ + private static void buildPlotSearch(ClientGameTestContext context, TestSingleplayerContext world, GrindExecutor g, BlockPos start) { + int reach = GrindPlot.SEARCH_RADIUS + 12; + world.getServer().runOnServer(server -> { + ServerPlayer p = world.getConnection().getServerPlayer(); + var level = p.level(); + for (int x = -reach; x <= reach; x++) for (int z = -reach; z <= reach; z++) { + level.setBlockAndUpdate(start.offset(x, -1, z), Blocks.STONE.defaultBlockState()); + boolean pillar = Math.floorMod(x, 3) == 1 && Math.floorMod(z, 3) == 1; + for (int y = 0; y <= GrindPlot.SCAN_TOP + 1; y++) + level.setBlockAndUpdate(start.offset(x, y, z), pillar && y <= 1 ? Blocks.COBBLESTONE.defaultBlockState() : Blocks.AIR.defaultBlockState()); + } + p.teleportTo(start.getX() + 0.5, start.getY(), start.getZ() + 0.5); + }); + world.getConnection().waitForChunksRender(); + context.waitTicks(40); + context.runOnClient(c -> { + g.reset(); + if (g.startSurvival(SurvivalProgression.Tier.IRON) != GrindExecutor.StartResult.STARTED) + throw new AssertionError("The campaign did not start on rough ground"); + if (g.state() != TaskRunner.State.NEEDS_MOVEMENT || g.blockedReason() == null || !g.blockedReason().startsWith("No clear, level spot")) + throw new AssertionError("Rough ground with no plot should pause with a clear reason; state=" + g.state() + " reason=" + g.blockedReason()); + g.stop(); + }); + // A clean patch east of the start: x 8..16, z -3..5 from the player. + world.getServer().runOnServer(server -> { + var level = world.getConnection().getServerPlayer().level(); + for (int x = 8; x <= 16; x++) for (int z = -3; z <= 5; z++) for (int y = 0; y <= 1; y++) + level.setBlockAndUpdate(start.offset(x, y, z), Blocks.AIR.defaultBlockState()); + }); + context.waitTicks(20); + int[] corner = context.computeOnClient(c -> { + if (g.startSurvival(SurvivalProgression.Tier.IRON) != GrindExecutor.StartResult.STARTED || g.state() != TaskRunner.State.RUNNING) + throw new AssertionError("The campaign did not start on the open patch; state=" + g.state() + " reason=" + g.blockedReason()); + String[] parts = g.baseCoordinates().split(" "); + g.stop(); + return new int[]{Integer.parseInt(parts[0]) - start.getX(), Integer.parseInt(parts[1]) - start.getY(), Integer.parseInt(parts[2]) - start.getZ()}; + }); + // The iron house is five by five with a path cell north of it, so its corner must sit at x 8..12, z -2..1. + if (corner[0] < 8 || corner[0] > 12 || corner[2] < -2 || corner[2] > 1 || corner[1] != 0) + throw new AssertionError("The chosen plot " + corner[0] + " " + corner[1] + " " + corner[2] + " is not on the open patch"); + context.runOnClient(c -> g.reset()); + } + /** Named iron ingots, unnamed iron ingots and sticks in the chest, read on the server. */ private static int[] chestContents(TestSingleplayerContext world, BlockPos chest) { return world.getServer().computeOnServer(server -> { diff --git a/src/main/java/me/mrhakan/agalarhack/services/GrindExecutor.java b/src/main/java/me/mrhakan/agalarhack/services/GrindExecutor.java index 98ede094..864fda80 100644 --- a/src/main/java/me/mrhakan/agalarhack/services/GrindExecutor.java +++ b/src/main/java/me/mrhakan/agalarhack/services/GrindExecutor.java @@ -1,6 +1,7 @@ package me.mrhakan.agalarhack.services; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -14,6 +15,8 @@ import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.LevelChunk; /** * Executes every current GrindBook goal. CraftingPlan remains the inventory-only planner; this @@ -57,6 +60,8 @@ enum Station { private int transitionWait; private SurvivalTasks survivalTasks; private BlockPos survivalBase; + /** True while the base is the unsearched default because no plot fit; a restart searches again. */ + private boolean provisionalBase; private ClientLevel homeWorld; private final Map, Set> protectedBlocks = new LinkedHashMap<>(); private final TaskRunner runner = new TaskRunner(); @@ -130,21 +135,78 @@ public StartResult startSurvival(SurvivalProgression.Tier tier) { useBaritone = true; ownerPlayer = client.player; ownerLevel = client.level; - if (survivalBase == null || homeWorld != client.level) { - survivalBase = client.player.blockPosition().offset(2, 0, 0).immutable(); homeWorld = client.level; - storage.clear(); + String plotProblem = null; + boolean newWorld = survivalBase == null || homeWorld != client.level; + if (newWorld || provisionalBase) { + BlockPos fallback = client.player.blockPosition().offset(2, 0, 0).immutable(); + BlockPos plot = choosePlot(tier, fallback); + survivalBase = plot != null ? plot : fallback; homeWorld = client.level; + provisionalBase = plot == null; + if (newWorld) storage.clear(); + if (plot == null) { + plotProblem = "No clear, level spot within " + GrindPlot.SEARCH_RADIUS + " blocks for the " + + tier.name().toLowerCase(java.util.Locale.ROOT) + " campaign's buildings; move to open, level ground and start again, or .grind resume to build at " + + coordinates(fallback) + " anyway."; + } } survivalTasks = new SurvivalTasks(this, tier, survivalBase); runner.start(survivalTasks.tasks()); + if (plotProblem != null) runner.pause(plotProblem); return StartResult.STARTED; } + + /** The nearest plot that fits the tier's buildings, or {@code null}; reads loaded chunks only, once. */ + private BlockPos choosePlot(SurvivalProgression.Tier tier, BlockPos fallback) { + long started = System.nanoTime(); + LoadedTerrain terrain = new LoadedTerrain(fallback.getY()); + var plot = GrindPlot.choose(terrain, SurvivalBlueprint.footprint(tier), fallback.getX(), fallback.getY(), fallback.getZ()); + LOGGER.info("AutoGrind build plot search: {} after reading {} columns in {} ms", plot == null ? "none" : plot, + terrain.columns.size(), (System.nanoTime() - started) / 1_000_000); + return plot == null ? null : new BlockPos(plot.x(), plot.y(), plot.z()); + } + + /** Column tops from loaded chunks, each read once per search. */ + private final class LoadedTerrain implements GrindPlot.Terrain { + final Map columns = new HashMap<>(); + private final int feetY; + private final BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); + + LoadedTerrain(int feetY) { this.feetY = feetY; } + + public int top(int x, int z) { return column(x, z)[0]; } + public boolean solid(int x, int z) { return column(x, z)[1] != 0; } + + private int[] column(int x, int z) { + return columns.computeIfAbsent(BlockPos.asLong(x, 0, z), key -> scan(x, z)); + } + + private int[] scan(int x, int z) { + LevelChunk chunk = scanner.loadedChunk(x >> 4, z >> 4); + if (chunk == null) return new int[]{GrindPlot.UNKNOWN, 0}; + int top = Math.min(feetY + GrindPlot.SCAN_TOP, client.level.getMaxY()); + int bottom = Math.max(feetY + GrindPlot.SCAN_BOTTOM, client.level.getMinY()); + for (int y = top; y >= bottom; y--) { + BlockState state = chunk.getBlockState(cursor.set(x, y, z)); + boolean fluid = !state.getFluidState().isEmpty(); + if (state.canBeReplaced() && !fluid) continue; + boolean solid = !fluid && !state.getCollisionShape(client.level, cursor).isEmpty(); + return new int[]{y, solid ? 1 : 0}; + } + return new int[]{GrindPlot.UNKNOWN, 0}; + } + } public boolean baritoneAvailable() { return baritone.available(); } public void useBaritone(boolean enabled) { useBaritone = enabled; if (!enabled) travel.cancelAutomation(); } public boolean usingBaritone() { return useBaritone; } public String survivalTier() { return survival && survivalTasks != null ? survivalTasks.tier.name().toLowerCase(java.util.Locale.ROOT) : null; } /** Resume a task paused for direct reach, an open screen, or a missing free inventory slot. */ - public boolean resume() { return runner.resume(); } + public boolean resume() { + boolean resumed = runner.resume(); + // Resuming the no-plot pause accepts the default corner; a later restart must not move it. + if (resumed) provisionalBase = false; + return resumed; + } /** Advances one task tick on the client thread. Container clicks remain owned by InventoryService. */ public void tick() { @@ -197,7 +259,7 @@ public boolean stop() { return wasActive; } - public void reset() { stop(); survivalBase = null; homeWorld = null; storage.clear(); protectedBlocks.clear(); } + public void reset() { stop(); survivalBase = null; provisionalBase = false; homeWorld = null; storage.clear(); protectedBlocks.clear(); } public boolean running() { return runner.running(); } public TaskRunner.State state() { return runner.state(); } public String currentTask() { diff --git a/src/main/java/me/mrhakan/agalarhack/services/GrindPlot.java b/src/main/java/me/mrhakan/agalarhack/services/GrindPlot.java new file mode 100644 index 00000000..c1035788 --- /dev/null +++ b/src/main/java/me/mrhakan/agalarhack/services/GrindPlot.java @@ -0,0 +1,85 @@ +package me.mrhakan.agalarhack.services; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Where the survival campaign builds: the nearest clear, level plot for every building its tier + * will put up, searched once when a campaign starts in a new world. + * + *

A plot fits when, for every column of {@link SurvivalBlueprint#footprint}, nothing a build + * could not replace (a block, leaves, a fluid) stands at or above floor level within the scan + * window, the ground under the floor is solid and at most {@value #MAX_DIP} blocks low, and at least + * {@value #SUPPORTED_PERCENT}% of the columns have it exactly one below the floor. A dip of a block or + * two is bridged by the floor's neighbours as it is placed; a hill, a tree, water or a cliff is not. + * + *

The corner the player would get without a search is tried first, so starting on open level + * ground builds exactly where it always did. Kept free of Minecraft types: the terrain arrives + * through {@link Terrain}, one column at a time. + */ +final class GrindPlot { + private GrindPlot() { } + + /** Horizontal distance from the default corner searched for a plot. */ + static final int SEARCH_RADIUS = 16; + /** Floor levels tried, relative to the player's feet. */ + static final int LOWEST_FLOOR = -6, HIGHEST_FLOOR = 4; + /** + * The window each column is scanned in, relative to the player's feet: from five above the + * highest floor tried, so a five-high build always lies inside it, to below the lowest. + */ + static final int SCAN_TOP = HIGHEST_FLOOR + 4, SCAN_BOTTOM = LOWEST_FLOOR - 4; + static final int MAX_DIP = 2; + static final int SUPPORTED_PERCENT = 80; + /** A column with no known top: unloaded, or open all the way down the window. */ + static final int UNKNOWN = Integer.MIN_VALUE; + + /** The terrain the search reads; implementations cache, because neighbouring plots share columns. */ + interface Terrain { + /** The highest y in the scan window holding something a build could not replace, or {@link #UNKNOWN}. */ + int top(int x, int z); + /** Whether that block can be built on: it has a collision shape and is not a fluid. */ + boolean solid(int x, int z); + } + + /** The base corner: the floor of every building is laid at {@code y}. */ + record Plot(int x, int y, int z) { } + + /** + * @param defaultX the corner a campaign uses without a search, which is tried first + * @param feetY the player's feet, which the scan window and floor levels are measured from + * @return the nearest plot that fits, or {@code null} when none within {@link #SEARCH_RADIUS} does + */ + static Plot choose(Terrain terrain, List footprint, int defaultX, int feetY, int defaultZ) { + List offsets = new ArrayList<>(); + for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) { + for (int dz = -SEARCH_RADIUS; dz <= SEARCH_RADIUS; dz++) offsets.add(new int[]{dx, dz}); + } + // Nearest first, then a fixed order, so the same terrain always gives the same plot. + offsets.sort(Comparator.comparingInt(o -> o[0] * o[0] + o[1] * o[1]) + .thenComparingInt(o -> o[0]).thenComparingInt(o -> o[1])); + for (int[] offset : offsets) { + int x = defaultX + offset[0], z = defaultZ + offset[1]; + Integer floor = floor(terrain, footprint, x, feetY, z); + if (floor != null) return new Plot(x, floor, z); + } + return null; + } + + /** The floor level a plot with its corner at this column would have, or {@code null} if it does not fit. */ + static Integer floor(Terrain terrain, List footprint, int x, int feetY, int z) { + int corner = terrain.top(x, z); + if (corner == UNKNOWN) return null; + int floor = corner + 1; + if (floor < feetY + LOWEST_FLOOR || floor > feetY + HIGHEST_FLOOR) return null; + int supported = 0; + for (SurvivalBlueprint.Column column : footprint) { + int cx = x + column.x(), cz = z + column.z(); + int top = terrain.top(cx, cz); + if (top == UNKNOWN || top >= floor || top < floor - 1 - MAX_DIP || !terrain.solid(cx, cz)) return null; + if (top == floor - 1) supported++; + } + return supported * 100 >= SUPPORTED_PERCENT * footprint.size() ? floor : null; + } +} diff --git a/src/main/java/me/mrhakan/agalarhack/services/SurvivalBlueprint.java b/src/main/java/me/mrhakan/agalarhack/services/SurvivalBlueprint.java index cb8a7e9e..1652b248 100644 --- a/src/main/java/me/mrhakan/agalarhack/services/SurvivalBlueprint.java +++ b/src/main/java/me/mrhakan/agalarhack/services/SurvivalBlueprint.java @@ -1,14 +1,25 @@ package me.mrhakan.agalarhack.services; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.LinkedHashMap; +import java.util.Set; +import java.util.TreeSet; /** Relative, ordered placements. Floor, walls, roof, then fixtures; no terrain is erased. */ public final class SurvivalBlueprint { private SurvivalBlueprint() { } public record Placement(int x, int y, int z, String item) { } + /** One ground column, relative to the base corner. */ + public record Column(int x, int z) { } + + /** Where the portal frame and the enchanting area stand relative to the base corner. */ + static final int PORTAL_X = -5; + static final int ENCHANTING_X = 8, ENCHANTING_Z = 10; + /** The enchanting area is the table, a ring of shelves two out, and the one-block gap between. */ + static final int ENCHANTING_REACH = 2; public static List house(boolean expanded) { int size = expanded ? 7 : 5, offset = expanded ? 6 : 0; List blocks = new ArrayList<>(); @@ -47,6 +58,38 @@ public static Map materials(boolean expanded) { for (Placement placement : house(expanded)) result.merge(placement.item(), 1, Integer::sum); return Map.copyOf(result); } + /** The table at the centre and fifteen shelves on the ring two blocks out, leaving the front open. */ + public static List enchantingArea() { + List layout = new ArrayList<>(); + layout.add(new Placement(0, 0, 0, "enchanting_table")); + for (int x = -ENCHANTING_REACH; x <= ENCHANTING_REACH; x++) for (int z = -ENCHANTING_REACH; z <= ENCHANTING_REACH; z++) { + if (Math.abs(x) != ENCHANTING_REACH && Math.abs(z) != ENCHANTING_REACH || x == 0 && z == -ENCHANTING_REACH) continue; + layout.add(new Placement(x, 0, z, "bookshelf")); + } + return List.copyOf(layout); + } + + /** + * Every ground column a tier's buildings stand on, relative to the base corner: the houses, the + * portal frame and the whole enchanting area, whose gap must stay clear for the shelves to count. + * Storage chests stand inside the houses. + */ + public static List footprint(SurvivalProgression.Tier tier) { + Set columns = new TreeSet<>(Comparator.comparingInt(Column::x).thenComparingInt(Column::z)); + for (SurvivalProgression.Goal goal : SurvivalProgression.goals(tier)) { + switch (goal.kind()) { + case HOUSE -> house(goal.count() > 1).forEach(p -> columns.add(new Column(p.x(), p.z()))); + case PORTAL -> portal().forEach(p -> columns.add(new Column(PORTAL_X + p.x(), p.z()))); + case ENCHANT -> { + for (int x = -ENCHANTING_REACH; x <= ENCHANTING_REACH; x++) for (int z = -ENCHANTING_REACH; z <= ENCHANTING_REACH; z++) + columns.add(new Column(ENCHANTING_X + x, ENCHANTING_Z + z)); + } + default -> { } + } + } + return List.copyOf(columns); + } + public static List portal() { List result = new ArrayList<>(); // Four-wide, five-high frame with corners for direct vanilla placement support. diff --git a/src/main/java/me/mrhakan/agalarhack/services/SurvivalTasks.java b/src/main/java/me/mrhakan/agalarhack/services/SurvivalTasks.java index 840d21a3..c6520855 100644 --- a/src/main/java/me/mrhakan/agalarhack/services/SurvivalTasks.java +++ b/src/main/java/me/mrhakan/agalarhack/services/SurvivalTasks.java @@ -51,10 +51,10 @@ List tasks() { : List.of(base.offset(7, 1, 5), base.offset(9, 1, 5), base.offset(11, 1, 5)); tasks.add(new StorageTask(grind, chests, Map.of(), true)); } - case PORTAL -> tasks.add(new PortalTask(grind, base.offset(-5, 0, 0))); + case PORTAL -> tasks.add(new PortalTask(grind, base.offset(SurvivalBlueprint.PORTAL_X, 0, 0))); case NETHER -> tasks.add(new DimensionTask(true)); case OVERWORLD -> tasks.add(new DimensionTask(false)); - case ENCHANT -> { tasks.add(new EnchantTask(grind, base.offset(8, 0, 10))); tasks.add(new EquipTask(grind)); } + case ENCHANT -> { tasks.add(new EnchantTask(grind, base.offset(SurvivalBlueprint.ENCHANTING_X, 0, SurvivalBlueprint.ENCHANTING_Z))); tasks.add(new EquipTask(grind)); } } while (taskGoals.size() < tasks.size()) taskGoals.add(goal); } @@ -782,7 +782,7 @@ public boolean satisfied() { public int budgetTicks() { return 24_000; } public boolean tick() { blocked = null; expectingDimension = true; - BlockPos portal = entering ? base.offset(-4, 1, 0) : netherEntry; + BlockPos portal = entering ? base.offset(SurvivalBlueprint.PORTAL_X + 1, 1, 0) : netherEntry; if (portal == null) { blocked = "Locate a return portal and enter it, then .grind resume."; return true; } if (grind.client.player.isOnPortalCooldown()) return true; if (!grind.travel.moveTo(portal)) blocked = grind.travel.movementProblem("Enter the portal at " + GrindExecutor.coordinates(portal) + "; Baritone pathing is unavailable."); @@ -801,14 +801,8 @@ static final class EnchantTask implements TaskRunner.Task { OpenTask open; String blocked; int wait; boolean enchantIssued; ItemGoalTask xpWork; StorageTask xpStorage; EnchantTask(GrindExecutor g, BlockPos table) { this.g = g; this.table = table; - List layout = new ArrayList<>(); // Table and the 15 shelves live outside the annex to keep its storage passage clear. - layout.add(new SurvivalBlueprint.Placement(0, 0, 0, "enchanting_table")); - for (int x = -2; x <= 2; x++) for (int z = -2; z <= 2; z++) { - if (Math.abs(x) != 2 && Math.abs(z) != 2 || x == 0 && z == -2) continue; - layout.add(new SurvivalBlueprint.Placement(x, 0, z, "bookshelf")); - } - setup = new BuildTask(g, table, List.copyOf(layout), "enchanting area"); + setup = new BuildTask(g, table, SurvivalBlueprint.enchantingArea(), "enchanting area"); } boolean enchantable(ItemStack s) { return Set.of("netherite_pickaxe", "netherite_axe", "netherite_shovel", "netherite_sword", "netherite_helmet", "netherite_chestplate", "netherite_leggings", "netherite_boots").contains(id(s)) && !s.has(DataComponents.CUSTOM_NAME) && (s.get(DataComponents.ENCHANTMENTS) == null || s.get(DataComponents.ENCHANTMENTS).isEmpty()); } diff --git a/src/test/java/me/mrhakan/agalarhack/services/GrindPlotTest.java b/src/test/java/me/mrhakan/agalarhack/services/GrindPlotTest.java new file mode 100644 index 00000000..8f053fec --- /dev/null +++ b/src/test/java/me/mrhakan/agalarhack/services/GrindPlotTest.java @@ -0,0 +1,116 @@ +package me.mrhakan.agalarhack.services; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; + +class GrindPlotTest { + private static final int FEET = 64; + private static final List IRON = SurvivalBlueprint.footprint(SurvivalProgression.Tier.IRON); + + /** Level stone at FEET - 1 everywhere, with chosen columns raised, lowered, flooded or unloaded. */ + private static final class Field implements GrindPlot.Terrain { + final Map tops = new HashMap<>(); + final Set fluid = new HashSet<>(); + int defaultTop = FEET - 1; + static long key(int x, int z) { return ((long) x << 32) ^ (z & 0xFFFFFFFFL); } + Field set(int x, int z, int top) { tops.put(key(x, z), top); return this; } + Field pillars(int fromX, int toX, int fromZ, int toZ, int every) { + for (int x = fromX; x <= toX; x++) for (int z = fromZ; z <= toZ; z++) + if (Math.floorMod(x, every) == 0 && Math.floorMod(z, every) == 0) set(x, z, FEET + 2); + return this; + } + public int top(int x, int z) { return tops.getOrDefault(key(x, z), defaultTop); } + public boolean solid(int x, int z) { return !fluid.contains(key(x, z)); } + } + + @Test + void levelGroundKeepsTheDefaultCorner() { + assertEquals(new GrindPlot.Plot(2, FEET, 0), GrindPlot.choose(new Field(), IRON, 2, FEET, 0)); + } + + @Test + void anObstructedStartMovesToTheNearestPlotThatFits() { + // A single pillar inside the default footprint; the nearest corner whose footprint avoids it wins. + Field field = new Field().set(4, 2, FEET + 1); + GrindPlot.Plot plot = GrindPlot.choose(field, IRON, 2, FEET, 0); + assertNotNull(plot); + for (SurvivalBlueprint.Column column : IRON) + assertTrue(plot.x() + column.x() != 4 || plot.z() + column.z() != 2, "the chosen plot covers the pillar"); + // The footprint is five wide, so the nearest corner that clears x = 4 is three blocks west. + assertEquals(new GrindPlot.Plot(-1, FEET, 0), plot); + } + + @Test + void leavesWaterAndUnloadedChunksDoNotFit() { + Field leaves = new Field().set(2, 1, FEET); // anything at floor level, a leaf included + assertEquals(null, GrindPlot.floor(leaves, IRON, 2, FEET, 0)); + Field water = new Field(); + water.fluid.add(Field.key(3, 3)); + assertEquals(null, GrindPlot.floor(water, IRON, 2, FEET, 0)); + Field unloaded = new Field().set(5, 0, GrindPlot.UNKNOWN); + assertEquals(null, GrindPlot.floor(unloaded, IRON, 2, FEET, 0)); + } + + @Test + void smallDipsAreBridgedButHolesAreNot() { + Field dips = new Field().set(3, 1, FEET - 2).set(4, 3, FEET - 3); + assertEquals(FEET, GrindPlot.floor(dips, IRON, 2, FEET, 0)); + Field hole = new Field().set(3, 1, FEET - 4); + assertEquals(null, GrindPlot.floor(hole, IRON, 2, FEET, 0)); + } + + @Test + void mostOfTheFloorMustRestOnGround() { + Field sunken = new Field(); + // Lower every column but the corner one block: level, but nearly all of it unsupported. + for (SurvivalBlueprint.Column column : IRON) + if (column.x() != 0 || column.z() != 0) sunken.set(2 + column.x(), column.z(), FEET - 2); + assertEquals(null, GrindPlot.floor(sunken, IRON, 2, FEET, 0)); + } + + @Test + void aPlotOnHigherOrLowerGroundUsesThatFloor() { + Field terrace = new Field(); + terrace.defaultTop = FEET + 2; + assertEquals(new GrindPlot.Plot(2, FEET + 3, 0), GrindPlot.choose(terrace, IRON, 2, FEET, 0)); + terrace.defaultTop = FEET + GrindPlot.HIGHEST_FLOOR; + assertNull(GrindPlot.choose(terrace, IRON, 2, FEET, 0), "a floor above the scan window's reach is refused"); + } + + @Test + void noPlotWithinTheRadiusIsReported() { + int reach = GrindPlot.SEARCH_RADIUS + 20; + Field crowded = new Field().pillars(-reach, reach, -reach, reach, 3); + assertNull(GrindPlot.choose(crowded, IRON, 2, FEET, 0)); + } + + @Test + void theSameTerrainAlwaysGivesTheSamePlot() { + Field field = new Field().pillars(-6, 10, -6, 6, 4); + assertEquals(GrindPlot.choose(field, IRON, 2, FEET, 0), GrindPlot.choose(field, IRON, 2, FEET, 0)); + } + + @Test + void eachTierCoversItsOwnBuildings() { + var iron = Set.copyOf(IRON); + var diamond = Set.copyOf(SurvivalBlueprint.footprint(SurvivalProgression.Tier.DIAMOND)); + var max = Set.copyOf(SurvivalBlueprint.footprint(SurvivalProgression.Tier.MAX)); + assertTrue(diamond.containsAll(iron) && max.containsAll(diamond)); + for (var p : SurvivalBlueprint.house(false)) assertTrue(iron.contains(new SurvivalBlueprint.Column(p.x(), p.z()))); + for (var p : SurvivalBlueprint.house(true)) assertTrue(diamond.contains(new SurvivalBlueprint.Column(p.x(), p.z()))); + for (var p : SurvivalBlueprint.portal()) + assertTrue(max.contains(new SurvivalBlueprint.Column(SurvivalBlueprint.PORTAL_X + p.x(), p.z()))); + // The gap between the enchanting table and its shelves must be clear too. + assertTrue(max.contains(new SurvivalBlueprint.Column(SurvivalBlueprint.ENCHANTING_X + 1, SurvivalBlueprint.ENCHANTING_Z))); + assertEquals(1 + 15, SurvivalBlueprint.enchantingArea().size(), "one table and fifteen shelves"); + } +}