From 353328bd8c0490b5e5e55cd1f8002cef68ba1f9c Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 26 Nov 2026 17:09:06 +0200 Subject: [PATCH] Make jugs and pots real fluid containers, with lids that seal them and light when the liquid glows. --- CHANGELOG.md | 8 +- build.gradle | 6 + .../fabric/PrimalPotteryFabric.java | 10 + .../client/PrimalPotteryFabricClient.java | 6 + neoforge/build.gradle | 65 ++ .../neoforge/PrimalPotteryNeoForge.java | 37 +- .../client/PrimalPotteryNeoForgeClient.java | 18 + .../neoforge/PotteryGameTests.java | 811 +++++++++++++++++- .../primalpottery/block/ModBlocks.java | 5 +- .../primalpottery/block/PotteryBlock.java | 159 ++-- .../block/PotteryBlockEntity.java | 98 ++- .../minecraft/primalpottery/client/Mesh.java | 82 ++ .../primalpottery/client/PotteryPreview.java | 23 +- .../primalpottery/client/PotteryRenderer.java | 133 ++- .../primalpottery/client/PotteryScreen.java | 187 ++++ .../primalpottery/client/Sprites.java | 91 +- .../primalpottery/item/PotteryItem.java | 249 +++++- .../primalpottery/network/LidPayload.java | 29 + .../primalpottery/network/LidSync.java | 42 + .../network/PlacedLidPayload.java | 31 + .../primalpottery/network/PlacedLidSync.java | 45 + .../minecraft/primalpottery/pottery/Nbt.java | 14 + .../primalpottery/pottery/Placement.java | 3 +- .../primalpottery/pottery/Pottery.java | 59 ++ .../primalpottery/pottery/VesselContents.java | 153 ++++ .../primalpottery/blockstates/pottery.json | 19 +- .../assets/primalpottery/lang/en_us.json | 1 + .../primalpottery/client/MeshTest.java | 92 ++ .../primalpottery/pottery/PotteryTest.java | 231 ++++- 29 files changed, 2568 insertions(+), 139 deletions(-) create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryScreen.java create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/network/LidPayload.java create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/network/LidSync.java create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidPayload.java create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidSync.java create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselContents.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c8e0e9..ec04fe3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,14 @@ After publishing, the action commits the next development version and changelog ## Unreleased +- A jug, jar, or pot holds liquid, and you can see the liquid when you look inside. Use it on water or lava, flowing or still, or on another fluid, and it fills without using up the source. A waterlogged block or a bubble column does not fill it. +- The tooltip shows how many millilitres it holds, and the liquid and how full it is when there is some. Water's name is blue. +- Use a vessel in the air, or right-click a placed one with an empty hand, to look inside and put a lid on or take it off. The lid sits just above the rim, a little wider than the mouth, with a small handle. +- Shift-right-click a placed piece with an empty hand to pick that piece up. Breaking the block breaks only the piece you are looking at. +- Pour from one filled vessel into a placed vessel. A bucket does not pour or scoop. With the lid on, you cannot fill the vessel or pour. +- A placed vessel with the lid off lights the block when its liquid's source block does. Lava does. The lid puts the light out. - NeoForge runs on Minecraft 1.20.6, 1.21.1, and 26.3. Fabric runs on 26.3. - A pottery wheel spins when you use it with an empty hand. Use a clay ball on it and the clay forms toward the blueprint installed on the wheel. Take the piece off when you want it. The clay ball stays in your hand. - Edit a raw pottery template. The left mouse button sets the outer radius and the right sets the inner. Saving turns it into a pottery blueprint. A blueprint can be edited again, set on the wheel, or crafted by itself back into a blank raw template. -- A sealed shape is a pot, a jar, or a jug from how wide the mouth is next to the widest point. Wider than nine tenths is a pot, under half is a jug, and between those is a jar. The tooltip names the type and how many millilitres it holds. A shape that is not a vessel says Lump. +- A sealed shape is a pot, a jar, or a jug from how wide the mouth is next to the widest point. Wider than nine tenths is a pot, under half is a jug, and between those is a jar. A blueprint's tooltip names the type and how many millilitres it holds. A shape that is not a vessel says Lump. - Finished pottery can sit in four places in one block. Pick a piece back up. diff --git a/build.gradle b/build.gradle index 8f00150..0798b64 100644 --- a/build.gradle +++ b/build.gradle @@ -34,6 +34,12 @@ dependencies { tasks.named('test', Test) { useJUnitPlatform() + // 1.20.6 and 1.21.1 keep en_us.json in the client-extra jar. Bootstrap reads it while validating + // creative-tab names. 26.3 packs that file into the game jar, so this tree is empty there. + classpath += fileTree(layout.buildDirectory.dir("moddev/artifacts")) { + include "*-client-extra*.jar" + builtBy "createMinecraftArtifacts" + } } // Geometry tests exercise the real PoseStack and arm transforms without launching a client. diff --git a/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/PrimalPotteryFabric.java b/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/PrimalPotteryFabric.java index 6fda9d9..a6bfc7d 100644 --- a/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/PrimalPotteryFabric.java +++ b/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/PrimalPotteryFabric.java @@ -13,6 +13,10 @@ import net.modcrafters.minecraft.primalpottery.block.PotteryBlock; import net.modcrafters.minecraft.primalpottery.item.ModItems; import net.modcrafters.minecraft.primalpottery.item.ModTab; +import net.modcrafters.minecraft.primalpottery.network.LidPayload; +import net.modcrafters.minecraft.primalpottery.network.LidSync; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidPayload; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidSync; import net.modcrafters.minecraft.primalpottery.network.TemplatePayload; import net.modcrafters.minecraft.primalpottery.network.TemplateSync; @@ -30,8 +34,14 @@ public void onInitialize() { .build() ); PayloadTypeRegistry.serverboundPlay().register(TemplatePayload.TYPE, TemplatePayload.STREAM_CODEC); + PayloadTypeRegistry.serverboundPlay().register(LidPayload.TYPE, LidPayload.STREAM_CODEC); + PayloadTypeRegistry.serverboundPlay().register(PlacedLidPayload.TYPE, PlacedLidPayload.STREAM_CODEC); ServerPlayNetworking.registerGlobalReceiver(TemplatePayload.TYPE, (payload, context) -> TemplateSync.apply(context.player(), payload.mainHand(), payload.discs())); + ServerPlayNetworking.registerGlobalReceiver(LidPayload.TYPE, (payload, context) -> + LidSync.apply(context.player(), payload.mainHand(), payload.closed())); + ServerPlayNetworking.registerGlobalReceiver(PlacedLidPayload.TYPE, (payload, context) -> + PlacedLidSync.apply(context.player(), payload.pos(), payload.slot(), payload.closed())); PlayerBlockBreakEvents.BEFORE.register((level, player, pos, state, entity) -> { if (!(state.getBlock() instanceof PotteryBlock)) { return true; diff --git a/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/client/PrimalPotteryFabricClient.java b/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/client/PrimalPotteryFabricClient.java index f0d9dc6..f2fe7f9 100644 --- a/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/client/PrimalPotteryFabricClient.java +++ b/fabric/src/main/java/net/modcrafters/minecraft/primalpottery/fabric/client/PrimalPotteryFabricClient.java @@ -13,6 +13,10 @@ import net.minecraft.world.phys.shapes.Shapes; import net.modcrafters.minecraft.primalpottery.block.ModBlockEntities; import net.modcrafters.minecraft.primalpottery.client.PotteryPreview; +import net.modcrafters.minecraft.primalpottery.network.LidPayload; +import net.modcrafters.minecraft.primalpottery.network.LidSync; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidPayload; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidSync; import net.modcrafters.minecraft.primalpottery.network.TemplatePayload; import net.modcrafters.minecraft.primalpottery.network.TemplateSync; import net.modcrafters.minecraft.primalpottery.client.PotteryRenderer; @@ -23,6 +27,8 @@ public class PrimalPotteryFabricClient implements ClientModInitializer { @Override public void onInitializeClient() { TemplateSync.sender = (mainHand, discs) -> ClientPlayNetworking.send(new TemplatePayload(mainHand, discs)); + LidSync.sender = (mainHand, closed) -> ClientPlayNetworking.send(new LidPayload(mainHand, closed)); + PlacedLidSync.sender = (pos, slot, closed) -> ClientPlayNetworking.send(new PlacedLidPayload(pos, slot, closed)); PictureInPictureRendererRegistry.register(context -> new PotteryPreview.Renderer()); PotteryPreview.SINK = (graphics, state) -> graphics.guiRenderState.addPicturesInPictureState(state); BlockEntityRendererRegistry.register(ModBlockEntities.WHEEL, context -> new WheelRenderer()); diff --git a/neoforge/build.gradle b/neoforge/build.gradle index 2961ca3..b065317 100644 --- a/neoforge/build.gradle +++ b/neoforge/build.gradle @@ -3,6 +3,71 @@ plugins { id 'net.neoforged.moddev' } +// Shared sources are generated with the common Stonecutter constant, so a +// `//? if neoforge` body in src/ stays commented in the file this project compiles. +// Splice the break override into that already version-switched PotteryBlock. +def commonProject = rootProject.project(":${project.name}") +def patchedPotteryBlock = layout.buildDirectory.file( + 'generated/pottery-block/net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java' +) +def potteryBlockSource = stonecutter.current.isActive + ? rootProject.file('src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java') + : commonProject.layout.buildDirectory.file( + 'generated/stonecutter/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java' + ) + +// 26.1 added the held tool. 1.20.6 and 1.21.1 still use the shorter override. +def toolParameter = stonecutter.current.parsed >= '26.1' ? '\n ItemStack tool,' : '' +def toolArgument = stonecutter.current.parsed >= '26.1' ? ', tool' : '' +def destroyedByPlayer = """ + @Override + public boolean onDestroyedByPlayer( + BlockState state, + Level level, + BlockPos pos, + Player player,${toolParameter} + boolean willHarvest, + net.minecraft.world.level.material.FluidState fluid + ) { + if (breakFocused(level, pos, player)) { + return false; + } + return super.onDestroyedByPlayer(state, level, pos, player${toolArgument}, willHarvest, fluid); + } +""" + +tasks.register('neoforgePotteryBlock') { + dependsOn(commonProject.tasks.named('stonecutterGenerate')) + inputs.file(potteryBlockSource).withPropertyName('potteryBlock') + outputs.file(patchedPotteryBlock) + doLast { + def source = inputs.files.singleFile + def text = source.getText('UTF-8') + if (text.contains('boolean onDestroyedByPlayer(')) { + throw new GradleException("${source} already declares onDestroyedByPlayer") + } + def end = text.lastIndexOf('}') + if (end < 0) { + throw new GradleException("${source} has no class body") + } + def patched = text.substring(0, end) + destroyedByPlayer + text.substring(end) + def out = patchedPotteryBlock.get().asFile + out.parentFile.mkdirs() + out.setText(patched, 'UTF-8') + } +} + +tasks.named('compileJava', JavaCompile) { + dependsOn('neoforgePotteryBlock') + source(layout.buildDirectory.dir('generated/pottery-block')) + exclude { element -> + def relative = element.path.replace('\\', '/') + def absolute = element.file.absolutePath.replace('\\', '/') + relative.endsWith('net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java') && + !absolute.contains('/generated/pottery-block/') + } +} + neoForge { version = neoforge_version def at = rootProject.file('src/main/resources/META-INF/accesstransformer.cfg') diff --git a/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PrimalPotteryNeoForge.java b/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PrimalPotteryNeoForge.java index a26de7a..4962dc6 100644 --- a/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PrimalPotteryNeoForge.java +++ b/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PrimalPotteryNeoForge.java @@ -15,6 +15,10 @@ import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.common.Mod; import net.neoforged.fml.loading.FMLEnvironment; +import net.modcrafters.minecraft.primalpottery.network.LidPayload; +import net.modcrafters.minecraft.primalpottery.network.LidSync; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidPayload; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidSync; import net.modcrafters.minecraft.primalpottery.network.TemplatePayload; import net.modcrafters.minecraft.primalpottery.network.TemplateSync; import net.neoforged.neoforge.common.NeoForge; @@ -39,20 +43,37 @@ public PrimalPotteryNeoForge(IEventBus modBus) { } private static void registerPayloads(RegisterPayloadHandlersEvent event) { - event.registrar(Constants.MOD_ID).playToServer( - TemplatePayload.TYPE, - TemplatePayload.STREAM_CODEC, - (payload, context) -> context.enqueueWork(() -> - TemplateSync.apply(context.player(), payload.mainHand(), payload.discs())) - ); + event.registrar(Constants.MOD_ID) + .playToServer( + TemplatePayload.TYPE, + TemplatePayload.STREAM_CODEC, + (payload, context) -> context.enqueueWork(() -> + TemplateSync.apply(context.player(), payload.mainHand(), payload.discs())) + ) + .playToServer( + LidPayload.TYPE, + LidPayload.STREAM_CODEC, + (payload, context) -> context.enqueueWork(() -> + LidSync.apply(context.player(), payload.mainHand(), payload.closed())) + ) + .playToServer( + PlacedLidPayload.TYPE, + PlacedLidPayload.STREAM_CODEC, + (payload, context) -> context.enqueueWork(() -> + PlacedLidSync.apply(context.player(), payload.pos(), payload.slot(), payload.closed())) + ); } private static void registerContent(RegisterEvent event) { event.register(Registries.BLOCK, helper -> ModBlocks.register(helper::register)); event.register(Registries.BLOCK_ENTITY_TYPE, helper -> ModBlockEntities.register(helper::register)); event.register(Registries.ITEM, helper -> ModItems.register(helper::register)); - //? if >=26.1 - event.register(net.minecraft.core.registries.Registries.TEST_INSTANCE_TYPE, helper -> helper.register(net.modcrafters.minecraft.primalpottery.Ids.of("wheel"), PotteryGameTests.codec())); + //? if >=26.1 { + event.register(net.minecraft.core.registries.Registries.TEST_INSTANCE_TYPE, helper -> { + helper.register(net.modcrafters.minecraft.primalpottery.Ids.of("wheel"), PotteryGameTests.codec()); + helper.register(net.modcrafters.minecraft.primalpottery.Ids.of("vessels"), PotteryGameTests.vesselsCodec()); + }); + //?} event.register(Registries.CREATIVE_MODE_TAB, ModTab.ID.identifier(), () -> ModTab.titled(CreativeModeTab.builder()) .displayItems((parameters, output) -> ModItems.tabContents().forEach(output::accept)) .build()); diff --git a/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java b/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java index e86d948..10219f5 100644 --- a/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java +++ b/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java @@ -6,6 +6,10 @@ import net.modcrafters.minecraft.primalpottery.block.ModBlockEntities; import net.modcrafters.minecraft.primalpottery.client.PotteryRenderer; import net.modcrafters.minecraft.primalpottery.client.WheelRenderer; +import net.modcrafters.minecraft.primalpottery.network.LidPayload; +import net.modcrafters.minecraft.primalpottery.network.LidSync; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidPayload; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidSync; import net.modcrafters.minecraft.primalpottery.network.TemplatePayload; import net.modcrafters.minecraft.primalpottery.network.TemplateSync; //? if >=26.1 @@ -42,6 +46,20 @@ public static void register(IEventBus modBus) { /*PacketDistributor.sendToServer(new TemplatePayload(mainHand, discs)); *///?} }; + LidSync.sender = (mainHand, closed) -> { + //? if >=26.1 { + ClientPacketDistributor.sendToServer(new LidPayload(mainHand, closed)); + //?} else { + /*PacketDistributor.sendToServer(new LidPayload(mainHand, closed)); + *///?} + }; + PlacedLidSync.sender = (pos, slot, closed) -> { + //? if >=26.1 { + ClientPacketDistributor.sendToServer(new PlacedLidPayload(pos, slot, closed)); + //?} else { + /*PacketDistributor.sendToServer(new PlacedLidPayload(pos, slot, closed)); + *///?} + }; modBus.addListener(PrimalPotteryNeoForgeClient::renderers); //? if >=26.1 { modBus.addListener(PrimalPotteryNeoForgeClient::pictures); diff --git a/neoforge/versions/26.3/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PotteryGameTests.java b/neoforge/versions/26.3/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PotteryGameTests.java index a7c9881..a26ac66 100644 --- a/neoforge/versions/26.3/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PotteryGameTests.java +++ b/neoforge/versions/26.3/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/PotteryGameTests.java @@ -4,15 +4,22 @@ import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.List; import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.gametest.framework.GameTestHelper; import net.minecraft.gametest.framework.GameTestInstance; import net.minecraft.gametest.framework.TestData; import net.minecraft.gametest.framework.TestEnvironmentDefinition; +import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.ProblemReporter; import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -22,19 +29,36 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.GameType; import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.storage.TagValueInput; +import net.minecraft.world.level.block.LiquidBlock; +import net.minecraft.world.level.block.SlabBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Fluids; +import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.BooleanOp; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.Shapes; import net.modcrafters.minecraft.primalpottery.Ids; import net.modcrafters.minecraft.primalpottery.block.ModBlocks; +import net.modcrafters.minecraft.primalpottery.block.PotteryBlock; import net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity; import net.modcrafters.minecraft.primalpottery.block.PotteryWheelBlockEntity; import net.modcrafters.minecraft.primalpottery.item.ModItems; import net.modcrafters.minecraft.primalpottery.item.PotteryItem; import net.modcrafters.minecraft.primalpottery.item.TemplateItem; +import net.modcrafters.minecraft.primalpottery.network.LidSync; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidSync; import net.modcrafters.minecraft.primalpottery.network.TemplateSync; +import net.modcrafters.minecraft.primalpottery.pottery.Nbt; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; import net.modcrafters.minecraft.primalpottery.pottery.PotteryType; +import net.modcrafters.minecraft.primalpottery.pottery.VesselContents; import net.neoforged.neoforge.event.RegisterGameTestsEvent; public final class PotteryGameTests { @@ -45,18 +69,26 @@ public static MapCodec codec() { return Wheel.CODEC; } + public static MapCodec vesselsCodec() { + return Vessels.CODEC; + } + public static void registerTests(RegisterGameTestsEvent event) { Holder> environment = event.registerEnvironment(Ids.of("empty"), new TestEnvironmentDefinition.AllOf()); event.registerTest( Ids.of("wheel"), new Wheel(new TestData<>(environment, Identifier.withDefaultNamespace("empty"), 100, 0, true)) ); + event.registerTest( + Ids.of("vessels"), + new Vessels(new TestData<>(environment, Identifier.withDefaultNamespace("empty"), 100, 0, true)) + ); } private static void wheel(GameTestHelper helper) { BlockPos wheelPos = new BlockPos(1, 2, 1); helper.setBlock(wheelPos, ModBlocks.WHEEL); - Player player = helper.makeMockServerPlayerInLevel(); + Player player = mockPlayer(helper); PotteryWheelBlockEntity wheel = helper.getBlockEntity(wheelPos, PotteryWheelBlockEntity.class); checkTemplateCycle(helper, player); @@ -102,8 +134,9 @@ private static void wheel(GameTestHelper helper) { helper.assertTrue(pots.get(0) != null, "pot was not placed"); player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); - aim(player, PotteryBlockEntity.BOXES.getFirst().move(helper.absolutePos(floor.above())).getCenter()); - helper.useBlock(floor.above(), player); + player.setShiftKeyDown(true); + useItemOn(helper, player, floor.above(), slotPoint(floor.above(), 0), Direction.UP); + player.setShiftKeyDown(false); helper.assertBlockNotPresent(ModBlocks.POTTERY, floor.above()); potteryItem(helper); helper.succeed(); @@ -146,6 +179,18 @@ private static ItemStack potteryItem(GameTestHelper helper) { return items.getFirst().getItem(); } + /** The batch places other tests nearby, so a bounds-wide search can see their empty pots. */ + private static ItemStack potteryItemNear(GameTestHelper helper, BlockPos relative) { + AABB box = new AABB(helper.absolutePos(relative)).inflate(2); + var items = helper.getLevel().getEntitiesOfClass( + ItemEntity.class, + box, + entity -> entity.getItem().is(ModItems.POTTERY) + ); + helper.assertFalse(items.isEmpty(), "pottery item was not dropped"); + return items.getFirst().getItem(); + } + private static Vec3 partCenter(GameTestHelper helper, BlockPos relative, int part) { return PotteryWheelBlockEntity.BOXES.get(part).move(helper.absolutePos(relative)).getCenter(); } @@ -162,6 +207,766 @@ private static void placeEyes(Player player, Vec3 eye) { player.setPos(player.getX() + eye.x - actual.x, player.getY() + eye.y - actual.y, player.getZ() + eye.z - actual.z); } + private static void vessels(GameTestHelper helper) { + Player player = mockPlayer(helper); + Pottery jug = jug(); + int volume = jug.classify().volume(); + helper.assertTrue(volume > 0, "jug has no volume"); + ItemStack empty = PotteryItem.stack(jug); + List emptyLines = tooltip(empty, player); + helper.assertFalse(emptyLines.contains(Blocks.WATER.getName()), "empty jug names a fluid"); + helper.assertTrue(emptyLines.contains(Component.translatable("tooltip.primalpottery.capacity", volume)), "empty capacity"); + helper.assertFalse(emptyLines.stream().anyMatch(line -> line.getString().contains("mL") && !line.getString().startsWith("Capacity")), "empty names an amount"); + + BlockPos waterStone = new BlockPos(5, 1, 1); + BlockPos water = pour(helper, waterStone, Blocks.WATER.defaultBlockState()); + hold(player, jug); + clickThrough(helper, player, waterStone); + helper.assertBlockState(water, Blocks.WATER.defaultBlockState()); + assertHeld(helper, player, Fluids.WATER, volume, "water source"); + helper.assertTrue(player.getMainHandItem().getCount() == 1, "fill shrank the jug"); + List waterLines = tooltip(player.getMainHandItem(), player); + helper.assertTrue(waterLines.contains(Component.translatable("tooltip.primalpottery.capacity", volume)), "water capacity"); + helper.assertTrue(waterLines.contains(Component.translatable("tooltip.primalpottery.contents", PotteryItem.fluidName(Fluids.WATER), volume)), "water amount"); + helper.assertTrue(coloredLine(waterLines, Blocks.WATER.getName().getString(), 0x3F76E4), "water tooltip"); + + clickThrough(helper, player, waterStone); + helper.assertBlockState(water, Blocks.WATER.defaultBlockState()); + assertHeld(helper, player, Fluids.WATER, volume, "second click"); + + hold(player, jug); + clickThrough(helper, player, waterStone); + helper.assertBlockState(water, Blocks.WATER.defaultBlockState()); + assertHeld(helper, player, Fluids.WATER, volume, "second jug"); + + BlockPos lavaStone = new BlockPos(2, 1, 1); + BlockPos lava = pour(helper, lavaStone, Blocks.LAVA.defaultBlockState()); + hold(player, jug); + clickThrough(helper, player, lavaStone); + helper.assertBlockState(lava, Blocks.LAVA.defaultBlockState()); + assertHeld(helper, player, Fluids.LAVA, volume, "lava source"); + List lavaLines = tooltip(player.getMainHandItem(), player); + helper.assertTrue(lavaLines.contains(Component.translatable("tooltip.primalpottery.capacity", volume)), "lava capacity"); + helper.assertTrue(lavaLines.contains(Component.translatable("tooltip.primalpottery.contents", PotteryItem.fluidName(Fluids.LAVA), volume)), "lava amount"); + helper.assertTrue(plainLine(lavaLines, Blocks.LAVA.getName().getString()), "lava tooltip"); + ItemStack lavaJug = player.getMainHandItem().copy(); + holdStack(player, PotteryItem.stack(jug, VesselContents.EMPTY, true)); + clickThrough(helper, player, lavaStone); + helper.assertBlockState(lava, Blocks.LAVA.defaultBlockState()); + helper.assertTrue(PotteryItem.contents(player.getMainHandItem()).isEmpty(), "lidded jug filled"); + helper.assertTrue(PotteryItem.lid(player.getMainHandItem()), "fill removed the lid"); + + BlockState flowingWater = Blocks.WATER.defaultBlockState().setValue(LiquidBlock.LEVEL, 1); + BlockPos flowStone = new BlockPos(8, 1, 1); + BlockPos flow = pour(helper, flowStone, flowingWater); + hold(player, jug); + clickThrough(helper, player, flowStone); + helper.assertBlockState(flow, flowingWater); + assertHeld(helper, player, Fluids.WATER, volume, "flowing water"); + + BlockState flowingLava = Blocks.LAVA.defaultBlockState().setValue(LiquidBlock.LEVEL, 1); + BlockPos lavaFlowStone = new BlockPos(11, 1, 1); + BlockPos lavaFlow = pour(helper, lavaFlowStone, flowingLava); + hold(player, jug); + clickThrough(helper, player, lavaFlowStone); + helper.assertBlockState(lavaFlow, flowingLava); + assertHeld(helper, player, Fluids.LAVA, volume, "flowing lava"); + + BlockPos free = new BlockPos(6, 4, 1); + helper.setBlock(free, Blocks.WATER); + hold(player, jug); + Vec3 freeCenter = helper.absoluteVec(new Vec3(free.getX() + 0.5, free.getY() + 0.5, free.getZ() + 0.5)); + placeEyes(player, freeCenter.add(0, 0, -2)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, freeCenter); + player.getMainHandItem().use(helper.getLevel(), player, InteractionHand.MAIN_HAND); + helper.assertBlockPresent(Blocks.WATER, free); + assertHeld(helper, player, Fluids.WATER, volume, "use"); + + BlockPos slabPos = new BlockPos(6, 1, 1); + helper.setBlock(slabPos, Blocks.STONE_SLAB.defaultBlockState().setValue(SlabBlock.WATERLOGGED, true)); + hold(player, jug); + Vec3 slabTop = helper.absoluteVec(new Vec3(slabPos.getX() + 0.2, slabPos.getY() + 0.5, slabPos.getZ() + 0.2)); + placeEyes(player, slabTop.add(0, 0, -1.5)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, slabTop); + player.getMainHandItem().useOn(new UseOnContext( + player, InteractionHand.MAIN_HAND, new BlockHitResult(slabTop, Direction.UP, helper.absolutePos(slabPos), false) + )); + helper.assertBlockProperty(slabPos, SlabBlock.WATERLOGGED, true); + helper.assertTrue(PotteryItem.contents(player.getMainHandItem()).isEmpty(), "waterlogged slab filled the jug"); + + BlockPos bubblePos = new BlockPos(6, 2, 5); + helper.setBlock(bubblePos, Blocks.BUBBLE_COLUMN.defaultBlockState()); + hold(player, jug); + Vec3 bubble = helper.absoluteVec(new Vec3(bubblePos.getX() + 0.5, bubblePos.getY() + 0.5, bubblePos.getZ() + 0.5)); + placeEyes(player, bubble.add(0, 0, -1.5)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, bubble); + player.getMainHandItem().useOn(new UseOnContext( + player, InteractionHand.MAIN_HAND, new BlockHitResult(bubble, Direction.SOUTH, helper.absolutePos(bubblePos), false) + )); + helper.assertBlockPresent(Blocks.BUBBLE_COLUMN, bubblePos); + helper.assertTrue(PotteryItem.contents(player.getMainHandItem()).isEmpty(), "bubble column filled the jug"); + + hold(player, Pottery.wheelShape()); + clickThrough(helper, player, waterStone); + helper.assertBlockState(water, Blocks.WATER.defaultBlockState()); + helper.assertTrue(PotteryItem.contents(player.getMainHandItem()).isEmpty(), "lump filled"); + List lumpLines = tooltip(player.getMainHandItem(), player); + helper.assertFalse(lumpLines.contains(Component.translatable("tooltip.primalpottery.capacity", 0)), "lump capacity"); + helper.assertFalse(lumpLines.stream().anyMatch(line -> line.getString().contains("mL")), "lump amount"); + + BlockPos sneakStone = new BlockPos(7, 1, 1); + BlockPos sneakWater = pour(helper, sneakStone, Blocks.WATER.defaultBlockState()); + hold(player, jug); + player.setShiftKeyDown(false); + clickThrough(helper, player, sneakStone); + assertHeld(helper, player, Fluids.WATER, volume, "jug for sneaking"); + player.setShiftKeyDown(true); + Vec3 sneakSurface = new Vec3(sneakStone.getX() + 0.2, sneakStone.getY() + 1, sneakStone.getZ() + 0.2); + placeEyes(player, helper.absoluteVec(sneakSurface.add(0, 0.5, -2))); + player.getMainHandItem().useOn(new UseOnContext( + player, + InteractionHand.MAIN_HAND, + new BlockHitResult(helper.absoluteVec(sneakSurface), Direction.UP, helper.absolutePos(sneakStone), false) + )); + player.setShiftKeyDown(false); + helper.assertBlockPresent(ModBlocks.POTTERY, sneakWater); + helper.assertBlockNotPresent(Blocks.WATER, sneakWater); + PotteryBlockEntity sneaked = helper.getBlockEntity(sneakWater, PotteryBlockEntity.class); + assertStored(helper, sneaked.contents(0), Fluids.WATER, volume, "sneak place"); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + player.setShiftKeyDown(true); + useItemOn(helper, player, sneakWater, slotPoint(sneakWater, 0), Direction.UP); + player.setShiftKeyDown(false); + assertFluid(helper, potteryItemNear(helper, sneakWater), Fluids.WATER, volume, "pickup"); + + BlockPos floor = new BlockPos(7, 1, 3); + helper.setBlock(floor, Blocks.STONE); + BlockPos pots = floor.above(); + hold(player, jug); + clickThrough(helper, player, waterStone); + assertHeld(helper, player, Fluids.WATER, volume, "water jug to place"); + clickOn(helper, player, floor, new Vec3(floor.getX() + 0.2, floor.getY() + 1, floor.getZ() + 0.2), Direction.UP); + helper.assertBlockPresent(ModBlocks.POTTERY, pots); + holdStack(player, lavaJug); + Vec3 secondSlot = new Vec3(pots.getX() + 0.8, pots.getY() + 1, pots.getZ() + 0.2); + clickOn(helper, player, pots, secondSlot, Direction.UP); + PotteryBlockEntity both = helper.getBlockEntity(pots, PotteryBlockEntity.class); + assertStored(helper, both.contents(0), Fluids.WATER, volume, "water slot"); + assertStored(helper, both.contents(1), Fluids.LAVA, volume, "lava slot"); + + BlockPos beside = pots.north(); + BlockState besideWater = Blocks.WATER.defaultBlockState(); + helper.setBlock(beside, besideWater); + hold(player, jug); + Vec3 slot = PotteryBlockEntity.BOXES.get(2).move(helper.absolutePos(pots)).getCenter(); + placeEyes(player, slot.add(1.5, 0, 0)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, slot); + player.getMainHandItem().useOn(new UseOnContext( + player, + InteractionHand.MAIN_HAND, + new BlockHitResult( + helper.absoluteVec(new Vec3(pots.getX() + 0.8, pots.getY() + 0.4, pots.getZ() + 0.8)), + Direction.NORTH, + helper.absolutePos(pots), + false + ) + )); + helper.assertBlockState(beside, besideWater); + helper.assertTrue(both.get(2) != null, "adjacent water blocked the merge"); + focusedPots(helper, player); + lidsAndBreaks(helper, player); + helper.succeed(); + } + + private static void lidsAndBreaks(GameTestHelper helper, Player player) { + ((ServerPlayer) player).setGameMode(GameType.SURVIVAL); + Pottery jug = jug(); + int volume = jug.classify().volume(); + + hold(player, jug); + Vec3 sky = helper.absoluteVec(new Vec3(0.5, 30, 0.5)); + placeEyes(player, sky); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, sky.add(0, 1, 0)); + InteractionResult used = player.getMainHandItem().getItem().use(helper.getLevel(), player, InteractionHand.MAIN_HAND); + helper.assertTrue(used == InteractionResult.SUCCESS, "air use " + used); + helper.assertTrue(PotteryItem.contents(player.getMainHandItem()).isEmpty(), "air use filled"); + helper.assertTrue(player.getMainHandItem().getCount() == 1, "air use consumed the jug"); + + hold(player, jug); + LidSync.apply(player, true, true); + helper.assertTrue(PotteryItem.lid(player.getMainHandItem()), "put lid"); + CompoundTag written = player.getMainHandItem().get(DataComponents.CUSTOM_DATA).copyTag(); + helper.assertTrue(written.contains("lid"), "lid key"); + LidSync.apply(player, true, false); + CompoundTag cleared = player.getMainHandItem().get(DataComponents.CUSTOM_DATA).copyTag(); + helper.assertFalse(cleared.contains("lid"), "take lid"); + helper.assertFalse(PotteryItem.lid(player.getMainHandItem()), "lid flag"); + + hold(player, Pottery.wheelShape()); + LidSync.apply(player, true, true); + helper.assertFalse(PotteryItem.lid(player.getMainHandItem()), "lump lid"); + + ItemStack lidded = PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, volume), true); + ItemStack open = PotteryItem.stack(jug); + BlockPos pots = placePair(helper, player, new BlockPos(10, 1, 1), lidded, open); + PotteryBlockEntity entity = helper.getBlockEntity(pots, PotteryBlockEntity.class); + helper.assertTrue(entity.lid(0), "placed lid"); + helper.assertFalse(entity.lid(1), "open neighbor"); + assertStored(helper, entity.contents(0), Fluids.WATER, volume, "lidded water"); + helper.assertTrue(entity.contents(1).isEmpty(), "open neighbor holds fluid"); + + CompoundTag saved = entity.saveCustomOnly(helper.getLevel().registryAccess()); + PotteryBlockEntity loaded = new PotteryBlockEntity(entity.getBlockPos(), entity.getBlockState()); + loaded.loadCustomOnly(TagValueInput.create( + ProblemReporter.DISCARDING, helper.getLevel().registryAccess(), saved + )); + helper.assertTrue(loaded.lid(0) && !loaded.lid(1), "saved lids"); + helper.assertTrue(loaded.get(0) != null && loaded.get(1) != null, "saved pots"); + assertStored(helper, loaded.contents(0), Fluids.WATER, volume, "saved water"); + + BlockPos absolute = helper.absolutePos(pots); + PlacedLidSync.apply(player, absolute, 0, false); + helper.assertFalse(entity.lid(0), "take placed lid"); + helper.assertFalse(entity.lid(1), "neighbor gained a lid"); + CompoundTag placedCleared = entity.saveCustomOnly(helper.getLevel().registryAccess()); + CompoundTag taken = Nbt.compoundAt(Nbt.list(Nbt.compound(placedCleared, "pottery"), "slots"), 0); + helper.assertFalse(taken.contains("lid"), "lid key"); + PlacedLidSync.apply(player, absolute, 0, true); + helper.assertTrue(entity.lid(0) && !entity.lid(1), "put placed lid"); + + BlockPos lumpFloor = new BlockPos(12, 1, 6); + helper.setBlock(lumpFloor, Blocks.STONE); + hold(player, Pottery.wheelShape()); + useItemOn(helper, player, lumpFloor, topPoint(lumpFloor, 0), Direction.UP); + BlockPos lumpPos = lumpFloor.above(); + helper.assertBlockPresent(ModBlocks.POTTERY, lumpPos); + PotteryBlockEntity lump = helper.getBlockEntity(lumpPos, PotteryBlockEntity.class); + PlacedLidSync.apply(player, helper.absolutePos(lumpPos), 0, true); + helper.assertFalse(lump.lid(0), "lump lid"); + helper.assertTrue(lump.get(0) != null, "lump was removed"); + + BlockState state = helper.getBlockState(pots); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + float progress = state.getDestroyProgress(player, helper.getLevel(), absolute); + helper.assertTrue(progress > 0.0F && progress < 1.0F, "destroy progress " + progress); + // The two-argument getCollisionShape returns the shape cached at startup, which is empty + // because no pot exists then. The block methods are what the outline and entity collision use. + assertFootprint(helper, pots, 0, 1); + + Vec3 gap = helper.absoluteVec(new Vec3(pots.getX() + 0.5, pots.getY() + 0.2, pots.getZ() + 0.5)); + placeEyes(player, gap.add(0, 2, 0)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, gap); + ((ServerPlayer) player).gameMode.destroyBlock(absolute); + helper.assertTrue(entity.get(0) != null && entity.get(1) != null, "a miss removed a pot"); + helper.assertBlockPresent(ModBlocks.POTTERY, pots); + + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + clearPottery(helper); + player.setShiftKeyDown(true); + useItemOn(helper, player, pots, slotPoint(pots, 1), Direction.UP); + player.setShiftKeyDown(false); + ItemStack picked = potteryItemNear(helper, pots); + helper.assertFalse(PotteryItem.lid(picked), "picked the lidded pot"); + helper.assertTrue(PotteryItem.contents(picked).isEmpty(), "picked the water"); + helper.assertTrue(entity.get(0) != null && entity.lid(0), "aimed pickup took the other pot"); + helper.assertTrue(entity.get(1) == null, "aimed pickup missed"); + + holdStack(player, open.copy()); + clickOn(helper, player, pots, new Vec3(pots.getX() + 0.8, pots.getY() + 1, pots.getZ() + 0.2), Direction.UP); + helper.assertTrue(entity.get(1) != null && !entity.lid(1), "neighbor replaced"); + + clearPottery(helper); + aim(player, PotteryBlockEntity.BOXES.get(0).move(absolute).getCenter()); + ((ServerPlayer) player).gameMode.destroyBlock(absolute); + var drops = helper.getLevel().getEntitiesOfClass( + ItemEntity.class, + new AABB(absolute).inflate(2), + dropped -> dropped.getItem().is(ModItems.POTTERY) + ); + helper.assertValueEqual(drops.size(), 1, "break drops"); + ItemStack broken = drops.getFirst().getItem(); + helper.assertTrue(PotteryItem.lid(broken), "break dropped the lid"); + assertFluid(helper, broken, Fluids.WATER, volume, "break"); + helper.assertValueEqual(PotteryItem.read(broken).discs(), jug.discs(), "break profile"); + helper.assertTrue(entity.get(0) == null, "break removed both"); + helper.assertTrue(entity.get(1) != null && !entity.lid(1), "neighbor survived"); + helper.assertBlockPresent(ModBlocks.POTTERY, pots); + + clearPottery(helper); + aim(player, PotteryBlockEntity.BOXES.get(1).move(absolute).getCenter()); + ((ServerPlayer) player).gameMode.destroyBlock(absolute); + helper.assertBlockNotPresent(ModBlocks.POTTERY, pots); + + ((ServerPlayer) player).setGameMode(GameType.SURVIVAL); + BlockPos creativePots = placePair(helper, player, new BlockPos(10, 1, 4), lidded, open); + ((ServerPlayer) player).setGameMode(GameType.CREATIVE); + clearPottery(helper); + BlockPos creativeAbsolute = helper.absolutePos(creativePots); + aim(player, PotteryBlockEntity.BOXES.get(0).move(creativeAbsolute).getCenter()); + ((ServerPlayer) player).gameMode.destroyBlock(creativeAbsolute); + PotteryBlockEntity creativeEntity = helper.getBlockEntity(creativePots, PotteryBlockEntity.class); + helper.assertTrue(creativeEntity.get(0) == null, "creative removed both"); + helper.assertTrue(creativeEntity.get(1) != null, "creative removed the neighbor"); + helper.assertBlockPresent(ModBlocks.POTTERY, creativePots); + var leftover = helper.getLevel().getEntitiesOfClass( + ItemEntity.class, + new AABB(creativeAbsolute).inflate(2), + dropped -> dropped.getItem().is(ModItems.POTTERY) + ); + helper.assertTrue(leftover.isEmpty(), "creative dropped a pot"); + ((ServerPlayer) player).setGameMode(GameType.SURVIVAL); + } + + private static BlockPos placePair(GameTestHelper helper, Player player, BlockPos floor, ItemStack first, ItemStack second) { + helper.setBlock(floor, Blocks.STONE); + holdStack(player, first.copy()); + clickOn(helper, player, floor, new Vec3(floor.getX() + 0.2, floor.getY() + 1, floor.getZ() + 0.2), Direction.UP); + BlockPos pots = floor.above(); + helper.assertBlockPresent(ModBlocks.POTTERY, pots); + holdStack(player, second.copy()); + clickOn(helper, player, pots, new Vec3(pots.getX() + 0.8, pots.getY() + 1, pots.getZ() + 0.2), Direction.UP); + PotteryBlockEntity placed = helper.getBlockEntity(pots, PotteryBlockEntity.class); + helper.assertTrue(placed.get(0) != null && placed.get(1) != null, "pair was not placed"); + return pots; + } + + private static void clearPottery(GameTestHelper helper) { + // The empty structure is small. Pots placed at relative x=10 sit outside bounds.inflate(8), + // so a pickup drop there survived and was counted as the break drop. + BlockPos min = helper.absolutePos(BlockPos.ZERO); + BlockPos max = helper.absolutePos(new BlockPos(16, 8, 16)); + AABB box = new AABB(min.getX() - 2, min.getY() - 2, min.getZ() - 2, max.getX() + 2, max.getY() + 2, max.getZ() + 2); + helper.getLevel().getEntitiesOfClass( + ItemEntity.class, + box, + entity -> entity.getItem().is(ModItems.POTTERY) + ).forEach(ItemEntity::discard); + } + + private static boolean coloredLine(List lines, String text, int color) { + for (Component line : lines) { + if (styledText(line, text, color)) { + return true; + } + } + return false; + } + + private static boolean plainLine(List lines, String text) { + for (Component line : lines) { + if (styledText(line, text, -1)) { + return true; + } + } + return false; + } + + private static boolean styledText(Component component, String text, int color) { + boolean colorMatches = color < 0 + ? component.getStyle().getColor() == null + : component.getStyle().getColor() != null && component.getStyle().getColor().getValue() == color; + if (component instanceof MutableComponent && component.getString().equals(text) && colorMatches) { + return true; + } + for (Component sibling : component.getSiblings()) { + if (styledText(sibling, text, color)) { + return true; + } + } + if (component.getContents() instanceof net.minecraft.network.chat.contents.TranslatableContents contents) { + for (Object argument : contents.getArgs()) { + if (argument instanceof Component child && styledText(child, text, color)) { + return true; + } + } + } + return false; + } + + private static Player mockPlayer(GameTestHelper helper) { + return helper.makeMockServerPlayerInLevel(); + } + + private static Pottery jug() { + return new Pottery(List.of( + new PotteryDisc(1, 4, 1), + new PotteryDisc(2, 5, 3), + new PotteryDisc(1, 5, 0) + )); + } + + private static BlockPos pour(GameTestHelper helper, BlockPos solid, BlockState fluid) { + helper.setBlock(solid, Blocks.STONE); + BlockPos cell = solid.above(); + helper.setBlock(cell, fluid); + return cell; + } + + private static void hold(Player player, Pottery pottery) { + holdStack(player, PotteryItem.stack(pottery)); + } + + private static void holdStack(Player player, ItemStack stack) { + player.setShiftKeyDown(false); + player.setItemInHand(InteractionHand.MAIN_HAND, stack); + } + + private static void clickThrough(GameTestHelper helper, Player player, BlockPos solid) { + clickOn(helper, player, solid, new Vec3(solid.getX() + 0.2, solid.getY() + 1, solid.getZ() + 0.2), Direction.UP); + } + + private static void clickOn(GameTestHelper helper, Player player, BlockPos block, Vec3 at, Direction face) { + Vec3 absolute = helper.absoluteVec(at); + placeEyes(player, absolute.add(0, 0.5, -2)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, absolute); + player.getMainHandItem().useOn(new UseOnContext( + player, InteractionHand.MAIN_HAND, new BlockHitResult(absolute, face, helper.absolutePos(block), false) + )); + } + + private static InteractionResult useItemOn(GameTestHelper helper, Player player, BlockPos block, Vec3 at, Direction face) { + ServerPlayer server = (ServerPlayer) player; + Vec3 absolute = helper.absoluteVec(at); + placeEyes(player, absolute.add(0, 0.5, -2)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, absolute); + return server.gameMode.useItemOn( + server, + helper.getLevel(), + player.getItemInHand(InteractionHand.MAIN_HAND), + InteractionHand.MAIN_HAND, + new BlockHitResult(absolute, face, helper.absolutePos(block), false) + ); + } + + private static Vec3 slotPoint(BlockPos relative, int slot) { + Vec3 center = PotteryBlockEntity.box(slot).getCenter(); + return new Vec3(relative.getX() + center.x, relative.getY() + center.y, relative.getZ() + center.z); + } + + private static Vec3 topPoint(BlockPos floor, int slot) { + Vec3 center = PotteryBlockEntity.box(slot).getCenter(); + return new Vec3(floor.getX() + center.x, floor.getY() + 1, floor.getZ() + center.z); + } + + private static void assertFootprint(GameTestHelper helper, BlockPos relative, int... occupied) { + BlockPos absolute = helper.absolutePos(relative); + BlockState state = helper.getBlockState(relative); + CollisionContext context = CollisionContext.empty(); + var shape = state.getShape(helper.getLevel(), absolute, context); + var collision = state.getCollisionShape(helper.getLevel(), absolute, context); + for (int index = 0; index < PotteryBlockEntity.SLOTS; index++) { + var box = Shapes.create(PotteryBlockEntity.box(index)); + helper.assertFalse(Shapes.joinIsNotEmpty(shape, box, BooleanOp.ONLY_SECOND), "outline missing " + index); + boolean filled = false; + for (int slot : occupied) { + if (slot == index) { + filled = true; + break; + } + } + helper.assertTrue(Shapes.joinIsNotEmpty(collision, box, BooleanOp.AND) == filled, "collision slot " + index); + } + } + + private static void assertNoPottery(GameTestHelper helper, BlockPos relative, String label) { + var drops = helper.getLevel().getEntitiesOfClass( + ItemEntity.class, + new AABB(helper.absolutePos(relative)).inflate(2), + entity -> entity.getItem().is(ModItems.POTTERY) + ); + helper.assertTrue(drops.isEmpty(), label); + } + + private static void focusedPots(GameTestHelper helper, Player player) { + ((ServerPlayer) player).setGameMode(GameType.SURVIVAL); + player.setShiftKeyDown(false); + Pottery jug = jug(); + int volume = jug.classify().volume(); + helper.assertValueEqual(volume, 54, "jug volume"); + + BlockPos floor = new BlockPos(1, 1, 10); + helper.setBlock(floor, Blocks.STONE); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 10))); + useItemOn(helper, player, floor, topPoint(floor, 3), Direction.UP); + BlockPos pots = floor.above(); + helper.assertBlockPresent(ModBlocks.POTTERY, pots); + helper.assertBlockNotPresent(ModBlocks.POTTERY, pots.above()); + helper.assertBlockNotPresent(ModBlocks.POTTERY, pots.north()); + PotteryBlockEntity entity = helper.getBlockEntity(pots, PotteryBlockEntity.class); + helper.assertTrue(entity.get(3) != null && entity.get(0) == null, "far column slot"); + assertStored(helper, entity.contents(3), Fluids.WATER, 10, "far slot"); + assertFootprint(helper, pots, 3); + + clearPottery(helper); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + useItemOn(helper, player, pots, slotPoint(pots, 3), Direction.UP); + assertNoPottery(helper, pots, "empty click dropped a pot"); + assertStored(helper, entity.contents(3), Fluids.WATER, 10, "empty click"); + helper.assertTrue(entity.get(0) == null, "empty click filled the front slot"); + + clearPottery(helper); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + player.setShiftKeyDown(true); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + player.setShiftKeyDown(false); + assertNoPottery(helper, pots, "shift on an empty box dropped a pot"); + helper.assertTrue(entity.get(3) != null && entity.get(0) == null, "shift on an empty box removed the far pot"); + assertStored(helper, entity.contents(3), Fluids.WATER, 10, "empty box shift"); + + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.LAVA, 20))); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + helper.assertTrue(entity.get(0) != null, "front slot stayed empty"); + assertStored(helper, entity.contents(0), Fluids.LAVA, 20, "front slot"); + assertStored(helper, entity.contents(3), Fluids.WATER, 10, "far slot changed"); + helper.assertBlockNotPresent(ModBlocks.POTTERY, pots.above()); + helper.assertTrue(player.getMainHandItem().isEmpty(), "filled vessel was not placed"); + + hold(player, jug); + useItemOn(helper, player, pots, slotPoint(pots, 1), Direction.UP); + hold(player, jug); + useItemOn(helper, player, pots, slotPoint(pots, 2), Direction.UP); + helper.assertTrue(entity.get(1) != null && entity.get(2) != null, "side slots"); + assertStored(helper, entity.contents(0), Fluids.LAVA, 20, "front slot after fill"); + assertStored(helper, entity.contents(3), Fluids.WATER, 10, "far slot after fill"); + assertFootprint(helper, pots, 0, 1, 2, 3); + + hold(player, jug); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + helper.assertTrue(player.getMainHandItem().is(ModItems.POTTERY), "fifth click placed the jug"); + helper.assertValueEqual(player.getMainHandItem().getCount(), 1, "fifth click consumed the jug"); + helper.assertTrue(PotteryItem.contents(player.getMainHandItem()).isEmpty(), "fifth click poured"); + assertStored(helper, entity.contents(0), Fluids.LAVA, 20, "fifth click changed the front slot"); + assertStored(helper, entity.contents(3), Fluids.WATER, 10, "fifth click changed the far slot"); + helper.assertBlockNotPresent(ModBlocks.POTTERY, pots.above()); + helper.assertBlockNotPresent(ModBlocks.POTTERY, pots.north()); + for (int index = 0; index < PotteryBlockEntity.SLOTS; index++) { + helper.assertTrue(entity.get(index) != null, "slot " + index + " emptied"); + } + + pourAndBuckets(helper, player, jug, volume); + focusedBreaks(helper, player, jug); + player.setShiftKeyDown(false); + } + + private static void pourAndBuckets(GameTestHelper helper, Player player, Pottery jug, int volume) { + BlockPos floor = new BlockPos(4, 1, 10); + helper.setBlock(floor, Blocks.STONE); + hold(player, jug); + useItemOn(helper, player, floor, topPoint(floor, 0), Direction.UP); + BlockPos pots = floor.above(); + PotteryBlockEntity entity = helper.getBlockEntity(pots, PotteryBlockEntity.class); + helper.assertTrue(entity.contents(0).isEmpty(), "placed jug was not empty"); + helper.assertBlockProperty(pots, PotteryBlock.LIGHT, 0); + + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20), true)); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + helper.assertTrue(entity.contents(0).isEmpty(), "lidded jug poured"); + assertFluid(helper, player.getMainHandItem(), Fluids.WATER, 20, "lidded jug lost fluid"); + helper.assertTrue(PotteryItem.lid(player.getMainHandItem()), "pour removed the lid"); + helper.assertBlockProperty(pots, PotteryBlock.LIGHT, 0); + + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20))); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + assertStored(helper, entity.contents(0), Fluids.WATER, 20, "poured twenty"); + helper.assertTrue(PotteryItem.contents(player.getMainHandItem()).isEmpty(), "held fluid remained"); + helper.assertValueEqual(PotteryItem.read(player.getMainHandItem()).discs(), jug.discs(), "held profile"); + helper.assertValueEqual(player.getMainHandItem().getCount(), 1, "pour shrank the jug"); + helper.assertFalse(entity.lid(0), "pour closed the pot"); + helper.assertBlockProperty(pots, PotteryBlock.LIGHT, 0); + + entity.setContents(0, VesselContents.of(Fluids.WATER, 10)); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 100))); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + assertStored(helper, entity.contents(0), Fluids.WATER, volume, "poured the room"); + assertFluid(helper, player.getMainHandItem(), Fluids.WATER, 56, "remainder"); + helper.assertFalse(PotteryItem.lid(player.getMainHandItem()), "remainder gained a lid"); + helper.assertValueEqual(PotteryItem.read(player.getMainHandItem()).discs(), jug.discs(), "remainder profile"); + helper.assertValueEqual(player.getMainHandItem().getCount(), 1, "remainder count"); + + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20), true)); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + assertStored(helper, entity.contents(0), Fluids.WATER, volume, "full pot"); + assertFluid(helper, player.getMainHandItem(), Fluids.WATER, 20, "full pot took fluid"); + helper.assertTrue(PotteryItem.lid(player.getMainHandItem()), "full pot cleared the held lid"); + + entity.setLid(0, true); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20))); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + assertStored(helper, entity.contents(0), Fluids.WATER, volume, "lidded pot"); + helper.assertTrue(entity.lid(0), "pour opened the lid"); + assertFluid(helper, player.getMainHandItem(), Fluids.WATER, 20, "lidded pot took fluid"); + + hold(player, Pottery.wheelShape()); + useItemOn(helper, player, pots, slotPoint(pots, 1), Direction.UP); + helper.assertTrue(entity.get(1) != null, "lump was not placed"); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20))); + useItemOn(helper, player, pots, slotPoint(pots, 1), Direction.UP); + helper.assertTrue(entity.contents(1).isEmpty(), "lump took fluid"); + helper.assertFalse(entity.lid(1), "lump closed"); + assertFluid(helper, player.getMainHandItem(), Fluids.WATER, 20, "lump pour"); + + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.LAVA, 10))); + useItemOn(helper, player, pots, slotPoint(pots, 2), Direction.UP); + assertStored(helper, entity.contents(2), Fluids.LAVA, 10, "lava pot"); + helper.assertFalse(entity.lid(2), "lava pot closed itself"); + helper.assertBlockProperty(pots, PotteryBlock.LIGHT, 15); + entity.setLid(2, true); + helper.assertBlockProperty(pots, PotteryBlock.LIGHT, 0); + entity.setLid(2, false); + helper.assertBlockProperty(pots, PotteryBlock.LIGHT, 15); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20))); + useItemOn(helper, player, pots, slotPoint(pots, 2), Direction.UP); + assertStored(helper, entity.contents(2), Fluids.LAVA, 10, "mixed fluids"); + assertFluid(helper, player.getMainHandItem(), Fluids.WATER, 20, "mixed pour"); + + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 40), true)); + player.setShiftKeyDown(true); + useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + player.setShiftKeyDown(false); + assertStored(helper, entity.contents(0), Fluids.WATER, volume, "sneak poured"); + helper.assertTrue(entity.lid(0), "sneak opened the lid"); + helper.assertTrue(entity.get(3) != null, "sneak did not place"); + assertStored(helper, entity.contents(3), Fluids.WATER, 40, "sneak place"); + helper.assertTrue(entity.lid(3), "sneak dropped the lid"); + helper.assertTrue(player.getMainHandItem().isEmpty(), "sneak kept the jug"); + + VesselContents kept = entity.contents(0); + boolean keptLid = entity.lid(0); + // 26.3 BucketItem places and picks up in Item.use. The client calls that after a block click that does not consume. + bucketClick(helper, player, pots, entity, Items.BUCKET, kept, keptLid, "empty bucket"); + bucketClick(helper, player, pots, entity, Items.WATER_BUCKET, kept, keptLid, "water bucket"); + bucketClick(helper, player, pots, entity, Items.LAVA_BUCKET, kept, keptLid, "lava bucket"); + } + + private static void bucketClick( + GameTestHelper helper, + Player player, + BlockPos pots, + PotteryBlockEntity entity, + Item item, + VesselContents kept, + boolean keptLid, + String label + ) { + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(item)); + InteractionResult clicked = useItemOn(helper, player, pots, slotPoint(pots, 0), Direction.UP); + helper.assertFalse(clicked.consumesAction(), label + " opened the pot"); + ItemStack hand = player.getMainHandItem(); + if (!hand.isEmpty()) { + hand.getItem().use(helper.getLevel(), player, InteractionHand.MAIN_HAND); + } + helper.assertBlockPresent(ModBlocks.POTTERY, pots); + helper.assertTrue(entity.get(0) != null, label + " removed the pot"); + assertStored(helper, entity.contents(0), kept.fluid(), kept.amount(), label); + helper.assertTrue(entity.lid(0) == keptLid, label + " changed the lid"); + } + + private static void focusedBreaks(GameTestHelper helper, Player player, Pottery jug) { + ((ServerPlayer) player).setGameMode(GameType.SURVIVAL); + BlockPos floor = new BlockPos(8, 1, 10); + helper.setBlock(floor, Blocks.STONE); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20), true)); + useItemOn(helper, player, floor, topPoint(floor, 0), Direction.UP); + BlockPos pots = floor.above(); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.LAVA, 5))); + useItemOn(helper, player, pots, slotPoint(pots, 1), Direction.UP); + PotteryBlockEntity entity = helper.getBlockEntity(pots, PotteryBlockEntity.class); + helper.assertTrue(entity.lid(0) && !entity.lid(1), "break setup lids"); + assertStored(helper, entity.contents(1), Fluids.LAVA, 5, "pot B"); + + clearPottery(helper); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + BlockPos absolute = helper.absolutePos(pots); + aim(player, PotteryBlockEntity.BOXES.get(0).move(absolute).getCenter()); + ((ServerPlayer) player).gameMode.destroyBlock(absolute); + var drops = helper.getLevel().getEntitiesOfClass( + ItemEntity.class, + new AABB(absolute).inflate(2), + dropped -> dropped.getItem().is(ModItems.POTTERY) + ); + helper.assertValueEqual(drops.size(), 1, "focused break drops"); + ItemStack broken = drops.getFirst().getItem(); + helper.assertTrue(PotteryItem.lid(broken), "break dropped A's lid"); + assertFluid(helper, broken, Fluids.WATER, 20, "break A"); + helper.assertTrue(entity.get(0) == null, "break left A"); + helper.assertTrue(entity.get(1) != null, "break removed B"); + assertStored(helper, entity.contents(1), Fluids.LAVA, 5, "pot B after break"); + helper.assertBlockPresent(ModBlocks.POTTERY, pots); + + BlockPos behindFloor = new BlockPos(11, 1, 10); + helper.setBlock(behindFloor, Blocks.STONE); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.WATER, 20), true)); + useItemOn(helper, player, behindFloor, topPoint(behindFloor, 3), Direction.UP); + BlockPos behind = behindFloor.above(); + holdStack(player, PotteryItem.stack(jug, VesselContents.of(Fluids.LAVA, 5))); + useItemOn(helper, player, behind, slotPoint(behind, 1), Direction.UP); + PotteryBlockEntity column = helper.getBlockEntity(behind, PotteryBlockEntity.class); + helper.assertTrue(column.get(0) == null && column.get(3) != null && column.get(1) != null, "empty front"); + + clearPottery(helper); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + BlockPos behindAbsolute = helper.absolutePos(behind); + Vec3 front = PotteryBlockEntity.BOXES.get(0).move(behindAbsolute).getCenter(); + Vec3 far = PotteryBlockEntity.BOXES.get(3).move(behindAbsolute).getCenter(); + placeEyes(player, front.add(0, 0, -1)); + player.lookAt(net.minecraft.commands.arguments.EntityAnchorArgument.Anchor.EYES, far); + ((ServerPlayer) player).gameMode.destroyBlock(behindAbsolute); + assertNoPottery(helper, behind, "empty box in front dropped a pot"); + helper.assertTrue(column.get(3) != null && column.get(1) != null, "empty box in front removed a pot"); + helper.assertTrue(column.lid(3), "empty box in front took the lid"); + assertStored(helper, column.contents(3), Fluids.WATER, 20, "far pot"); + assertStored(helper, column.contents(1), Fluids.LAVA, 5, "side pot"); + helper.assertBlockPresent(ModBlocks.POTTERY, behind); + } + + private static void assertHeld(GameTestHelper helper, Player player, Fluid fluid, int amount, String label) { + assertFluid(helper, player.getMainHandItem(), fluid, amount, label); + } + + private static void assertFluid(GameTestHelper helper, ItemStack stack, Fluid fluid, int amount, String label) { + VesselContents contents = PotteryItem.contents(stack); + helper.assertTrue(contents.fluid() == fluid, label + " stored " + BuiltInRegistries.FLUID.getKey(contents.fluid())); + helper.assertValueEqual(contents.amount(), amount, label + " amount"); + } + + private static void assertStored(GameTestHelper helper, VesselContents contents, Fluid fluid, int amount, String label) { + helper.assertTrue(contents.fluid() == fluid, label + " stored " + BuiltInRegistries.FLUID.getKey(contents.fluid())); + helper.assertValueEqual(contents.amount(), amount, label + " amount"); + } + + private static List tooltip(ItemStack stack, Player player) { + return stack.getTooltipLines(Item.TooltipContext.EMPTY, player, TooltipFlag.Default.NORMAL); + } + + private static final class Vessels extends GameTestInstance { + private static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( + TestData.CODEC.forGetter(Vessels::data) + ).apply(instance, Vessels::new)); + + private Vessels(TestData>> data) { + super(data); + } + + private TestData>> data() { + return this.info(); + } + + @Override + public void run(GameTestHelper helper) { + vessels(helper); + } + + @Override + public MapCodec codec() { + return CODEC; + } + + @Override + protected MutableComponent typeDescription() { + return Component.literal("vessels"); + } + } + private static final class Wheel extends GameTestInstance { private static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( TestData.CODEC.forGetter(Wheel::data) diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/block/ModBlocks.java b/src/main/java/net/modcrafters/minecraft/primalpottery/block/ModBlocks.java index 722dc73..9c073a8 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/block/ModBlocks.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/block/ModBlocks.java @@ -27,8 +27,9 @@ public final class ModBlocks { public static final PotteryBlock POTTERY = new PotteryBlock(properties(POTTERY_ID) .mapColor(MapColor.TERRACOTTA_RED) .sound(SoundType.DECORATED_POT) - .strength(-1.0F, 3600000.0F) - .noOcclusion()); + .strength(0.5F, 3600000.0F) + .noOcclusion() + .lightLevel(state -> state.getValue(PotteryBlock.LIGHT))); private ModBlocks() { } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java index 6cf5b2e..9bfc3f3 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlock.java @@ -2,12 +2,14 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.component.DataComponents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; @@ -16,30 +18,39 @@ import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.AABB; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; +import net.modcrafters.minecraft.primalpottery.client.PotteryScreen; import net.modcrafters.minecraft.primalpottery.item.PotteryItem; import net.modcrafters.minecraft.primalpottery.pottery.PartHits; import net.modcrafters.minecraft.primalpottery.pottery.Placement; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.VesselContents; import org.jspecify.annotations.Nullable; public class PotteryBlock extends Block implements EntityBlock { - private static final VoxelShape BASE = Shapes.box(0, 0, 0, 1, PotteryBlockEntity.SIZE / 32.0, 1); + public static final IntegerProperty LIGHT = IntegerProperty.create("light", 0, 15); private static final VoxelShape[] PARTS = parts(); private static final VoxelShape[] OCCUPIED = occupied(); + private static final VoxelShape FOOTPRINT = OCCUPIED[(1 << PotteryBlockEntity.SLOTS) - 1]; public PotteryBlock(Properties properties) { super(properties); + this.registerDefaultState(this.stateDefinition.any().setValue(LIGHT, 0)); + } + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(LIGHT); } @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return BASE; + return FOOTPRINT; } @Override @@ -59,55 +70,27 @@ protected boolean propagatesSkylightDown(BlockState state, BlockGetter level, Bl } *///?} - //? if neoforge { - /*//? if >=26.1 { - @Override - public boolean onDestroyedByPlayer( - BlockState state, - Level level, - BlockPos pos, - Player player, - ItemStack tool, - boolean willHarvest, - net.minecraft.world.level.material.FluidState fluid - ) { - if (breakFocused(level, pos, player)) { - return false; - } - return super.onDestroyedByPlayer(state, level, pos, player, tool, willHarvest, fluid); - } - //?} else { - /^@Override - public boolean onDestroyedByPlayer( - BlockState state, - Level level, - BlockPos pos, - Player player, - boolean willHarvest, - net.minecraft.world.level.material.FluidState fluid - ) { - if (breakFocused(level, pos, player)) { - return false; - } - return super.onDestroyedByPlayer(state, level, pos, player, willHarvest, fluid); - } - ^///?} - *///?} - public static boolean breakFocused(Level level, BlockPos pos, Player player) { if (!(level.getBlockEntity(pos) instanceof PotteryBlockEntity pottery)) { return false; } - int part = aimedPart(level, pos, player, aimedClick(pos, player)); - Pottery taken = part < 0 ? null : pottery.get(part); - if (taken == null) { + int part = PartHits.nearest( + PotteryBlockEntity.BOXES, + pos, + player.getEyePosition(), + Placement.reachEnd(player) + ); + if (part < 0 || pottery.get(part) == null) { return true; } + Pottery taken = pottery.get(part); + VesselContents contents = pottery.contents(part); + boolean lid = pottery.lid(part); BlockState state = level.getBlockState(pos); pottery.take(part); if (!level.isClientSide()) { if (!player.hasInfiniteMaterials()) { - popResource(level, pos, PotteryItem.stack(taken)); + popResource(level, pos, PotteryItem.stack(taken, contents, lid)); } level.levelEvent(2001, pos, Block.getId(state)); } @@ -143,6 +126,9 @@ public net.minecraft.world.ItemInteractionResult useItemOn( if (result.consumesAction()) { return net.minecraft.world.ItemInteractionResult.SUCCESS; } + if (!stack.isEmpty()) { + return net.minecraft.world.ItemInteractionResult.SKIP_DEFAULT_BLOCK_INTERACTION; + } return net.minecraft.world.ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } *///?} @@ -163,7 +149,7 @@ public static InteractionResult tryPlace( return InteractionResult.FAIL; } if (!level.isClientSide()) { - if (!pottery.put(target, PotteryItem.read(stack))) { + if (!pottery.put(target, PotteryItem.read(stack), PotteryItem.contents(stack), PotteryItem.lid(stack))) { return InteractionResult.FAIL; } level.playSound(null, pos, SoundType.DECORATED_POT.getPlaceSound(), SoundSource.BLOCKS, 1, 0.8F); @@ -178,19 +164,63 @@ private static InteractionResult interact(Level level, BlockPos pos, Player play if (!(level.getBlockEntity(pos) instanceof PotteryBlockEntity pottery)) { return InteractionResult.PASS; } - int part = aimedPart(level, pos, player, hit.getLocation()); - if (!player.isShiftKeyDown() && pottery.get(part) != null) { - Pottery taken = pottery.get(part); - if (!level.isClientSide()) { - pottery.take(part); - level.addFreshEntity(new ItemEntity(level, pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, PotteryItem.stack(taken))); + int part = PartHits.quadrant(pos, hit.getLocation()); + if (stack.isEmpty()) { + if (pottery.get(part) == null) { + return InteractionResult.PASS; + } + if (player.isShiftKeyDown()) { + if (!level.isClientSide()) { + Pottery taken = pottery.get(part); + VesselContents contents = pottery.contents(part); + boolean lid = pottery.lid(part); + pottery.take(part); + level.addFreshEntity(new ItemEntity( + level, pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, PotteryItem.stack(taken, contents, lid) + )); + } + return InteractionResult.SUCCESS; + } + if (level.isClientSide()) { + PotteryScreen.open(level, pos, part); } return InteractionResult.SUCCESS; } - if (!Placement.holding(stack)) { - return InteractionResult.PASS; + if (Placement.holding(stack) && !PotteryItem.contents(stack).isEmpty() && !player.isShiftKeyDown() && pottery.get(part) != null) { + pour(level, pos, stack, pottery, part); + return InteractionResult.SUCCESS; + } + if (Placement.holding(stack)) { + return tryPlace(level, pos, player, stack, part, player.isShiftKeyDown(), hit.getDirection()); } - return tryPlace(level, pos, player, stack, part, player.isShiftKeyDown(), hit.getDirection()); + return InteractionResult.PASS; + } + + private static void pour(Level level, BlockPos pos, ItemStack stack, PotteryBlockEntity pottery, int part) { + if (level.isClientSide()) { + return; + } + Pottery pot = pottery.get(part); + if (pot == null || pottery.lid(part) || PotteryItem.lid(stack)) { + return; + } + Pottery.Info info = pot.classify(); + if (!info.type().isVessel() || info.volume() <= 0) { + return; + } + VesselContents held = PotteryItem.contents(stack); + VesselContents stored = pottery.contents(part); + int moved = VesselContents.poured(held, stored, info.volume()); + if (moved <= 0) { + return; + } + int storedAmount = stored.isEmpty() ? 0 : stored.amount(); + pottery.setContents(part, VesselContents.of(held.fluid(), storedAmount + moved)); + int left = held.amount() - moved; + VesselContents remainder = left > 0 ? VesselContents.of(held.fluid(), left) : VesselContents.EMPTY; + CustomData.update(DataComponents.CUSTOM_DATA, stack, remainder::write); + held.fluid().getPickupSound().ifPresent(sound -> + level.playSound(null, pos, sound, SoundSource.BLOCKS, 1.0F, 1.0F)); } private static VoxelShape occupied(BlockGetter level, BlockPos pos) { @@ -206,29 +236,6 @@ private static VoxelShape occupied(BlockGetter level, BlockPos pos) { return OCCUPIED[mask]; } - public static int aimedPart(Level level, BlockPos pos, @Nullable Player player, Vec3 click) { - if (player != null && level.getBlockEntity(pos) instanceof PotteryBlockEntity pottery) { - int pot = PartHits.nearest( - PotteryBlockEntity.BOXES, - pos, - player.getEyePosition(), - Placement.reachEnd(player), - index -> pottery.get(index) != null - ); - if (pot >= 0) { - return pot; - } - } - return PartHits.quadrant(pos, click); - } - - private static Vec3 aimedClick(BlockPos pos, Player player) { - Vec3 from = player.getEyePosition(); - Vec3 to = Placement.reachEnd(player); - AABB base = new AABB(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + PotteryBlockEntity.SIZE / 32.0, pos.getZ() + 1); - return base.clip(from, to).orElse(from); - } - private static VoxelShape[] parts() { VoxelShape[] shapes = new VoxelShape[PotteryBlockEntity.SLOTS]; for (int index = 0; index < shapes.length; index++) { diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java index 9cf71e0..77a6652 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java @@ -16,6 +16,7 @@ import net.modcrafters.minecraft.primalpottery.item.PotteryItem; import net.modcrafters.minecraft.primalpottery.pottery.Nbt; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.VesselContents; import org.jspecify.annotations.Nullable; public class PotteryBlockEntity extends BlockEntity { @@ -25,6 +26,8 @@ public class PotteryBlockEntity extends BlockEntity { public static final List BOXES = List.of(box(0), box(1), box(2), box(3)); private final Pottery[] slots = new Pottery[SLOTS]; + private final VesselContents[] contents = blank(); + private final boolean[] lids = new boolean[SLOTS]; public PotteryBlockEntity(BlockPos pos, BlockState state) { super(ModBlockEntities.POTTERY, pos, state); @@ -46,13 +49,61 @@ public Pottery[] slots() { return Arrays.copyOf(this.slots, this.slots.length); } - public boolean put(int index, Pottery pottery) { + public VesselContents contents(int index) { + return this.contents[index]; + } + + public VesselContents[] contents() { + return Arrays.copyOf(this.contents, this.contents.length); + } + + public boolean lid(int index) { + return this.lids[index]; + } + + public boolean[] lids() { + return Arrays.copyOf(this.lids, this.lids.length); + } + + /** Brightest open fluid. A lid, an empty slot, and a dark fluid contribute nothing. */ + public int light() { + int light = 0; + for (int index = 0; index < SLOTS; index++) { + if (this.slots[index] == null || this.lids[index]) { + continue; + } + light = Math.max(light, this.contents[index].emission()); + } + return light; + } + + public void setContents(int index, VesselContents contents) { + if (index < 0 || index >= SLOTS || this.slots[index] == null) { + return; + } + this.contents[index] = contents == null || contents.isEmpty() ? VesselContents.EMPTY : contents; + this.sync(); + } + + public void setLid(int index, boolean lid) { + if (index < 0 || index >= SLOTS || this.slots[index] == null) { + return; + } + this.lids[index] = lid; + this.sync(); + } + + public boolean put(int index, Pottery pottery, VesselContents contents, boolean lid) { if (index < 0 || index >= this.slots.length || this.slots[index] != null) { return false; } Pottery[] next = Arrays.copyOf(this.slots, this.slots.length); + VesselContents[] nextContents = Arrays.copyOf(this.contents, this.contents.length); + boolean[] nextLids = Arrays.copyOf(this.lids, this.lids.length); next[index] = pottery; - this.replace(next); + nextContents[index] = contents == null || contents.isEmpty() ? VesselContents.EMPTY : contents; + nextLids[index] = lid; + this.replace(next, nextContents, nextLids); return true; } @@ -62,8 +113,12 @@ public boolean put(int index, Pottery pottery) { } Pottery taken = this.slots[index]; Pottery[] next = Arrays.copyOf(this.slots, this.slots.length); + VesselContents[] nextContents = Arrays.copyOf(this.contents, this.contents.length); + boolean[] nextLids = Arrays.copyOf(this.lids, this.lids.length); next[index] = null; - this.replace(next); + nextContents[index] = VesselContents.EMPTY; + nextLids[index] = false; + this.replace(next, nextContents, nextLids); return taken; } @@ -71,7 +126,8 @@ public void dropAll() { if (this.level == null || this.level.isClientSide()) { return; } - for (Pottery pottery : this.slots) { + for (int index = 0; index < this.slots.length; index++) { + Pottery pottery = this.slots[index]; if (pottery == null) { continue; } @@ -80,15 +136,17 @@ public void dropAll() { this.worldPosition.getX() + 0.5, this.worldPosition.getY() + 0.5, this.worldPosition.getZ() + 0.5, - PotteryItem.stack(pottery) + PotteryItem.stack(pottery, this.contents[index], this.lids[index]) )); } } - private void replace(Pottery[] next) { + private void replace(Pottery[] next, VesselContents[] nextContents, boolean[] nextLids) { boolean any = false; for (int index = 0; index < next.length; index++) { this.slots[index] = next[index]; + this.contents[index] = nextContents[index] == null ? VesselContents.EMPTY : nextContents[index]; + this.lids[index] = next[index] != null && nextLids[index]; any |= next[index] != null; } if (!any && this.level != null) { @@ -124,13 +182,24 @@ protected void loadAdditional(CompoundTag tag, net.minecraft.core.HolderLookup.P } *///?} + private static VesselContents[] blank() { + VesselContents[] contents = new VesselContents[SLOTS]; + Arrays.fill(contents, VesselContents.EMPTY); + return contents; + } + private CompoundTag saveSlots() { CompoundTag tag = new CompoundTag(); ListTag list = new ListTag(); - for (Pottery slot : this.slots) { + for (int index = 0; index < this.slots.length; index++) { + Pottery slot = this.slots[index]; CompoundTag entry = new CompoundTag(); if (slot != null) { entry.put("pottery", slot.save()); + this.contents[index].write(entry); + if (this.lids[index]) { + entry.putBoolean("lid", true); + } } list.add(entry); } @@ -142,6 +211,8 @@ private void loadSlots(CompoundTag tag) { ListTag list = Nbt.list(tag, "slots"); for (int index = 0; index < this.slots.length; index++) { this.slots[index] = null; + this.contents[index] = VesselContents.EMPTY; + this.lids[index] = false; if (index >= list.size()) { continue; } @@ -149,15 +220,24 @@ private void loadSlots(CompoundTag tag) { CompoundTag pottery = Nbt.compound(entry, "pottery"); if (!pottery.isEmpty()) { this.slots[index] = Pottery.load(pottery); + this.contents[index] = VesselContents.read(entry); + this.lids[index] = Nbt.getBoolean(entry, "lid"); } } } private void sync() { this.setChanged(); - if (this.level != null && !this.level.isClientSide()) { - this.level.sendBlockUpdated(this.worldPosition, this.getBlockState(), this.getBlockState(), Block.UPDATE_CLIENTS); + if (this.level == null || this.level.isClientSide()) { + return; + } + BlockState state = this.getBlockState(); + int light = this.light(); + if (state.is(ModBlocks.POTTERY) && state.getValue(PotteryBlock.LIGHT) != light) { + this.level.setBlock(this.worldPosition, state.setValue(PotteryBlock.LIGHT, light), Block.UPDATE_ALL); + state = this.getBlockState(); } + this.level.sendBlockUpdated(this.worldPosition, state, state, Block.UPDATE_CLIENTS); } @Override diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java index b265d2f..f5681b6 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java @@ -4,9 +4,12 @@ import java.util.Collections; import java.util.List; import net.minecraft.core.Direction; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; public final class Mesh { + static final double FLUID_INSET = 0.05; + public enum Texture { PLANKS, STONE, @@ -120,6 +123,18 @@ public void vessel(double centerX, double base, double centerZ, List Math.max(0, disc.innerRadius()) ? disc.radius() : 0; } @@ -182,6 +197,73 @@ private static double cut(double backX, double heel, double reach, double radius return backX - heel - (reach - radius); } + /** + * The fluid body. Each open disc is an octagon at its inner radius, inset so it stays inside the clay. + * The top face sits just under the top of the rim disc. A slice whose inset radius is not positive is skipped. + */ + public void cavity(double centerX, double base, double centerZ, List discs) { + int rim = openRim(discs); + if (rim < 0) { + return; + } + int end = rim; + while (end < discs.size() && discs.get(end).innerRadius() > 0) { + end++; + } + double y = base; + for (int index = discs.size() - 1; index >= end; index--) { + y += Math.max(0, discs.get(index).height()); + } + for (int index = end - 1; index >= rim; index--) { + PotteryDisc disc = discs.get(index); + double height = disc.height(); + double radius = disc.innerRadius() - FLUID_INSET; + boolean top = index == rim; + double drop = top ? Math.min(FLUID_INSET, Math.max(0, height) * 0.5) : 0; + double drawHeight = height - drop; + if (radius > 0 && drawHeight > 0) { + this.ringWalls(centerX, centerZ, y, drawHeight, radius, Texture.CLAY); + if (top) { + this.cap(centerX, centerZ, y + drawHeight, radius, Texture.CLAY, true); + } + } + y += height; + } + } + + private static int openRim(List discs) { + int rim = -1; + for (int index = 0; index < discs.size(); index++) { + PotteryDisc disc = discs.get(index); + if (!Double.isFinite(disc.height()) || !Double.isFinite(disc.radius()) || !Double.isFinite(disc.innerRadius()) + || disc.height() <= 0 || disc.radius() < 0 || disc.innerRadius() < 0) { + return -1; + } + if (disc.radius() == 0 && disc.innerRadius() == 0) { + continue; + } + if (disc.radius() - disc.innerRadius() < 0.5) { + return -1; + } + if (rim < 0) { + rim = index; + } + } + if (rim < 0 || discs.get(rim).innerRadius() == 0) { + return -1; + } + return rim; + } + + private void ringWalls(double centerX, double centerZ, double bottom, double height, double radius, Texture texture) { + double start = Math.PI / 8.0; + double step = Math.PI / 4.0; + for (int side = 0; side < 8; side++) { + double a0 = start + side * step; + this.wall(centerX, centerZ, bottom, height, radius, a0, a0 + step, texture, true); + } + } + public void fitSprite() { if (this.quads.isEmpty()) { return; diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java index 086d1d4..035b599 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; //? if <26.1 { /*import net.minecraft.client.renderer.MultiBufferSource; @@ -29,7 +30,16 @@ private PotteryPreview() { } static void draw(GuiGraphicsExtractor graphics, List discs, int x0, int y0, int x1, int y1) { - Model model = model(discs, x1 - x0, y1 - y0); + draw(graphics, discs, null, x0, y0, x1, y1); + } + + static void draw(GuiGraphicsExtractor graphics, Pottery pottery, boolean closed, int x0, int y0, int x1, int y1) { + Pottery.Cover cover = closed ? pottery.cover() : null; + draw(graphics, pottery.discs(), cover, x0, y0, x1, y1); + } + + private static void draw(GuiGraphicsExtractor graphics, List discs, Pottery.Cover cover, int x0, int y0, int x1, int y1) { + Model model = model(discs, x1 - x0, y1 - y0, cover); if (model.mesh().quads().isEmpty()) { return; } @@ -51,15 +61,24 @@ static void draw(GuiGraphicsExtractor graphics, List discs, int x0, } static Model model(List discs, int width, int height) { + return model(discs, width, height, null); + } + + static Model model(List discs, int width, int height, Pottery.Cover cover) { Mesh mesh = new Mesh(); mesh.vessel(0, 0, 0, discs, Mesh.Texture.CLAY); - mesh.fitSprite(); double vesselHeight = 0; double radius = 0; for (PotteryDisc disc : discs) { vesselHeight += disc.height(); radius = Math.max(radius, disc.radius()); } + if (cover != null) { + mesh.cover(0, 0, 0, cover, Mesh.Texture.CLAY); + vesselHeight += cover.layer() + Pottery.PIXEL * 2; + radius = Math.max(radius, cover.hole() + Pottery.PIXEL / 2.0); + } + mesh.fitSprite(); // Leave a two-pixel margin on each side at every spin angle. double tilt = Math.toRadians(TILT); double projectedHeight = vesselHeight * Math.cos(tilt) + 2 * radius * Math.sin(tilt); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java index f18e933..367fa86 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java @@ -4,11 +4,13 @@ import java.util.ArrayList; import java.util.List; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; //? if >=26.1 import net.minecraft.client.renderer.blockentity.state.BlockEntityRenderState; import net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.pottery.VesselContents; import net.minecraft.world.phys.AABB; //? if >=26.1 { @@ -33,6 +35,8 @@ public void extractRenderState( ) { BlockEntityRenderState.extractBase(blockEntity, state, breakProgress); state.slots = blockEntity.slots(); + state.contents = blockEntity.contents(); + state.lids = blockEntity.lids(); } @Override @@ -42,22 +46,41 @@ public void submit( net.minecraft.client.renderer.SubmitNodeCollector collector, net.minecraft.client.renderer.state.level.CameraRenderState camera ) { - Mesh mesh = pots(state.slots); - if (mesh.quads().isEmpty()) { + Mesh mesh = clay(state.slots, state.lids); + List draws = fluids(state.slots, state.contents); + boolean solidFluid = has(draws, true); + boolean translucent = has(draws, false); + if (mesh.quads().isEmpty() && !solidFluid && !translucent) { return; } poseStack.pushPose(); poseStack.scale(1 / 32.0F, 1 / 32.0F, 1 / 32.0F); - collector.submitCustomGeometry( - poseStack, - net.minecraft.client.renderer.rendertype.RenderTypes.entitySolid(Sprites.blocks()), - (pose, buffer) -> Sprites.draw(mesh, buffer, pose, state.lightCoords) - ); + if (!mesh.quads().isEmpty() || solidFluid) { + collector.submitCustomGeometry( + poseStack, + net.minecraft.client.renderer.rendertype.RenderTypes.entitySolid(Sprites.blocks()), + (pose, buffer) -> { + if (!mesh.quads().isEmpty()) { + Sprites.draw(mesh, buffer, pose, state.lightCoords); + } + drawFluids(draws, buffer, pose, state.lightCoords, true); + } + ); + } + if (translucent) { + collector.submitCustomGeometry( + poseStack, + net.minecraft.client.renderer.rendertype.RenderTypes.entityTranslucent(Sprites.blocks()), + (pose, buffer) -> drawFluids(draws, buffer, pose, state.lightCoords, false) + ); + } poseStack.popPose(); } public static final class State extends BlockEntityRenderState { public Pottery[] slots = new Pottery[PotteryBlockEntity.SLOTS]; + public VesselContents[] contents = new VesselContents[PotteryBlockEntity.SLOTS]; + public boolean[] lids = new boolean[PotteryBlockEntity.SLOTS]; } //?} else { /*@Override @@ -69,36 +92,106 @@ public void render( int light, int overlay ) { - Mesh mesh = pots(blockEntity.slots()); - if (mesh.quads().isEmpty()) { + Mesh mesh = clay(blockEntity.slots(), blockEntity.lids()); + List draws = fluids(blockEntity.slots(), blockEntity.contents()); + boolean solidFluid = has(draws, true); + boolean translucent = has(draws, false); + if (mesh.quads().isEmpty() && !solidFluid && !translucent) { return; } poseStack.pushPose(); poseStack.scale(1 / 32.0F, 1 / 32.0F, 1 / 32.0F); - Sprites.draw(mesh, buffers.getBuffer(net.minecraft.client.renderer.RenderType.entitySolid(Sprites.blocks())), poseStack.last(), light); + if (!mesh.quads().isEmpty() || solidFluid) { + var buffer = buffers.getBuffer(net.minecraft.client.renderer.RenderType.entitySolid(Sprites.blocks())); + if (!mesh.quads().isEmpty()) { + Sprites.draw(mesh, buffer, poseStack.last(), light); + } + drawFluids(draws, buffer, poseStack.last(), light, true); + } + if (translucent) { + var buffer = buffers.getBuffer(net.minecraft.client.renderer.RenderType.entityTranslucent(Sprites.blocks())); + drawFluids(draws, buffer, poseStack.last(), light, false); + } poseStack.popPose(); } *///?} - private static Mesh pots(Pottery[] slots) { + private static boolean has(List draws, boolean solid) { + for (FluidDraw draw : draws) { + if (draw.solid == solid) { + return true; + } + } + return false; + } + + private static void drawFluids( + List draws, com.mojang.blaze3d.vertex.VertexConsumer buffer, PoseStack.Pose pose, int light, boolean solid + ) { + for (FluidDraw draw : draws) { + if (draw.solid == solid) { + Sprites.drawFluid(draw.mesh, buffer, pose, light, draw.sprite, draw.color); + } + } + } + + private record FluidDraw(Mesh mesh, TextureAtlasSprite sprite, int color, boolean solid) { + } + + private static Mesh clay(Pottery[] slots, boolean[] lids) { Mesh mesh = new Mesh(); for (int index = 0; index < slots.length; index++) { Pottery pottery = slots[index]; if (pottery == null) { continue; } - AABB box = PotteryBlockEntity.box(index); - double centerX = (box.minX + box.maxX) / 2.0 * 32.0; - double centerZ = (box.minZ + box.maxZ) / 2.0 * 32.0; - List discs = new ArrayList<>(); - for (PotteryDisc disc : pottery.discs()) { - discs.add(new PotteryDisc(disc.height(), disc.radius(), Math.max(0, disc.radius() - 1))); - } + boolean closed = lids != null && index < lids.length && lids[index]; Mesh pot = new Mesh(); - pot.vessel(centerX, box.minY * 32.0, centerZ, discs, Mesh.Texture.CLAY); - pot.fitSprite(); + placed(index, pot, pottery, closed, false); mesh.add(pot); } return mesh; } + + private static List fluids(Pottery[] slots, VesselContents[] contents) { + List draws = new ArrayList<>(); + if (contents == null) { + return draws; + } + for (int index = 0; index < slots.length && index < contents.length; index++) { + Pottery pottery = slots[index]; + VesselContents held = contents[index]; + if (pottery == null || held == null || held.isEmpty()) { + continue; + } + TextureAtlasSprite sprite = Sprites.fluid(held.fluid()); + if (sprite == null) { + continue; + } + Mesh body = new Mesh(); + placed(index, body, pottery, false, true); + if (body.quads().isEmpty()) { + continue; + } + draws.add(new FluidDraw(body, sprite, Sprites.fluidColor(held.fluid()), Sprites.fluidSolid(held.fluid()))); + } + return draws; + } + + private static void placed(int index, Mesh mesh, Pottery pottery, boolean closed, boolean fluid) { + AABB box = PotteryBlockEntity.box(index); + double centerX = (box.minX + box.maxX) / 2.0 * 32.0; + double centerZ = (box.minZ + box.maxZ) / 2.0 * 32.0; + double base = box.minY * 32.0; + List discs = pottery.discs(); + if (fluid) { + mesh.cavity(centerX, base, centerZ, discs); + return; + } + mesh.vessel(centerX, base, centerZ, discs, Mesh.Texture.CLAY); + if (closed && pottery.cover() != null) { + mesh.cover(centerX, base, centerZ, pottery.cover(), Mesh.Texture.CLAY); + } + mesh.fitSprite(); + } } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryScreen.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryScreen.java new file mode 100644 index 0000000..393eec7 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryScreen.java @@ -0,0 +1,187 @@ +package net.modcrafters.minecraft.primalpottery.client; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity; +import net.modcrafters.minecraft.primalpottery.item.PotteryItem; +import net.modcrafters.minecraft.primalpottery.network.LidSync; +import net.modcrafters.minecraft.primalpottery.network.PlacedLidSync; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.VesselContents; +import org.jspecify.annotations.Nullable; +//? if >=26.1 +import net.minecraft.client.gui.GuiGraphicsExtractor; +//? if <26.1 +//import net.minecraft.client.gui.GuiGraphicsExtractor; + +/** What a held pot contains, and a button that puts or takes its lid. */ +public final class PotteryScreen extends Screen { + private static final int IMAGE_WIDTH = 120; + private static final int IMAGE_HEIGHT = 90; + private static final int PANEL = 0xF0201814; + + private final boolean mainHand; + private final @Nullable BlockPos placed; + private final int slot; + private final Pottery pottery; + private final VesselContents contents; + private boolean closed; + private Button lidButton; + private int left; + private int top; + + public PotteryScreen(boolean mainHand, Pottery pottery, VesselContents contents, boolean closed) { + this(mainHand, null, 0, pottery, contents, closed); + } + + public PotteryScreen(BlockPos pos, int slot, Pottery pottery, VesselContents contents, boolean closed) { + this(false, pos, slot, pottery, contents, closed); + } + + private PotteryScreen( + boolean mainHand, @Nullable BlockPos placed, int slot, Pottery pottery, VesselContents contents, boolean closed + ) { + //? if >=26.1 { + super(Minecraft.getInstance(), Minecraft.getInstance().font, Component.literal("Pottery")); + //?} else + //super(Component.literal("Pottery")); + this.mainHand = mainHand; + this.placed = placed == null ? null : placed.immutable(); + this.slot = slot; + this.pottery = pottery; + this.contents = contents; + this.closed = closed; + } + + public static void open(Player player, InteractionHand hand) { + ItemStack stack = player.getItemInHand(hand); + show(new PotteryScreen( + hand == InteractionHand.MAIN_HAND, + PotteryItem.read(stack), + PotteryItem.contents(stack), + PotteryItem.lid(stack) + )); + } + + public static void open(Level level, BlockPos pos, int slot) { + if (slot < 0 || slot >= PotteryBlockEntity.SLOTS) { + return; + } + if (!(level.getBlockEntity(pos) instanceof PotteryBlockEntity pottery)) { + return; + } + Pottery pot = pottery.get(slot); + if (pot == null) { + return; + } + show(new PotteryScreen(pos, slot, pot, pottery.contents(slot), pottery.lid(slot))); + } + + private static void show(PotteryScreen screen) { + //? if >=26.1 { + Minecraft.getInstance().setScreenAndShow(screen); + //?} else + //Minecraft.getInstance().setScreen(screen); + } + + @Override + protected void init() { + this.layout(); + this.lidButton = this.addRenderableWidget(Button.builder(Component.literal(this.label()), button -> this.pressLid()) + .bounds(this.left + 10, this.top + 66, 100, 20) + .build()); + } + + @Override + public boolean isPauseScreen() { + return false; + } + + //? if >=26.1 { + @Override + public boolean isInGameUi() { + return true; + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float partialTick) { + this.layout(); + this.paint(graphics); + super.extractRenderState(graphics, mouseX, mouseY, partialTick); + this.drawContents(graphics); + } + //?} else { + /*@Override + public void render(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float partialTick) { + this.layout(); + super.render(graphics, mouseX, mouseY, partialTick); + this.drawContents(graphics); + } + + @Override + public void renderBackground(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float partialTick) { + super.renderBackground(graphics, mouseX, mouseY, partialTick); + this.paint(graphics); + } + *///?} + + private void pressLid() { + if (this.closed) { + this.closed = false; + this.lidButton.setMessage(Component.literal(this.label())); + this.send(false); + return; + } + if (this.pottery.lidDisc() == null) { + return; + } + this.closed = true; + this.lidButton.setMessage(Component.literal(this.label())); + this.send(true); + } + + private void send(boolean closed) { + if (this.placed != null) { + PlacedLidSync.send(this.placed, this.slot, closed); + return; + } + LidSync.send(this.mainHand, closed); + } + + private String label() { + return this.closed ? "Take lid" : "Put lid"; + } + + private void paint(GuiGraphicsExtractor graphics) { + graphics.fill(this.left, this.top, this.left + IMAGE_WIDTH, this.top + IMAGE_HEIGHT, PANEL); + } + + private void drawContents(GuiGraphicsExtractor graphics) { + PotteryPreview.draw(graphics, this.pottery, this.closed, this.left + 8, this.top + 4, this.left + 112, this.top + 36); + if (!this.pottery.classify().type().isVessel()) { + return; + } + int x = this.left + 8; + int y = this.top + 38; + int line = this.font.lineHeight; + List lines = new ArrayList<>(); + PotteryItem.contentsTooltip(this.pottery, this.contents, lines::add); + for (int index = 0; index < lines.size(); index++) { + graphics.text(this.font, lines.get(index), x, y + line * index, -1); + } + } + + private void layout() { + this.left = (this.width - IMAGE_WIDTH) / 2; + this.top = (this.height - IMAGE_HEIGHT) / 2; + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java index c3dc813..631558e 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java @@ -7,7 +7,11 @@ import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.resources.Identifier; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Fluids; import net.modcrafters.minecraft.primalpottery.Ids; +import org.jspecify.annotations.Nullable; public final class Sprites { private Sprites() { @@ -31,6 +35,60 @@ public static Identifier blocks() { return TextureAtlas.LOCATION_BLOCKS; } + public static final int WATER_TINT = 0x3F76E4; + + /** Water and lava use the still blocks-atlas sprite. Another fluid uses its particle sprite. A missing sprite is absent. */ + public static @Nullable TextureAtlasSprite fluid(Fluid fluid) { + if (fluid == Fluids.WATER) { + return still("block/water_still"); + } + if (fluid == Fluids.LAVA) { + return still("block/lava_still"); + } + return particle(fluid.defaultFluidState().createLegacyBlock()); + } + + public static boolean fluidSolid(Fluid fluid) { + return fluid == Fluids.LAVA; + } + + public static int fluidColor(Fluid fluid) { + return fluid == Fluids.WATER ? WATER_TINT : 0xFFFFFF; + } + + private static @Nullable TextureAtlasSprite still(String path) { + Identifier id = Ids.of("minecraft", path); + //? if >=26.1 { + TextureAtlas atlas = Minecraft.getInstance().getAtlasManager().getAtlasOrThrow(net.minecraft.data.AtlasIds.BLOCKS); + TextureAtlasSprite sprite = atlas.getSprite(id); + return sprite == atlas.missingSprite() ? null : sprite; + //?} else { + /*java.util.function.Function atlas = Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS); + TextureAtlasSprite sprite = atlas.apply(id); + TextureAtlasSprite missing = atlas.apply(net.minecraft.client.renderer.texture.MissingTextureAtlasSprite.getLocation()); + return sprite == missing ? null : sprite; + *///?} + } + + private static @Nullable TextureAtlasSprite particle(BlockState state) { + //? if >=26.1 { + TextureAtlasSprite sprite = Minecraft.getInstance().getModelManager().getBlockStateModelSet().getParticleMaterial(state).sprite(); + TextureAtlas atlas = Minecraft.getInstance().getAtlasManager().getAtlasOrThrow(net.minecraft.data.AtlasIds.BLOCKS); + if (sprite == null || sprite == atlas.missingSprite()) { + return null; + } + return sprite; + //?} else { + /*TextureAtlasSprite sprite = Minecraft.getInstance().getBlockRenderer().getBlockModel(state).getParticleIcon(); + java.util.function.Function atlas = Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS); + TextureAtlasSprite missing = atlas.apply(net.minecraft.client.renderer.texture.MissingTextureAtlasSprite.getLocation()); + if (sprite == null || sprite == missing) { + return null; + } + return sprite; + *///?} + } + public static void draw(Mesh mesh, VertexConsumer buffer, PoseStack.Pose pose, int light) { draw(mesh, buffer, pose, light, 255); } @@ -39,7 +97,18 @@ public static void draw(Mesh mesh, VertexConsumer buffer, PoseStack.Pose pose, i for (Mesh.Quad quad : mesh.quads()) { TextureAtlasSprite sprite = get(quad.texture); for (int vertex = 0; vertex < 4; vertex++) { - put(buffer, pose, quad.x[vertex], quad.y[vertex], quad.z[vertex], sampleU(sprite, quad.u[vertex]), sampleV(sprite, quad.v[vertex]), light, alpha, quad.nx, quad.ny, quad.nz); + put(buffer, pose, quad.x[vertex], quad.y[vertex], quad.z[vertex], sampleU(sprite, quad.u[vertex]), sampleV(sprite, quad.v[vertex]), light, 255, 255, 255, alpha, quad.nx, quad.ny, quad.nz); + } + } + } + + public static void drawFluid(Mesh mesh, VertexConsumer buffer, PoseStack.Pose pose, int light, TextureAtlasSprite sprite, int color) { + int red = (color >> 16) & 255; + int green = (color >> 8) & 255; + int blue = color & 255; + for (Mesh.Quad quad : mesh.quads()) { + for (int vertex = 0; vertex < 4; vertex++) { + put(buffer, pose, quad.x[vertex], quad.y[vertex], quad.z[vertex], sampleU(sprite, quad.u[vertex]), sampleV(sprite, quad.v[vertex]), light, red, green, blue, 255, quad.nx, quad.ny, quad.nz); } } } @@ -53,12 +122,26 @@ private static float sampleV(TextureAtlasSprite sprite, float unit) { } private static void put( - VertexConsumer buffer, PoseStack.Pose pose, float x, float y, float z, float u, float v, int light, int alpha, float nx, float ny, float nz + VertexConsumer buffer, + PoseStack.Pose pose, + float x, + float y, + float z, + float u, + float v, + int light, + int red, + int green, + int blue, + int alpha, + float nx, + float ny, + float nz ) { //? if <1.21 { - /*buffer.vertex(pose, x, y, z).color(255, 255, 255, alpha).uv(u, v).overlayCoords(OverlayTexture.NO_OVERLAY).uv2(light).normal(pose, nx, ny, nz).endVertex(); + /*buffer.vertex(pose, x, y, z).color(red, green, blue, alpha).uv(u, v).overlayCoords(OverlayTexture.NO_OVERLAY).uv2(light).normal(pose, nx, ny, nz).endVertex(); *///?} else { - buffer.addVertex(pose, x, y, z).setColor(255, 255, 255, alpha).setUv(u, v).setOverlay(OverlayTexture.NO_OVERLAY).setUv2(light & 0xFFFF, light >> 16).setNormal(pose, nx, ny, nz); + buffer.addVertex(pose, x, y, z).setColor(red, green, blue, alpha).setUv(u, v).setOverlay(OverlayTexture.NO_OVERLAY).setUv2(light & 0xFFFF, light >> 16).setNormal(pose, nx, ny, nz); //?} } } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java index 87fbbfe..1cf3342 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java @@ -1,22 +1,44 @@ package net.modcrafters.minecraft.primalpottery.item; +import java.util.function.Consumer; +import net.minecraft.core.BlockPos; import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; -import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; import net.modcrafters.minecraft.primalpottery.block.ModBlocks; import net.modcrafters.minecraft.primalpottery.block.PotteryBlock; import net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity; +import net.modcrafters.minecraft.primalpottery.client.PotteryScreen; import net.modcrafters.minecraft.primalpottery.pottery.Nbt; import net.modcrafters.minecraft.primalpottery.pottery.PartHits; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.VesselContents; +import org.jspecify.annotations.Nullable; +//? if >=26.1 +import net.minecraft.world.item.component.TooltipDisplay; +//? if <26.1 +//import net.minecraft.world.InteractionResultHolder; public class PotteryItem extends BlockItem { public PotteryItem(Properties properties) { @@ -24,25 +46,154 @@ public PotteryItem(Properties properties) { } public static ItemStack stack(Pottery pottery) { + return stack(pottery, VesselContents.EMPTY); + } + + public static ItemStack stack(Pottery pottery, VesselContents contents) { + return stack(pottery, contents, false); + } + + public static ItemStack stack(Pottery pottery, VesselContents contents, boolean lid) { ItemStack stack = new ItemStack(ModItems.POTTERY); CompoundTag tag = new CompoundTag(); tag.put("pottery", pottery.save()); + contents.write(tag); + if (lid) { + tag.putBoolean("lid", true); + } stack.set(DataComponents.CUSTOM_DATA, CustomData.of(tag)); return stack; } + public static boolean lid(ItemStack stack) { + CompoundTag tag = tag(stack); + return tag != null && Nbt.getBoolean(tag, "lid"); + } + + public static Component fluidName(Fluid fluid) { + Component name = fluid.defaultFluidState().createLegacyBlock().getBlock().getName(); + int color = VesselContents.tooltipColor(fluid); + if (color == -1) { + return name; + } + return name.copy().withStyle(style -> style.withColor(color)); + } + public static Pottery read(ItemStack stack) { - CustomData data = stack.get(DataComponents.CUSTOM_DATA); - if (data == null) { + CompoundTag tag = tag(stack); + if (tag == null) { return Pottery.display(); } - CompoundTag pottery = Nbt.compound(data.copyTag(), "pottery"); + CompoundTag pottery = Nbt.compound(tag, "pottery"); if (pottery.isEmpty()) { return Pottery.display(); } return Pottery.load(pottery); } + public static VesselContents contents(ItemStack stack) { + CompoundTag tag = tag(stack); + return tag == null ? VesselContents.EMPTY : VesselContents.read(tag); + } + + private static @Nullable CompoundTag tag(ItemStack stack) { + CustomData data = stack.get(DataComponents.CUSTOM_DATA); + return data == null ? null : data.copyTag(); + } + + //? if >=26.1 { + @Override + public void appendHoverText(ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer tooltip, TooltipFlag flag) { + super.appendHoverText(stack, context, display, tooltip, flag); + appendFluid(stack, tooltip); + } + //?} else { + /*@Override + public void appendHoverText(ItemStack stack, TooltipContext context, java.util.List tooltip, TooltipFlag flag) { + super.appendHoverText(stack, context, tooltip, flag); + appendFluid(stack, tooltip::add); + } + *///?} + + public static void contentsTooltip(Pottery pottery, VesselContents contents, Consumer tooltip) { + Pottery.Info info = pottery.classify(); + if (!info.type().isVessel()) { + return; + } + tooltip.accept(Component.translatable("tooltip.primalpottery.capacity", info.volume())); + if (!contents.isEmpty()) { + tooltip.accept(Component.translatable("tooltip.primalpottery.contents", fluidName(contents.fluid()), contents.amount())); + } + } + + private static void appendFluid(ItemStack stack, Consumer tooltip) { + contentsTooltip(read(stack), contents(stack), tooltip); + } + + @Override + public InteractionResult useOn(UseOnContext context) { + Player player = context.getPlayer(); + Level level = context.getLevel(); + ItemStack stack = context.getItemInHand(); + BlockHitResult look = player == null ? null : getPlayerPOVHitResult(level, player, ClipContext.Fluid.ANY); + BlockPlaceContext place = new BlockPlaceContext(context); + VesselContents.Facts facts = facts(stack, player, level, look, place, true); + if (VesselContents.choose(facts) == VesselContents.Choice.FILL) { + if (!level.isClientSide() && look != null) { + fill(level, stack, look); + } + return InteractionResult.SUCCESS; + } + if (denied(facts)) { + return InteractionResult.FAIL; + } + return this.place(place); + } + + //? if >=26.1 { + @Override + public InteractionResult use(Level level, Player player, InteractionHand hand) { + ItemStack stack = player.getItemInHand(hand); + BlockHitResult look = getPlayerPOVHitResult(level, player, ClipContext.Fluid.ANY); + VesselContents.Facts facts = facts(stack, player, level, look, null, true); + VesselContents.Choice choice = VesselContents.choose(facts); + if (choice == VesselContents.Choice.FILL) { + if (!level.isClientSide()) { + fill(level, stack, look); + } + return InteractionResult.SUCCESS; + } + if (choice == VesselContents.Choice.REFUSE) { + return InteractionResult.FAIL; + } + if (level.isClientSide()) { + PotteryScreen.open(player, hand); + } + return InteractionResult.SUCCESS; + } + //?} else { + /*@Override + public InteractionResultHolder use(Level level, Player player, InteractionHand hand) { + ItemStack stack = player.getItemInHand(hand); + BlockHitResult look = getPlayerPOVHitResult(level, player, ClipContext.Fluid.ANY); + VesselContents.Facts facts = facts(stack, player, level, look, null, true); + VesselContents.Choice choice = VesselContents.choose(facts); + if (choice == VesselContents.Choice.FILL) { + if (!level.isClientSide()) { + fill(level, stack, look); + } + return InteractionResultHolder.success(stack); + } + if (choice == VesselContents.Choice.REFUSE) { + return InteractionResultHolder.fail(stack); + } + if (level.isClientSide()) { + PotteryScreen.open(player, hand); + } + return InteractionResultHolder.success(stack); + } + *///?} + @Override public InteractionResult place(BlockPlaceContext context) { BlockPos clicked = context.replacingClickedOnBlock() @@ -55,15 +206,24 @@ public InteractionResult place(BlockPlaceContext context) { clicked, player, context.getItemInHand(), - PotteryBlock.aimedPart(context.getLevel(), clicked, player, context.getClickLocation()), + PartHits.quadrant(clicked, context.getClickLocation()), player != null && player.isShiftKeyDown(), context.getClickedFace() ); } + VesselContents.Facts facts = facts( + context.getItemInHand(), context.getPlayer(), context.getLevel(), null, context, false + ); + if (VesselContents.choose(facts) == VesselContents.Choice.REFUSE) { + return InteractionResult.FAIL; + } if (context.getClickedFace() != net.minecraft.core.Direction.UP) { return InteractionResult.FAIL; } - Pottery shaped = read(context.getItemInHand()); + ItemStack stack = context.getItemInHand(); + Pottery shaped = read(stack); + VesselContents contents = contents(stack); + boolean closed = lid(stack); InteractionResult result = super.place(context); if (!result.consumesAction()) { return result; @@ -71,8 +231,83 @@ public InteractionResult place(BlockPlaceContext context) { Level level = context.getLevel(); BlockEntity blockEntity = level.getBlockEntity(context.getClickedPos()); if (blockEntity instanceof PotteryBlockEntity pottery) { - pottery.put(PartHits.quadrant(context.getClickedPos(), context.getClickLocation()), shaped); + pottery.put(PartHits.quadrant(context.getClickedPos(), context.getClickLocation()), shaped, contents, closed); } return result; } + + private static void fill(Level level, ItemStack stack, BlockHitResult look) { + if (lid(stack)) { + return; + } + BlockPos pos = look.getBlockPos(); + BlockState state = level.getBlockState(pos); + FluidState fluid = state.getFluidState(); + if (!VesselContents.ownsFluidBlock(state, fluid)) { + return; + } + int volume = read(stack).classify().volume(); + Fluid source = VesselContents.source(fluid.getType()); + VesselContents contents = VesselContents.of(source, volume); + CustomData.update(DataComponents.CUSTOM_DATA, stack, contents::write); + source.getPickupSound().ifPresent(sound -> + level.playSound(null, pos, sound, SoundSource.BLOCKS, 1.0F, 1.0F)); + } + + /** A fill the player is not allowed to perform. It must fail before placement. */ + private static boolean denied(VesselContents.Facts facts) { + return facts.povFluid() && facts.player() && facts.vessel() && facts.empty() && facts.volume() > 0 && !facts.interact(); + } + + private static VesselContents.Facts facts( + ItemStack stack, + @Nullable Player player, + Level level, + @Nullable BlockHitResult look, + @Nullable BlockPlaceContext place, + boolean pov + ) { + Pottery pottery = read(stack); + VesselContents contents = contents(stack); + boolean fluidBlock = false; + String sourceId = ""; + boolean interact = false; + if (pov && player != null && look != null && look.getType() == HitResult.Type.BLOCK) { + BlockPos pos = look.getBlockPos(); + BlockState state = level.getBlockState(pos); + FluidState fluid = state.getFluidState(); + fluidBlock = VesselContents.ownsFluidBlock(state, fluid); + if (fluidBlock) { + Identifier id = BuiltInRegistries.FLUID.getKey(VesselContents.source(fluid.getType())); + sourceId = id == null ? "" : id.toString(); + } + interact = level.mayInteract(player, pos) + && player.mayUseItemAt(pos.relative(look.getDirection()), look.getDirection(), stack); + } + boolean canPlace = false; + boolean clickedFluid = false; + boolean clickedSource = false; + if (place != null) { + canPlace = place.canPlace(); + BlockState state = level.getBlockState(place.getClickedPos()); + FluidState fluid = state.getFluidState(); + clickedFluid = !fluid.isEmpty(); + clickedSource = fluid.isSource() && (state.getBlock() == Blocks.WATER || state.getBlock() == Blocks.LAVA); + } + Pottery.Info info = pottery.classify(); + return new VesselContents.Facts( + player != null, + info.type().isVessel(), + contents.isEmpty(), + info.volume(), + fluidBlock, + sourceId, + interact, + canPlace, + clickedFluid, + clickedSource, + player != null && player.isShiftKeyDown(), + !contents.isEmpty() + ); + } } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/network/LidPayload.java b/src/main/java/net/modcrafters/minecraft/primalpottery/network/LidPayload.java new file mode 100644 index 0000000..d33e335 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/network/LidPayload.java @@ -0,0 +1,29 @@ +package net.modcrafters.minecraft.primalpottery.network; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.modcrafters.minecraft.primalpottery.Ids; + +/** A lid put on or taken off the pottery item in one hand. */ +public record LidPayload(boolean mainHand, boolean closed) implements CustomPacketPayload { + public static final CustomPacketPayload.Type TYPE = new CustomPacketPayload.Type<>(Ids.of("lid")); + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + LidPayload::write, + LidPayload::read + ); + + private static void write(RegistryFriendlyByteBuf buf, LidPayload payload) { + buf.writeBoolean(payload.mainHand); + buf.writeBoolean(payload.closed); + } + + private static LidPayload read(RegistryFriendlyByteBuf buf) { + return new LidPayload(buf.readBoolean(), buf.readBoolean()); + } + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/network/LidSync.java b/src/main/java/net/modcrafters/minecraft/primalpottery/network/LidSync.java new file mode 100644 index 0000000..fedc410 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/network/LidSync.java @@ -0,0 +1,42 @@ +package net.modcrafters.minecraft.primalpottery.network; + +import net.minecraft.core.component.DataComponents; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; +import net.modcrafters.minecraft.primalpottery.item.ModItems; +import net.modcrafters.minecraft.primalpottery.item.PotteryItem; + +/** The server writes the lid flag onto the pottery item in the chosen hand. */ +public final class LidSync { + public interface Sender { + void send(boolean mainHand, boolean closed); + } + + public static Sender sender = (mainHand, closed) -> { + }; + + private LidSync() { + } + + public static void send(boolean mainHand, boolean closed) { + sender.send(mainHand, closed); + } + + public static void apply(Player player, boolean mainHand, boolean closed) { + InteractionHand hand = mainHand ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; + ItemStack stack = player.getItemInHand(hand); + if (!stack.is(ModItems.POTTERY)) { + return; + } + if (closed) { + if (PotteryItem.read(stack).lidDisc() == null) { + return; + } + CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.putBoolean("lid", true)); + return; + } + CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.remove("lid")); + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidPayload.java b/src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidPayload.java new file mode 100644 index 0000000..88ebbad --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidPayload.java @@ -0,0 +1,31 @@ +package net.modcrafters.minecraft.primalpottery.network; + +import net.minecraft.core.BlockPos; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.modcrafters.minecraft.primalpottery.Ids; + +/** A lid put on or taken off one pot in a placed pottery block. */ +public record PlacedLidPayload(BlockPos pos, int slot, boolean closed) implements CustomPacketPayload { + public static final CustomPacketPayload.Type TYPE = new CustomPacketPayload.Type<>(Ids.of("placed_lid")); + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + PlacedLidPayload::write, + PlacedLidPayload::read + ); + + private static void write(RegistryFriendlyByteBuf buf, PlacedLidPayload payload) { + buf.writeBlockPos(payload.pos); + buf.writeVarInt(payload.slot); + buf.writeBoolean(payload.closed); + } + + private static PlacedLidPayload read(RegistryFriendlyByteBuf buf) { + return new PlacedLidPayload(buf.readBlockPos(), buf.readVarInt(), buf.readBoolean()); + } + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidSync.java b/src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidSync.java new file mode 100644 index 0000000..7a7e68c --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/network/PlacedLidSync.java @@ -0,0 +1,45 @@ +package net.modcrafters.minecraft.primalpottery.network; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.modcrafters.minecraft.primalpottery.block.ModBlocks; +import net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity; + +/** The server writes the lid flag onto one occupied pot the player may interact with. */ +public final class PlacedLidSync { + public interface Sender { + void send(BlockPos pos, int slot, boolean closed); + } + + public static Sender sender = (pos, slot, closed) -> { + }; + + private PlacedLidSync() { + } + + public static void send(BlockPos pos, int slot, boolean closed) { + sender.send(pos, slot, closed); + } + + public static void apply(Player player, BlockPos pos, int slot, boolean closed) { + Level level = player.level(); + if (!level.mayInteract(player, pos) || !level.getBlockState(pos).is(ModBlocks.POTTERY)) { + return; + } + if (!(level.getBlockEntity(pos) instanceof PotteryBlockEntity pottery)) { + return; + } + if (slot < 0 || slot >= PotteryBlockEntity.SLOTS || pottery.get(slot) == null) { + return; + } + if (closed) { + if (pottery.get(slot).lidDisc() == null) { + return; + } + pottery.setLid(slot, true); + return; + } + pottery.setLid(slot, false); + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Nbt.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Nbt.java index ac1d195..9aae771 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Nbt.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Nbt.java @@ -7,6 +7,20 @@ public final class Nbt { private Nbt() { } + public static String getString(CompoundTag tag, String key) { + //? if >=26.1 { + return tag.getStringOr(key, ""); + //?} else + //return tag.getString(key); + } + + public static int getInt(CompoundTag tag, String key) { + //? if >=26.1 { + return tag.getIntOr(key, 0); + //?} else + //return tag.getInt(key); + } + public static double getDouble(CompoundTag tag, String key) { //? if >=26.1 { return tag.getDoubleOr(key, 0); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Placement.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Placement.java index c315e67..e8f580c 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Placement.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Placement.java @@ -9,7 +9,6 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.modcrafters.minecraft.primalpottery.block.ModBlocks; -import net.modcrafters.minecraft.primalpottery.block.PotteryBlock; import net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity; import net.modcrafters.minecraft.primalpottery.item.ModItems; import org.jspecify.annotations.Nullable; @@ -29,7 +28,7 @@ private Placement() { } int part = destination( pottery, - PotteryBlock.aimedPart(level, pos, player, hit.getLocation()), + PartHits.quadrant(pos, hit.getLocation()), player.isShiftKeyDown(), hit.getDirection() ); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java index 9739272..b430ce2 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java @@ -4,6 +4,7 @@ import java.util.List; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; +import org.jspecify.annotations.Nullable; public final class Pottery { // The clay mesh uses regular octagons whose vertices lie on the disc radius. @@ -68,6 +69,64 @@ public Info classify() { return new Info(PotteryType.LUMP_NO_BOTTOM, 0); } + /** One block pixel in the placed mesh, which uses 32 units per block. */ + public static final double PIXEL = 2; + + /** + * Where a lid is drawn. {@code top} is the pot's top, {@code layer} is the top disc's height, + * and {@code hole} is that disc's inner radius. The lid is not stored on the profile. + */ + public record Cover(double top, double layer, double hole) { + } + + /** The rim a lid can cover, or null when the profile has no open mouth. */ + public @Nullable Cover cover() { + int rim = this.rimIndex(); + if (rim < 0) { + return null; + } + double top = 0; + for (PotteryDisc disc : this.discs) { + top += disc.height(); + } + PotteryDisc disc = this.discs.get(rim); + return new Cover(top, disc.height(), disc.innerRadius()); + } + + /** + * The lid plate: one pixel thick, and one pixel wider than the hole. Null when {@link #cover()} is null. + */ + public @Nullable PotteryDisc lidDisc() { + Cover cover = this.cover(); + if (cover == null) { + return null; + } + return new PotteryDisc(PIXEL, cover.hole() + PIXEL / 2.0, 0); + } + + /** The saved discs. A lid is drawn from {@link #cover()} and is not another profile disc. */ + public List drawDiscs(boolean closed) { + return this.discs(); + } + + private int rimIndex() { + for (int index = 0; index < this.discs.size(); index++) { + PotteryDisc disc = this.discs.get(index); + if (!Double.isFinite(disc.height()) || !Double.isFinite(disc.radius()) || !Double.isFinite(disc.innerRadius()) + || disc.height() <= 0 || disc.radius() < 0 || disc.innerRadius() < 0) { + return -1; + } + if (disc.radius() == 0 && disc.innerRadius() == 0) { + continue; + } + if (disc.radius() - disc.innerRadius() < 0.5 || disc.innerRadius() <= 0) { + return -1; + } + return index; + } + return -1; + } + private static PotteryType vesselType(double openingRadius, double maxRadius) { if (openingRadius > 0.9 * maxRadius) { return PotteryType.POT; diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselContents.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselContents.java new file mode 100644 index 0000000..ad44a77 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselContents.java @@ -0,0 +1,153 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.Identifier; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FlowingFluid; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.Fluids; + +/** A vessel is empty, or it holds one source fluid and an amount in millilitres. */ +public record VesselContents(Fluid fluid, int amount) { + public static final VesselContents EMPTY = new VesselContents(Fluids.EMPTY, 0); + + public enum Choice { + FILL, + PLACE, + REFUSE + } + + /** + * Facts for {@link #choose}. The source id is what a fill would store. It does not + * decide the choice: a fluid other than water or lava still fills. + */ + public record Facts( + boolean player, + boolean vessel, + boolean empty, + int volume, + boolean povFluid, + String sourceId, + boolean interact, + boolean canPlace, + boolean clickedFluid, + boolean clickedSource, + boolean sneaking, + boolean holding + ) { + } + + public boolean isEmpty() { + return this.fluid == Fluids.EMPTY || this.amount <= 0; + } + + /** Light of this fluid's registered source block. An empty vessel emits nothing. */ + public int emission() { + if (this.isEmpty()) { + return 0; + } + int light = this.fluid.defaultFluidState().createLegacyBlock().getLightEmission(); + if (light < 0) { + return 0; + } + return Math.min(light, 15); + } + + /** Millilitres of {@code held} that fit in a pot storing {@code stored} with capacity {@code volume}. */ + public static int poured(VesselContents held, VesselContents stored, int volume) { + if (held.isEmpty() || volume <= 0) { + return 0; + } + if (!stored.isEmpty() && stored.fluid() != held.fluid()) { + return 0; + } + int room = volume - (stored.isEmpty() ? 0 : stored.amount()); + if (room <= 0) { + return 0; + } + return Math.min(held.amount(), room); + } + + /** Water uses the same blue as the world mesh. Lava and every other fluid stay uncolored. */ + public static int tooltipColor(Fluid fluid) { + return fluid == Fluids.WATER ? 0x3F76E4 : -1; + } + + public static VesselContents of(Fluid fluid, int amount) { + Fluid source = source(fluid); + if (source == Fluids.EMPTY || amount <= 0) { + return EMPTY; + } + return new VesselContents(source, amount); + } + + /** Flowing water and lava become their source. Any other fluid stays itself. */ + public static Fluid source(Fluid fluid) { + if (fluid instanceof FlowingFluid flowing) { + return flowing.getSource(); + } + return fluid == null ? Fluids.EMPTY : fluid; + } + + /** True when the block is that fluid's own block. A waterlogged block and a bubble column are not. */ + public static boolean ownsFluidBlock(BlockState state, FluidState fluid) { + if (fluid.isEmpty()) { + return false; + } + Block legacy = fluid.createLegacyBlock().getBlock(); + //? if >=26.1 { + return state.getBlock() == legacy; + //?} else + //return state.is(legacy); + } + + public static Choice choose(Facts facts) { + if (facts.player && facts.vessel && facts.empty && facts.volume > 0 && facts.povFluid) { + return facts.interact ? Choice.FILL : Choice.REFUSE; + } + boolean sneakPlace = facts.sneaking && facts.vessel && facts.holding && facts.clickedSource; + if (facts.canPlace && facts.clickedFluid && !sneakPlace) { + return Choice.REFUSE; + } + return Choice.PLACE; + } + + public void write(CompoundTag tag) { + if (this.isEmpty()) { + tag.remove("fluid"); + tag.remove("amount"); + return; + } + Identifier id = BuiltInRegistries.FLUID.getKey(this.fluid); + if (id == null) { + tag.remove("fluid"); + tag.remove("amount"); + return; + } + tag.putString("fluid", id.toString()); + tag.putInt("amount", this.amount); + } + + public static VesselContents read(CompoundTag tag) { + String id = Nbt.getString(tag, "fluid"); + int amount = Nbt.getInt(tag, "amount"); + if (id.isBlank() || amount <= 0) { + return EMPTY; + } + Identifier parsed = Identifier.tryParse(id); + if (parsed == null || !BuiltInRegistries.FLUID.containsKey(parsed)) { + return EMPTY; + } + //? if >=26.1 { + Fluid fluid = source(BuiltInRegistries.FLUID.getValue(parsed)); + //?} else + //Fluid fluid = source(BuiltInRegistries.FLUID.get(parsed)); + if (fluid == Fluids.EMPTY) { + return EMPTY; + } + return new VesselContents(fluid, amount); + } +} diff --git a/src/main/resources/assets/primalpottery/blockstates/pottery.json b/src/main/resources/assets/primalpottery/blockstates/pottery.json index e6637c1..4dea9a9 100644 --- a/src/main/resources/assets/primalpottery/blockstates/pottery.json +++ b/src/main/resources/assets/primalpottery/blockstates/pottery.json @@ -1,7 +1,20 @@ { "variants": { - "": { - "model": "primalpottery:block/pottery" - } + "light=0": { "model": "primalpottery:block/pottery" }, + "light=1": { "model": "primalpottery:block/pottery" }, + "light=2": { "model": "primalpottery:block/pottery" }, + "light=3": { "model": "primalpottery:block/pottery" }, + "light=4": { "model": "primalpottery:block/pottery" }, + "light=5": { "model": "primalpottery:block/pottery" }, + "light=6": { "model": "primalpottery:block/pottery" }, + "light=7": { "model": "primalpottery:block/pottery" }, + "light=8": { "model": "primalpottery:block/pottery" }, + "light=9": { "model": "primalpottery:block/pottery" }, + "light=10": { "model": "primalpottery:block/pottery" }, + "light=11": { "model": "primalpottery:block/pottery" }, + "light=12": { "model": "primalpottery:block/pottery" }, + "light=13": { "model": "primalpottery:block/pottery" }, + "light=14": { "model": "primalpottery:block/pottery" }, + "light=15": { "model": "primalpottery:block/pottery" } } } diff --git a/src/main/resources/assets/primalpottery/lang/en_us.json b/src/main/resources/assets/primalpottery/lang/en_us.json index 8308ffa..9e27df3 100644 --- a/src/main/resources/assets/primalpottery/lang/en_us.json +++ b/src/main/resources/assets/primalpottery/lang/en_us.json @@ -8,6 +8,7 @@ "item.primalpottery.raw_pottery_template": "Raw Pottery Template", "tooltip.primalpottery.type": "Type: %s", "tooltip.primalpottery.capacity": "Capacity: %s mL", + "tooltip.primalpottery.contents": "%s: %s mL", "pottery.primalpottery.type.lump": "Lump", "pottery.primalpottery.type.pot": "Pot", "pottery.primalpottery.type.jar": "Jar", diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java index 8534917..6f90831 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java @@ -1,11 +1,13 @@ package net.modcrafters.minecraft.primalpottery.client; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.mojang.blaze3d.vertex.PoseStack; import java.util.ArrayList; import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; import org.joml.Vector3f; import org.junit.jupiter.api.Test; @@ -107,6 +109,16 @@ void boardPushesIntoTheNarrowerClay() { assertEquals(28.0, westEdge(mesh, 24, 26), 0.01); } + private static float maxY(Mesh mesh) { + float highest = Float.NEGATIVE_INFINITY; + for (Mesh.Quad quad : mesh.quads()) { + for (int vertex = 0; vertex < 4; vertex++) { + highest = Math.max(highest, quad.y[vertex]); + } + } + return highest; + } + private static float reach(Mesh mesh, float low, float high) { float reach = 0; for (Mesh.Quad quad : mesh.quads()) { @@ -140,6 +152,86 @@ private static float westEdge(Mesh mesh, float low, float high) { return edge; } + @Test + void lidSitsOnTheRimAndCavityStaysOpen() { + Pottery pottery = new Pottery(List.of( + new PotteryDisc(2, 4, 2), + new PotteryDisc(4, 6, 5), + new PotteryDisc(1, 6, 0) + )); + Mesh open = new Mesh(); + open.vessel(0, 0, 0, pottery.discs(), Mesh.Texture.CLAY); + Mesh lidded = new Mesh(); + lidded.vessel(0, 0, 0, pottery.discs(), Mesh.Texture.CLAY); + lidded.cover(0, 0, 0, pottery.cover(), Mesh.Texture.CLAY); + float rimTop = maxY(open); + float layer = (float) pottery.cover().layer(); + float lidBottom = Float.POSITIVE_INFINITY; + boolean above = false; + for (Mesh.Quad quad : lidded.quads()) { + float min = quad.y[0]; + float max = quad.y[0]; + for (int vertex = 1; vertex < 4; vertex++) { + min = Math.min(min, quad.y[vertex]); + max = Math.max(max, quad.y[vertex]); + } + if (max > rimTop + 0.01F) { + above = true; + lidBottom = Math.min(lidBottom, min); + } + } + assertTrue(above); + assertEquals(rimTop + layer, lidBottom, 0.05); + assertEquals(rimTop + layer + (float) Pottery.PIXEL * 2, maxY(lidded), 0.05); + float plateTop = rimTop + layer + (float) Pottery.PIXEL; + assertEquals((float) (pottery.cover().hole() + Pottery.PIXEL / 2.0), reach(lidded, rimTop + layer, plateTop), 0.05); + assertTrue(reach(lidded, plateTop, maxY(lidded)) < reach(lidded, rimTop + layer, plateTop)); + + Mesh cavity = new Mesh(); + cavity.cavity(0, 0, 0, pottery.discs()); + assertFalse(cavity.quads().isEmpty()); + assertEquals(pottery.classify().volume(), new Pottery(pottery.discs()).classify().volume()); + } + + @Test + void fluidSurfaceFollowsEachOpenDisc() { + List discs = List.of( + new PotteryDisc(2, 4, 2), + new PotteryDisc(4, 6, 5), + new PotteryDisc(1, 6, 0) + ); + Mesh mesh = new Mesh(); + mesh.cavity(0, 0, 0, discs); + assertFalse(mesh.quads().isEmpty()); + float rimTop = 7; + float belly = 0; + float rim = 0; + float highest = 0; + for (Mesh.Quad quad : mesh.quads()) { + for (int vertex = 0; vertex < 4; vertex++) { + float y = quad.y[vertex]; + float radius = (float) Math.hypot(quad.x[vertex], quad.z[vertex]); + assertTrue(y < rimTop); + assertTrue(y >= 1); + highest = Math.max(highest, y); + if (y > 5.01F) { + assertTrue(radius < 2); + rim = Math.max(rim, radius); + } else if (y > 1.01F) { + assertTrue(radius < 5); + belly = Math.max(belly, radius); + } + } + } + assertEquals(5 - Mesh.FLUID_INSET, belly, 0.02); + assertEquals(2 - Mesh.FLUID_INSET, rim, 0.02); + assertEquals(rimTop - Mesh.FLUID_INSET, highest, 0.02); + + Mesh skipped = new Mesh(); + skipped.cavity(0, 0, 0, List.of(new PotteryDisc(2, 4, Mesh.FLUID_INSET), new PotteryDisc(1, 4, 0))); + assertEquals(0, skipped.quads().size()); + } + @Test void fittedClayStaysOnOneSprite() { List discs = List.of(new PotteryDisc(12, 5.5, 0)); diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java index 9ae6ae8..5ded518 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java @@ -1,12 +1,32 @@ package net.modcrafters.minecraft.primalpottery.pottery; import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; +import net.minecraft.SharedConstants; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.BubbleColumnBlock; +import net.minecraft.world.level.block.LiquidBlock; +import net.minecraft.world.level.block.SlabBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Fluids; +import net.modcrafters.minecraft.primalpottery.item.PotteryItem; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; class PotteryTest { + @BeforeAll + static void bootstrap() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + @Test void classificationUsesTheOpeningAndWidestOutsideDiameter() { assertEquals(PotteryType.POT, vessel(5).classify().type()); @@ -62,6 +82,55 @@ void wheelFormsTheInstalledTemplate() { assertEquals(1, Pottery.formed(template).discs().getFirst().innerRadius(), 0.0001); } + @Test + void lidCopiesTheRimAndLeavesTheProfile() { + Pottery pottery = new Pottery(List.of( + new PotteryDisc(1, 0, 0), + new PotteryDisc(2, 4, 2), + new PotteryDisc(3, 5, 3), + new PotteryDisc(1, 5, 0) + )); + int volume = pottery.classify().volume(); + PotteryDisc lid = pottery.lidDisc(); + assertEquals(Pottery.PIXEL, lid.height(), 0.0001); + assertEquals(2 + Pottery.PIXEL / 2.0, lid.radius(), 0.0001); + assertEquals(0, lid.innerRadius(), 0.0001); + assertEquals(pottery.discs(), pottery.drawDiscs(true)); + assertEquals(pottery.discs(), pottery.drawDiscs(false)); + assertEquals(volume, pottery.classify().volume()); + Pottery.Cover cover = pottery.cover(); + assertEquals(1 + 2 + 3 + 1, cover.top(), 0.0001); + assertEquals(2, cover.layer(), 0.0001); + assertEquals(2, cover.hole(), 0.0001); + + Pottery lump = new Pottery(List.of(new PotteryDisc(2, 4, 0), new PotteryDisc(2, 4, 0))); + assertNull(lump.lidDisc()); + assertEquals(lump.discs(), lump.drawDiscs(true)); + assertNull(new Pottery(List.of(new PotteryDisc(2, 0.4, 0))).lidDisc()); + } + + @Test + void lidKeyIsOmittedWhenOpen() { + CompoundTag tag = new CompoundTag(); + tag.putBoolean("lid", true); + assertTrue(Nbt.getBoolean(tag, "lid")); + assertTrue(tag.contains("lid")); + tag.remove("lid"); + assertFalse(Nbt.getBoolean(tag, "lid")); + assertFalse(tag.contains("lid")); + } + + @Test + void tooltipColorTintsOnlyWater() { + assertEquals(0x3F76E4, VesselContents.tooltipColor(Fluids.WATER)); + assertEquals(-1, VesselContents.tooltipColor(Fluids.LAVA)); + assertEquals(-1, VesselContents.tooltipColor(Fluids.EMPTY)); + assertEquals(0x3F76E4, PotteryItem.fluidName(Fluids.WATER).getStyle().getColor().getValue()); + assertEquals(Blocks.WATER.getName().getString(), PotteryItem.fluidName(Fluids.WATER).getString()); + assertNull(PotteryItem.fluidName(Fluids.LAVA).getStyle().getColor()); + assertEquals(Blocks.LAVA.getName().getString(), PotteryItem.fluidName(Fluids.LAVA).getString()); + } + @Test void nbtRoundTripKeepsTheShape() { Pottery pottery = new Pottery(List.of( @@ -78,6 +147,164 @@ void nbtRoundTripKeepsTheShape() { assertEquals(1, loaded.discs().get(2).height(), 0.0001); } + @Test + void emissionFollowsTheFluidSourceBlock() { + assertEquals(15, Blocks.LAVA.defaultBlockState().getLightEmission()); + assertEquals(0, Blocks.WATER.defaultBlockState().getLightEmission()); + assertEquals(15, VesselContents.of(Fluids.LAVA, 1).emission()); + assertEquals(15, VesselContents.of(Fluids.FLOWING_LAVA, 1).emission()); + assertEquals(0, VesselContents.of(Fluids.WATER, 1).emission()); + assertEquals(0, VesselContents.of(Fluids.FLOWING_WATER, 1).emission()); + assertEquals(0, VesselContents.EMPTY.emission()); + } + + @Test + void chooseFillsFromASource() { + assertEquals(VesselContents.Choice.FILL, VesselContents.choose(looking("minecraft:water"))); + } + + @Test + void chooseFillsFromFlowingWaterAndLava() { + assertEquals(VesselContents.Choice.FILL, VesselContents.choose(looking("minecraft:water"))); + assertEquals(Fluids.WATER, VesselContents.source(Fluids.FLOWING_WATER)); + assertEquals(VesselContents.Choice.FILL, VesselContents.choose(looking("minecraft:lava"))); + assertEquals(Fluids.LAVA, VesselContents.source(Fluids.FLOWING_LAVA)); + assertTrue(VesselContents.ownsFluidBlock(flowing(Blocks.WATER), flowing(Blocks.WATER).getFluidState())); + assertTrue(VesselContents.ownsFluidBlock(flowing(Blocks.LAVA), flowing(Blocks.LAVA).getFluidState())); + } + + @Test + void chooseFillsFromAnotherFluid() { + assertEquals(VesselContents.Choice.FILL, VesselContents.choose(looking("example:oil"))); + } + + @Test + void waterloggedAndBubbleColumnDoNotFill() { + BlockState slab = Blocks.STONE_SLAB.defaultBlockState().setValue(SlabBlock.WATERLOGGED, true); + BlockState bubble = Blocks.BUBBLE_COLUMN.defaultBlockState(); + assertFalse(VesselContents.ownsFluidBlock(slab, slab.getFluidState())); + assertFalse(bubble.getFluidState().isEmpty()); + assertFalse(VesselContents.ownsFluidBlock(bubble, bubble.getFluidState())); + assertEquals(VesselContents.Choice.REFUSE, VesselContents.choose(blocked())); + VesselContents.Facts logged = blocked(); + assertEquals(VesselContents.Choice.REFUSE, VesselContents.choose(new VesselContents.Facts( + logged.player(), logged.vessel(), false, logged.volume(), logged.povFluid(), logged.sourceId(), + logged.interact(), logged.canPlace(), logged.clickedFluid(), false, true, true + ))); + } + + @Test + void nullPlayerDoesNotFill() { + VesselContents.Facts facts = looking("minecraft:water"); + assertEquals(VesselContents.Choice.REFUSE, VesselContents.choose(new VesselContents.Facts( + false, facts.vessel(), facts.empty(), facts.volume(), facts.povFluid(), facts.sourceId(), + false, facts.canPlace(), facts.clickedFluid(), facts.clickedSource(), false, false + ))); + } + + @Test + void failedInteractCheckDoesNotFill() { + VesselContents.Facts facts = looking("minecraft:water"); + assertEquals(VesselContents.Choice.REFUSE, VesselContents.choose(new VesselContents.Facts( + facts.player(), facts.vessel(), facts.empty(), facts.volume(), facts.povFluid(), facts.sourceId(), + false, facts.canPlace(), facts.clickedFluid(), facts.clickedSource(), facts.sneaking(), facts.holding() + ))); + } + + @Test + void topFaceLumpRefusesFluid() { + assertEquals(VesselContents.Choice.REFUSE, VesselContents.choose(new VesselContents.Facts( + true, false, true, 0, true, "minecraft:water", true, true, true, true, false, false + ))); + } + + @Test + void nonSneakOnFluidRefuses() { + assertEquals(VesselContents.Choice.REFUSE, VesselContents.choose(new VesselContents.Facts( + true, true, false, 54, false, "minecraft:water", true, true, true, true, false, true + ))); + } + + @Test + void sneakOnAWaterSourcePlaces() { + assertEquals(VesselContents.Choice.PLACE, VesselContents.choose(new VesselContents.Facts( + true, true, false, 54, false, "minecraft:water", true, true, true, true, true, true + ))); + } + + @Test + void sneakOnFlowingFluidRefuses() { + assertEquals(VesselContents.Choice.REFUSE, VesselContents.choose(new VesselContents.Facts( + true, true, false, 54, false, "minecraft:water", true, true, true, false, true, true + ))); + } + + @Test + void pourMovesWhatFits() { + VesselContents twenty = VesselContents.of(Fluids.WATER, 20); + VesselContents hundred = VesselContents.of(Fluids.WATER, 100); + assertEquals(20, VesselContents.poured(twenty, VesselContents.EMPTY, 54)); + assertEquals(44, VesselContents.poured(hundred, VesselContents.of(Fluids.WATER, 10), 54)); + assertEquals(0, VesselContents.poured(twenty, VesselContents.of(Fluids.WATER, 54), 54)); + assertEquals(0, VesselContents.poured(twenty, VesselContents.of(Fluids.LAVA, 10), 54)); + assertEquals(0, VesselContents.poured(VesselContents.EMPTY, VesselContents.EMPTY, 54)); + assertEquals(0, VesselContents.poured(twenty, VesselContents.EMPTY, 0)); + } + + @Test + void contentsRoundTrip() { + CompoundTag tag = new CompoundTag(); + VesselContents.of(Fluids.WATER, 54).write(tag); + VesselContents loaded = VesselContents.read(tag); + assertEquals(Fluids.WATER, loaded.fluid()); + assertEquals(54, loaded.amount()); + assertEquals("minecraft:water", Nbt.getString(tag, "fluid")); + + CompoundTag flowing = new CompoundTag(); + flowing.putString("fluid", BuiltInRegistries.FLUID.getKey(Fluids.FLOWING_WATER).toString()); + flowing.putInt("amount", 12); + assertEquals(Fluids.WATER, VesselContents.read(flowing).fluid()); + assertEquals(12, VesselContents.read(flowing).amount()); + + CompoundTag flowingLava = new CompoundTag(); + flowingLava.putString("fluid", BuiltInRegistries.FLUID.getKey(Fluids.FLOWING_LAVA).toString()); + flowingLava.putInt("amount", 3); + assertEquals(Fluids.LAVA, VesselContents.read(flowingLava).fluid()); + + CompoundTag empty = new CompoundTag(); + empty.putString("fluid", "minecraft:lava"); + empty.putInt("amount", 1); + VesselContents.EMPTY.write(empty); + assertEquals("", Nbt.getString(empty, "fluid")); + assertEquals(0, Nbt.getInt(empty, "amount")); + + assertTrue(VesselContents.read(new CompoundTag()).isEmpty()); + CompoundTag blank = new CompoundTag(); + blank.putString("fluid", " "); + blank.putInt("amount", 4); + assertTrue(VesselContents.read(blank).isEmpty()); + CompoundTag unknown = new CompoundTag(); + unknown.putString("fluid", "example:oil"); + unknown.putInt("amount", 4); + assertTrue(VesselContents.read(unknown).isEmpty()); + CompoundTag none = new CompoundTag(); + none.putString("fluid", "minecraft:water"); + none.putInt("amount", 0); + assertTrue(VesselContents.read(none).isEmpty()); + } + + private static VesselContents.Facts looking(String sourceId) { + return new VesselContents.Facts(true, true, true, 54, true, sourceId, true, true, true, true, false, false); + } + + private static VesselContents.Facts blocked() { + return new VesselContents.Facts(true, true, true, 54, false, "", true, true, true, false, false, false); + } + + private static BlockState flowing(net.minecraft.world.level.block.Block block) { + return block.defaultBlockState().setValue(LiquidBlock.LEVEL, 1); + } + private static Pottery vessel(double opening) { return new Pottery(List.of( new PotteryDisc(1, opening + 0.5, opening),