BlueGit

timfa copperfarmer

Add harvest break timing, replant windup, nether wart/cocoa expansion, and door use.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-14 · 3 months ago

Hash
b677827daa5e63541d5e1c82d3480fb12374af8b
Parent
6a31cef8
2 files changed +361 −84
src/main/java/nl/timfalken/copperfarmer/CropRegistry.java +83 −14
@@ -4,6 +4,9 @@ import org.bukkit.Material;
4 4 import org.bukkit.block.Block;
5 5 import org.bukkit.block.BlockFace;
6 6 import org.bukkit.block.data.Ageable;
7 import org.bukkit.block.data.BlockData;
8 import org.bukkit.block.data.Directional;
9 import org.bukkit.block.data.type.Cocoa;
7 10
8 11 import java.util.Collection;
9 12 import java.util.EnumMap;
@@ -12,26 +15,41 @@ import java.util.Map;
12 15 import java.util.Set;
13 16
14 17 final class CropRegistry {
15 record Crop(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {}
18 enum PlantSupport {
19 NONE,
20 FARMLAND,
21 SOUL_SAND,
22 JUNGLE_LOG_SIDE
23 }
24
25 record Crop(Material block, Material seed, PlantSupport support, boolean breakOnlyFruit) {
26 boolean expands() {
27 return support != PlantSupport.NONE;
28 }
29 }
30
31 private static final BlockFace[] HORIZONTAL = {
32 BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
33 };
16 34
17 35 private final Map<Material, Crop> crops = new EnumMap<>(Material.class);
18 36 private final Set<Material> seedMaterials = EnumSet.noneOf(Material.class);
19 37
20 38 CropRegistry() {
21 register(Material.WHEAT, Material.WHEAT_SEEDS, true, false);
22 register(Material.CARROTS, Material.CARROT, true, false);
23 register(Material.POTATOES, Material.POTATO, true, false);
24 register(Material.BEETROOTS, Material.BEETROOT_SEEDS, true, false);
25 register(Material.NETHER_WART, Material.NETHER_WART, false, false);
26 register(Material.COCOA, Material.COCOA_BEANS, false, false);
27 register(Material.SWEET_BERRY_BUSH, Material.SWEET_BERRIES, false, false);
28 register(Material.TORCHFLOWER_CROP, Material.TORCHFLOWER_SEEDS, true, false);
29 register(Material.MELON, Material.MELON_SEEDS, false, true);
30 register(Material.PUMPKIN, Material.PUMPKIN_SEEDS, false, true);
39 register(Material.WHEAT, Material.WHEAT_SEEDS, PlantSupport.FARMLAND, false);
40 register(Material.CARROTS, Material.CARROT, PlantSupport.FARMLAND, false);
41 register(Material.POTATOES, Material.POTATO, PlantSupport.FARMLAND, false);
42 register(Material.BEETROOTS, Material.BEETROOT_SEEDS, PlantSupport.FARMLAND, false);
43 register(Material.NETHER_WART, Material.NETHER_WART, PlantSupport.SOUL_SAND, false);
44 register(Material.COCOA, Material.COCOA_BEANS, PlantSupport.JUNGLE_LOG_SIDE, false);
45 register(Material.SWEET_BERRY_BUSH, Material.SWEET_BERRIES, PlantSupport.NONE, false);
46 register(Material.TORCHFLOWER_CROP, Material.TORCHFLOWER_SEEDS, PlantSupport.FARMLAND, false);
47 register(Material.MELON, Material.MELON_SEEDS, PlantSupport.NONE, true);
48 register(Material.PUMPKIN, Material.PUMPKIN_SEEDS, PlantSupport.NONE, true);
31 49 }
32 50
33 private void register(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {
34 Crop crop = new Crop(block, seed, farmland, breakOnlyFruit);
51 private void register(Material block, Material seed, PlantSupport support, boolean breakOnlyFruit) {
52 Crop crop = new Crop(block, seed, support, breakOnlyFruit);
35 53 crops.put(block, crop);
36 54 seedMaterials.add(seed);
37 55 }
@@ -64,8 +82,59 @@ final class CropRegistry {
64 82 return false;
65 83 }
66 84
85 boolean canPlantAt(Block space, Crop crop) {
86 if (space == null || !space.getType().isAir() || crop == null) return false;
87 return switch (crop.support()) {
88 case NONE -> false;
89 case FARMLAND -> space.getRelative(BlockFace.DOWN).getType() == Material.FARMLAND;
90 case SOUL_SAND -> space.getRelative(BlockFace.DOWN).getType() == Material.SOUL_SAND;
91 case JUNGLE_LOG_SIDE -> cocoaFacing(space) != null;
92 };
93 }
94
95 BlockData plantData(Block space, Crop crop) {
96 if (crop.support() == PlantSupport.JUNGLE_LOG_SIDE) {
97 BlockFace towardsLog = cocoaFacing(space);
98 Cocoa cocoa = (Cocoa) Material.COCOA.createBlockData();
99 if (towardsLog != null) cocoa.setFacing(towardsLog);
100 cocoa.setAge(0);
101 return cocoa;
102 }
103 BlockData data = crop.block().createBlockData();
104 if (data instanceof Ageable ageable) ageable.setAge(0);
105 return data;
106 }
107
108 BlockData replantData(BlockData harvested) {
109 BlockData data = harvested.clone();
110 if (data instanceof Ageable ageable) ageable.setAge(0);
111 return data;
112 }
113
114 boolean isCocoaSupport(Material material) {
115 return material == Material.JUNGLE_LOG
116 || material == Material.JUNGLE_WOOD
117 || material == Material.STRIPPED_JUNGLE_LOG
118 || material == Material.STRIPPED_JUNGLE_WOOD;
119 }
120
121 Block cocoaLog(Block cocoaBlock, BlockData harvested) {
122 if (harvested instanceof Directional directional) {
123 return cocoaBlock.getRelative(directional.getFacing());
124 }
125 BlockFace facing = cocoaFacing(cocoaBlock);
126 return facing == null ? cocoaBlock : cocoaBlock.getRelative(facing);
127 }
128
129 private BlockFace cocoaFacing(Block space) {
130 for (BlockFace face : HORIZONTAL) {
131 if (isCocoaSupport(space.getRelative(face).getType())) return face;
132 }
133 return null;
134 }
135
67 136 private boolean hasAttachedStem(Block fruit, Material attachedStem) {
68 for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
137 for (BlockFace face : HORIZONTAL) {
69 138 if (fruit.getRelative(face).getType() == attachedStem) return true;
70 139 }
71 140 return false;
@@ -4,6 +4,9 @@ import org.bukkit.Material;
4import org.bukkit.block.Block;
4import org.bukkit.block.Block;
5import org.bukkit.block.BlockFace;
5import org.bukkit.block.BlockFace;
6import org.bukkit.block.data.Ageable;
6import org.bukkit.block.data.Ageable;
7import org.bukkit.block.data.BlockData;
8import org.bukkit.block.data.Directional;
9import org.bukkit.block.data.type.Cocoa;
7
10
8import java.util.Collection;
11import java.util.Collection;
9import java.util.EnumMap;
12import java.util.EnumMap;
@@ -12,26 +15,41 @@ import java.util.Map;
12import java.util.Set;
15import java.util.Set;
13
16
14final class CropRegistry {
17final class CropRegistry {
15 record Crop(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {}
18 enum PlantSupport {
19 NONE,
20 FARMLAND,
21 SOUL_SAND,
22 JUNGLE_LOG_SIDE
23 }
24
25 record Crop(Material block, Material seed, PlantSupport support, boolean breakOnlyFruit) {
26 boolean expands() {
27 return support != PlantSupport.NONE;
28 }
29 }
30
31 private static final BlockFace[] HORIZONTAL = {
32 BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
33 };
16
34
17 private final Map<Material, Crop> crops = new EnumMap<>(Material.class);
35 private final Map<Material, Crop> crops = new EnumMap<>(Material.class);
18 private final Set<Material> seedMaterials = EnumSet.noneOf(Material.class);
36 private final Set<Material> seedMaterials = EnumSet.noneOf(Material.class);
19
37
20 CropRegistry() {
38 CropRegistry() {
21 register(Material.WHEAT, Material.WHEAT_SEEDS, true, false);
39 register(Material.WHEAT, Material.WHEAT_SEEDS, PlantSupport.FARMLAND, false);
22 register(Material.CARROTS, Material.CARROT, true, false);
40 register(Material.CARROTS, Material.CARROT, PlantSupport.FARMLAND, false);
23 register(Material.POTATOES, Material.POTATO, true, false);
41 register(Material.POTATOES, Material.POTATO, PlantSupport.FARMLAND, false);
24 register(Material.BEETROOTS, Material.BEETROOT_SEEDS, true, false);
42 register(Material.BEETROOTS, Material.BEETROOT_SEEDS, PlantSupport.FARMLAND, false);
25 register(Material.NETHER_WART, Material.NETHER_WART, false, false);
43 register(Material.NETHER_WART, Material.NETHER_WART, PlantSupport.SOUL_SAND, false);
26 register(Material.COCOA, Material.COCOA_BEANS, false, false);
44 register(Material.COCOA, Material.COCOA_BEANS, PlantSupport.JUNGLE_LOG_SIDE, false);
27 register(Material.SWEET_BERRY_BUSH, Material.SWEET_BERRIES, false, false);
45 register(Material.SWEET_BERRY_BUSH, Material.SWEET_BERRIES, PlantSupport.NONE, false);
28 register(Material.TORCHFLOWER_CROP, Material.TORCHFLOWER_SEEDS, true, false);
46 register(Material.TORCHFLOWER_CROP, Material.TORCHFLOWER_SEEDS, PlantSupport.FARMLAND, false);
29 register(Material.MELON, Material.MELON_SEEDS, false, true);
47 register(Material.MELON, Material.MELON_SEEDS, PlantSupport.NONE, true);
30 register(Material.PUMPKIN, Material.PUMPKIN_SEEDS, false, true);
48 register(Material.PUMPKIN, Material.PUMPKIN_SEEDS, PlantSupport.NONE, true);
31 }
49 }
32
50
33 private void register(Material block, Material seed, boolean farmland, boolean breakOnlyFruit) {
51 private void register(Material block, Material seed, PlantSupport support, boolean breakOnlyFruit) {
34 Crop crop = new Crop(block, seed, farmland, breakOnlyFruit);
52 Crop crop = new Crop(block, seed, support, breakOnlyFruit);
35 crops.put(block, crop);
53 crops.put(block, crop);
36 seedMaterials.add(seed);
54 seedMaterials.add(seed);
37 }
55 }
@@ -64,8 +82,59 @@ final class CropRegistry {
64 return false;
82 return false;
65 }
83 }
66
84
85 boolean canPlantAt(Block space, Crop crop) {
86 if (space == null || !space.getType().isAir() || crop == null) return false;
87 return switch (crop.support()) {
88 case NONE -> false;
89 case FARMLAND -> space.getRelative(BlockFace.DOWN).getType() == Material.FARMLAND;
90 case SOUL_SAND -> space.getRelative(BlockFace.DOWN).getType() == Material.SOUL_SAND;
91 case JUNGLE_LOG_SIDE -> cocoaFacing(space) != null;
92 };
93 }
94
95 BlockData plantData(Block space, Crop crop) {
96 if (crop.support() == PlantSupport.JUNGLE_LOG_SIDE) {
97 BlockFace towardsLog = cocoaFacing(space);
98 Cocoa cocoa = (Cocoa) Material.COCOA.createBlockData();
99 if (towardsLog != null) cocoa.setFacing(towardsLog);
100 cocoa.setAge(0);
101 return cocoa;
102 }
103 BlockData data = crop.block().createBlockData();
104 if (data instanceof Ageable ageable) ageable.setAge(0);
105 return data;
106 }
107
108 BlockData replantData(BlockData harvested) {
109 BlockData data = harvested.clone();
110 if (data instanceof Ageable ageable) ageable.setAge(0);
111 return data;
112 }
113
114 boolean isCocoaSupport(Material material) {
115 return material == Material.JUNGLE_LOG
116 || material == Material.JUNGLE_WOOD
117 || material == Material.STRIPPED_JUNGLE_LOG
118 || material == Material.STRIPPED_JUNGLE_WOOD;
119 }
120
121 Block cocoaLog(Block cocoaBlock, BlockData harvested) {
122 if (harvested instanceof Directional directional) {
123 return cocoaBlock.getRelative(directional.getFacing());
124 }
125 BlockFace facing = cocoaFacing(cocoaBlock);
126 return facing == null ? cocoaBlock : cocoaBlock.getRelative(facing);
127 }
128
129 private BlockFace cocoaFacing(Block space) {
130 for (BlockFace face : HORIZONTAL) {
131 if (isCocoaSupport(space.getRelative(face).getType())) return face;
132 }
133 return null;
134 }
135
67 private boolean hasAttachedStem(Block fruit, Material attachedStem) {
136 private boolean hasAttachedStem(Block fruit, Material attachedStem) {
68 for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
137 for (BlockFace face : HORIZONTAL) {
69 if (fruit.getRelative(face).getType() == attachedStem) return true;
138 if (fruit.getRelative(face).getType() == attachedStem) return true;
70 }
139 }
71 return false;
140 return false;
src/main/java/nl/timfalken/copperfarmer/FarmerManager.java +278 −70
@@ -8,13 +8,16 @@ import org.bukkit.Location;
8 8 import org.bukkit.Material;
9 9 import org.bukkit.Sound;
10 10 import org.bukkit.SoundCategory;
11 import org.bukkit.Tag;
11 12 import org.bukkit.World;
12 13 import org.bukkit.block.Block;
13 14 import org.bukkit.block.BlockFace;
14 15 import org.bukkit.block.BlockState;
15 16 import org.bukkit.block.Lidded;
16 import org.bukkit.block.data.Ageable;
17 17 import org.bukkit.block.data.BlockData;
18 import org.bukkit.block.data.Openable;
19 import org.bukkit.block.data.type.Door;
20 import org.bukkit.block.data.type.Gate;
18 21 import org.bukkit.entity.CopperGolem;
19 22 import org.bukkit.entity.Entity;
20 23 import org.bukkit.entity.Player;
@@ -112,7 +115,11 @@ final class FarmerManager {
112 115
113 116 void unregister(Entity entity) {
114 117 Brain brain = brains.remove(entity.getUniqueId());
115 if (brain != null) brain.closeOpenedLid();
118 if (brain != null) {
119 brain.closeOpenedLid();
120 brain.closeAllDoors();
121 brain.clearHarvestCrack();
122 }
116 123 }
117 124
118 125 boolean isFarmer(Entity entity) {
@@ -128,7 +135,7 @@ final class FarmerManager {
128 135 golem.setCanPickupItems(false);
129 136 golem.getPathfinder().setCanFloat(true);
130 137 golem.getPathfinder().setCanPassDoors(true);
131 golem.getPathfinder().setCanOpenDoors(false);
138 golem.getPathfinder().setCanOpenDoors(true);
132 139 golem.setGolemState(CopperGolem.State.IDLE);
133 140 if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());
134 141 equipHand(golem, itemCodec.readTool(golem), false);
@@ -205,9 +212,10 @@ final class FarmerManager {
205 212 private BlockRef chest;
206 213 private BlockRef cropTarget;
207 214 private CropRegistry.Crop activeCrop;
208 private final Deque<BlockRef> plantQueue = new ArrayDeque<>();
209 private final Map<BlockRef, Long> unreachableCrops = new HashMap<>();
215 private final Deque<PlantJob> plantQueue = new ArrayDeque<>();
216 private final Set<BlockRef> unreachableCrops = new HashSet<>();
210 217 private final Map<BlockRef, Long> unreachableChests = new HashMap<>();
218 private final Map<BlockRef, Long> openedDoors = new HashMap<>();
211 219
212 220 private Location navigationTarget;
213 221 private Location lastProgressLocation;
@@ -219,6 +227,9 @@ final class FarmerManager {
219 227 private BlockRef openedLid;
220 228 private long closeLidAt;
221 229 private ItemStack carriedProduce;
230 private long harvestStartTick;
231 private long harvestReadyTick;
232 private int harvestBreakTicks;
222 233
223 234 Brain(CopperGolem golem) {
224 235 this.golem = golem;
@@ -238,6 +249,7 @@ final class FarmerManager {
238 249 golem.setOxidizing(CopperGolem.Oxidizing.waxed());
239 250 }
240 251 cleanupCooldowns();
252 tickDoors();
241 253
242 254 if (!isChestValid(chest)) {
243 255 clearChest();
@@ -246,6 +258,7 @@ final class FarmerManager {
246 258 switch (state) {
247 259 case IDLE -> tickIdle();
248 260 case MOVING_TO_CROP -> tickMovingToCrop();
261 case WAITING_TO_HARVEST -> tickWaitingToHarvest();
249 262 case MOVING_TO_PLANT -> tickMovingToPlant();
250 263 case WAITING_TO_PLANT -> tickWaitingToPlant();
251 264 case MOVING_TO_CHEST -> tickMovingToChest();
@@ -267,10 +280,13 @@ final class FarmerManager {
267 280 }
268 281
269 282 if (clock < nextScanTick) return;
270 nextScanTick = clock + scanInterval;
271 283
272 284 Block target = findMatureCrop();
273 if (target == null) return;
285 if (target == null) {
286 unreachableCrops.clear();
287 nextScanTick = clock + scanInterval;
288 return;
289 }
274 290
275 291 CropRegistry.Crop crop = cropRegistry.get(target.getType());
276 292 if (crop == null) {
@@ -284,7 +300,6 @@ final class FarmerManager {
284 300 markCropUnreachable(cropTarget);
285 301 cropTarget = null;
286 302 activeCrop = null;
287 state = State.IDLE;
288 303 }
289 304 }
290 305
@@ -299,7 +314,7 @@ final class FarmerManager {
299 314
300 315 if (reachedNavigationTarget() && near(cropBlock)) {
301 316 stopNavigation();
302 harvest(cropBlock, activeCrop);
317 beginHarvest(cropBlock);
303 318 return;
304 319 }
305 320
@@ -311,6 +326,38 @@ final class FarmerManager {
311 326 }
312 327 }
313 328
329 private void beginHarvest(Block cropBlock) {
330 lookAt(cropBlock);
331 playInteractAnimation();
332 harvestBreakTicks = (int) Math.max(1L, vanillaBreakTicks(cropBlock, tool));
333 harvestStartTick = clock;
334 harvestReadyTick = clock + harvestBreakTicks;
335 animationHoldUntil = harvestReadyTick + 10;
336 state = State.WAITING_TO_HARVEST;
337 sendHarvestCrack(cropBlock, 0.1f);
338 }
339
340 private void tickWaitingToHarvest() {
341 Block cropBlock = block(cropTarget);
342 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
343 || !cropRegistry.isReady(cropBlock)) {
344 clearHarvestCrack();
345 resetCropTask();
346 return;
347 }
348
349 lookAt(cropBlock);
350 playInteractAnimation();
351 float progress = harvestBreakTicks <= 1
352 ? 1.0f
353 : Math.min(1.0f, (clock - harvestStartTick + 1f) / harvestBreakTicks);
354 sendHarvestCrack(cropBlock, progress);
355
356 if (clock < harvestReadyTick) return;
357 clearHarvestCrack();
358 harvest(cropBlock, activeCrop);
359 }
360
314 361 private void tickMovingToPlant() {
315 362 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
316 363 plantQueue.clear();
@@ -318,19 +365,16 @@ final class FarmerManager {
318 365 return;
319 366 }
320 367
321 BlockRef targetRef = plantQueue.peekFirst();
322 Block target = block(targetRef);
323 if (target == null || !canPlantOn(target, activeCrop)) {
324 plantQueue.pollFirst();
368 PlantJob job = plantQueue.peekFirst();
369 Block target = job == null ? null : block(job.space());
370 if (job == null || target == null || !jobStillValid(job)) {
371 if (!plantQueue.isEmpty()) plantQueue.pollFirst();
325 372 advancePlantQueue();
326 373 return;
327 374 }
328 375
329 376 if (reachedNavigationTarget() && near(target)) {
330 stopNavigation();
331 lookAt(target);
332 plantReadyTick = clock + plantWindupTicks;
333 state = State.WAITING_TO_PLANT;
377 beginPlantWait(target);
334 378 return;
335 379 }
336 380
@@ -347,20 +391,21 @@ final class FarmerManager {
347 391 return;
348 392 }
349 393
350 BlockRef targetRef = plantQueue.peekFirst();
351 Block target = block(targetRef);
352 if (target == null || !canPlantOn(target, activeCrop)) {
353 plantQueue.pollFirst();
394 PlantJob job = plantQueue.peekFirst();
395 Block target = job == null ? null : block(job.space());
396 if (job == null || target == null || !jobStillValid(job)) {
397 if (!plantQueue.isEmpty()) plantQueue.pollFirst();
354 398 advancePlantQueue();
355 399 return;
356 400 }
357 401
358 402 lookAt(target);
403 playInteractAnimation();
359 404 if (clock < plantReadyTick) return;
360 405
361 406 if (cargo.remove(activeCrop.seed(), 1)) {
362 playWorkAnimation(target);
363 target.setType(activeCrop.block(), false);
407 playInteractAnimation();
408 target.setBlockData(job.data(), false);
364 409 playPlantSound(target);
365 410 }
366 411 plantQueue.pollFirst();
@@ -409,7 +454,6 @@ final class FarmerManager {
409 454 }
410 455
411 456 private void harvest(Block cropBlock, CropRegistry.Crop crop) {
412 playWorkAnimation(cropBlock);
413 457 playHarvestEffects(cropBlock);
414 458 BlockData oldData = cropBlock.getBlockData().clone();
415 459 List<ItemStack> calculatedDrops = new ArrayList<>(cropBlock.getDrops(tool.clone(), golem));
@@ -421,24 +465,19 @@ final class FarmerManager {
421 465 cropBlock.getWorld().dropItemNaturally(cropBlock.getLocation().add(0.5, 0.5, 0.5), item);
422 466 }
423 467
424 if (!crop.breakOnlyFruit()) {
425 ensureSeed(crop.seed());
426 if (cargo.remove(crop.seed(), 1)) {
427 if (oldData instanceof Ageable ageable) ageable.setAge(0);
428 cropBlock.setBlockData(oldData, false);
429 playPlantSound(cropBlock);
430 }
431 }
432
433 468 cropTarget = null;
469 if (!crop.breakOnlyFruit()) ensureSeed(crop.seed());
434 470
435 if (!crop.breakOnlyFruit() && crop.farmland() && cargo.count(crop.seed()) > 0) {
436 buildPlantQueue(cropBlock, crop);
437 if (!plantQueue.isEmpty()) {
438 activeCrop = crop;
439 advancePlantQueue();
440 return;
441 }
471 plantQueue.clear();
472 if (!crop.breakOnlyFruit() && cargo.count(crop.seed()) > 0) {
473 plantQueue.addLast(new PlantJob(BlockRef.of(cropBlock), cropRegistry.replantData(oldData)));
474 if (crop.expands()) buildExtraPlantQueue(cropBlock, oldData, crop);
475 }
476
477 if (!plantQueue.isEmpty()) {
478 activeCrop = crop;
479 advancePlantQueue();
480 return;
442 481 }
443 482
444 483 activeCrop = null;
@@ -462,52 +501,108 @@ final class FarmerManager {
462 501 return false;
463 502 }
464 503
465 private void buildPlantQueue(Block harvestedCropBlock, CropRegistry.Crop crop) {
466 plantQueue.clear();
467 Block startFarmland = harvestedCropBlock.getRelative(BlockFace.DOWN);
468 if (startFarmland.getType() != Material.FARMLAND) return;
504 private void buildExtraPlantQueue(Block harvestedCropBlock, BlockData harvestedData, CropRegistry.Crop crop) {
505 switch (crop.support()) {
506 case FARMLAND -> queueConnectedBeds(harvestedCropBlock.getRelative(BlockFace.DOWN), Material.FARMLAND, crop);
507 case SOUL_SAND -> queueConnectedBeds(harvestedCropBlock.getRelative(BlockFace.DOWN), Material.SOUL_SAND, crop);
508 case JUNGLE_LOG_SIDE -> queueCocoaSides(harvestedCropBlock, harvestedData, crop);
509 case NONE -> {
510 }
511 }
512 }
513
514 private void queueConnectedBeds(Block startBed, Material bedType, CropRegistry.Crop crop) {
515 if (startBed.getType() != bedType) return;
469 516
470 517 Set<BlockRef> visited = new HashSet<>();
471 518 Deque<Block> search = new ArrayDeque<>();
472 search.add(startFarmland);
473 visited.add(BlockRef.of(startFarmland));
519 search.add(startBed);
520 visited.add(BlockRef.of(startBed));
474 521
475 522 while (!search.isEmpty()) {
476 Block farmland = search.pollFirst();
477 Block above = farmland.getRelative(BlockFace.UP);
478 if (above.getType().isAir() && withinCropRadius(above) && canPlantOn(above, crop)) {
479 plantQueue.add(BlockRef.of(above));
523 Block bed = search.pollFirst();
524 Block above = bed.getRelative(BlockFace.UP);
525 if (withinCropRadius(above) && cropRegistry.canPlantAt(above, crop)) {
526 queuePlant(above, cropRegistry.plantData(above, crop));
480 527 }
481 528
482 529 for (BlockFace face : HORIZONTAL) {
483 Block next = farmland.getRelative(face);
484 if (next.getType() != Material.FARMLAND || !withinCropRadius(next)) continue;
530 Block next = bed.getRelative(face);
531 if (next.getType() != bedType || !withinCropRadius(next)) continue;
485 532 BlockRef ref = BlockRef.of(next);
486 533 if (visited.add(ref)) search.addLast(next);
487 534 }
488 535 }
489 536 }
490 537
538 private void queueCocoaSides(Block harvestedCocoa, BlockData harvestedData, CropRegistry.Crop crop) {
539 Block startLog = cropRegistry.cocoaLog(harvestedCocoa, harvestedData);
540 if (!cropRegistry.isCocoaSupport(startLog.getType())) return;
541
542 Set<BlockRef> visited = new HashSet<>();
543 Deque<Block> search = new ArrayDeque<>();
544 search.add(startLog);
545 visited.add(BlockRef.of(startLog));
546
547 while (!search.isEmpty()) {
548 Block log = search.pollFirst();
549 for (BlockFace face : HORIZONTAL) {
550 Block side = log.getRelative(face);
551 if (withinCropRadius(side) && cropRegistry.canPlantAt(side, crop)) {
552 queuePlant(side, cropRegistry.plantData(side, crop));
553 }
554 if (!cropRegistry.isCocoaSupport(side.getType()) || !withinCropRadius(side)) continue;
555 BlockRef ref = BlockRef.of(side);
556 if (visited.add(ref)) search.addLast(side);
557 }
558 }
559 }
560
561 private void queuePlant(Block space, BlockData data) {
562 BlockRef ref = BlockRef.of(space);
563 for (PlantJob existing : plantQueue) {
564 if (existing.space().equals(ref)) return;
565 }
566 plantQueue.addLast(new PlantJob(ref, data));
567 }
568
491 569 private void advancePlantQueue() {
492 570 while (!plantQueue.isEmpty()) {
493 571 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
494 572 plantQueue.clear();
495 573 break;
496 574 }
497 Block target = block(plantQueue.peekFirst());
498 if (target == null || !canPlantOn(target, activeCrop)) {
575 PlantJob job = plantQueue.peekFirst();
576 Block target = job == null ? null : block(job.space());
577 if (job == null || target == null || !jobStillValid(job)) {
499 578 plantQueue.pollFirst();
500 579 continue;
501 580 }
581 if (near(target)) {
582 beginPlantWait(target);
583 return;
584 }
502 585 if (beginPathToBlock(target, State.MOVING_TO_PLANT)) return;
503 586 plantQueue.pollFirst();
504 587 }
505 588 beginReturnToChest();
506 589 }
507 590
508 private boolean canPlantOn(Block cropSpace, CropRegistry.Crop crop) {
509 if (!crop.farmland()) return false;
510 return cropSpace.getType().isAir() && cropSpace.getRelative(BlockFace.DOWN).getType() == Material.FARMLAND;
591 private void beginPlantWait(Block target) {
592 stopNavigation();
593 lookAt(target);
594 playInteractAnimation();
595 plantReadyTick = clock + plantWindupTicks;
596 animationHoldUntil = plantReadyTick + 5;
597 state = State.WAITING_TO_PLANT;
598 }
599
600 private boolean jobStillValid(PlantJob job) {
601 Block space = block(job.space());
602 if (space == null || activeCrop == null) return false;
603 if (!space.getType().isAir()) return false;
604 if (activeCrop.support() == CropRegistry.PlantSupport.NONE) return true;
605 return cropRegistry.canPlantAt(space, activeCrop);
511 606 }
512 607
513 608 private void beginReturnToChest() {
@@ -589,8 +684,7 @@ final class FarmerManager {
589 684 Block block = world.getBlockAt(x, y, z);
590 685 if (!cropRegistry.isReady(block)) continue;
591 686 BlockRef ref = BlockRef.of(block);
592 Long blockedUntil = unreachableCrops.get(ref);
593 if (blockedUntil != null && blockedUntil > clock) continue;
687 if (unreachableCrops.contains(ref)) continue;
594 688 candidates.add(block);
595 689 }
596 690 }
@@ -678,14 +772,21 @@ final class FarmerManager {
678 772 if (target == null) return false;
679 773
680 774 List<Block> positions = new ArrayList<>();
681 for (BlockFace face : HORIZONTAL) {
682 Block feet = target.getRelative(face);
683 if (isStandable(feet)) positions.add(feet);
775 Set<BlockRef> seen = new HashSet<>();
776 for (int dy = 0; dy >= -2; dy--) {
777 for (BlockFace face : HORIZONTAL) {
778 Block feet = target.getRelative(face.getModX(), dy, face.getModZ());
779 if (seen.add(BlockRef.of(feet)) && isStandable(feet)) positions.add(feet);
780 }
781 if (dy < 0) {
782 Block below = target.getRelative(0, dy, 0);
783 if (seen.add(BlockRef.of(below)) && isStandable(below)) positions.add(below);
784 }
684 785 }
685 786 positions.sort(Comparator.comparingDouble(block -> block.getLocation().add(0.5, 0, 0.5)
686 787 .distanceSquared(golem.getLocation())));
687 788
688 // Try each valid side once. After a side has produced a native path,
789 // Try each valid stand position once. After a side has produced a native path,
689 790 // Minecraft owns that path; we do not recalculate it every brain tick.
690 791 for (Block feet : positions) {
691 792 if (beginPath(feet.getLocation().add(0.5, 0.0, 0.5), newState)) return true;
@@ -708,11 +809,14 @@ final class FarmerManager {
708 809 return now.distanceSquared(navigationTarget) <= 1.25 * 1.25;
709 810 }
710 811
812 private void playInteractAnimation() {
813 golem.setGolemState(CopperGolem.State.GETTING_ITEM);
814 animationHoldUntil = Math.max(animationHoldUntil, clock + 20);
815 }
816
711 817 private void playWorkAnimation(Block target) {
712 818 lookAt(target);
713 // Copper golems have no melee-attack clip; the arm swing is the same
714 // packet vanilla uses for attacking / using a held tool.
715 golem.swingMainHand();
819 playInteractAnimation();
716 820 }
717 821
718 822 private ItemStack heldAppearance() {
@@ -800,7 +904,7 @@ final class FarmerManager {
800 904 private boolean isStandable(Block feet) {
801 905 if (!feet.isPassable() || !feet.getRelative(BlockFace.UP).isPassable()) return false;
802 906 Material below = feet.getRelative(BlockFace.DOWN).getType();
803 return below.isSolid() || below == Material.FARMLAND;
907 return below.isSolid() || below == Material.FARMLAND || below == Material.SOUL_SAND;
804 908 }
805 909
806 910 private boolean near(Block block) {
@@ -819,11 +923,12 @@ final class FarmerManager {
819 923
820 924 private void resetCropTask() {
821 925 stopNavigation();
926 clearHarvestCrack();
822 927 cropTarget = null;
823 928 activeCrop = null;
824 929 plantQueue.clear();
825 930 state = State.IDLE;
826 nextScanTick = clock + scanInterval;
931 nextScanTick = clock;
827 932 }
828 933
829 934 private void stopNavigation() {
@@ -834,7 +939,7 @@ final class FarmerManager {
834 939 }
835 940
836 941 private void markCropUnreachable(BlockRef ref) {
837 if (ref != null) unreachableCrops.put(ref, clock + unreachableCooldown);
942 if (ref != null) unreachableCrops.add(ref);
838 943 }
839 944
840 945 private void markChestUnreachable(BlockRef ref) {
@@ -842,7 +947,6 @@ final class FarmerManager {
842 947 }
843 948
844 949 private void cleanupCooldowns() {
845 unreachableCrops.entrySet().removeIf(entry -> entry.getValue() <= clock);
846 950 unreachableChests.entrySet().removeIf(entry -> entry.getValue() <= clock);
847 951 }
848 952
@@ -859,11 +963,115 @@ final class FarmerManager {
859 963 Block block = block(ref);
860 964 return isCopperChest(block);
861 965 }
966
967 private void tickDoors() {
968 Location loc = golem.getLocation();
969 tryOpenDoor(loc.getBlock());
970 tryOpenDoor(loc.getBlock().getRelative(BlockFace.UP));
971
972 Location ahead = loc.clone();
973 if (navigationTarget != null && navigationTarget.getWorld() == loc.getWorld()) {
974 var delta = navigationTarget.toVector().subtract(loc.toVector());
975 if (delta.lengthSquared() > 0.0001) {
976 delta.normalize().multiply(0.8);
977 ahead.add(delta);
978 }
979 } else {
980 ahead.add(loc.getDirection().multiply(0.8));
981 }
982 tryOpenDoor(ahead.getBlock());
983 tryOpenDoor(ahead.getBlock().getRelative(BlockFace.UP));
984
985 for (var iterator = openedDoors.entrySet().iterator(); iterator.hasNext(); ) {
986 var entry = iterator.next();
987 Block doorBlock = block(entry.getKey());
988 if (doorBlock != null && golem.getLocation().distanceSquared(
989 doorBlock.getLocation().add(0.5, 0.5, 0.5)) <= 4.0) {
990 entry.setValue(clock + 30);
991 continue;
992 }
993 if (entry.getValue() > clock) continue;
994 closeDoor(doorBlock);
995 iterator.remove();
996 }
997 }
998
999 private void tryOpenDoor(Block block) {
1000 if (block == null || !isWoodenPassage(block.getType())) return;
1001 BlockData data = block.getBlockData();
1002 if (!(data instanceof Openable openable) || openable.isOpen()) return;
1003 if (!(data instanceof Door) && !(data instanceof Gate)) return;
1004 openable.setOpen(true);
1005 block.setBlockData(openable, true);
1006 openedDoors.put(BlockRef.of(block), clock + 40);
1007 Sound sound = data instanceof Gate ? Sound.BLOCK_FENCE_GATE_OPEN : Sound.BLOCK_WOODEN_DOOR_OPEN;
1008 block.getWorld().playSound(block.getLocation().add(0.5, 0.5, 0.5), sound, SoundCategory.BLOCKS, 1.0f, 1.0f);
1009 if (data instanceof Door) {
1010 for (BlockFace face : HORIZONTAL) {
1011 Block neighbour = block.getRelative(face);
1012 if (!isWoodenPassage(neighbour.getType())) continue;
1013 BlockData neighbourData = neighbour.getBlockData();
1014 if (!(neighbourData instanceof Door neighbourDoor) || neighbourDoor.isOpen()) continue;
1015 neighbourDoor.setOpen(true);
1016 neighbour.setBlockData(neighbourDoor, true);
1017 openedDoors.put(BlockRef.of(neighbour), clock + 40);
1018 }
1019 }
1020 }
1021
1022 private void closeDoor(Block block) {
1023 if (block == null || !isWoodenPassage(block.getType())) return;
1024 BlockData data = block.getBlockData();
1025 if (!(data instanceof Openable openable) || !openable.isOpen()) return;
1026 openable.setOpen(false);
1027 block.setBlockData(openable, true);
1028 Sound sound = data instanceof Gate ? Sound.BLOCK_FENCE_GATE_CLOSE : Sound.BLOCK_WOODEN_DOOR_CLOSE;
1029 block.getWorld().playSound(block.getLocation().add(0.5, 0.5, 0.5), sound, SoundCategory.BLOCKS, 1.0f, 1.0f);
1030 }
1031
1032 private void closeAllDoors() {
1033 for (BlockRef ref : openedDoors.keySet()) closeDoor(block(ref));
1034 openedDoors.clear();
1035 }
1036
1037 private boolean isWoodenPassage(Material type) {
1038 return Tag.WOODEN_DOORS.isTagged(type) || Tag.FENCE_GATES.isTagged(type);
1039 }
1040
1041 private long vanillaBreakTicks(Block block, ItemStack tool) {
1042 float hardness = block.getType().getHardness();
1043 if (hardness < 0f) return 1L;
1044 if (hardness == 0f) return 1L;
1045 BlockData data = block.getBlockData();
1046 float speed = Math.max(0.001f, data.getDestroySpeed(tool, true));
1047 int factor = data.requiresCorrectToolForDrops() && !data.isPreferredTool(tool) ? 100 : 30;
1048 return Math.max(1L, (long) Math.ceil(hardness * factor / speed));
1049 }
1050
1051 private void sendHarvestCrack(Block cropBlock, float progress) {
1052 Location location = cropBlock.getLocation();
1053 float clamped = Math.max(0.0f, Math.min(1.0f, progress));
1054 for (Player player : golem.getTrackedBy()) {
1055 player.sendBlockDamage(location, clamped, golem);
1056 }
1057 }
1058
1059 private void clearHarvestCrack() {
1060 Block cropBlock = block(cropTarget);
1061 if (cropBlock == null) return;
1062 Location location = cropBlock.getLocation();
1063 for (Player player : golem.getTrackedBy()) {
1064 player.sendBlockDamage(location, 0.0f, golem);
1065 }
1066 }
862 1067 }
863 1068
1069 private record PlantJob(BlockRef space, BlockData data) {}
1070
864 1071 private enum State {
865 1072 IDLE,
866 1073 MOVING_TO_CROP,
1074 WAITING_TO_HARVEST,
867 1075 MOVING_TO_PLANT,
868 1076 WAITING_TO_PLANT,
869 1077 MOVING_TO_CHEST,
@@ -8,13 +8,16 @@ import org.bukkit.Location;
8import org.bukkit.Material;
8import org.bukkit.Material;
9import org.bukkit.Sound;
9import org.bukkit.Sound;
10import org.bukkit.SoundCategory;
10import org.bukkit.SoundCategory;
11import org.bukkit.Tag;
11import org.bukkit.World;
12import org.bukkit.World;
12import org.bukkit.block.Block;
13import org.bukkit.block.Block;
13import org.bukkit.block.BlockFace;
14import org.bukkit.block.BlockFace;
14import org.bukkit.block.BlockState;
15import org.bukkit.block.BlockState;
15import org.bukkit.block.Lidded;
16import org.bukkit.block.Lidded;
16import org.bukkit.block.data.Ageable;
17import org.bukkit.block.data.BlockData;
17import org.bukkit.block.data.BlockData;
18import org.bukkit.block.data.Openable;
19import org.bukkit.block.data.type.Door;
20import org.bukkit.block.data.type.Gate;
18import org.bukkit.entity.CopperGolem;
21import org.bukkit.entity.CopperGolem;
19import org.bukkit.entity.Entity;
22import org.bukkit.entity.Entity;
20import org.bukkit.entity.Player;
23import org.bukkit.entity.Player;
@@ -112,7 +115,11 @@ final class FarmerManager {
112
115
113 void unregister(Entity entity) {
116 void unregister(Entity entity) {
114 Brain brain = brains.remove(entity.getUniqueId());
117 Brain brain = brains.remove(entity.getUniqueId());
115 if (brain != null) brain.closeOpenedLid();
118 if (brain != null) {
119 brain.closeOpenedLid();
120 brain.closeAllDoors();
121 brain.clearHarvestCrack();
122 }
116 }
123 }
117
124
118 boolean isFarmer(Entity entity) {
125 boolean isFarmer(Entity entity) {
@@ -128,7 +135,7 @@ final class FarmerManager {
128 golem.setCanPickupItems(false);
135 golem.setCanPickupItems(false);
129 golem.getPathfinder().setCanFloat(true);
136 golem.getPathfinder().setCanFloat(true);
130 golem.getPathfinder().setCanPassDoors(true);
137 golem.getPathfinder().setCanPassDoors(true);
131 golem.getPathfinder().setCanOpenDoors(false);
138 golem.getPathfinder().setCanOpenDoors(true);
132 golem.setGolemState(CopperGolem.State.IDLE);
139 golem.setGolemState(CopperGolem.State.IDLE);
133 if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());
140 if (preventOxidation) golem.setOxidizing(CopperGolem.Oxidizing.waxed());
134 equipHand(golem, itemCodec.readTool(golem), false);
141 equipHand(golem, itemCodec.readTool(golem), false);
@@ -205,9 +212,10 @@ final class FarmerManager {
205 private BlockRef chest;
212 private BlockRef chest;
206 private BlockRef cropTarget;
213 private BlockRef cropTarget;
207 private CropRegistry.Crop activeCrop;
214 private CropRegistry.Crop activeCrop;
208 private final Deque<BlockRef> plantQueue = new ArrayDeque<>();
215 private final Deque<PlantJob> plantQueue = new ArrayDeque<>();
209 private final Map<BlockRef, Long> unreachableCrops = new HashMap<>();
216 private final Set<BlockRef> unreachableCrops = new HashSet<>();
210 private final Map<BlockRef, Long> unreachableChests = new HashMap<>();
217 private final Map<BlockRef, Long> unreachableChests = new HashMap<>();
218 private final Map<BlockRef, Long> openedDoors = new HashMap<>();
211
219
212 private Location navigationTarget;
220 private Location navigationTarget;
213 private Location lastProgressLocation;
221 private Location lastProgressLocation;
@@ -219,6 +227,9 @@ final class FarmerManager {
219 private BlockRef openedLid;
227 private BlockRef openedLid;
220 private long closeLidAt;
228 private long closeLidAt;
221 private ItemStack carriedProduce;
229 private ItemStack carriedProduce;
230 private long harvestStartTick;
231 private long harvestReadyTick;
232 private int harvestBreakTicks;
222
233
223 Brain(CopperGolem golem) {
234 Brain(CopperGolem golem) {
224 this.golem = golem;
235 this.golem = golem;
@@ -238,6 +249,7 @@ final class FarmerManager {
238 golem.setOxidizing(CopperGolem.Oxidizing.waxed());
249 golem.setOxidizing(CopperGolem.Oxidizing.waxed());
239 }
250 }
240 cleanupCooldowns();
251 cleanupCooldowns();
252 tickDoors();
241
253
242 if (!isChestValid(chest)) {
254 if (!isChestValid(chest)) {
243 clearChest();
255 clearChest();
@@ -246,6 +258,7 @@ final class FarmerManager {
246 switch (state) {
258 switch (state) {
247 case IDLE -> tickIdle();
259 case IDLE -> tickIdle();
248 case MOVING_TO_CROP -> tickMovingToCrop();
260 case MOVING_TO_CROP -> tickMovingToCrop();
261 case WAITING_TO_HARVEST -> tickWaitingToHarvest();
249 case MOVING_TO_PLANT -> tickMovingToPlant();
262 case MOVING_TO_PLANT -> tickMovingToPlant();
250 case WAITING_TO_PLANT -> tickWaitingToPlant();
263 case WAITING_TO_PLANT -> tickWaitingToPlant();
251 case MOVING_TO_CHEST -> tickMovingToChest();
264 case MOVING_TO_CHEST -> tickMovingToChest();
@@ -267,10 +280,13 @@ final class FarmerManager {
267 }
280 }
268
281
269 if (clock < nextScanTick) return;
282 if (clock < nextScanTick) return;
270 nextScanTick = clock + scanInterval;
271
283
272 Block target = findMatureCrop();
284 Block target = findMatureCrop();
273 if (target == null) return;
285 if (target == null) {
286 unreachableCrops.clear();
287 nextScanTick = clock + scanInterval;
288 return;
289 }
274
290
275 CropRegistry.Crop crop = cropRegistry.get(target.getType());
291 CropRegistry.Crop crop = cropRegistry.get(target.getType());
276 if (crop == null) {
292 if (crop == null) {
@@ -284,7 +300,6 @@ final class FarmerManager {
284 markCropUnreachable(cropTarget);
300 markCropUnreachable(cropTarget);
285 cropTarget = null;
301 cropTarget = null;
286 activeCrop = null;
302 activeCrop = null;
287 state = State.IDLE;
288 }
303 }
289 }
304 }
290
305
@@ -299,7 +314,7 @@ final class FarmerManager {
299
314
300 if (reachedNavigationTarget() && near(cropBlock)) {
315 if (reachedNavigationTarget() && near(cropBlock)) {
301 stopNavigation();
316 stopNavigation();
302 harvest(cropBlock, activeCrop);
317 beginHarvest(cropBlock);
303 return;
318 return;
304 }
319 }
305
320
@@ -311,6 +326,38 @@ final class FarmerManager {
311 }
326 }
312 }
327 }
313
328
329 private void beginHarvest(Block cropBlock) {
330 lookAt(cropBlock);
331 playInteractAnimation();
332 harvestBreakTicks = (int) Math.max(1L, vanillaBreakTicks(cropBlock, tool));
333 harvestStartTick = clock;
334 harvestReadyTick = clock + harvestBreakTicks;
335 animationHoldUntil = harvestReadyTick + 10;
336 state = State.WAITING_TO_HARVEST;
337 sendHarvestCrack(cropBlock, 0.1f);
338 }
339
340 private void tickWaitingToHarvest() {
341 Block cropBlock = block(cropTarget);
342 if (cropBlock == null || activeCrop == null || cropBlock.getType() != activeCrop.block()
343 || !cropRegistry.isReady(cropBlock)) {
344 clearHarvestCrack();
345 resetCropTask();
346 return;
347 }
348
349 lookAt(cropBlock);
350 playInteractAnimation();
351 float progress = harvestBreakTicks <= 1
352 ? 1.0f
353 : Math.min(1.0f, (clock - harvestStartTick + 1f) / harvestBreakTicks);
354 sendHarvestCrack(cropBlock, progress);
355
356 if (clock < harvestReadyTick) return;
357 clearHarvestCrack();
358 harvest(cropBlock, activeCrop);
359 }
360
314 private void tickMovingToPlant() {
361 private void tickMovingToPlant() {
315 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
362 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
316 plantQueue.clear();
363 plantQueue.clear();
@@ -318,19 +365,16 @@ final class FarmerManager {
318 return;
365 return;
319 }
366 }
320
367
321 BlockRef targetRef = plantQueue.peekFirst();
368 PlantJob job = plantQueue.peekFirst();
322 Block target = block(targetRef);
369 Block target = job == null ? null : block(job.space());
323 if (target == null || !canPlantOn(target, activeCrop)) {
370 if (job == null || target == null || !jobStillValid(job)) {
324 plantQueue.pollFirst();
371 if (!plantQueue.isEmpty()) plantQueue.pollFirst();
325 advancePlantQueue();
372 advancePlantQueue();
326 return;
373 return;
327 }
374 }
328
375
329 if (reachedNavigationTarget() && near(target)) {
376 if (reachedNavigationTarget() && near(target)) {
330 stopNavigation();
377 beginPlantWait(target);
331 lookAt(target);
332 plantReadyTick = clock + plantWindupTicks;
333 state = State.WAITING_TO_PLANT;
334 return;
378 return;
335 }
379 }
336
380
@@ -347,20 +391,21 @@ final class FarmerManager {
347 return;
391 return;
348 }
392 }
349
393
350 BlockRef targetRef = plantQueue.peekFirst();
394 PlantJob job = plantQueue.peekFirst();
351 Block target = block(targetRef);
395 Block target = job == null ? null : block(job.space());
352 if (target == null || !canPlantOn(target, activeCrop)) {
396 if (job == null || target == null || !jobStillValid(job)) {
353 plantQueue.pollFirst();
397 if (!plantQueue.isEmpty()) plantQueue.pollFirst();
354 advancePlantQueue();
398 advancePlantQueue();
355 return;
399 return;
356 }
400 }
357
401
358 lookAt(target);
402 lookAt(target);
403 playInteractAnimation();
359 if (clock < plantReadyTick) return;
404 if (clock < plantReadyTick) return;
360
405
361 if (cargo.remove(activeCrop.seed(), 1)) {
406 if (cargo.remove(activeCrop.seed(), 1)) {
362 playWorkAnimation(target);
407 playInteractAnimation();
363 target.setType(activeCrop.block(), false);
408 target.setBlockData(job.data(), false);
364 playPlantSound(target);
409 playPlantSound(target);
365 }
410 }
366 plantQueue.pollFirst();
411 plantQueue.pollFirst();
@@ -409,7 +454,6 @@ final class FarmerManager {
409 }
454 }
410
455
411 private void harvest(Block cropBlock, CropRegistry.Crop crop) {
456 private void harvest(Block cropBlock, CropRegistry.Crop crop) {
412 playWorkAnimation(cropBlock);
413 playHarvestEffects(cropBlock);
457 playHarvestEffects(cropBlock);
414 BlockData oldData = cropBlock.getBlockData().clone();
458 BlockData oldData = cropBlock.getBlockData().clone();
415 List<ItemStack> calculatedDrops = new ArrayList<>(cropBlock.getDrops(tool.clone(), golem));
459 List<ItemStack> calculatedDrops = new ArrayList<>(cropBlock.getDrops(tool.clone(), golem));
@@ -421,24 +465,19 @@ final class FarmerManager {
421 cropBlock.getWorld().dropItemNaturally(cropBlock.getLocation().add(0.5, 0.5, 0.5), item);
465 cropBlock.getWorld().dropItemNaturally(cropBlock.getLocation().add(0.5, 0.5, 0.5), item);
422 }
466 }
423
467
424 if (!crop.breakOnlyFruit()) {
425 ensureSeed(crop.seed());
426 if (cargo.remove(crop.seed(), 1)) {
427 if (oldData instanceof Ageable ageable) ageable.setAge(0);
428 cropBlock.setBlockData(oldData, false);
429 playPlantSound(cropBlock);
430 }
431 }
432
433 cropTarget = null;
468 cropTarget = null;
469 if (!crop.breakOnlyFruit()) ensureSeed(crop.seed());
434
470
435 if (!crop.breakOnlyFruit() && crop.farmland() && cargo.count(crop.seed()) > 0) {
471 plantQueue.clear();
436 buildPlantQueue(cropBlock, crop);
472 if (!crop.breakOnlyFruit() && cargo.count(crop.seed()) > 0) {
437 if (!plantQueue.isEmpty()) {
473 plantQueue.addLast(new PlantJob(BlockRef.of(cropBlock), cropRegistry.replantData(oldData)));
438 activeCrop = crop;
474 if (crop.expands()) buildExtraPlantQueue(cropBlock, oldData, crop);
439 advancePlantQueue();
475 }
440 return;
476
441 }
477 if (!plantQueue.isEmpty()) {
478 activeCrop = crop;
479 advancePlantQueue();
480 return;
442 }
481 }
443
482
444 activeCrop = null;
483 activeCrop = null;
@@ -462,52 +501,108 @@ final class FarmerManager {
462 return false;
501 return false;
463 }
502 }
464
503
465 private void buildPlantQueue(Block harvestedCropBlock, CropRegistry.Crop crop) {
504 private void buildExtraPlantQueue(Block harvestedCropBlock, BlockData harvestedData, CropRegistry.Crop crop) {
466 plantQueue.clear();
505 switch (crop.support()) {
467 Block startFarmland = harvestedCropBlock.getRelative(BlockFace.DOWN);
506 case FARMLAND -> queueConnectedBeds(harvestedCropBlock.getRelative(BlockFace.DOWN), Material.FARMLAND, crop);
468 if (startFarmland.getType() != Material.FARMLAND) return;
507 case SOUL_SAND -> queueConnectedBeds(harvestedCropBlock.getRelative(BlockFace.DOWN), Material.SOUL_SAND, crop);
508 case JUNGLE_LOG_SIDE -> queueCocoaSides(harvestedCropBlock, harvestedData, crop);
509 case NONE -> {
510 }
511 }
512 }
513
514 private void queueConnectedBeds(Block startBed, Material bedType, CropRegistry.Crop crop) {
515 if (startBed.getType() != bedType) return;
469
516
470 Set<BlockRef> visited = new HashSet<>();
517 Set<BlockRef> visited = new HashSet<>();
471 Deque<Block> search = new ArrayDeque<>();
518 Deque<Block> search = new ArrayDeque<>();
472 search.add(startFarmland);
519 search.add(startBed);
473 visited.add(BlockRef.of(startFarmland));
520 visited.add(BlockRef.of(startBed));
474
521
475 while (!search.isEmpty()) {
522 while (!search.isEmpty()) {
476 Block farmland = search.pollFirst();
523 Block bed = search.pollFirst();
477 Block above = farmland.getRelative(BlockFace.UP);
524 Block above = bed.getRelative(BlockFace.UP);
478 if (above.getType().isAir() && withinCropRadius(above) && canPlantOn(above, crop)) {
525 if (withinCropRadius(above) && cropRegistry.canPlantAt(above, crop)) {
479 plantQueue.add(BlockRef.of(above));
526 queuePlant(above, cropRegistry.plantData(above, crop));
480 }
527 }
481
528
482 for (BlockFace face : HORIZONTAL) {
529 for (BlockFace face : HORIZONTAL) {
483 Block next = farmland.getRelative(face);
530 Block next = bed.getRelative(face);
484 if (next.getType() != Material.FARMLAND || !withinCropRadius(next)) continue;
531 if (next.getType() != bedType || !withinCropRadius(next)) continue;
485 BlockRef ref = BlockRef.of(next);
532 BlockRef ref = BlockRef.of(next);
486 if (visited.add(ref)) search.addLast(next);
533 if (visited.add(ref)) search.addLast(next);
487 }
534 }
488 }
535 }
489 }
536 }
490
537
538 private void queueCocoaSides(Block harvestedCocoa, BlockData harvestedData, CropRegistry.Crop crop) {
539 Block startLog = cropRegistry.cocoaLog(harvestedCocoa, harvestedData);
540 if (!cropRegistry.isCocoaSupport(startLog.getType())) return;
541
542 Set<BlockRef> visited = new HashSet<>();
543 Deque<Block> search = new ArrayDeque<>();
544 search.add(startLog);
545 visited.add(BlockRef.of(startLog));
546
547 while (!search.isEmpty()) {
548 Block log = search.pollFirst();
549 for (BlockFace face : HORIZONTAL) {
550 Block side = log.getRelative(face);
551 if (withinCropRadius(side) && cropRegistry.canPlantAt(side, crop)) {
552 queuePlant(side, cropRegistry.plantData(side, crop));
553 }
554 if (!cropRegistry.isCocoaSupport(side.getType()) || !withinCropRadius(side)) continue;
555 BlockRef ref = BlockRef.of(side);
556 if (visited.add(ref)) search.addLast(side);
557 }
558 }
559 }
560
561 private void queuePlant(Block space, BlockData data) {
562 BlockRef ref = BlockRef.of(space);
563 for (PlantJob existing : plantQueue) {
564 if (existing.space().equals(ref)) return;
565 }
566 plantQueue.addLast(new PlantJob(ref, data));
567 }
568
491 private void advancePlantQueue() {
569 private void advancePlantQueue() {
492 while (!plantQueue.isEmpty()) {
570 while (!plantQueue.isEmpty()) {
493 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
571 if (activeCrop == null || cargo.count(activeCrop.seed()) <= 0) {
494 plantQueue.clear();
572 plantQueue.clear();
495 break;
573 break;
496 }
574 }
497 Block target = block(plantQueue.peekFirst());
575 PlantJob job = plantQueue.peekFirst();
498 if (target == null || !canPlantOn(target, activeCrop)) {
576 Block target = job == null ? null : block(job.space());
577 if (job == null || target == null || !jobStillValid(job)) {
499 plantQueue.pollFirst();
578 plantQueue.pollFirst();
500 continue;
579 continue;
501 }
580 }
581 if (near(target)) {
582 beginPlantWait(target);
583 return;
584 }
502 if (beginPathToBlock(target, State.MOVING_TO_PLANT)) return;
585 if (beginPathToBlock(target, State.MOVING_TO_PLANT)) return;
503 plantQueue.pollFirst();
586 plantQueue.pollFirst();
504 }
587 }
505 beginReturnToChest();
588 beginReturnToChest();
506 }
589 }
507
590
508 private boolean canPlantOn(Block cropSpace, CropRegistry.Crop crop) {
591 private void beginPlantWait(Block target) {
509 if (!crop.farmland()) return false;
592 stopNavigation();
510 return cropSpace.getType().isAir() && cropSpace.getRelative(BlockFace.DOWN).getType() == Material.FARMLAND;
593 lookAt(target);
594 playInteractAnimation();
595 plantReadyTick = clock + plantWindupTicks;
596 animationHoldUntil = plantReadyTick + 5;
597 state = State.WAITING_TO_PLANT;
598 }
599
600 private boolean jobStillValid(PlantJob job) {
601 Block space = block(job.space());
602 if (space == null || activeCrop == null) return false;
603 if (!space.getType().isAir()) return false;
604 if (activeCrop.support() == CropRegistry.PlantSupport.NONE) return true;
605 return cropRegistry.canPlantAt(space, activeCrop);
511 }
606 }
512
607
513 private void beginReturnToChest() {
608 private void beginReturnToChest() {
@@ -589,8 +684,7 @@ final class FarmerManager {
589 Block block = world.getBlockAt(x, y, z);
684 Block block = world.getBlockAt(x, y, z);
590 if (!cropRegistry.isReady(block)) continue;
685 if (!cropRegistry.isReady(block)) continue;
591 BlockRef ref = BlockRef.of(block);
686 BlockRef ref = BlockRef.of(block);
592 Long blockedUntil = unreachableCrops.get(ref);
687 if (unreachableCrops.contains(ref)) continue;
593 if (blockedUntil != null && blockedUntil > clock) continue;
594 candidates.add(block);
688 candidates.add(block);
595 }
689 }
596 }
690 }
@@ -678,14 +772,21 @@ final class FarmerManager {
678 if (target == null) return false;
772 if (target == null) return false;
679
773
680 List<Block> positions = new ArrayList<>();
774 List<Block> positions = new ArrayList<>();
681 for (BlockFace face : HORIZONTAL) {
775 Set<BlockRef> seen = new HashSet<>();
682 Block feet = target.getRelative(face);
776 for (int dy = 0; dy >= -2; dy--) {
683 if (isStandable(feet)) positions.add(feet);
777 for (BlockFace face : HORIZONTAL) {
778 Block feet = target.getRelative(face.getModX(), dy, face.getModZ());
779 if (seen.add(BlockRef.of(feet)) && isStandable(feet)) positions.add(feet);
780 }
781 if (dy < 0) {
782 Block below = target.getRelative(0, dy, 0);
783 if (seen.add(BlockRef.of(below)) && isStandable(below)) positions.add(below);
784 }
684 }
785 }
685 positions.sort(Comparator.comparingDouble(block -> block.getLocation().add(0.5, 0, 0.5)
786 positions.sort(Comparator.comparingDouble(block -> block.getLocation().add(0.5, 0, 0.5)
686 .distanceSquared(golem.getLocation())));
787 .distanceSquared(golem.getLocation())));
687
788
688 // Try each valid side once. After a side has produced a native path,
789 // Try each valid stand position once. After a side has produced a native path,
689 // Minecraft owns that path; we do not recalculate it every brain tick.
790 // Minecraft owns that path; we do not recalculate it every brain tick.
690 for (Block feet : positions) {
791 for (Block feet : positions) {
691 if (beginPath(feet.getLocation().add(0.5, 0.0, 0.5), newState)) return true;
792 if (beginPath(feet.getLocation().add(0.5, 0.0, 0.5), newState)) return true;
@@ -708,11 +809,14 @@ final class FarmerManager {
708 return now.distanceSquared(navigationTarget) <= 1.25 * 1.25;
809 return now.distanceSquared(navigationTarget) <= 1.25 * 1.25;
709 }
810 }
710
811
812 private void playInteractAnimation() {
813 golem.setGolemState(CopperGolem.State.GETTING_ITEM);
814 animationHoldUntil = Math.max(animationHoldUntil, clock + 20);
815 }
816
711 private void playWorkAnimation(Block target) {
817 private void playWorkAnimation(Block target) {
712 lookAt(target);
818 lookAt(target);
713 // Copper golems have no melee-attack clip; the arm swing is the same
819 playInteractAnimation();
714 // packet vanilla uses for attacking / using a held tool.
715 golem.swingMainHand();
716 }
820 }
717
821
718 private ItemStack heldAppearance() {
822 private ItemStack heldAppearance() {
@@ -800,7 +904,7 @@ final class FarmerManager {
800 private boolean isStandable(Block feet) {
904 private boolean isStandable(Block feet) {
801 if (!feet.isPassable() || !feet.getRelative(BlockFace.UP).isPassable()) return false;
905 if (!feet.isPassable() || !feet.getRelative(BlockFace.UP).isPassable()) return false;
802 Material below = feet.getRelative(BlockFace.DOWN).getType();
906 Material below = feet.getRelative(BlockFace.DOWN).getType();
803 return below.isSolid() || below == Material.FARMLAND;
907 return below.isSolid() || below == Material.FARMLAND || below == Material.SOUL_SAND;
804 }
908 }
805
909
806 private boolean near(Block block) {
910 private boolean near(Block block) {
@@ -819,11 +923,12 @@ final class FarmerManager {
819
923
820 private void resetCropTask() {
924 private void resetCropTask() {
821 stopNavigation();
925 stopNavigation();
926 clearHarvestCrack();
822 cropTarget = null;
927 cropTarget = null;
823 activeCrop = null;
928 activeCrop = null;
824 plantQueue.clear();
929 plantQueue.clear();
825 state = State.IDLE;
930 state = State.IDLE;
826 nextScanTick = clock + scanInterval;
931 nextScanTick = clock;
827 }
932 }
828
933
829 private void stopNavigation() {
934 private void stopNavigation() {
@@ -834,7 +939,7 @@ final class FarmerManager {
834 }
939 }
835
940
836 private void markCropUnreachable(BlockRef ref) {
941 private void markCropUnreachable(BlockRef ref) {
837 if (ref != null) unreachableCrops.put(ref, clock + unreachableCooldown);
942 if (ref != null) unreachableCrops.add(ref);
838 }
943 }
839
944
840 private void markChestUnreachable(BlockRef ref) {
945 private void markChestUnreachable(BlockRef ref) {
@@ -842,7 +947,6 @@ final class FarmerManager {
842 }
947 }
843
948
844 private void cleanupCooldowns() {
949 private void cleanupCooldowns() {
845 unreachableCrops.entrySet().removeIf(entry -> entry.getValue() <= clock);
846 unreachableChests.entrySet().removeIf(entry -> entry.getValue() <= clock);
950 unreachableChests.entrySet().removeIf(entry -> entry.getValue() <= clock);
847 }
951 }
848
952
@@ -859,11 +963,115 @@ final class FarmerManager {
859 Block block = block(ref);
963 Block block = block(ref);
860 return isCopperChest(block);
964 return isCopperChest(block);
861 }
965 }
966
967 private void tickDoors() {
968 Location loc = golem.getLocation();
969 tryOpenDoor(loc.getBlock());
970 tryOpenDoor(loc.getBlock().getRelative(BlockFace.UP));
971
972 Location ahead = loc.clone();
973 if (navigationTarget != null && navigationTarget.getWorld() == loc.getWorld()) {
974 var delta = navigationTarget.toVector().subtract(loc.toVector());
975 if (delta.lengthSquared() > 0.0001) {
976 delta.normalize().multiply(0.8);
977 ahead.add(delta);
978 }
979 } else {
980 ahead.add(loc.getDirection().multiply(0.8));
981 }
982 tryOpenDoor(ahead.getBlock());
983 tryOpenDoor(ahead.getBlock().getRelative(BlockFace.UP));
984
985 for (var iterator = openedDoors.entrySet().iterator(); iterator.hasNext(); ) {
986 var entry = iterator.next();
987 Block doorBlock = block(entry.getKey());
988 if (doorBlock != null && golem.getLocation().distanceSquared(
989 doorBlock.getLocation().add(0.5, 0.5, 0.5)) <= 4.0) {
990 entry.setValue(clock + 30);
991 continue;
992 }
993 if (entry.getValue() > clock) continue;
994 closeDoor(doorBlock);
995 iterator.remove();
996 }
997 }
998
999 private void tryOpenDoor(Block block) {
1000 if (block == null || !isWoodenPassage(block.getType())) return;
1001 BlockData data = block.getBlockData();
1002 if (!(data instanceof Openable openable) || openable.isOpen()) return;
1003 if (!(data instanceof Door) && !(data instanceof Gate)) return;
1004 openable.setOpen(true);
1005 block.setBlockData(openable, true);
1006 openedDoors.put(BlockRef.of(block), clock + 40);
1007 Sound sound = data instanceof Gate ? Sound.BLOCK_FENCE_GATE_OPEN : Sound.BLOCK_WOODEN_DOOR_OPEN;
1008 block.getWorld().playSound(block.getLocation().add(0.5, 0.5, 0.5), sound, SoundCategory.BLOCKS, 1.0f, 1.0f);
1009 if (data instanceof Door) {
1010 for (BlockFace face : HORIZONTAL) {
1011 Block neighbour = block.getRelative(face);
1012 if (!isWoodenPassage(neighbour.getType())) continue;
1013 BlockData neighbourData = neighbour.getBlockData();
1014 if (!(neighbourData instanceof Door neighbourDoor) || neighbourDoor.isOpen()) continue;
1015 neighbourDoor.setOpen(true);
1016 neighbour.setBlockData(neighbourDoor, true);
1017 openedDoors.put(BlockRef.of(neighbour), clock + 40);
1018 }
1019 }
1020 }
1021
1022 private void closeDoor(Block block) {
1023 if (block == null || !isWoodenPassage(block.getType())) return;
1024 BlockData data = block.getBlockData();
1025 if (!(data instanceof Openable openable) || !openable.isOpen()) return;
1026 openable.setOpen(false);
1027 block.setBlockData(openable, true);
1028 Sound sound = data instanceof Gate ? Sound.BLOCK_FENCE_GATE_CLOSE : Sound.BLOCK_WOODEN_DOOR_CLOSE;
1029 block.getWorld().playSound(block.getLocation().add(0.5, 0.5, 0.5), sound, SoundCategory.BLOCKS, 1.0f, 1.0f);
1030 }
1031
1032 private void closeAllDoors() {
1033 for (BlockRef ref : openedDoors.keySet()) closeDoor(block(ref));
1034 openedDoors.clear();
1035 }
1036
1037 private boolean isWoodenPassage(Material type) {
1038 return Tag.WOODEN_DOORS.isTagged(type) || Tag.FENCE_GATES.isTagged(type);
1039 }
1040
1041 private long vanillaBreakTicks(Block block, ItemStack tool) {
1042 float hardness = block.getType().getHardness();
1043 if (hardness < 0f) return 1L;
1044 if (hardness == 0f) return 1L;
1045 BlockData data = block.getBlockData();
1046 float speed = Math.max(0.001f, data.getDestroySpeed(tool, true));
1047 int factor = data.requiresCorrectToolForDrops() && !data.isPreferredTool(tool) ? 100 : 30;
1048 return Math.max(1L, (long) Math.ceil(hardness * factor / speed));
1049 }
1050
1051 private void sendHarvestCrack(Block cropBlock, float progress) {
1052 Location location = cropBlock.getLocation();
1053 float clamped = Math.max(0.0f, Math.min(1.0f, progress));
1054 for (Player player : golem.getTrackedBy()) {
1055 player.sendBlockDamage(location, clamped, golem);
1056 }
1057 }
1058
1059 private void clearHarvestCrack() {
1060 Block cropBlock = block(cropTarget);
1061 if (cropBlock == null) return;
1062 Location location = cropBlock.getLocation();
1063 for (Player player : golem.getTrackedBy()) {
1064 player.sendBlockDamage(location, 0.0f, golem);
1065 }
1066 }
862 }
1067 }
863
1068
1069 private record PlantJob(BlockRef space, BlockData data) {}
1070
864 private enum State {
1071 private enum State {
865 IDLE,
1072 IDLE,
866 MOVING_TO_CROP,
1073 MOVING_TO_CROP,
1074 WAITING_TO_HARVEST,
867 MOVING_TO_PLANT,
1075 MOVING_TO_PLANT,
868 WAITING_TO_PLANT,
1076 WAITING_TO_PLANT,
869 MOVING_TO_CHEST,
1077 MOVING_TO_CHEST,