From 96b91168a2c4b07c36e063d2412d5f5175e518ed Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:49:51 +0100 Subject: [PATCH 01/64] Update the GTNH build toolchain and compatibility dependencies --- dependencies.gradle | 18 ++++++++++++++++++ gradle/gradle-daemon-jvm.properties | 12 ++++++++++++ gradle/wrapper/gradle-wrapper.properties | 2 +- settings.gradle | 2 +- 4 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 gradle/gradle-daemon-jvm.properties diff --git a/dependencies.gradle b/dependencies.gradle index 03105e0b..96977d96 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -3,4 +3,22 @@ dependencies { implementation('com.github.GTNewHorizons:LunatriusCore:1.3.0-GTNH:dev') compileOnly rfg.deobf('curse.maven:lotr-423748:4091561') + compileOnly('com.github.GTNewHorizons:ForgeMultipart:1.7.18:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:CodeChickenCore:1.4.22:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:ArchitectureCraft:1.12.19:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:CarpentersBlocks:3.7.3-GTNH:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:CookingForBlockheads:1.4.14-GTNH:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:Postea:1.2.7:dev') { transitive = false } + + // Optional mods and their dependencies for the compatibility test client. + runtimeOnlyNonPublishable('com.github.GTNewHorizons:ForgeMultipart:1.7.18:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:CodeChickenCore:1.4.22:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:ArchitectureCraft:1.12.19:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:CarpentersBlocks:3.7.3-GTNH:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:Postea:1.2.7:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:CookingForBlockheads:1.4.14-GTNH:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:AppleCore:3.3.13:dev') { transitive = false } + runtimeOnlyNonPublishable('ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.65-GTNH:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.11.48:dev') { transitive = false } + runtimeOnlyNonPublishable('io.github.legacymoddingmc:unimixins:0.3.1:dev') { transitive = false } } diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 00000000..9926fc2a --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,12 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/50d5fe9033e125599b2aa94dc590a27d/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/b4d79acf73eaf165b8c6bc8fba023764/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/50d5fe9033e125599b2aa94dc590a27d/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/b4d79acf73eaf165b8c6bc8fba023764/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/54e1f31b8c26d88fb972744b5f1ba132/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/5d8d54de3a467a8da01a32410565830f/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/50d5fe9033e125599b2aa94dc590a27d/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/b4d79acf73eaf165b8c6bc8fba023764/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/a7c7be8a3ec5d8e677e7250d9c1ce3ed/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d0edfb63e02dc58e61e6c804b15e02e8/redirect +toolchainVersion=25 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37f853b1..c42672d9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/settings.gradle b/settings.gradle index ff436f2c..bbc17851 100644 --- a/settings.gradle +++ b/settings.gradle @@ -17,7 +17,7 @@ pluginManagement { } plugins { - id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.38' + id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.34' } From 6c50317a3d90eb4295a3834c0b085c7c5e476ee5 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:50:00 +0100 Subject: [PATCH 02/64] Cache optional mod detection --- .../handler/client/InputHandler.java | 8 ++++---- .../schematica/proxy/ClientProxy.java | 4 ++-- .../schematica/proxy/CommonProxy.java | 3 --- .../lunatrius/schematica/reference/Mods.java | 20 +++++++++++++++++++ 4 files changed, 26 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/github/lunatrius/schematica/reference/Mods.java diff --git a/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java index 3a6bbfa8..e8f4fbbf 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java @@ -12,13 +12,13 @@ import org.lwjgl.input.Keyboard; -import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.client.gui.control.GuiSchematicControl; import com.github.lunatrius.schematica.client.gui.load.GuiSchematicLoad; import com.github.lunatrius.schematica.client.gui.save.GuiSchematicSave; import com.github.lunatrius.schematica.client.renderer.RendererSchematicGlobal; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.proxy.ClientProxy; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; @@ -31,15 +31,15 @@ public class InputHandler { private static final KeyBinding KEY_BINDING_LOAD = new KeyBinding( Names.Keys.LOAD, - Schematica.proxy.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_DIVIDE, + Mods.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_DIVIDE, Names.Keys.CATEGORY); private static final KeyBinding KEY_BINDING_SAVE = new KeyBinding( Names.Keys.SAVE, - Schematica.proxy.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_MULTIPLY, + Mods.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_MULTIPLY, Names.Keys.CATEGORY); private static final KeyBinding KEY_BINDING_CONTROL = new KeyBinding( Names.Keys.CONTROL, - Schematica.proxy.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_SUBTRACT, + Mods.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_SUBTRACT, Names.Keys.CATEGORY); private static final KeyBinding KEY_BINDING_LAYER_INC = new KeyBinding( Names.Keys.LAYER_INC, diff --git a/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java b/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java index f9b9277e..8087a0ec 100644 --- a/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java +++ b/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java @@ -37,6 +37,7 @@ import com.github.lunatrius.schematica.handler.client.TickHandler; import com.github.lunatrius.schematica.handler.client.WorldHandler; import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.util.Coordinates; import com.github.lunatrius.schematica.world.schematic.SchematicFormat; @@ -47,7 +48,6 @@ import cpw.mods.fml.client.config.GuiConfigEntries; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @@ -343,7 +343,7 @@ public void init(FMLInitializationEvent event) { public void postInit(FMLPostInitializationEvent event) { super.postInit(event); try { - if (Loader.isModLoaded("lotr")) { + if (Mods.LOTR) { Reference.logger.info("Lotr mod detected, creating proxy"); lotrProxy = Class.forName(Reference.LOTR_PROXY) .asSubclass(ILOTRPresent.class) diff --git a/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java b/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java index 8c310a86..74721e36 100644 --- a/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java +++ b/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java @@ -30,7 +30,6 @@ import com.github.lunatrius.schematica.world.storage.Schematic; import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @@ -40,10 +39,8 @@ public abstract class CommonProxy { public boolean isSaveEnabled = true; public boolean isLoadEnabled = true; - public boolean GTNH = false; public void preInit(FMLPreInitializationEvent event) { - GTNH = Loader.isModLoaded("dreamcraft"); Reference.logger = event.getModLog(); ConfigurationHandler.init(event.getSuggestedConfigurationFile()); } diff --git a/src/main/java/com/github/lunatrius/schematica/reference/Mods.java b/src/main/java/com/github/lunatrius/schematica/reference/Mods.java new file mode 100644 index 00000000..b4167ae2 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/reference/Mods.java @@ -0,0 +1,20 @@ +package com.github.lunatrius.schematica.reference; + +import cpw.mods.fml.common.Loader; + +/** Snapshots mod presence on first use, after FML mod discovery. */ +public final class Mods { + + public static final String COOKING_FOR_BLOCKHEADS_ID = "cookingforblockheads"; + + public static final boolean ARCHITECTURE_CRAFT = Loader.isModLoaded("ArchitectureCraft"); + public static final boolean CARPENTERS_BLOCKS = Loader.isModLoaded("CarpentersBlocks"); + public static final boolean COOKING_FOR_BLOCKHEADS = Loader.isModLoaded(COOKING_FOR_BLOCKHEADS_ID); + public static final boolean FORGE_MICROBLOCK = Loader.isModLoaded("ForgeMicroblock"); + public static final boolean FORGE_MULTIPART = Loader.isModLoaded("ForgeMultipart"); + public static final boolean GTNH = Loader.isModLoaded("dreamcraft"); + public static final boolean LOTR = Loader.isModLoaded("lotr"); + public static final boolean POSTEA = Loader.isModLoaded("postea"); + + private Mods() {} +} From 2f8d449652d8e7b0a1ad5a7f3a39881f655ef9ee Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:50:21 +0100 Subject: [PATCH 03/64] Preserve modded block data in schematics --- .../schematica/nbt/CarpentersBlocksNBT.java | 31 ++++ .../schematica/nbt/ForgeMultipart.java | 28 +++- .../schematica/nbt/LegacyGregTechOre.java | 27 ++++ .../lunatrius/schematica/reference/Names.java | 1 + .../world/schematic/SchematicAlpha.java | 143 ++++++++++++------ .../schematica/world/storage/Schematic.java | 8 +- 6 files changed, 184 insertions(+), 54 deletions(-) create mode 100644 src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java create mode 100644 src/main/java/com/github/lunatrius/schematica/nbt/LegacyGregTechOre.java diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java b/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java new file mode 100644 index 00000000..8ccfb86a --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java @@ -0,0 +1,31 @@ +package com.github.lunatrius.schematica.nbt; + +import net.minecraft.item.Item; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; + +import com.carpentersblocks.tileentity.TEBase; + +import cpw.mods.fml.common.registry.GameData; + +public final class CarpentersBlocksNBT { + + private static final String ITEM_REGISTRY_NAME = "cbUniqueId"; + + private CarpentersBlocksNBT() {} + + public static void remapAttributeItems(NBTTagCompound tile) { + final NBTTagList attributes = tile.getTagList(TEBase.TAG_ATTR_LIST, Constants.NBT.TAG_COMPOUND); + for (int i = 0; i < attributes.tagCount(); i++) { + final NBTTagCompound attribute = attributes.getCompoundTagAt(i); + final String name = attribute.getString(ITEM_REGISTRY_NAME); + if (!name.isEmpty()) { + // Carpenter's Blocks uses the registry name only when the numeric ID fails to resolve. + final Item item = GameData.getItemRegistry() + .getObject(name); + attribute.setShort("id", (short) (item == null ? 0 : Item.getIdFromItem(item))); + } + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java b/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java index 9e3516ba..8547fe5d 100644 --- a/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java +++ b/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java @@ -10,10 +10,10 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; import cpw.mods.fml.relauncher.ReflectionHelper; import scala.Option; import scala.collection.Iterable; @@ -28,6 +28,8 @@ public class ForgeMultipart { private static Map instancesTypeMap; private static Method methodMaterialID; private static Method methodCreatePart; + private static Object instanceMultiPartRegistry; + private static Method methodLoadRegisteredPart; private static Method methodLoad; private static Method methodOnPartChanged; private static Object instanceMultipartGenerator$; @@ -36,7 +38,7 @@ public class ForgeMultipart { private static Method methodCreateFromNBT; public static void init() { - enabled = Loader.isModLoaded("ForgeMultipart"); + enabled = Mods.FORGE_MULTIPART; client = FMLCommonHandler.instance() .getSide() .isClient(); @@ -54,6 +56,13 @@ public static void init() { final Object instanceMultiPartRegistry$module$ = fieldMultiPartRegistry$module$ .get(classMultiPartRegistry$); instancesTypeMap = (Map) field$typeMap.get(instanceMultiPartRegistry$module$); + instanceMultiPartRegistry = instanceMultiPartRegistry$module$; + methodLoadRegisteredPart = ReflectionHelper.findMethod( + classMultiPartRegistry$, + null, + new String[] { "loadPart" }, + String.class, + NBTTagCompound.class); final Class classMicroMaterialRegistry = ReflectionHelper .getClass(classLoader, "codechicken.microblock.MicroMaterialRegistry"); @@ -130,9 +139,7 @@ private static TileEntity createFromNBTClient(final NBTTagCompound tileEntityCom for (int i = 0; i < partList.tagCount(); i++) { final NBTTagCompound partTag = partList.getCompoundTagAt(i); final String partID = partTag.getString("id"); - final int materialID = materialID(partTag.getString("material")); - - final Object part = createPart(partID, client, materialID); + final Object part = createPart(partID, client, partTag); if (part != null) { load(part, partTag); parts.add(part); @@ -173,7 +180,7 @@ private static int materialID(final String material) throws ReflectiveOperationE return (Integer) methodMaterialID.invoke(null, material); } - private static Object createPart(final String partID, final boolean client, final int materialID) + private static Object createPart(final String partID, final boolean client, final NBTTagCompound partTag) throws ReflectiveOperationException { final Option option = instancesTypeMap.get(partID); if (option.isEmpty()) { @@ -181,7 +188,14 @@ private static Object createPart(final String partID, final boolean client, fina return null; } - return methodCreatePart.invoke(option.get(), client, materialID); + final Object factory = option.get(); + if (methodCreatePart.getDeclaringClass() + .isInstance(factory)) { + return methodCreatePart.invoke(factory, client, materialID(partTag.getString("material"))); + } + + // Other multipart factories load their own NBT and can share a tile with microblocks. + return methodLoadRegisteredPart.invoke(instanceMultiPartRegistry, partID, partTag); } private static Object load(final Object part, final NBTTagCompound partTag) throws ReflectiveOperationException { diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/LegacyGregTechOre.java b/src/main/java/com/github/lunatrius/schematica/nbt/LegacyGregTechOre.java new file mode 100644 index 00000000..fcf7c4a7 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/nbt/LegacyGregTechOre.java @@ -0,0 +1,27 @@ +package com.github.lunatrius.schematica.nbt; + +import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; + +import com.github.lunatrius.schematica.api.ISchematic; +import com.gtnewhorizons.postea.utility.BlockInfo; +import com.gtnewhorizons.postea.utility.TransformerRegistry; + +public final class LegacyGregTechOre { + + private static final String TILE_ID = "GT_TileEntity_Ores"; + + private LegacyGregTechOre() {} + + public static boolean replace(ISchematic schematic, NBTTagCompound tag) { + for (var converter : TransformerRegistry.getTileEntityToNormalBlockTransformerFunction(TILE_ID)) { + // GregTech's ore converter needs only the material, host rock and natural flag from the tile tag. + final BlockInfo ore = converter.apply(tag, null, null); + if (ore != null && ore.block != Blocks.air && ore.tileTransformer == null) { + return schematic + .setBlock(tag.getInteger("x"), tag.getInteger("y"), tag.getInteger("z"), ore.block, ore.metadata); + } + } + return false; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/reference/Names.java b/src/main/java/com/github/lunatrius/schematica/reference/Names.java index 8590d37c..33e9c6b3 100644 --- a/src/main/java/com/github/lunatrius/schematica/reference/Names.java +++ b/src/main/java/com/github/lunatrius/schematica/reference/Names.java @@ -231,6 +231,7 @@ public static final class NBT { public static final String ICON = "Icon"; public static final String BLOCKS = "Blocks"; public static final String DATA = "Data"; + public static final String DATA_HIGH = "SchematicaDataHigh"; public static final String ADD_BLOCKS = "AddBlocks"; public static final String ADD_BLOCKS_SCHEMATICA = "Add"; public static final String WIDTH = "Width"; diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java index 63e35ad9..f8547372 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java @@ -19,7 +19,10 @@ import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.api.event.PreSchematicSaveEvent; import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.nbt.CarpentersBlocksNBT; +import com.github.lunatrius.schematica.nbt.LegacyGregTechOre; import com.github.lunatrius.schematica.nbt.NBTHelper; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.world.storage.Schematic; @@ -38,19 +41,23 @@ public ISchematic readFromNBT(NBTTagCompound tagCompound) { byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); + byte[] highMetadata = readHighMetadata(tagCompound, localMetadata.length); byte[] extraBlocks = tagCompound.getByteArray(Names.NBT.ADD_BLOCKS); + if (extraBlocks.length != localBlocks.length) { + throw new IllegalArgumentException("Invalid schemplus AddBlocks length"); + } short width = tagCompound.getShort(Names.NBT.WIDTH); short length = tagCompound.getShort(Names.NBT.LENGTH); short height = tagCompound.getShort(Names.NBT.HEIGHT); - Short id; - Map oldToNew = new HashMap<>(); + Integer id; + Map oldToNew = new HashMap<>(); if (tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); Set names = mapping.func_150296_c(); for (String name : names) { - oldToNew.put(mapping.getShort(name), (short) BLOCK_REGISTRY.getId(name)); + oldToNew.put(mapping.getShort(name), BLOCK_REGISTRY.getId(name)); } } @@ -59,8 +66,11 @@ public ISchematic readFromNBT(NBTTagCompound tagCompound) { for (int y = 0; y < height; y++) { for (int z = 0; z < length; z++) { int index = x + (y * length + z) * width; - int blockID = (localBlocks[index] & 0xFF) | ((extraBlocks[index] & 0xFF) * 256); + int blockID = (localBlocks[index] & 0xFF) | ((extraBlocks[index] & 0xFF) << 8); int meta = localMetadata[index] & 0xFF; + if (highMetadata != null) { + meta |= (highMetadata[index] & 0xFF) << 8; + } if ((id = oldToNew.get((short) blockID)) != null) { blockID = id; @@ -71,18 +81,7 @@ public ISchematic readFromNBT(NBTTagCompound tagCompound) { } } - NBTTagList tileEntitiesList = tagCompound.getTagList(Names.NBT.TILE_ENTITIES, Constants.NBT.TAG_COMPOUND); - - for (int i = 0; i < tileEntitiesList.tagCount(); i++) { - try { - TileEntity tileEntity = NBTHelper.readTileEntityFromCompound(tileEntitiesList.getCompoundTagAt(i)); - if (tileEntity != null) { - schematic.setTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity); - } - } catch (Exception e) { - Reference.logger.error("TileEntity failed to load properly!", e); - } - } + loadTiles(tagCompound, schematic); return schematic; } else { @@ -90,6 +89,7 @@ public ISchematic readFromNBT(NBTTagCompound tagCompound) { byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); + byte[] highMetadata = readHighMetadata(tagCompound, localMetadata.length); boolean extra = false; byte[] extraBlocks = null; @@ -111,13 +111,13 @@ public ISchematic readFromNBT(NBTTagCompound tagCompound) { short length = tagCompound.getShort(Names.NBT.LENGTH); short height = tagCompound.getShort(Names.NBT.HEIGHT); - Short id; - Map oldToNew = new HashMap<>(); + Integer id; + Map oldToNew = new HashMap<>(); if (tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); Set names = mapping.func_150296_c(); for (String name : names) { - oldToNew.put(mapping.getShort(name), (short) BLOCK_REGISTRY.getId(name)); + oldToNew.put(mapping.getShort(name), BLOCK_REGISTRY.getId(name)); } } @@ -128,6 +128,9 @@ public ISchematic readFromNBT(NBTTagCompound tagCompound) { int index = x + (y * length + z) * width; int blockID = (localBlocks[index] & 0xFF) | (extra ? ((extraBlocks[index] & 0xFF) << 8) : 0); int meta = localMetadata[index] & 0xFF; + if (highMetadata != null) { + meta |= (highMetadata[index] & 0xFF) << 8; + } if ((id = oldToNew.get((short) blockID)) != null) { blockID = id; @@ -138,24 +141,53 @@ public ISchematic readFromNBT(NBTTagCompound tagCompound) { } } - NBTTagList tileEntitiesList = tagCompound.getTagList(Names.NBT.TILE_ENTITIES, Constants.NBT.TAG_COMPOUND); - - for (int i = 0; i < tileEntitiesList.tagCount(); i++) { - try { - TileEntity tileEntity = NBTHelper.readTileEntityFromCompound(tileEntitiesList.getCompoundTagAt(i)); - if (tileEntity != null) { - schematic.setTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity); - } - } catch (Exception e) { - Reference.logger.error("TileEntity failed to load properly!", e); - } - } + loadTiles(tagCompound, schematic); return schematic; } } + private static byte[] readHighMetadata(NBTTagCompound tag, int length) { + if (!tag.hasKey(Names.NBT.DATA_HIGH)) { + return null; + } + if (!tag.hasKey(Names.NBT.DATA_HIGH, Constants.NBT.TAG_BYTE_ARRAY)) { + throw new IllegalArgumentException("Invalid " + Names.NBT.DATA_HIGH + " type"); + } + final byte[] metadata = tag.getByteArray(Names.NBT.DATA_HIGH); + if (metadata.length != length) { + throw new IllegalArgumentException("Invalid " + Names.NBT.DATA_HIGH + " length"); + } + return metadata; + } + + private void loadTiles(NBTTagCompound tagCompound, ISchematic schematic) { + final NBTTagList tiles = tagCompound.getTagList(Names.NBT.TILE_ENTITIES, Constants.NBT.TAG_COMPOUND); + for (int i = 0; i < tiles.tagCount(); i++) { + final NBTTagCompound tag = tiles.getCompoundTagAt(i); + try { + if (Mods.POSTEA && "GT_TileEntity_Ores".equals(tag.getString("id")) + && LegacyGregTechOre.replace(schematic, tag)) { + continue; + } + } catch (Exception e) { + Reference.logger.debug("Could not convert a legacy GregTech ore", e); + } + try { + if (Mods.CARPENTERS_BLOCKS) { + CarpentersBlocksNBT.remapAttributeItems(tag); + } + final TileEntity tileEntity = NBTHelper.readTileEntityFromCompound(tag); + if (tileEntity != null) { + schematic.setTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity); + } + } catch (Exception e) { + Reference.logger.error("TileEntity failed to load properly!", e); + } + } + } + @Override public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, World backupWorld) { if (ConfigurationHandler.useSchematicplusFormat) { @@ -171,6 +203,7 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl int size = schematic.getWidth() * schematic.getLength() * schematic.getHeight(); byte[] localBlocks = new byte[size]; byte[] localMetadata = new byte[size]; + byte[] highMetadata = null; byte[] extraBlocks = new byte[size]; Map mappings = new HashMap<>(); @@ -180,15 +213,16 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl final int index = x + (y * schematic.getLength() + z) * schematic.getWidth(); final Block block = schematic.getBlock(x, y, z); int blockId = BLOCK_REGISTRY.getId(block); - int tempblockId = blockId; - int numextra = 0; - for (int i = 1; tempblockId > 256; i++) { - tempblockId = tempblockId - 256; - numextra = i; + localBlocks[index] = (byte) blockId; + extraBlocks[index] = (byte) (blockId >>> 8); + final int metadata = schematic.getBlockMetadata(x, y, z); + localMetadata[index] = (byte) metadata; + if ((metadata >>> 8) != 0) { + if (highMetadata == null) { + highMetadata = new byte[size]; + } + highMetadata[index] = (byte) (metadata >>> 8); } - localBlocks[index] = (byte) tempblockId; - extraBlocks[index] = (byte) numextra; - localMetadata[index] = (byte) schematic.getBlockMetadata(x, y, z); String name = BLOCK_REGISTRY.getNameForObject(block); if (!mappings.containsKey(name)) { mappings.put(name, (short) blockId); @@ -221,6 +255,9 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl } localBlocks[pos] = (byte) BLOCK_REGISTRY.getId(Blocks.bedrock); localMetadata[pos] = 0; + if (highMetadata != null) { + highMetadata[pos] = 0; + } extraBlocks[pos] = 0; } } @@ -249,6 +286,9 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); tagCompound.setByteArray(Names.NBT.BLOCKS, localBlocks); tagCompound.setByteArray(Names.NBT.DATA, localMetadata); + if (highMetadata != null) { + tagCompound.setByteArray(Names.NBT.DATA_HIGH, highMetadata); + } tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, extraBlocks); tagCompound.setTag(Names.NBT.ENTITIES, entityList); tagCompound.setTag(Names.NBT.TILE_ENTITIES, tileEntitiesList); @@ -272,9 +312,11 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl int size = schematic.getWidth() * schematic.getLength() * schematic.getHeight(); byte[] localBlocks = new byte[size]; byte[] localMetadata = new byte[size]; + byte[] highMetadata = null; byte[] extraBlocks = new byte[size]; byte[] extraBlocksNibble = new byte[(int) Math.ceil(size / 2.0)]; boolean extra = false; + boolean extendedIds = false; Map mappings = new HashMap<>(); for (int x = 0; x < schematic.getWidth(); x++) { @@ -284,10 +326,17 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl final Block block = schematic.getBlock(x, y, z); final int blockId = BLOCK_REGISTRY.getId(block); localBlocks[index] = (byte) blockId; - localMetadata[index] = (byte) schematic.getBlockMetadata(x, y, z); - if ((extraBlocks[index] = (byte) (blockId >> 8)) > 0) { - extra = true; + final int metadata = schematic.getBlockMetadata(x, y, z); + localMetadata[index] = (byte) metadata; + if ((metadata >>> 8) != 0) { + if (highMetadata == null) { + highMetadata = new byte[size]; + } + highMetadata[index] = (byte) (metadata >>> 8); } + extraBlocks[index] = (byte) (blockId >>> 8); + extra |= blockId > 0xFF; + extendedIds |= blockId > 0xFFF; String name = BLOCK_REGISTRY.getNameForObject(block); if (!mappings.containsKey(name)) { @@ -321,6 +370,9 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl } localBlocks[pos] = (byte) BLOCK_REGISTRY.getId(Blocks.bedrock); localMetadata[pos] = 0; + if (highMetadata != null) { + highMetadata[pos] = 0; + } extraBlocks[pos] = 0; } } @@ -357,7 +409,12 @@ public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, Worl tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); tagCompound.setByteArray(Names.NBT.BLOCKS, localBlocks); tagCompound.setByteArray(Names.NBT.DATA, localMetadata); - if (extra) { + if (highMetadata != null) { + tagCompound.setByteArray(Names.NBT.DATA_HIGH, highMetadata); + } + if (extendedIds) { + tagCompound.setByteArray(Names.NBT.ADD_BLOCKS_SCHEMATICA, extraBlocks); + } else if (extra) { tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, extraBlocksNibble); } tagCompound.setTag(Names.NBT.ENTITIES, entityList); diff --git a/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java b/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java index 680237f5..7705975e 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java +++ b/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java @@ -22,7 +22,7 @@ public class Schematic implements ISchematic { private ItemStack icon; private final short[][][] blocks; - private final byte[][][] metadata; + private final char[][][] metadata; private final List tileEntities = new ArrayList<>(); private final List entities = new ArrayList<>(); private final int width; @@ -32,7 +32,7 @@ public class Schematic implements ISchematic { public Schematic(final ItemStack icon, final int width, final int height, final int length) { this.icon = icon; this.blocks = new short[width][height][length]; - this.metadata = new byte[width][height][length]; + this.metadata = new char[width][height][length]; this.width = width; this.height = height; @@ -45,7 +45,7 @@ public Block getBlock(final int x, final int y, final int z) { return Blocks.air; } - return BLOCK_REGISTRY.getObjectById(this.blocks[x][y][z]); + return BLOCK_REGISTRY.getObjectById(this.blocks[x][y][z] & 0xffff); } @Override @@ -120,7 +120,7 @@ public boolean setBlockMetadata(final int x, final int y, final int z, final int return false; } - this.metadata[x][y][z] = (byte) (metadata & 0x0F); + this.metadata[x][y][z] = (char) metadata; return true; } From 0c1df8e37e18851af0b21d18ea93c4141086d587 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:50:49 +0100 Subject: [PATCH 04/64] Improve client printing and previews for modded blocks --- .../compat/ArchitectureCraftSupport.java | 214 ++++++++ .../compat/CarpentersBlocksSupport.java | 298 ++++++++++ .../compat/CarpentersHammerSupport.java | 458 ++++++++++++++++ .../client/compat/MicroblockSupport.java | 508 ++++++++++++++++++ .../schematica/client/gui/GuiHelper.java | 2 +- .../printer/ArchitectureCraftPrinter.java | 46 ++ .../client/printer/CarpentersPrinter.java | 223 ++++++++ .../client/printer/MicroblockPrinter.java | 78 +++ .../client/printer/PrinterInteraction.java | 217 ++++++++ .../client/printer/SchematicPrinter.java | 437 +++++++-------- .../printer/registry/PlacementRegistry.java | 25 +- .../renderer/RendererSchematicChunk.java | 59 +- .../schematica/client/util/BlockList.java | 151 +++++- .../client/util/BlockToItemStack.java | 60 ++- .../client/world/SchematicWorld.java | 13 + src/main/resources/META-INF/schematica_at.cfg | 2 + 16 files changed, 2493 insertions(+), 298 deletions(-) create mode 100644 src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java create mode 100644 src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java create mode 100644 src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java create mode 100644 src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java create mode 100644 src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java create mode 100644 src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java create mode 100644 src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java create mode 100644 src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java new file mode 100644 index 00000000..f362e4b3 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -0,0 +1,214 @@ +package com.github.lunatrius.schematica.client.compat; + +import net.minecraft.block.Block; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import gcewing.architecture.ArchitectureCraft; +import gcewing.architecture.common.block.BlockShape; +import gcewing.architecture.common.shape.Shape; +import gcewing.architecture.common.shape.ShapeItem; +import gcewing.architecture.common.shape.ShapeSymmetry; +import gcewing.architecture.common.tile.TileShape; +import gcewing.architecture.compat.BlockCompatUtils; +import gcewing.architecture.compat.BlockPos; +import gcewing.architecture.compat.Trans3; +import gcewing.architecture.compat.Vector3; +import gcewing.architecture.util.Utils; + +public final class ArchitectureCraftSupport { + + private static final double[] HIT_OFFSETS = { 0.5, 0.125, 0.875 }; + + private ArchitectureCraftSupport() {} + + public static boolean isShapeBlock(Block block) { + return block instanceof BlockShape; + } + + public static boolean isShapeItem(ItemStack stack) { + return stack.getItem() instanceof ShapeItem; + } + + public static String getMaterialName(ItemStack stack) { + final NBTTagCompound tag = stack.getTagCompound(); + final Block base = tag == null ? null : Block.getBlockFromName(tag.getString("BaseName")); + return base == null ? "" : Utils.displayNameOfBlock(base, tag.getInteger("BaseData")); + } + + public static ItemStack getSecondaryItem(TileEntity tile) { + if (tile instanceof TileShape shape && shape.shape != null && shape.secondaryBlockState != null) { + return shape.shape.kind.newSecondaryMaterialStack(shape.secondaryBlockState); + } + return null; + } + + public static ItemStack getItem(TileEntity tile, Block block) { + if (tile instanceof TileShape shape && shape.shape != null) { + return shape.shape.kind + .newStack(shape.shape, shape.baseBlockState, 1, block == ArchitectureCraft.content.blockShapeSE); + } + return null; + } + + public static boolean itemsMatch(ItemStack stack, ItemStack target) { + final NBTTagCompound tag = stack.getTagCompound(); + final NBTTagCompound expected = target.getTagCompound(); + return tag != null && expected != null + && tag.hasKey("Shape") + && expected.hasKey("Shape") + && tag.getInteger("Shape") == expected.getInteger("Shape") + && tag.getInteger("BaseData") == expected.getInteger("BaseData") + && tag.getString("BaseName") + .equals(expected.getString("BaseName")); + } + + public static boolean matches(TileEntity placed, TileEntity target, Block block) { + if (!(placed instanceof TileShape actual) || !(target instanceof TileShape expected)) { + return false; + } + final ItemStack actualItem = getItem(actual, block); + final ItemStack expectedItem = getItem(expected, block); + return actualItem != null && expectedItem != null + && itemsMatch(actualItem, expectedItem) + && sameOrientation(actual, expected); + } + + private static boolean sameOrientation(TileShape actual, TileShape expected) { + return actual.side == expected.side && actual.getOffsetX() == expected.getOffsetX() + && (actual.turn == expected.turn || expected.shape.symmetry == ShapeSymmetry.Quadrilateral); + } + + public static Vec3 findHit(EntityClientPlayerMP player, World world, TileEntity target, ItemStack stack, int x, + int y, int z, ForgeDirection support, boolean sneaking) { + if (!(target instanceof TileShape expected) || expected.shape == null) { + return null; + } + + final boolean originalSneak = player.movementInput.sneak; + player.movementInput.sneak = sneaking; + try { + final ForgeDirection face = support.getOpposite(); + final BlockPos neighbor = new BlockPos(x + support.offsetX, y + support.offsetY, z + support.offsetZ); + final TileEntity neighborTile = world.getTileEntity(neighbor.x, neighbor.y, neighbor.z); + final TileShape candidate = new TileShape(); + candidate.xCoord = x; + candidate.yCoord = y; + candidate.zCoord = z; + candidate.setWorldObj(world); + candidate.readFromItemStack(stack); + for (double u : HIT_OFFSETS) { + for (double v : HIT_OFFSETS) { + final double hitX = support.offsetX == 0 ? u : (1 + face.offsetX) / 2.0; + final double hitY = support.offsetY == 0 ? (support.offsetX == 0 ? v : u) + : (1 + face.offsetY) / 2.0; + final double hitZ = support.offsetZ == 0 ? v : (1 + face.offsetZ) / 2.0; + final Vector3 relative = new Vector3( + hitX - face.offsetX - 0.5, + hitY - face.offsetY - 0.5, + hitZ - face.offsetZ - 0.5); + candidate.setSide(0); + candidate.setTurn(0); + candidate.setOffsetX(0); + candidate.shape.orientOnPlacement( + player, + candidate, + neighbor, + BlockCompatUtils.getWorldBlockState(world, neighbor), + neighborTile, + EnumFacing.values()[face.ordinal()], + relative); + if (sameOrientation(candidate, expected)) { + return Vec3.createVectorHelper(neighbor.x + hitX, neighbor.y + hitY, neighbor.z + hitZ); + } + } + } + return null; + } finally { + player.movementInput.sneak = originalSneak; + } + } + + public static void transform(TileEntity tile, ForgeDirection axis, boolean mirror) { + if (!(tile instanceof TileShape shape) || shape.shape == null + || shape.side < 0 + || shape.side >= 6 + || shape.turn < 0 + || shape.turn >= 4) { + return; + } + + Trans3 orientation = Trans3.sideTurn(shape.side, shape.turn); + int mirrorTurn = 0; + if (mirror) { + // The reflection is represented by a proper rotation and a reflection across the shape's local X axis. + switch (shape.shape) { + case RoofOverhangGableLH -> shape.shape = Shape.RoofOverhangGableRH; + case RoofOverhangGableRH -> shape.shape = Shape.RoofOverhangGableLH; + case RoofOverhangGableEndLH -> shape.shape = Shape.RoofOverhangGableEndRH; + case RoofOverhangGableEndRH -> shape.shape = Shape.RoofOverhangGableEndLH; + case CorniceLH -> shape.shape = Shape.CorniceRH; + case CorniceRH -> shape.shape = Shape.CorniceLH; + case CorniceEndLH -> shape.shape = Shape.CorniceEndRH; + case CorniceEndRH -> shape.shape = Shape.CorniceEndLH; + default -> {} + } + shape.setOffsetX(-shape.getOffsetX()); + // Placement symmetry differs from the mirrored geometry of these models. + mirrorTurn = switch (shape.shape) { + case DoricTriglyphCorner -> 1; + case IonicCapital, DoricCapital, CorinthianCapital -> 2; + default -> shape.shape.symmetry == ShapeSymmetry.Unilateral ? 1 : 0; + }; + } + + final Vector3 up = transform(orientation.v(0, 1, 0), axis, mirror); + final Vector3 forward = transform(orientation.v(0, 0, 1), axis, mirror); + for (int side = 0; side < 6; side++) { + for (int turn = 0; turn < 4; turn++) { + final Trans3 candidate = Trans3.sideTurn(side, turn); + if (candidate.v(0, 1, 0) + .dot(up) > 0.99 + && candidate.v(0, 0, 1) + .dot(forward) > 0.99) { + shape.setSide(side); + shape.setTurn((turn + mirrorTurn) & 3); + } + } + } + + int connections = shape.disabledConnections & ~0x3f; + for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { + if ((shape.disabledConnections & 1 << direction.ordinal()) == 0) { + continue; + } + final Vector3 transformed = transform( + new Vector3(direction.offsetX, direction.offsetY, direction.offsetZ), + axis, + mirror); + for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) { + if (transformed.dot(face.offsetX, face.offsetY, face.offsetZ) > 0.99) { + connections |= 1 << face.ordinal(); + } + } + } + shape.disabledConnections = connections; + } + + private static Vector3 transform(Vector3 vector, ForgeDirection axis, boolean mirror) { + return switch (axis) { + case EAST -> mirror ? new Vector3(-vector.x, vector.y, vector.z) + : new Vector3(vector.x, vector.z, -vector.y); + case UP -> mirror ? new Vector3(vector.x, -vector.y, vector.z) : new Vector3(-vector.z, vector.y, vector.x); + case SOUTH -> mirror ? new Vector3(vector.x, vector.y, -vector.z) + : new Vector3(vector.y, -vector.x, vector.z); + default -> vector; + }; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java new file mode 100644 index 00000000..66a22cb4 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -0,0 +1,298 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.util.function.BiConsumer; +import java.util.function.Predicate; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockDirectional; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Direction; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.carpentersblocks.block.BlockCarpentersBlock; +import com.carpentersblocks.block.BlockCarpentersGarageDoor; +import com.carpentersblocks.block.BlockCarpentersSlope; +import com.carpentersblocks.block.BlockCarpentersStairs; +import com.carpentersblocks.block.BlockCoverable; +import com.carpentersblocks.data.GarageDoor; +import com.carpentersblocks.data.Stairs; +import com.carpentersblocks.tileentity.TEBase; +import com.carpentersblocks.util.BlockProperties; +import com.carpentersblocks.util.registry.FeatureRegistry; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.reference.Mods; + +public final class CarpentersBlocksSupport { + + private static final int BASE = 6; + private static final byte[][] SURFACE_ATTRIBUTES = { TEBase.ATTR_COVER, TEBase.ATTR_DYE, TEBase.ATTR_OVERLAY }; + private static final int[] TOP_BOTTOM_FACING = { 0, 3, 1, 2 }; + + private CarpentersBlocksSupport() {} + + public static boolean isCoverable(Block block) { + return block instanceof BlockCoverable; + } + + public static boolean isStairs(Block block) { + return block instanceof BlockCarpentersStairs; + } + + public static boolean isGarageDoor(Block block) { + return block instanceof BlockCarpentersGarageDoor; + } + + public static boolean passesThroughMicroblockClick(Block block) { + return block instanceof BlockCarpentersBlock || isStairs(block); + } + + public static boolean allowsPlacementClick(Block clicked, ItemStack stack, boolean sneaking) { + if (!isCoverable(clicked)) { + return true; + } + if (sneaking) { + return stack.getItem() instanceof ItemBlock && !BlockProperties.isOverlay(stack); + } + return Mods.FORGE_MICROBLOCK && MicroblockSupport.isMicroblockItem(stack) + && passesThroughMicroblockClick(clicked); + } + + public static void addMaterials(TileEntity target, TileEntity placed, BiConsumer add) { + if (!(target instanceof TEBase expected)) { + return; + } + final TEBase actual = placed instanceof TEBase carpenter ? carpenter : null; + for (byte[] attributes : SURFACE_ATTRIBUTES) { + for (byte attribute : attributes) { + addMaterial(expected, actual, attribute, add); + } + } + addMaterial(expected, actual, TEBase.ATTR_ILLUMINATOR, add); + } + + private static void addMaterial(TEBase expected, TEBase actual, byte attribute, + BiConsumer add) { + final ItemStack stack = expected.getAttribute(attribute); + if (stack != null) { + add.accept(ingredient(stack, attribute), matches(stack, actual, attribute)); + } + } + + private static boolean matches(ItemStack expected, TEBase actual, byte attribute) { + final ItemStack placed = actual == null ? null : actual.getAttribute(attribute); + return expected == null ? placed == null : placed != null && BlockToItemStack.matches(placed, expected); + } + + private static ItemStack ingredient(ItemStack stack, byte attribute) { + final ItemStack ingredient = stack.copy(); + ingredient.stackSize = 1; + if (attribute <= TEBase.ATTR_COVER[BASE]) { + final Block block = BlockProperties.toBlock(stack); + final int damage = stack.getItemDamage(); + if (BlockProperties.blockRotates(stack) || block instanceof BlockDirectional) { + ingredient.setItemDamage(block.damageDropped(damage)); + } + } + return ingredient; + } + + public static boolean matches(Block block, TileEntity target, TileEntity placed) { + if (!(target instanceof TEBase expected)) { + return placed == null; + } + if (!(placed instanceof TEBase actual) || !matchesShape(block, expected, actual) + || !CarpentersHammerSupport.matchesSettings(block, expected, actual)) { + return false; + } + for (byte[] attributes : SURFACE_ATTRIBUTES) { + for (byte attribute : attributes) { + if (!matches(expected.getAttribute(attribute), actual, attribute)) { + return false; + } + } + } + return matches(expected.getAttribute(TEBase.ATTR_ILLUMINATOR), actual, TEBase.ATTR_ILLUMINATOR); + } + + private static boolean matchesShape(Block block, TEBase expected, TEBase actual) { + if (isGarageDoor(block)) { + return GarageDoor.INSTANCE.getDirection(actual) == GarageDoor.INSTANCE.getDirection(expected); + } + return !(block instanceof BlockCarpentersBlock || block instanceof BlockCarpentersSlope || isStairs(block)) + || actual.getData() == expected.getData(); + } + + public static Float findGarageDoorYaw(Block block, SchematicWorld schematic, World world, int x, int y, int z) { + final GarageDoor door = GarageDoor.INSTANCE; + if (!(schematic.getTileEntity(x, y, z) instanceof TEBase host) || !door.isHost(host)) { + return null; + } + final ForgeDirection direction = door.getDirection(host); + if (direction.offsetY != 0 || direction == ForgeDirection.UNKNOWN) { + return null; + } + final int wx = schematic.position.x + x; + final int wy = schematic.position.y + y; + final int wz = schematic.position.z + z; + if (!block.canPlaceBlockOnSide(world, wx, wy, wz, ForgeDirection.DOWN.ordinal())) { + return null; + } + + // A single use creates every panel below the host until the first non-replaceable block. + int panelY = y - 1; + int worldY = wy - 1; + while (worldY >= 0 && world.getBlock(wx, worldY, wz) + .isReplaceable(world, wx, worldY, wz)) { + if (schematic.getBlock(x, panelY, z) != block + || !(schematic.getTileEntity(x, panelY, z) instanceof TEBase panel) + || door.isHost(panel) + || door.getDirection(panel) != direction) { + return null; + } + panelY--; + worldY--; + } + if (schematic.getBlock(x, panelY, z) == block && (world.getBlock(wx, worldY, wz) != block + || !(world.getTileEntity(wx, worldY, wz) instanceof TEBase panel) + || door.getDirection(panel) != direction)) { + return null; + } + return Direction.facingToDirection[direction.ordinal()] * 90.0f; + } + + public static boolean matchesStairPlacement(TileEntity tile, Block block, World world, int x, int y, int z, + int side, float hitX, float hitY, float hitZ, EntityPlayer player) { + if (!(tile instanceof TEBase expected)) { + return false; + } + final int metadata = block.onBlockPlaced(world, x, y, z, side, hitX, hitY, hitZ, 0); + final int facing = MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; + final int data = metadata < 12 ? metadata + : (metadata == 12 ? Stairs.ID_NORMAL_NEG_N : Stairs.ID_NORMAL_POS_N) + TOP_BOTTOM_FACING[facing]; + return data == expected.getData(); + } + + public static Interaction findAttachment(Block block, TileEntity target, TileEntity placed, EntityPlayer player, + Predicate available) { + if (!(target instanceof TEBase expected) || !(placed instanceof TEBase actual) + || !matchesShape(block, expected, actual) + || (isGarageDoor(block) && GarageDoor.INSTANCE.isOpen(actual))) { + return null; + } + final boolean hasBaseCover = actual.hasAttribute(TEBase.ATTR_COVER[BASE]); + final int bareFace = uncoveredFace(actual); + if (bareFace != -1) { + final Interaction decoration = findDecoration(expected, actual, BASE, bareFace, available); + if (decoration != null) { + return decoration; + } + } + final boolean needsBaseDecoration = (FeatureRegistry.enableDyeColors + && isMissing(expected, actual, TEBase.ATTR_DYE[BASE])) + || (FeatureRegistry.enableOverlays && isMissing(expected, actual, TEBase.ATTR_OVERLAY[BASE])); + for (int side = BASE; side >= 0; side--) { + final byte attribute = TEBase.ATTR_COVER[side]; + final ItemStack cover = expected.getAttribute(attribute); + // Leave a bare face available for base decorations, even if their items are currently missing. + if (side == bareFace && needsBaseDecoration) { + continue; + } + if (FeatureRegistry.enableCovers && cover != null + && !actual.hasAttribute(attribute) + && (side == BASE ? bareFace != -1 : hasBaseCover)) { + final ItemStack item = ingredient(cover, attribute); + if (available.test(item) && BlockProperties.isCover(item) + && matchesCoverDamage(cover, item, actual, player)) { + return new Interaction(item, side == BASE ? bareFace : side, false, attribute, cover); + } + } + } + if (FeatureRegistry.enableIllumination) { + final Interaction illuminator = missing(expected, actual, TEBase.ATTR_ILLUMINATOR, 1, available); + if (illuminator != null) { + return illuminator; + } + } + for (int face = 0; face < BASE; face++) { + if (actual.hasAttribute(TEBase.ATTR_COVER[face])) { + final Interaction decoration = findDecoration(expected, actual, face, face, available); + if (decoration != null) { + return decoration; + } + } + } + return null; + } + + private static Interaction findDecoration(TEBase expected, TEBase actual, int side, int face, + Predicate available) { + final Interaction dye = FeatureRegistry.enableDyeColors + ? missing(expected, actual, TEBase.ATTR_DYE[side], face, available) + : null; + return dye != null || !FeatureRegistry.enableOverlays ? dye + : missing(expected, actual, TEBase.ATTR_OVERLAY[side], face, available); + } + + private static boolean matchesCoverDamage(ItemStack cover, ItemStack item, TEBase tile, EntityPlayer player) { + final Block block = BlockProperties.toBlock(item); + int damage = block instanceof BlockDirectional + ? MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 2.5D) & 3 + : item.getItemDamage(); + if (BlockProperties.blockRotates(item)) { + final int facing = MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; + final int side = player.rotationPitch < -45 ? 0 + : player.rotationPitch > 45 ? 1 : Direction.directionToFacing[Direction.rotateOpposite[facing]]; + damage = block + .onBlockPlaced(player.worldObj, tile.xCoord, tile.yCoord, tile.zCoord, side, 0.5f, 0.5f, 0.5f, damage); + } + return damage == cover.getItemDamage(); + } + + private static int uncoveredFace(TEBase tile) { + for (int side = 0; side < BASE; side++) { + if (!tile.hasAttribute(TEBase.ATTR_COVER[side])) { + return side; + } + } + return -1; + } + + private static Interaction missing(TEBase expected, TEBase actual, byte attribute, int face, + Predicate available) { + final ItemStack stack = expected.getAttribute(attribute); + return stack != null && !actual.hasAttribute(attribute) && available.test(stack) + ? new Interaction(stack, face, true, attribute, stack) + : null; + } + + private static boolean isMissing(TEBase expected, TEBase actual, byte attribute) { + return expected.hasAttribute(attribute) && !actual.hasAttribute(attribute); + } + + public static final class Interaction { + + public final ItemStack item; + public final int face; + public final boolean sneaking; + private final byte attribute; + private final ItemStack expected; + + private Interaction(ItemStack item, int face, boolean sneaking, byte attribute, ItemStack expected) { + this.item = item; + this.face = face; + this.sneaking = sneaking; + this.attribute = attribute; + this.expected = expected; + } + + public boolean isConfirmed(TileEntity tile) { + return tile instanceof TEBase carpenter && matches(this.expected, carpenter, this.attribute); + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java new file mode 100644 index 00000000..cc00e132 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -0,0 +1,458 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.IntUnaryOperator; +import java.util.function.Predicate; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.carpentersblocks.api.ICarpentersHammer; +import com.carpentersblocks.block.BlockCarpentersBarrier; +import com.carpentersblocks.block.BlockCarpentersBed; +import com.carpentersblocks.block.BlockCarpentersBlock; +import com.carpentersblocks.block.BlockCarpentersButton; +import com.carpentersblocks.block.BlockCarpentersDaylightSensor; +import com.carpentersblocks.block.BlockCarpentersDoor; +import com.carpentersblocks.block.BlockCarpentersFlowerPot; +import com.carpentersblocks.block.BlockCarpentersGarageDoor; +import com.carpentersblocks.block.BlockCarpentersGate; +import com.carpentersblocks.block.BlockCarpentersHatch; +import com.carpentersblocks.block.BlockCarpentersLadder; +import com.carpentersblocks.block.BlockCarpentersLever; +import com.carpentersblocks.block.BlockCarpentersPressurePlate; +import com.carpentersblocks.block.BlockCarpentersSafe; +import com.carpentersblocks.block.BlockCarpentersSlope; +import com.carpentersblocks.block.BlockCarpentersStairs; +import com.carpentersblocks.block.BlockCarpentersTorch; +import com.carpentersblocks.data.Barrier; +import com.carpentersblocks.data.Bed; +import com.carpentersblocks.data.Button; +import com.carpentersblocks.data.DaylightSensor; +import com.carpentersblocks.data.GarageDoor; +import com.carpentersblocks.data.Gate; +import com.carpentersblocks.data.Hatch; +import com.carpentersblocks.data.Hinge; +import com.carpentersblocks.data.Ladder; +import com.carpentersblocks.data.Lever; +import com.carpentersblocks.data.PressurePlate; +import com.carpentersblocks.data.Safe; +import com.carpentersblocks.data.Slab; +import com.carpentersblocks.data.Slope; +import com.carpentersblocks.data.Stairs; +import com.carpentersblocks.data.Torch; +import com.carpentersblocks.tileentity.TEBase; +import com.carpentersblocks.util.handler.DesignHandler; +import com.carpentersblocks.util.registry.ItemRegistry; +import com.github.lunatrius.schematica.client.world.SchematicWorld; + +public final class CarpentersHammerSupport { + + private static final Click[] SHAPE_CLICKS = { Click.LEFT, Click.RIGHT }; + private static final Slab SLAB = new Slab(); + private static final Ladder LADDER = new Ladder(); + private static final Torch TORCH = new Torch(); + private static final DaylightSensor SENSOR = new DaylightSensor(); + private static final PressurePlate PRESSURE_PLATE = new PressurePlate(); + private static final Button BUTTON = new Button(); + private static final Lever LEVER = new Lever(); + + // BlockCarpentersSlope's left click uses the UP row of Slope.ROTATION_Y. + private static final int[] SLOPE_ROTATIONS = { 3, 2, 0, 1, 7, 6, 4, 5, 11, 10, 8, 9, 15, 14, 12, 13, 19, 18, 16, 17, + 23, 22, 20, 21, 27, 26, 24, 25, 31, 30, 28, 29, 35, 34, 32, 33, 39, 38, 36, 37, 43, 42, 40, 41, 44, 45, 49, 48, + 46, 47, 51, 50, 55, 54, 52, 53, 59, 58, 56, 57, 60, 64, 63, 61, 62 }; + + private static final BlockSettings NO_SETTINGS = new BlockSettings(Block.class); + // Settings are ordered by the sequence in which the hammer should adjust them. + private static final BlockSettings[] BLOCK_SETTINGS = { + new BlockSettings( + BlockCarpentersGarageDoor.class, + shortestCycle(GarageDoor.INSTANCE::getType, BlockCarpentersGarageDoor.type.length), + toggle(GarageDoor.INSTANCE::getRigidity, Click.SNEAK_RIGHT)), + new BlockSettings( + BlockCarpentersBarrier.class, + new Setting<>(Barrier::getType, CarpentersHammerSupport::fenceClick), + toggle(Barrier::getPost, Click.LEFT)), + new BlockSettings(BlockCarpentersGate.class, new Setting<>(Gate::getType, CarpentersHammerSupport::fenceClick)), + new BlockSettings( + BlockCarpentersDoor.class, + forwardCycle(Hinge::getType, BlockCarpentersDoor.type.length), + toggle(Hinge::getHinge, Click.LEFT)), + new BlockSettings( + BlockCarpentersHatch.class, + forwardCycle(Hatch::getType, Hatch.TYPE_PANEL + 1), + toggle(Hatch::getRigidity, Click.SNEAK_RIGHT), + toggle(Hatch::getDir, Click.LEFT)), + new BlockSettings( + BlockCarpentersLadder.class, + shortestCycle(LADDER::getType, BlockCarpentersLadder.type.length)), + new BlockSettings(BlockCarpentersTorch.class, forwardCycle(TORCH::getType, BlockCarpentersTorch.type.length)), + new BlockSettings(BlockCarpentersBed.class, decoration("bed")), + new BlockSettings(BlockCarpentersFlowerPot.class, decoration("flowerpot")), + new BlockSettings( + BlockCarpentersDaylightSensor.class, + forwardCycle(SENSOR::getSensitivity, 3), + toggle(SENSOR::getPolarity, Click.LEFT)), + new BlockSettings( + BlockCarpentersPressurePlate.class, + forwardCycle(PRESSURE_PLATE::getTriggerEntity, 4), + toggle(PRESSURE_PLATE::getPolarity, Click.LEFT)), + new BlockSettings(BlockCarpentersButton.class, toggle(BUTTON::getPolarity, Click.LEFT)), + new BlockSettings(BlockCarpentersLever.class, toggle(LEVER::getPolarity, Click.LEFT)), + new BlockSettings( + BlockCarpentersSafe.class, + toggle(Safe::isLocked, Click.SNEAK_RIGHT), + forwardCycle(Safe::getAutoPerm, 4)) }; + + private CarpentersHammerSupport() {} + + static boolean matchesSettings(Block block, TEBase expected, TEBase actual) { + return settingsFor(block).findClick(expected, actual) == null; + } + + public static ItemStack findHammer(ItemStack[] inventory, Predicate available) { + for (ItemStack stack : inventory) { + if (stack != null && stack.stackSize > 0 + && stack.getItem() instanceof ICarpentersHammer + && available.test(stack)) { + return stack; + } + } + if (ItemRegistry.itemCarpentersHammer != null) { + final ItemStack hammer = new ItemStack(ItemRegistry.itemCarpentersHammer); + if (available.test(hammer)) { + return hammer; + } + } + return null; + } + + public static boolean canUseHammer(EntityPlayer player, World world) { + final ItemStack stack = player.getHeldItem(); + return stack != null && stack.stackSize > 0 + && stack.getItem() instanceof ICarpentersHammer hammer + && hammer.canUseHammer(world, player); + } + + public static Adjustment findAdjustment(Block block, SchematicWorld schematic, TileEntity target, + TileEntity placed) { + if (!(target instanceof TEBase expected) || !(placed instanceof TEBase actual)) { + return null; + } + + final BlockSettings settings = settingsFor(block); + Click click = settings.findClick(expected, actual); + ForgeDirection face = ForgeDirection.UP; + if (block instanceof BlockCarpentersBlock && expected.getData() != actual.getData() + && validIndex(expected.getData(), Slab.SLAB_Z_POS + 1) + && validIndex(actual.getData(), Slab.SLAB_Z_POS + 1)) { + // A second click shapes a different half only after the first restores the full cube. + face = SLAB.isFullCube(actual) ? SLAB.getDirection(expected) + .getOpposite() : ForgeDirection.UP; + click = Click.RIGHT; + } else if (block instanceof BlockCarpentersStairs) { + click = shapeClick( + expected.getData(), + actual.getData(), + Stairs.stairsList.length, + id -> (id & ~3) | ((id + 1) & 3), + CarpentersHammerSupport::nextStairShape); + } else if (block instanceof BlockCarpentersSlope) { + click = shapeClick( + expected.getData(), + actual.getData(), + SLOPE_ROTATIONS.length, + id -> SLOPE_ROTATIONS[id], + id -> { + final Slope slope = Slope.getSlopeById(id); + return slope.slopeType.getNextSlopeType(slope).slopeID; + }); + } + if (click == null) { + return null; + } + if (click == Click.LEFT && block instanceof BlockCarpentersHatch + && !block.canPlaceBlockOnSide( + actual.getWorldObj(), + actual.xCoord, + actual.yCoord, + actual.zCoord, + Hatch.getDir(expected) + 2)) { + return null; + } + + final Collection affected = affectedBlocks(block, actual, expected, click); + if (affected.isEmpty()) { + return null; + } + for (TEBase piece : affected) { + final int x = piece.xCoord - schematic.position.x; + final int y = piece.yCoord - schematic.position.y; + final int z = piece.zCoord - schematic.position.z; + if (schematic.getBlock(x, y, z) != block || !(schematic.getTileEntity(x, y, z) instanceof TEBase saved) + || settings.findClick(expected, saved) != null) { + return null; + } + } + return new Adjustment(click, face.ordinal(), affected, block, actual, settings); + } + + private static Collection affectedBlocks(Block block, TEBase actual, TEBase expected, Click click) { + final World world = actual.getWorldObj(); + if (CarpentersBlocksSupport.isGarageDoor(block)) { + final GarageDoor door = GarageDoor.INSTANCE; + if (door.getDirection(actual) != door.getDirection(expected) || door.getDirection(actual) + .ordinal() < 2 || door.getDirection(actual) == ForgeDirection.UNKNOWN || !door.isVisible(actual)) { + return Collections.emptyList(); + } + final Collection pieces = door.getBlocks(actual, block); + final int type = door.getType(actual); + if (click == Click.RIGHT && door.isOpen(actual)) { + // An open door activates the bottommost panel, so every possible source must agree on the current + // style. + for (TEBase piece : pieces) { + if (door.getType(piece) != type) { + return Collections.emptyList(); + } + } + } + return pieces; + } + if (block instanceof BlockCarpentersBed) { + final TEBase other = Bed.getOppositeTE(actual); + return other == null ? Collections.emptyList() : Arrays.asList(actual, other); + } + if (block instanceof BlockCarpentersFlowerPot && actual.hasAttribute(TEBase.ATTR_COVER[6])) { + // Turning the pot's design drops its existing base cover. + return Collections.emptyList(); + } + if (block instanceof BlockCarpentersDoor) { + final int otherY = actual.yCoord + (Hinge.getPiece(actual) == Hinge.PIECE_TOP ? -1 : 1); + if (world.getBlock(actual.xCoord, otherY, actual.zCoord) == block + && world.getTileEntity(actual.xCoord, otherY, actual.zCoord) instanceof TEBase other) { + return Arrays.asList(actual, other); + } + return Collections.emptyList(); + } + return Collections.singletonList(actual); + } + + private static BlockSettings settingsFor(Block block) { + for (BlockSettings settings : BLOCK_SETTINGS) { + if (settings.blockType.isInstance(block)) { + return settings; + } + } + return NO_SETTINGS; + } + + private static Setting toggle(Function read, Click click) { + return new Setting<>(read, (expected, actual) -> expected.equals(actual) ? null : click); + } + + private static Setting forwardCycle(Function read, int variants) { + return new Setting<>(read, (expected, actual) -> cycle(expected, actual, variants)); + } + + private static Setting shortestCycle(Function read, int variants) { + return new Setting<>(read, (expected, actual) -> bidirectionalCycle(expected, actual, variants)); + } + + private static Setting decoration(String designType) { + return new Setting<>(TEBase::getDesign, (expected, actual) -> { + if (expected.equals(actual)) { + return null; + } + return expected.isEmpty() ? Click.SNEAK_RIGHT + : DesignHandler.getListForType(designType) + .contains(expected) ? Click.RIGHT : null; + }); + } + + private static Click fenceClick(int expected, int actual) { + final Click type = cycle(expected, actual, Barrier.TYPE_WALL + 1); + return type != null && expected <= Barrier.TYPE_VANILLA_X3 && actual <= Barrier.TYPE_VANILLA_X3 + ? Click.SNEAK_RIGHT + : type; + } + + private static Click cycle(int expected, int actual, int variants) { + return toggle( + expected != actual && validIndex(expected, variants) && validIndex(actual, variants), + Click.RIGHT); + } + + private static Click bidirectionalCycle(int expected, int actual, int variants) { + if (cycle(expected, actual, variants) == null) { + return null; + } + final int forward = Math.floorMod(expected - actual, variants); + return forward < variants - forward ? Click.LEFT : Click.RIGHT; + } + + private static Click toggle(boolean different, Click click) { + return different ? click : null; + } + + private static boolean validIndex(int value, int size) { + return value >= 0 && value < size; + } + + private static int nextStairShape(int id) { + return switch (id >> 2) { + case 0 -> id + 8; + case 1, 3 -> id + 12; + case 2, 4, 6 -> id - 4; + case 5 -> Stairs.ID_NORMAL_SE; + default -> id; + }; + } + + private static Click shapeClick(int expected, int actual, int variants, IntUnaryOperator turn, + IntUnaryOperator reshape) { + if (expected == actual || !validIndex(expected, variants) || !validIndex(actual, variants)) { + return null; + } + final Click[] firstClicks = new Click[variants]; + final ArrayDeque remaining = new ArrayDeque<>(); + remaining.add(actual); + while (!remaining.isEmpty()) { + final int current = remaining.remove(); + for (Click click : SHAPE_CLICKS) { + final int next = (click == Click.LEFT ? turn : reshape).applyAsInt(current); + if (next == actual || firstClicks[next] != null) { + continue; + } + firstClicks[next] = current == actual ? click : firstClicks[current]; + if (next == expected) { + return firstClicks[next]; + } + remaining.add(next); + } + } + return null; + } + + private static final class Setting { + + private final Function read; + private final BiFunction chooseClick; + + private Setting(Function read, BiFunction chooseClick) { + this.read = read; + this.chooseClick = chooseClick; + } + + private Click findClick(TEBase expected, TEBase actual) { + return this.chooseClick.apply(this.read.apply(expected), this.read.apply(actual)); + } + } + + private static final class BlockSettings { + + private final Class blockType; + private final Setting[] settings; + + private BlockSettings(Class blockType, Setting... settings) { + this.blockType = blockType; + this.settings = settings; + } + + private Click findClick(TEBase expected, TEBase actual) { + for (Setting setting : this.settings) { + final Click click = setting.findClick(expected, actual); + if (click != null) { + return click; + } + } + return null; + } + + private boolean usesEntireDataValue() { + // Shape IDs and barriers retain their existing raw-data acknowledgment. + return this.settings.length == 0 || this.blockType == BlockCarpentersBarrier.class; + } + + private Object[] snapshot(TEBase tile) { + if (usesEntireDataValue()) { + return new Object[] { tile.getData() }; + } + final Object[] values = new Object[this.settings.length]; + for (int i = 0; i < values.length; i++) { + values[i] = this.settings[i].read.apply(tile); + } + return values; + } + + private boolean matches(TEBase tile, Object[] values) { + if (usesEntireDataValue()) { + return values[0].equals(tile.getData()); + } + for (int i = 0; i < values.length; i++) { + if (!values[i].equals(this.settings[i].read.apply(tile))) { + return false; + } + } + return true; + } + } + + public enum Click { + LEFT, + RIGHT, + SNEAK_RIGHT + } + + public static final class Adjustment { + + public final Click click; + public final int face; + public final Collection affected; + + private final Block block; + private final TEBase clicked; + private final BlockSettings settings; + private final Object[] previousState; + + private Adjustment(Click click, int face, Collection affected, Block block, TEBase clicked, + BlockSettings settings) { + this.click = click; + this.face = face; + this.affected = affected; + this.block = block; + this.clicked = clicked; + this.settings = settings; + this.previousState = settings.snapshot(clicked); + } + + public boolean isConfirmed(World world) { + if (!(world.getTileEntity( + this.clicked.xCoord, + this.clicked.yCoord, + this.clicked.zCoord) instanceof TEBase current)) { + return false; + } + if (this.settings.matches(current, this.previousState)) { + return false; + } + final Object[] state = this.settings.snapshot(current); + for (TileEntity piece : this.affected) { + if (world.getBlock(piece.xCoord, piece.yCoord, piece.zCoord) != this.block + || !(world.getTileEntity(piece.xCoord, piece.yCoord, piece.zCoord) instanceof TEBase updated) + || !this.settings.matches(updated, state)) { + return false; + } + } + return true; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java new file mode 100644 index 00000000..6f6184ca --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -0,0 +1,508 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Predicate; + +import net.minecraft.block.Block; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.github.lunatrius.schematica.reference.Mods; + +import codechicken.lib.raytracer.IndexedCuboid6; +import codechicken.lib.raytracer.RayTracer; +import codechicken.lib.render.CCRenderState; +import codechicken.lib.vec.Cuboid6; +import codechicken.lib.vec.Vector3; +import codechicken.microblock.CommonMicroClass; +import codechicken.microblock.ExecutablePlacement; +import codechicken.microblock.ExpandingPlacement; +import codechicken.microblock.ItemMicroPart; +import codechicken.microblock.Microblock; +import codechicken.microblock.MicroblockPlacement; +import codechicken.multipart.TMultiPart; +import codechicken.multipart.TileMultipart; +import scala.collection.Iterator; + +public final class MicroblockSupport { + + private static final double[] FACE_SAMPLES = { 0.5, 0.125, 0.875, 0.03125, 0.96875 }; + private static final double SERVER_SNEAK_EYE_OFFSET = 0.08; + + private MicroblockSupport() {} + + public static boolean isMicroblockItem(ItemStack stack) { + return stack.getItem() instanceof ItemMicroPart; + } + + public static boolean itemsMatch(ItemStack stack, ItemStack target) { + return stack.isItemEqual(target) && stack.hasTagCompound() + && target.hasTagCompound() + && stack.getTagCompound() + .getString("mat") + .equals( + target.getTagCompound() + .getString("mat")); + } + + public static boolean hasMicroblocks(TileEntity tile) { + return !getParts(tile).isEmpty(); + } + + public static void renderMissingParts(IBlockAccess schematic, TileEntity placed, int x, int y, int z, int pass) { + if (!(placed instanceof TileMultipart)) { + return; + } + + final List missing = getParts(schematic.getTileEntity(x, y, z)); + if (missing.isEmpty()) { + return; + } + final List actual = getParts(placed); + missing.removeIf(part -> removeMatch(actual, part)); + if (missing.isEmpty()) { + return; + } + + final CCRenderState state = CCRenderState.instance(); + state.resetInstance(); + state.lightMatrix.locate(schematic, x, y, z); + try { + final Vector3 position = new Vector3(x, y, z); + for (Microblock part : missing) { + part.renderStatic(position, pass); + } + } finally { + state.lightMatrix.access = null; + } + } + + public static boolean addMaterials(TileEntity schematic, TileEntity world, BiConsumer add) { + final List expected = getParts(schematic); + if (expected.isEmpty()) { + return false; + } + + final List unmatched = getParts(world); + for (Microblock part : expected) { + if (removeMatch(unmatched, part)) { + for (ItemStack stack : part.getDrops()) { + add.accept(stack, true); + } + continue; + } + final Microblock partial = findPartialMatch(unmatched, part); + if (partial == null) { + for (ItemStack stack : part.getDrops()) { + add.accept(stack, false); + } + continue; + } + unmatched.remove(partial); + for (ItemStack stack : partial.getDrops()) { + add.accept(stack, true); + } + int remaining = part.getSize() - partial.getSize(); + while (remaining > 0) { + final int size = Integer.highestOneBit(remaining); + add.accept(ItemMicroPart.create(part.itemClassID() << 8 | size, part.getMaterial()), false); + remaining -= size; + } + } + return true; + } + + public static Click findPlacement(EntityClientPlayerMP player, TileEntity schematic, int x, int y, int z, + Predicate hasItem) { + final List expected = getParts(schematic); + final List unmatched = getParts(player.worldObj.getTileEntity(x, y, z)); + expected.removeIf(part -> removeMatch(unmatched, part)); + + final List additions = new ArrayList<>(); + final List expansions = new ArrayList<>(); + for (Microblock part : expected) { + final Microblock partial = findPartialMatch(unmatched, part); + final int existingSize = partial == null ? 0 : partial.getSize(); + final List requests = existingSize == 0 ? additions : expansions; + for (int size = Integer.highestOneBit(part.getSize() - existingSize); size > 0; size >>= 1) { + final ItemStack item = ItemMicroPart.create(part.itemClassID() << 8 | size, part.getMaterial()); + if (hasItem.test(item)) { + requests.add(new PlacementRequest(part, item, existingSize + size)); + } + } + } + if (additions.isEmpty() && expansions.isEmpty()) { + return null; + } + + final float yaw = player.rotationYaw; + final float pitch = player.rotationPitch; + final boolean sneaking = player.movementInput.sneak; + try { + // Additions sneak to bypass block activation. FMP expands an existing part with a normal click. + // Finish an exposed partial part before adding parts that could obstruct it. + final Click expansion = findClick(player, x, y, z, expansions, false, true, block -> true); + if (expansion != null) { + return expansion; + } + player.rotationYaw = yaw; + player.rotationPitch = pitch; + final Click addition = findClick( + player, + x, + y, + z, + additions, + true, + false, + block -> !Mods.CARPENTERS_BLOCKS || !CarpentersBlocksSupport.isCoverable(block)); + if (addition != null || !Mods.CARPENTERS_BLOCKS) { + return addition; + } + player.rotationYaw = yaw; + player.rotationPitch = pitch; + // Carpenter's intercepts sneak-clicks with microblocks before Forge Multipart can use them. + return findClick( + player, + x, + y, + z, + additions, + false, + false, + CarpentersBlocksSupport::passesThroughMicroblockClick); + } finally { + player.rotationYaw = yaw; + player.rotationPitch = pitch; + player.movementInput.sneak = sneaking; + } + } + + private static Click findClick(EntityClientPlayerMP player, int x, int y, int z, List requests, + boolean sneaking, boolean expanding, Predicate canClick) { + if (requests.isEmpty()) { + return null; + } + player.movementInput.sneak = sneaking; + final Vec3 eye = RayTracer.getStartVec(player); + // CodeChickenLib uses the server's standing eye height above the player's feet, then adjusts for sneaking. + final double serverEyeOffset = player.boundingBox.minY + 1.62F + - player.posY + - (sneaking ? SERVER_SNEAK_EYE_OFFSET : 0); + return new PlacementSearch(player, x, y, z, requests, eye, serverEyeOffset, expanding, canClick).find(); + } + + private static final class PlacementSearch { + + private final EntityClientPlayerMP player; + private final World world; + private final int x, y, z; + private final List requests; + private final Vec3 eye; + private final Vec3 serverEye; + private final double reach; + private final double aimOffsetY; + private final boolean expanding; + private final Predicate canClick; + + private PlacementSearch(EntityClientPlayerMP player, int x, int y, int z, List requests, + Vec3 eye, double serverEyeOffset, boolean expanding, Predicate canClick) { + this.player = player; + this.world = player.worldObj; + this.x = x; + this.y = y; + this.z = z; + this.requests = requests; + this.eye = eye; + this.serverEye = eye.addVector(0, serverEyeOffset, 0); + this.reach = RayTracer.getBlockReachDistance(player); + this.aimOffsetY = -serverEyeOffset / 2; + this.expanding = expanding; + this.canClick = canClick; + } + + private Click find() { + final Vec3 look = player.getLook(1); + final MovingObjectPosition visible = world.rayTraceBlocks( + eye.addVector(0, 0, 0), + eye.addVector(look.xCoord * reach, look.yCoord * reach, look.zCoord * reach)); + if (visible != null + && Math.abs(visible.blockX - x) + Math.abs(visible.blockY - y) + Math.abs(visible.blockZ - z) + <= (expanding ? 0 : 1)) { + final Click click = tryAim(visible.blockX, visible.blockY, visible.blockZ, visible.sideHit); + if (click != null) { + return click; + } + } + + final Click internal = tryBlock(x, y, z, ForgeDirection.UNKNOWN); + if (internal != null || expanding) { + return internal; + } + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final Click external = tryBlock( + x + side.offsetX, + y + side.offsetY, + z + side.offsetZ, + side.getOpposite()); + if (external != null) { + return external; + } + } + return null; + } + + private Click tryBlock(int bx, int by, int bz, ForgeDirection face) { + final Block block = world.getBlock(bx, by, bz); + if (world.isAirBlock(bx, by, bz) || !canClick.test(block)) { + return null; + } + if (world.getTileEntity(bx, by, bz) instanceof TileMultipart multipart) { + final Iterator parts = multipart.partList() + .iterator(); + final Vector3 origin = new Vector3(bx, by, bz); + while (parts.hasNext()) { + for (IndexedCuboid6 box : parts.next() + .getSubParts()) { + final Click click = tryBounds( + bx, + by, + bz, + face, + box.copy() + .add(origin)); + if (click != null) { + return click; + } + } + } + return null; + } + + block.setBlockBoundsBasedOnState(world, bx, by, bz); + final AxisAlignedBB selected = block.getSelectedBoundingBoxFromPool(world, bx, by, bz); + final Cuboid6 bounds = selected == null ? new Cuboid6(bx, by, bz, bx + 1, by + 1, bz + 1) + : new Cuboid6(selected); + return tryBounds(bx, by, bz, face, bounds); + } + + private Click tryBounds(int bx, int by, int bz, ForgeDirection face, Cuboid6 bounds) { + if (face != ForgeDirection.UNKNOWN) { + return tryFace(bx, by, bz, face, bounds); + } + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final Click click = tryFace(bx, by, bz, side, bounds); + if (click != null) { + return click; + } + } + return null; + } + + private Click tryFace(int bx, int by, int bz, ForgeDirection face, Cuboid6 bounds) { + final double plane = bounds.getSide(face.ordinal()); + final double distance = face.offsetX != 0 ? (eye.xCoord - plane) * face.offsetX + : face.offsetY != 0 ? (eye.yCoord - plane) * face.offsetY : (eye.zCoord - plane) * face.offsetZ; + if (distance <= 0 || distance > reach) { + return null; + } + + // Sample the actual click surface, including the narrow borders used by the placement grid. + for (double u : FACE_SAMPLES) { + for (double v : FACE_SAMPLES) { + final double hx = face.offsetX == 0 ? bounds.min.x + (bounds.max.x - bounds.min.x) * u : plane; + final double hy = face.offsetY == 0 + ? bounds.min.y + (bounds.max.y - bounds.min.y) * (face.offsetX == 0 ? v : u) + : plane; + final double hz = face.offsetZ == 0 ? bounds.min.z + (bounds.max.z - bounds.min.z) * v : plane; + final double aimY = hy + aimOffsetY; + if (eye.squareDistanceTo(hx, aimY, hz) > reach * reach) { + continue; + } + aimAt(player, eye, hx, aimY, hz); + final Click click = tryAim(bx, by, bz, face.ordinal()); + if (click != null) { + return click; + } + } + } + return null; + } + + private Click tryAim(int bx, int by, int bz, int face) { + final Vec3 look = player.getLook(1); + final double dx = look.xCoord * reach; + final double dy = look.yCoord * reach; + final double dz = look.zCoord * reach; + final Vec3 end = eye.addVector(dx, dy, dz); + final Block block = world.getBlock(bx, by, bz); + if (!canClick.test(block)) { + return null; + } + final MovingObjectPosition hit = block.collisionRayTrace(world, bx, by, bz, eye, end); + if (hit == null || hit.sideHit != face) { + return null; + } + + for (PlacementRequest request : requests) { + final ExecutablePlacement placement = predictPlacement(player, x, y, z, request, hit, expanding); + if (placement == null) { + continue; + } + final MovingObjectPosition serverHit = block + .collisionRayTrace(world, bx, by, bz, serverEye, serverEye.addVector(dx, dy, dz)); + if (serverHit == null || serverHit.sideHit != face + || predictPlacement(player, x, y, z, request, serverHit, expanding) == null) { + continue; + } + final MovingObjectPosition visible = world.rayTraceBlocks(eye.addVector(0, 0, 0), end); + if (visible != null && visible.blockX == bx + && visible.blockY == by + && visible.blockZ == bz + && visible.sideHit == face) { + return new Click( + request.item, + hit, + player.rotationYaw, + player.rotationPitch, + player.isSneaking(), + x, + y, + z, + placement.part()); + } + return null; + } + return null; + } + } + + private static ExecutablePlacement predictPlacement(EntityClientPlayerMP player, int x, int y, int z, + PlacementRequest request, MovingObjectPosition hit, boolean expanding) { + final int damage = request.item.getItemDamage(); + final CommonMicroClass microClass = CommonMicroClass.getMicroClass(damage); + final ExecutablePlacement placement = new MicroblockPlacement( + player, + hit, + damage & 0xff, + request.part.getMaterial(), + !player.capabilities.isCreativeMode, + microClass.placementProperties()).apply(); + return placement != null && (placement instanceof ExpandingPlacement) == expanding + && placement.pos().x == x + && placement.pos().y == y + && placement.pos().z == z + && sameOrientation(placement.part(), request.part) + && placement.part() + .getSize() == request.resultSize ? placement : null; + } + + private static void aimAt(EntityClientPlayerMP player, Vec3 eye, double x, double y, double z) { + final double dx = x - eye.xCoord; + final double dy = y - eye.yCoord; + final double dz = z - eye.zCoord; + player.rotationYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + player.rotationPitch = (float) -Math.toDegrees(Math.atan2(dy, Math.hypot(dx, dz))); + } + + private static List getParts(TileEntity tile) { + final List parts = new ArrayList<>(); + if (tile instanceof TileMultipart multipart) { + final Iterator iterator = multipart.partList() + .iterator(); + while (iterator.hasNext()) { + if (iterator.next() instanceof Microblock part) { + parts.add(part); + } + } + } + return parts; + } + + private static boolean removeMatch(List parts, Microblock expected) { + for (int i = 0; i < parts.size(); i++) { + final Microblock part = parts.get(i); + if (part.getSize() == expected.getSize() && sameOrientation(part, expected)) { + parts.remove(i); + return true; + } + } + return false; + } + + private static boolean sameOrientation(Microblock part, Microblock expected) { + return part.getMaterial() == expected.getMaterial() && part.getShape() == expected.getShape() + && part.microClass() == expected.microClass(); + } + + private static Microblock findPartialMatch(List parts, Microblock expected) { + Microblock partial = null; + for (Microblock part : parts) { + if (sameOrientation(part, expected) && part.getSize() < expected.getSize() + && (partial == null || part.getSize() > partial.getSize())) { + partial = part; + } + } + return partial; + } + + private static final class PlacementRequest { + + private final Microblock part; + private final ItemStack item; + private final int resultSize; + + private PlacementRequest(Microblock part, ItemStack item, int resultSize) { + this.part = part; + this.item = item; + this.resultSize = resultSize; + } + } + + public static final class Click { + + public final ItemStack item; + public final MovingObjectPosition hit; + public final float yaw; + public final float pitch; + public final boolean sneaking; + + private final int x, y, z; + private final Microblock result; + + private Click(ItemStack item, MovingObjectPosition hit, float yaw, float pitch, boolean sneaking, int x, int y, + int z, Microblock result) { + this.item = item; + this.hit = hit; + this.yaw = yaw; + this.pitch = pitch; + this.sneaking = sneaking; + this.x = x; + this.y = y; + this.z = z; + this.result = result; + } + + public boolean targets(int x, int y, int z) { + return this.x == x && this.y == y && this.z == z; + } + + public boolean isConfirmed(TileEntity tile) { + for (Microblock part : getParts(tile)) { + if (part.getSize() == result.getSize() && sameOrientation(part, result)) { + return true; + } + } + return false; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java b/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java index b27d5808..b83a25e6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java @@ -22,7 +22,7 @@ public static void drawItemStack(TextureManager textureManager, FontRenderer fon if (itemStack != null && itemStack.getItem() != null) { GL11.glEnable(GL12.GL_RESCALE_NORMAL); RenderHelper.enableGUIStandardItemLighting(); - renderItem.renderItemIntoGUI(fontRenderer, textureManager, itemStack, x + 2, y + 2); + renderItem.renderItemAndEffectIntoGUI(fontRenderer, textureManager, itemStack, x + 2, y + 2); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java new file mode 100644 index 00000000..a74a7940 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java @@ -0,0 +1,46 @@ +package com.github.lunatrius.schematica.client.printer; + +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; + +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; + +final class ArchitectureCraftPrinter { + + private ArchitectureCraftPrinter() {} + + static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEntity tile, ItemStack item) { + if (!interaction.canSelectItem(item)) { + return false; + } + for (ForgeDirection support : interaction.findSupports(x, y, z)) { + for (boolean sneaking : new boolean[] { true, false }) { + // A standing click on the support could activate it instead of placing the shape. + final int clickedX = x + (sneaking ? support.offsetX : 0); + final int clickedY = y + (sneaking ? support.offsetY : 0); + final int clickedZ = z + (sneaking ? support.offsetZ : 0); + if (!PrinterInteraction + .canClickForPlacement(interaction.world.getBlock(clickedX, clickedY, clickedZ), item, sneaking)) { + continue; + } + final Vec3 hit = ArchitectureCraftSupport + .findHit(interaction.player, interaction.world, tile, item, x, y, z, support, sneaking); + if (hit != null) { + return interaction.selectItem(item) && interaction.withSneaking( + sneaking, + () -> interaction.place( + interaction.player.getHeldItem(), + clickedX, + clickedY, + clickedZ, + support.getOpposite() + .ordinal(), + sneaking ? hit : hit.addVector(-support.offsetX, -support.offsetY, -support.offsetZ))); + } + } + } + return false; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java new file mode 100644 index 00000000..5aed6830 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -0,0 +1,223 @@ +package com.github.lunatrius.schematica.client.printer; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BooleanSupplier; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Vec3; +import net.minecraft.world.ChunkPosition; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersHammerSupport; +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.handler.ConfigurationHandler; + +final class CarpentersPrinter { + + private static final float[] STAIR_HIT_OFFSETS = { 0.5f, 0.125f, 0.875f, 0.25f, 0.75f }; + + private final Map pendingClicks = new HashMap<>(); + private long currentPass; + + void reset() { + this.pendingClicks.clear(); + } + + void beginPass(World world) { + final long pass = ++this.currentPass; + this.pendingClicks.values() + .removeIf(click -> click.allowsNextClick(world, pass)); + } + + boolean isWaiting(int x, int y, int z) { + return !this.pendingClicks.isEmpty() && this.pendingClicks.containsKey(new ChunkPosition(x, y, z)); + } + + boolean configureBlock(PrinterInteraction interaction, SchematicWorld schematic, Block block, TileEntity target, + int x, int y, int z) { + final World world = interaction.world; + final TileEntity placed = world.getTileEntity(x, y, z); + final CarpentersHammerSupport.Adjustment adjustment = CarpentersHammerSupport + .findAdjustment(block, schematic, target, placed); + if (adjustment != null && applyHammer(interaction, adjustment, x, y, z)) { + final PendingClick click = new PendingClick(world, this.currentPass, () -> adjustment.isConfirmed(world)); + for (TileEntity piece : adjustment.affected) { + this.pendingClicks.put(new ChunkPosition(piece.xCoord, piece.yCoord, piece.zCoord), click); + } + return true; + } + + final CarpentersBlocksSupport.Interaction attachment = CarpentersBlocksSupport + .findAttachment(block, target, placed, interaction.player, interaction::canSelectItem); + if (attachment == null || !interaction.selectItem(attachment.item)) { + return false; + } + if (!useFace(interaction, x, y, z, attachment.face, attachment.sneaking)) { + return false; + } + this.pendingClicks.put( + new ChunkPosition(x, y, z), + new PendingClick(world, this.currentPass, () -> attachment.isConfirmed(world.getTileEntity(x, y, z)))); + return true; + } + + private static boolean applyHammer(PrinterInteraction interaction, CarpentersHammerSupport.Adjustment adjustment, + int x, int y, int z) { + final ItemStack hammer = findHammer(interaction); + if (hammer == null || !interaction.selectItem(hammer) + || !CarpentersHammerSupport.canUseHammer(interaction.player, interaction.world)) { + return false; + } + if (adjustment.click != CarpentersHammerSupport.Click.LEFT) { + return useFace( + interaction, + x, + y, + z, + adjustment.face, + adjustment.click == CarpentersHammerSupport.Click.SNEAK_RIGHT); + } + return interaction.withSneaking( + false, + () -> CarpentersBlocksSupport.isCoverable(interaction.world.getBlock(x, y, z)) + && interaction.tapWithoutMining(x, y, z, adjustment.face)); + } + + private static boolean useFace(PrinterInteraction interaction, int x, int y, int z, int side, boolean sneaking) { + final ForgeDirection face = ForgeDirection.getOrientation(side); + final Vec3 hit = Vec3.createVectorHelper( + x + 0.5 + face.offsetX * 0.5, + y + 0.5 + face.offsetY * 0.5, + z + 0.5 + face.offsetZ * 0.5); + final boolean used = interaction + .withSneaking(sneaking, () -> interaction.useBlock(interaction.player.getHeldItem(), x, y, z, side, hit)); + // Carpenter's Blocks cancels its sneak interaction after dispatching a separate activation packet. + return used || sneaking; + } + + static boolean place(PrinterInteraction interaction, SchematicWorld schematic, Block block, int localX, int localY, + int localZ, ItemStack item, BooleanSupplier placeNormally) { + final int x = schematic.position.x + localX; + final int y = schematic.position.y + localY; + final int z = schematic.position.z + localZ; + if (CarpentersBlocksSupport.isGarageDoor(block)) { + final Float yaw = CarpentersBlocksSupport + .findGarageDoorYaw(block, schematic, interaction.world, localX, localY, localZ); + return yaw != null && placeGarageDoor(interaction, x, y, z, block, item, yaw); + } + if (CarpentersBlocksSupport.isStairs(block)) { + final TileEntity tile = schematic.getTileEntity(localX, localY, localZ); + return placeStairs(interaction, x, y, z, block, tile, item) + || (findHammer(interaction) != null && placeNormally.getAsBoolean()); + } + return placeNormally.getAsBoolean(); + } + + private static ItemStack findHammer(PrinterInteraction interaction) { + return CarpentersHammerSupport + .findHammer(interaction.player.inventory.mainInventory, interaction::canSelectItem); + } + + private static boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, int z, Block block, + ItemStack item, float yaw) { + if (PrinterInteraction.isBlacklisted(block, item) || !interaction.selectItem(item)) { + return false; + } + return interaction.withSneaking( + true, + () -> interaction.withLook( + yaw, + interaction.player.rotationPitch, + () -> interaction.place( + interaction.player.getHeldItem(), + x, + y + 1, + z, + ForgeDirection.DOWN.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 1, z + 0.5)))); + } + + private static boolean placeStairs(PrinterInteraction interaction, int x, int y, int z, Block block, + TileEntity tile, ItemStack item) { + if (PrinterInteraction.isBlacklisted(block, item) || !interaction.canSelectItem(item)) { + return false; + } + final ForgeDirection[] supports = interaction.findSupports(x, y, z); + final boolean hasSupport = supports.length > 0; + if (!hasSupport && ConfigurationHandler.placeAdjacent) { + return false; + } + for (ForgeDirection support : hasSupport ? supports : ForgeDirection.VALID_DIRECTIONS) { + final ForgeDirection face = support.getOpposite(); + final int clickedX = hasSupport ? x + support.offsetX : x; + final int clickedY = hasSupport ? y + support.offsetY : y; + final int clickedZ = hasSupport ? z + support.offsetZ : z; + for (float across : STAIR_HIT_OFFSETS) { + for (float height : STAIR_HIT_OFFSETS) { + final float hitX = face.offsetX == 0 ? across : (1 + face.offsetX) * 0.5f; + final float hitY = face.offsetY == 0 ? height : (1 + face.offsetY) * 0.5f; + final float hitZ = face.offsetZ == 0 ? across : (1 + face.offsetZ) * 0.5f; + if (CarpentersBlocksSupport.matchesStairPlacement( + tile, + block, + interaction.world, + x, + y, + z, + face.ordinal(), + hitX, + hitY, + hitZ, + interaction.player)) { + final Vec3 hit = Vec3.createVectorHelper(clickedX + hitX, clickedY + hitY, clickedZ + hitZ); + return interaction.withSneaking( + true, + () -> interaction.selectItem(item) && interaction.place( + interaction.player.getHeldItem(), + clickedX, + clickedY, + clickedZ, + face.ordinal(), + hit)); + } + } + } + } + return false; + } + + private static final class PendingClick { + + private final World world; + private final long retryPass; + private final BooleanSupplier confirmed; + private long lastChecked = Long.MIN_VALUE; + private boolean ready; + + private PendingClick(World world, long pass, BooleanSupplier confirmed) { + final int delay = Math.max(1, ConfigurationHandler.placeDelay); + final int timeout = Math.max(20, ConfigurationHandler.timeout); + this.world = world; + // Keep the original retry interval in printer passes for clicks without a server update. + this.retryPass = pass + 2 + (timeout - 1) / delay; + this.confirmed = confirmed; + } + + private boolean allowsNextClick(World world, long pass) { + if (world != this.world || pass >= this.retryPass) { + return true; + } + // Connected panels share a click. Check all of them once per printer pass. + if (pass != this.lastChecked) { + this.lastChecked = pass; + this.ready = this.confirmed.getAsBoolean(); + } + return this.ready; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java new file mode 100644 index 00000000..7395ae94 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java @@ -0,0 +1,78 @@ +package com.github.lunatrius.schematica.client.printer; + +import java.util.HashMap; +import java.util.Map; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.ChunkPosition; +import net.minecraft.world.World; + +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; +import com.github.lunatrius.schematica.handler.ConfigurationHandler; + +final class MicroblockPrinter { + + private final Map pendingPlacements = new HashMap<>(); + + void reset() { + this.pendingPlacements.clear(); + } + + boolean isWaiting(World world, int localX, int localY, int localZ, int x, int y, int z) { + if (this.pendingPlacements.isEmpty()) { + return false; + } + final ChunkPosition cell = new ChunkPosition(localX, localY, localZ); + final PendingPlacement pending = this.pendingPlacements.get(cell); + if (pending == null) { + return false; + } + if (!pending.click.targets(x, y, z) || pending.click.isConfirmed(world.getTileEntity(x, y, z))) { + this.pendingPlacements.remove(cell); + return false; + } + pending.remainingDelay -= Math.max(1, ConfigurationHandler.placeDelay); + if (pending.remainingDelay <= 0) { + this.pendingPlacements.remove(cell); + } + return true; + } + + boolean place(PrinterInteraction interaction, TileEntity tile, int localX, int localY, int localZ, int x, int y, + int z) { + final MicroblockSupport.Click click = MicroblockSupport + .findPlacement(interaction.player, tile, x, y, z, interaction::canSelectItem); + if (click == null || !interaction.selectItem(click.item)) { + return false; + } + final MovingObjectPosition hit = click.hit; + // ItemMicroPart re-traces the clicked block from the player's aim on both sides. + if (!interaction.withSneaking( + click.sneaking, + () -> interaction.withLook( + click.yaw, + click.pitch, + () -> interaction.place( + interaction.player.getCurrentEquippedItem(), + hit.blockX, + hit.blockY, + hit.blockZ, + hit.sideHit, + hit.hitVec)))) { + return false; + } + this.pendingPlacements.put(new ChunkPosition(localX, localY, localZ), new PendingPlacement(click)); + return true; + } + + private static final class PendingPlacement { + + private final MicroblockSupport.Click click; + private int remainingDelay = Math.max(1, ConfigurationHandler.timeout); + + private PendingPlacement(MicroblockSupport.Click click) { + this.click = click; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java new file mode 100644 index 00000000..9a21c6fc --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -0,0 +1,217 @@ +package com.github.lunatrius.schematica.client.printer; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockLiquid; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.client.multiplayer.PlayerControllerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.ItemBucket; +import net.minecraft.item.ItemStack; +import net.minecraft.network.play.client.C03PacketPlayer.C05PacketPlayerLook; +import net.minecraft.network.play.client.C07PacketPlayerDigging; +import net.minecraft.network.play.client.C0BPacketEntityAction; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; +import net.minecraftforge.fluids.BlockFluidBase; +import net.minecraftforge.fluids.IFluidBlock; + +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; +import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.proxy.ClientProxy; +import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; + +final class PrinterInteraction { + + final World world; + final EntityClientPlayerMP player; + private final PlayerControllerMP controller; + private final InventoryPlayer inventory; + + PrinterInteraction(World world, EntityClientPlayerMP player, PlayerControllerMP controller) { + this.world = world; + this.player = player; + this.controller = controller; + this.inventory = player.inventory; + } + + boolean canSelectItem(ItemStack item) { + final int slot = findItemSlot(item); + return (slot >= 0 && slot < Constants.Inventory.Size.HOTBAR) + || (!ConfigurationHandler.swapSlotsQueue.isEmpty() && (slot >= 0 || this.controller.isInCreativeMode())); + } + + boolean selectItem(ItemStack item) { + return selectItem(item, true) && this.inventory.getCurrentItem() != null + && BlockToItemStack.matches(this.inventory.getCurrentItem(), item); + } + + private boolean selectItem(ItemStack item, boolean allowInventorySwap) { + final int slot = findItemSlot(item); + final boolean inHotbar = slot >= Constants.Inventory.InventoryOffset.HOTBAR + && slot < Constants.Inventory.InventoryOffset.HOTBAR + Constants.Inventory.Size.HOTBAR; + + if (this.controller.isInCreativeMode() && !inHotbar && !ConfigurationHandler.swapSlotsQueue.isEmpty()) { + this.inventory.currentItem = nextSwapSlot(); + this.inventory.setInventorySlotContents(this.inventory.currentItem, item.copy()); + this.controller.sendSlotPacket( + this.inventory.getStackInSlot(this.inventory.currentItem), + Constants.Inventory.SlotOffset.HOTBAR + this.inventory.currentItem); + return true; + } + + if (inHotbar) { + this.inventory.currentItem = slot; + return true; + } + return allowInventorySwap && slot >= Constants.Inventory.InventoryOffset.INVENTORY + && slot < Constants.Inventory.InventoryOffset.INVENTORY + Constants.Inventory.Size.INVENTORY + && swapIntoHotbar(slot) + && selectItem(item, false); + } + + private int findItemSlot(ItemStack item) { + for (int i = 0; i < this.inventory.mainInventory.length; i++) { + final ItemStack stack = this.inventory.mainInventory[i]; + if (stack != null && stack.stackSize > 0 && BlockToItemStack.matches(stack, item)) { + return i; + } + } + return -1; + } + + private boolean swapIntoHotbar(int sourceSlot) { + if (this.player.openContainer != this.player.inventoryContainer + || ConfigurationHandler.swapSlotsQueue.isEmpty()) { + return false; + } + this.controller + .windowClick(this.player.inventoryContainer.windowId, sourceSlot, nextSwapSlot(), 2, this.player); + return true; + } + + private static int nextSwapSlot() { + final int slot = ConfigurationHandler.swapSlotsQueue.poll() % Constants.Inventory.Size.HOTBAR; + ConfigurationHandler.swapSlotsQueue.offer(slot); + return slot; + } + + static boolean isBlacklisted(Block block, ItemStack item) { + return block instanceof IFluidBlock || block instanceof BlockLiquid + || item.getItem() instanceof ItemBucket + || item.getItem() == Items.sign + || ClientProxy.lotrProxy.isBlackListed(block, item); + } + + ForgeDirection[] findSupports(int x, int y, int z) { + final List supports = new ArrayList<>(); + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final int sx = x + side.offsetX; + final int sy = y + side.offsetY; + final int sz = z + side.offsetZ; + final Block block = this.world.getBlock(sx, sy, sz); + if (block != null && !block.isAir(this.world, sx, sy, sz) + && !(block instanceof BlockFluidBase) + && !block.isReplaceable(this.world, sx, sy, sz)) { + supports.add(side); + } + } + return supports.toArray(new ForgeDirection[supports.size()]); + } + + static boolean canClickForPlacement(Block clicked, ItemStack item, boolean sneaking) { + return !Mods.CARPENTERS_BLOCKS || CarpentersBlocksSupport.allowsPlacementClick(clicked, item, sneaking); + } + + boolean place(ItemStack held, int x, int y, int z, int side, Vec3 hit) { + return held != null && canClickForPlacement(this.world.getBlock(x, y, z), held, this.player.isSneaking()) + && useBlock(held, x, y, z, side, hit); + } + + boolean useBlock(ItemStack held, int x, int y, int z, int side, Vec3 hit) { + if (!isStillHolding(held)) { + return false; + } + // Interaction listeners can send packets before PlayerControllerMP handles the vanilla click. + this.controller.syncCurrentPlayItem(); + if (ForgeEventFactory.onPlayerInteract(this.player, Action.RIGHT_CLICK_BLOCK, x, y, z, side, this.world) + .isCanceled() || !isStillHolding(held)) { + return false; + } + final boolean success = this.controller.onPlayerRightClick(this.player, this.world, held, x, y, z, side, hit); + if (success) { + this.player.swingItem(); + } + return success; + } + + boolean tapWithoutMining(int x, int y, int z, int side) { + final ItemStack held = this.player.getHeldItem(); + final Block block = this.world.getBlock(x, y, z); + if (!isStillHolding(held) || block.getPlayerRelativeBlockHardness(this.player, this.world, x, y, z) >= 0) { + return false; + } + this.controller.syncCurrentPlayItem(); + if (ForgeEventFactory.onPlayerInteract(this.player, Action.LEFT_CLICK_BLOCK, x, y, z, side, this.world) + .isCanceled() || held != this.player.getHeldItem() + || this.world.getBlock(x, y, z) != block) { + return false; + } + // Send the initial hit and cancel mining so the mod can handle the tool without client-side block removal. + this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(0, x, y, z, side)); + this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(1, x, y, z, side)); + this.player.swingItem(); + return true; + } + + private boolean isStillHolding(ItemStack item) { + return item != null && item.stackSize > 0 && item == this.player.getHeldItem(); + } + + void syncSneaking(boolean sneaking) { + this.player.setSneaking(sneaking); + this.player.sendQueue.addToSendQueue(new C0BPacketEntityAction(this.player, sneaking ? 1 : 2)); + } + + boolean withSneaking(boolean sneaking, BooleanSupplier action) { + final boolean previousInput = this.player.movementInput.sneak; + this.player.movementInput.sneak = sneaking; + if (!sneaking) { + syncSneaking(false); + } + try { + return action.getAsBoolean(); + } finally { + this.player.movementInput.sneak = previousInput; + if (!sneaking) { + syncSneaking(true); + } + } + } + + boolean withLook(float yaw, float pitch, BooleanSupplier action) { + final float previousYaw = this.player.rotationYaw; + final float previousPitch = this.player.rotationPitch; + syncLook(yaw, pitch); + try { + return action.getAsBoolean(); + } finally { + syncLook(previousYaw, previousPitch); + } + } + + private void syncLook(float yaw, float pitch) { + this.player.rotationYaw = yaw; + this.player.rotationPitch = pitch; + this.player.sendQueue.addToSendQueue(new C05PacketPlayerLook(yaw, pitch, this.player.onGround)); + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 38156a62..f25f4116 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -1,35 +1,30 @@ package com.github.lunatrius.schematica.client.printer; -import java.util.ArrayList; -import java.util.List; - import net.minecraft.block.Block; -import net.minecraft.block.BlockLiquid; import net.minecraft.block.BlockPistonBase; +import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.ItemBucket; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; -import net.minecraft.network.play.client.C0BPacketEntityAction; +import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; -import net.minecraftforge.fluids.BlockFluidBase; -import net.minecraftforge.fluids.IFluidBlock; import com.github.lunatrius.core.util.vector.Vector3i; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.printer.registry.PlacementData; import com.github.lunatrius.schematica.client.printer.registry.PlacementRegistry; import com.github.lunatrius.schematica.client.util.BlockToItemStack; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; -import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; @@ -39,14 +34,14 @@ public class SchematicPrinter { public static final SchematicPrinter INSTANCE = new SchematicPrinter(); public static final FMLControlledNamespacedRegistry BLOCK_REGISTRY = GameData.getBlockRegistry(); - private final Minecraft minecraft = Minecraft.getMinecraft(); + private final MicroblockPrinter microblocks = new MicroblockPrinter(); + private final CarpentersPrinter carpenters = new CarpentersPrinter(); private boolean isEnabled; private boolean isPrinting; - - private SchematicWorld schematic = null; - private byte[][][] timeout = null; + private SchematicWorld schematic; + private byte[][][] retryDelay; public boolean isEnabled() { return this.isEnabled; @@ -80,18 +75,21 @@ public void setSchematic(SchematicWorld schematic) { } public void refresh() { + this.microblocks.reset(); + this.carpenters.reset(); if (this.schematic != null) { - this.timeout = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic.getLength()]; + this.retryDelay = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic + .getLength()]; } else { - this.timeout = null; + this.retryDelay = null; } } public boolean print() { final EntityClientPlayerMP player = this.minecraft.thePlayer; final World world = this.minecraft.theWorld; - - syncSneaking(player, true); + final PrinterInteraction interaction = new PrinterInteraction(world, player, this.minecraft.playerController); + this.carpenters.beginPass(world); final Vector3i trans = ClientProxy.playerPosition.clone() .sub(this.schematic.position.x, this.schematic.position.y, this.schematic.position.z) @@ -104,62 +102,103 @@ public boolean print() { final int maxZ = Math.min(this.schematic.getLength(), trans.z + 4); final int slot = player.inventory.currentItem; - final boolean isSneaking = player.isSneaking(); - - final boolean isRenderingLayer = this.schematic.isRenderingLayer; - final int renderingLayer = this.schematic.renderingLayer; - for (int y = minY; y < maxY; y++) { - if (isRenderingLayer && y != renderingLayer) { - continue; - } - - for (int x = minX; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - try { - if (placeBlock(world, player, x, y, z)) { - player.inventory.currentItem = slot; - syncSneaking(player, isSneaking); + final boolean wasSneaking = player.isSneaking(); + interaction.syncSneaking(true); + try { + final boolean isRenderingLayer = this.schematic.isRenderingLayer; + final int renderingLayer = this.schematic.renderingLayer; + for (int y = minY; y < maxY; y++) { + if (isRenderingLayer && renderingLayer != y) { + continue; + } + for (int x = minX; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + if (printCell(interaction, x, y, z)) { return true; } - } catch (Exception e) { - Reference.logger.error("Could not place block!", e); - player.inventory.currentItem = slot; - syncSneaking(player, isSneaking); - return false; } } } + return true; + } catch (Exception e) { + Reference.logger.error("Could not place block!", e); + return false; + } finally { + player.inventory.currentItem = slot; + interaction.syncSneaking(wasSneaking); } - - player.inventory.currentItem = slot; - syncSneaking(player, isSneaking); - return true; } - private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z) { - if (this.timeout[x][y][z] > 0) { - this.timeout[x][y][z] -= ConfigurationHandler.placeDelay; + // Returns true when placement should end the current pass. + private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { + final World world = interaction.world; + final EntityClientPlayerMP player = interaction.player; + final int worldX = this.schematic.position.x + x; + final int worldY = this.schematic.position.y + y; + final int worldZ = this.schematic.position.z + z; + + if (this.carpenters.isWaiting(worldX, worldY, worldZ) + || this.microblocks.isWaiting(world, x, y, z, worldX, worldY, worldZ)) { + return false; + } + if (this.retryDelay[x][y][z] > 0) { + this.retryDelay[x][y][z] -= Math.max(1, ConfigurationHandler.placeDelay); return false; } - - final int wx = this.schematic.position.x + x; - final int wy = this.schematic.position.y + y; - final int wz = this.schematic.position.z + z; final Block block = this.schematic.getBlock(x, y, z); - final Block realBlock = world.getBlock(wx, wy, wz); + final Block placedBlock = world.getBlock(worldX, worldY, worldZ); final int metadata = this.schematic.getBlockMetadata(x, y, z); - final int realMetadata = world.getBlockMetadata(wx, wy, wz); + final int placedMetadata = world.getBlockMetadata(worldX, worldY, worldZ); + + if (block.hasTileEntity(metadata) && Mods.FORGE_MICROBLOCK) { + final TileEntity tile = this.schematic.getTileEntity(x, y, z); + if (MicroblockSupport.hasMicroblocks(tile)) { + return this.microblocks.place(interaction, tile, x, y, z, worldX, worldY, worldZ) + && !ConfigurationHandler.placeInstantly; + } + } - if (block == realBlock && metadata == realMetadata) { + final boolean carpenterBlock = Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block); + if (carpenterBlock && block == placedBlock) { + return this.carpenters.configureBlock( + interaction, + this.schematic, + block, + this.schematic.getTileEntity(x, y, z), + worldX, + worldY, + worldZ) && !ConfigurationHandler.placeInstantly; + } + + final boolean architectureShape = Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block); + final TileEntity architectureTile = architectureShape ? this.schematic.getTileEntity(x, y, z) : null; + if (block == placedBlock && BlockToItemStack.matchesMetadata(block, placedMetadata, metadata) + && (!architectureShape || ArchitectureCraftSupport + .matches(world.getTileEntity(worldX, worldY, worldZ), architectureTile, block))) { return false; } - if (ConfigurationHandler.destroyBlocks && !world.isAirBlock(wx, wy, wz) + if (block instanceof BlockSlab && block.isOpaqueCube() + && placedBlock instanceof BlockSlab + && !placedBlock.isOpaqueCube()) { + final ItemStack slab = BlockToItemStack.getItemStack(player, block, this.schematic, x, y, z); + if (slab != null && slab.getItem() instanceof ItemSlab + && isMatchingHalfSlab(world, worldX, worldY, worldZ, slab)) { + if (interaction.selectItem(slab) + && mergeSlab(interaction, worldX, worldY, worldZ, player.getHeldItem())) { + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; + return !ConfigurationHandler.placeInstantly; + } + return false; + } + } + + if (ConfigurationHandler.destroyBlocks && !world.isAirBlock(worldX, worldY, worldZ) && this.minecraft.playerController.isInCreativeMode()) { - this.minecraft.playerController.clickBlock(wx, wy, wz, 0); + this.minecraft.playerController.clickBlock(worldX, worldY, worldZ, 0); - this.timeout[x][y][z] = (byte) ConfigurationHandler.timeout; + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; return !ConfigurationHandler.destroyInstantly; } @@ -168,7 +207,7 @@ private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z return false; } - if (!realBlock.isReplaceable(world, wx, wy, wz)) { + if (!placedBlock.isReplaceable(world, worldX, worldY, worldZ)) { return false; } @@ -178,8 +217,24 @@ private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z return false; } - if (placeBlock(world, player, wx, wy, wz, block, metadata, itemStack)) { - this.timeout[x][y][z] = (byte) ConfigurationHandler.timeout; + final boolean success; + if (architectureShape) { + success = ArchitectureCraftPrinter.place(interaction, worldX, worldY, worldZ, architectureTile, itemStack); + } else if (carpenterBlock) { + success = CarpentersPrinter.place( + interaction, + this.schematic, + block, + x, + y, + z, + itemStack, + () -> placeVanillaBlock(interaction, worldX, worldY, worldZ, block, metadata, itemStack)); + } else { + success = placeVanillaBlock(interaction, worldX, worldY, worldZ, block, metadata, itemStack); + } + if (success) { + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; if (!ConfigurationHandler.placeInstantly) { return true; @@ -189,105 +244,86 @@ private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z return false; } - private boolean isSolid(World world, int x, int y, int z, ForgeDirection side) { - x += side.offsetX; - y += side.offsetY; - z += side.offsetZ; - - Block block = world.getBlock(x, y, z); - - if (block == null) { - return false; - } - - if (block.isAir(world, x, y, z)) { - return false; - } - - if (block instanceof BlockFluidBase) { - return false; - } - - if (block.isReplaceable(world, x, y, z)) { - return false; - } - - return true; - } - - private ForgeDirection[] getSolidSides(World world, int x, int y, int z) { - List list = new ArrayList<>(); - - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { - if (isSolid(world, x, y, z, side)) { - list.add(side); - } - } - - ForgeDirection[] sides = new ForgeDirection[list.size()]; - return list.toArray(sides); - } - - private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z, Block block, int metadata, + private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, int z, Block block, int metadata, ItemStack itemStack) { - if (isBlacklisted(block, itemStack)) { + final World world = interaction.world; + if (PrinterInteraction.isBlacklisted(block, itemStack)) { return false; } PlacementData data = PlacementRegistry.INSTANCE.getPlacementData(block, itemStack); - if (!isValidOrientation(player, x, y, z, data, metadata)) { + if (!isValidOrientation(interaction.player, x, y, z, data, metadata)) { return false; } - ForgeDirection[] solidSides = getSolidSides(world, x, y, z); + final ForgeDirection[] solidSides = interaction.findSupports(x, y, z); + final ForgeDirection[] validSides = data == null ? solidSides : data.getValidDirections(solidSides, metadata); + final boolean slab = block instanceof BlockSlab && itemStack.getItem() instanceof ItemSlab; ForgeDirection direction = ForgeDirection.UNKNOWN; - float offsetY = 0.0f; - int extraClicks = 0; - - if (solidSides.length > 0) { - if (data != null) { - ForgeDirection[] validDirections = data.getValidDirections(solidSides, metadata); - if (validDirections.length > 0) { - direction = validDirections[0]; - } - - offsetY = data.getOffsetFromMetadata(metadata); - extraClicks = data.getExtraClicks(block, metadata); - } else { - direction = solidSides[0]; + for (ForgeDirection support : validSides) { + if (PrinterInteraction.canClickForPlacement( + world.getBlock(x + support.offsetX, y + support.offsetY, z + support.offsetZ), + itemStack, + true) && (!slab || !wouldMergeSupportingSlab(world, x, y, z, support, itemStack))) { + direction = support; + break; } + } - if (!swapToItem(player.inventory, itemStack)) { + final boolean adjacent = direction != ForgeDirection.UNKNOWN; + if (!adjacent) { + if ((ConfigurationHandler.placeAdjacent && solidSides.length == 0) + || (validSides.length == 0 && data != null + && data.type == PlacementData.PlacementType.BLOCK + && !data.mapping.isEmpty()) + || !(itemStack.getItem() instanceof ItemBlock)) { + return false; + } + final ForgeDirection[] valid = data == null ? ForgeDirection.VALID_DIRECTIONS + : data.getValidDirections(ForgeDirection.VALID_DIRECTIONS, metadata); + for (ForgeDirection side : valid) { + // ItemSlab checks the block across the clicked face before placing into the clicked cell. + if (!slab + || !isMatchingHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack)) { + direction = side; + break; + } + } + if (direction == ForgeDirection.UNKNOWN) { return false; } } - if (direction != ForgeDirection.UNKNOWN || !ConfigurationHandler.placeAdjacent) { - return placeBlock(world, player, x, y, z, direction, 0.0f, offsetY, 0.0f, extraClicks); - } - - return false; + final float offsetY = data == null || data.maskOffset == 0 ? 0.5f : data.getOffsetFromMetadata(metadata); + final int extraClicks = data == null ? 0 : data.getExtraClicks(block, metadata); + return interaction.selectItem(itemStack) + && placeAgainstSupport(interaction, x, y, z, direction, adjacent, offsetY, extraClicks); } - private boolean isBlacklisted(Block block, ItemStack itemStack) { - if (block instanceof IFluidBlock || block instanceof BlockLiquid) { - return true; - } - - if (itemStack.getItem() instanceof ItemBucket) { - return true; - } - - if (itemStack.getItem() == Items.sign) { - return true; + private boolean wouldMergeSupportingSlab(World world, int x, int y, int z, ForgeDirection support, ItemStack slab) { + if (support.offsetY == 0 || !isMatchingHalfSlab(world, x, y + support.offsetY, z, slab)) { + return false; } + final boolean top = (world.getBlockMetadata(x, y + support.offsetY, z) & 8) != 0; + return top ? support == ForgeDirection.UP : support == ForgeDirection.DOWN; + } - if (ClientProxy.lotrProxy.isBlackListed(block, itemStack)) { - return true; - } + private boolean isMatchingHalfSlab(World world, int x, int y, int z, ItemStack slab) { + final Block block = world.getBlock(x, y, z); + return block == Block.getBlockFromItem(slab.getItem()) && !block.isOpaqueCube() + && (world.getBlockMetadata(x, y, z) & 7) == slab.getItemDamage(); + } - return false; + private boolean mergeSlab(PrinterInteraction interaction, int x, int y, int z, ItemStack slab) { + final boolean top = (interaction.world.getBlockMetadata(x, y, z) & 8) != 0; + return interaction.place( + slab, + x, + y, + z, + top ? ForgeDirection.DOWN.ordinal() : ForgeDirection.UP.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 0.5, z + 0.5)); } private boolean isValidOrientation(EntityPlayer player, int x, int y, int z, PlacementData data, int metadata) { @@ -320,27 +356,36 @@ private boolean isValidOrientation(EntityPlayer player, int x, int y, int z, Pla return true; } - private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z, ForgeDirection direction, - float offsetX, float offsetY, float offsetZ, int extraClicks) { - ItemStack itemStack = player.getCurrentEquippedItem(); + private boolean placeAgainstSupport(PrinterInteraction interaction, int x, int y, int z, ForgeDirection direction, + boolean adjacent, float offsetY, int extraClicks) { + final EntityClientPlayerMP player = interaction.player; + final ItemStack itemStack = player.getCurrentEquippedItem(); if (!this.minecraft.playerController.isInCreativeMode() && itemStack != null && itemStack.stackSize <= extraClicks) { return false; } - x += direction.offsetX; - y += direction.offsetY; - z += direction.offsetZ; - - int side = direction.getOpposite() - .ordinal(); - final Vec3 hitVec = Vec3.createVectorHelper(x + offsetX, y + offsetY, z + offsetZ); - - boolean success = placeBlock(world, player, itemStack, x, y, z, side, hitVec); - for (int i = 0; success && i < extraClicks; i++) { - success = placeBlock(world, player, itemStack, x, y, z, side, hitVec); - } + final int clickedX = adjacent ? x + direction.offsetX : x; + final int clickedY = adjacent ? y + direction.offsetY : y; + final int clickedZ = adjacent ? z + direction.offsetZ : z; + final ForgeDirection face = direction.getOpposite(); + final int side = face.ordinal(); + final Vec3 hit = Vec3.createVectorHelper( + clickedX + 0.5 + face.offsetX * 0.5, + clickedY + (face.offsetY == 0 ? offsetY : (1 + face.offsetY) * 0.5), + clickedZ + 0.5 + face.offsetZ * 0.5); + + final boolean success = interaction.withSneaking(true, () -> { + boolean placed = interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); + for (int i = 0; placed && i < extraClicks; i++) { + placed = itemStack.getItem() instanceof ItemSlab + ? isMatchingHalfSlab(interaction.world, x, y, z, itemStack) + && mergeSlab(interaction, x, y, z, itemStack) + : interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); + } + return placed; + }); if (itemStack != null && itemStack.stackSize == 0 && success) { player.inventory.mainInventory[player.inventory.currentItem] = null; @@ -348,88 +393,4 @@ private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z return success; } - - private boolean placeBlock(World world, EntityPlayer player, ItemStack itemStack, int x, int y, int z, int side, - Vec3 hitVec) { - boolean success = !ForgeEventFactory.onPlayerInteract(player, Action.RIGHT_CLICK_BLOCK, x, y, z, side, world) - .isCanceled(); - if (success) { - success = this.minecraft.playerController - .onPlayerRightClick(player, world, itemStack, x, y, z, side, hitVec); - if (success) { - player.swingItem(); - } - } - - return success; - } - - private void syncSneaking(EntityClientPlayerMP player, boolean isSneaking) { - player.setSneaking(isSneaking); - player.sendQueue.addToSendQueue(new C0BPacketEntityAction(player, isSneaking ? 1 : 2)); - } - - private boolean swapToItem(InventoryPlayer inventory, ItemStack itemStack) { - return swapToItem(inventory, itemStack, true); - } - - private boolean swapToItem(InventoryPlayer inventory, ItemStack itemStack, boolean swapSlots) { - int slot = getInventorySlotWithItem(inventory, itemStack); - - if (this.minecraft.playerController.isInCreativeMode() - && (slot < Constants.Inventory.InventoryOffset.HOTBAR - || slot >= Constants.Inventory.InventoryOffset.HOTBAR + Constants.Inventory.Size.HOTBAR) - && !ConfigurationHandler.swapSlotsQueue.isEmpty()) { - inventory.currentItem = getNextSlot(); - inventory.setInventorySlotContents(inventory.currentItem, itemStack.copy()); - this.minecraft.playerController.sendSlotPacket( - inventory.getStackInSlot(inventory.currentItem), - Constants.Inventory.SlotOffset.HOTBAR + inventory.currentItem); - return true; - } - - if (slot >= Constants.Inventory.InventoryOffset.HOTBAR - && slot < Constants.Inventory.InventoryOffset.HOTBAR + Constants.Inventory.Size.HOTBAR) { - inventory.currentItem = slot; - return true; - } else if (swapSlots && slot >= Constants.Inventory.InventoryOffset.INVENTORY - && slot < Constants.Inventory.InventoryOffset.INVENTORY + Constants.Inventory.Size.INVENTORY) { - if (swapSlots(inventory, slot)) { - return swapToItem(inventory, itemStack, false); - } - } - return false; - } - - private int getInventorySlotWithItem(final InventoryPlayer inventory, final ItemStack itemStack) { - for (int i = 0; i < inventory.mainInventory.length; i++) { - if (inventory.mainInventory[i] != null && inventory.mainInventory[i].isItemEqual(itemStack)) { - return i; - } - } - return -1; - } - - private boolean swapSlots(InventoryPlayer inventory, int from) { - if (!ConfigurationHandler.swapSlotsQueue.isEmpty()) { - int slot = getNextSlot(); - - swapSlots(from, slot); - return true; - } - - return false; - } - - private int getNextSlot() { - int slot = ConfigurationHandler.swapSlotsQueue.poll() % Constants.Inventory.Size.HOTBAR; - ConfigurationHandler.swapSlotsQueue.offer(slot); - return slot; - } - - private boolean swapSlots(final int from, final int to) { - return this.minecraft.playerController - .windowClick(this.minecraft.thePlayer.inventoryContainer.windowId, from, to, 2, this.minecraft.thePlayer) - == null; - } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java index 27478d60..17bcc463 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java @@ -13,11 +13,13 @@ import net.minecraft.block.BlockPistonBase; import net.minecraft.block.BlockPumpkin; import net.minecraft.block.BlockRotatedPillar; +import net.minecraft.block.BlockSlab; import net.minecraft.block.BlockStairs; import net.minecraft.block.BlockTorch; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; +import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; public class PlacementRegistry { @@ -27,14 +29,16 @@ public class PlacementRegistry { private final Map, PlacementData> classPlacementMap = new HashMap<>(); private final Map blockPlacementMap = new HashMap<>(); private final Map itemPlacementMap = new HashMap<>(); + private final PlacementData halfSlab = new PlacementData(PlacementData.PlacementType.BLOCK) + .setOffset(0x8, 0.25f, 0.75f); + private final PlacementData doubleSlab = new PlacementData(PlacementData.PlacementType.BLOCK) + .setExtraClick((block, metadata) -> 1); public void populatePlacementMaps() { this.classPlacementMap.clear(); this.blockPlacementMap.clear(); this.itemPlacementMap.clear(); - final IExtraClick extraClickDoubleSlab = (block, metadata) -> block.isOpaqueCube() ? 1 : 0; - addPlacementMapping( BlockButton.class, new PlacementData(PlacementData.PlacementType.BLOCK, -1, -1, 3, 4, 1, 2).setMaskMeta(0x7)); @@ -76,13 +80,6 @@ public void populatePlacementMaps() { addPlacementMapping(Blocks.wool, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.yellow_flower, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.red_flower, new PlacementData(PlacementData.PlacementType.BLOCK)); - addPlacementMapping( - Blocks.double_stone_slab, - new PlacementData(PlacementData.PlacementType.BLOCK).setExtraClick(extraClickDoubleSlab)); - addPlacementMapping( - Blocks.stone_slab, - new PlacementData(PlacementData.PlacementType.BLOCK).setOffset(0x8, 0.0f, 1.0f) - .setMaskMeta(0x7)); addPlacementMapping(Blocks.stained_glass, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.ladder, new PlacementData(PlacementData.PlacementType.BLOCK, -1, -1, 3, 2, 5, 4)); addPlacementMapping( @@ -102,12 +99,6 @@ public void populatePlacementMaps() { addPlacementMapping( Blocks.fence_gate, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 2, 0, 1, 3).setMaskMeta(0x3)); - addPlacementMapping(Blocks.double_wooden_slab, new PlacementData(PlacementData.PlacementType.BLOCK)); - addPlacementMapping( - Blocks.wooden_slab, - new PlacementData(PlacementData.PlacementType.BLOCK).setOffset(0x8, 0.0f, 1.0f) - .setMaskMeta(0x7) - .setExtraClick(extraClickDoubleSlab)); addPlacementMapping( Blocks.anvil, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 1, 3, 0, 2).setMaskMeta(0x3)); @@ -163,6 +154,10 @@ public PlacementData getPlacementData(Block block, ItemStack itemStack) { return placementDataBlock; } + if (block instanceof BlockSlab && itemStack.getItem() instanceof ItemSlab) { + return block.isOpaqueCube() ? this.doubleSlab : this.halfSlab; + } + for (Class clazz : this.classPlacementMap.keySet()) { if (clazz.isInstance(block)) { return this.classPlacementMap.get(clazz); diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index 4f1bf4d7..df639d56 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -15,17 +15,22 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.IBlockAccess; +import net.minecraftforge.client.ForgeHooksClient; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; import com.github.lunatrius.core.util.vector.Vector3d; import com.github.lunatrius.core.util.vector.Vector3f; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.renderer.shader.ShaderProgram; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; public class RendererSchematicChunk { @@ -145,8 +150,15 @@ public void updateRenderer() { } GL11.glNewList(this.glList + pass, GL11.GL_COMPILE); - renderBlocks(pass, minX, minY, minZ, maxX, maxY, maxZ); - GL11.glEndList(); + final int previousPass = ForgeHooksClient.getWorldRenderPass(); + try { + // Multipart uses Forge's chunk-building pass to choose the parts to render. + ForgeHooksClient.worldRenderPass = pass; + renderBlocks(pass, minX, minY, minZ, maxX, maxY, maxZ); + } finally { + ForgeHooksClient.worldRenderPass = previousPass; + GL11.glEndList(); + } GL11.glNewList(this.glListHighlight + pass, GL11.GL_COMPILE); int quadCount = RenderHelper.getQuadCount(); @@ -236,6 +248,8 @@ public void render(int renderPass) { public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { IBlockAccess mcWorld = this.minecraft.theWorld; RenderBlocks renderBlocks = RendererSchematicGlobal.INSTANCE.renderBlocks; + final boolean renderMicroblocks = renderPass < 2 && Mods.FORGE_MICROBLOCK; + final boolean highlightCarpenters = renderPass == 2 && Mods.CARPENTERS_BLOCKS; int x, y, z, wx, wy, wz; int sides; @@ -292,6 +306,16 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, || ConfigurationHandler.isExtraAirBlock(mcBlock); if (!isMcAirBlock) { + if (renderMicroblocks && block == mcBlock + && block.hasTileEntity(this.schematic.getBlockMetadata(x, y, z))) { + MicroblockSupport.renderMissingParts( + this.schematic, + mcWorld.getTileEntity(wx, wy, wz), + x, + y, + z, + renderPass); + } if (ConfigurationHandler.highlight && renderPass == 2) { if (isAirBlock && ConfigurationHandler.highlightAir) { zero.set(x, y, z); @@ -325,19 +349,26 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, if (ConfigurationHandler.drawLines) { RenderHelper.drawCuboidOutline(zero, size, sides, 1.0f, 0.0f, 0.0f, 0.25f); } - } else if (this.schematic.getBlockMetadata(x, y, z) - != mcWorld.getBlockMetadata(wx, wy, wz)) { - zero.set(x, y, z); - size.set(x + 1, y + 1, z + 1); - if (ConfigurationHandler.drawQuads) { - RenderHelper - .drawCuboidSurface(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); + } else if (highlightCarpenters && CarpentersBlocksSupport.isCoverable(block) + ? !CarpentersBlocksSupport.matches( + block, + this.schematic.getTileEntity(x, y, z), + mcWorld.getTileEntity(wx, wy, wz)) + : !BlockToItemStack.matchesMetadata( + block, + mcWorld.getBlockMetadata(wx, wy, wz), + this.schematic.getBlockMetadata(x, y, z))) { + zero.set(x, y, z); + size.set(x + 1, y + 1, z + 1); + if (ConfigurationHandler.drawQuads) { + RenderHelper + .drawCuboidSurface(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); + } + if (ConfigurationHandler.drawLines) { + RenderHelper + .drawCuboidOutline(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); + } } - if (ConfigurationHandler.drawLines) { - RenderHelper - .drawCuboidOutline(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); - } - } } } else if (!isAirBlock) { if (ConfigurationHandler.highlight && renderPass == 2) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index d23b0040..0467e307 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -3,17 +3,25 @@ import java.util.ArrayList; import java.util.List; +import net.blay09.mods.cookingforblockheads.utils.DyeUtils; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import net.minecraft.util.MovingObjectPosition; +import net.minecraft.tileentity.TileEntity; -import com.github.lunatrius.core.entity.EntityHelper; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.nbt.NBTHelper; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; +import cpw.mods.fml.common.registry.GameRegistry; + public class BlockList { public List getList(final EntityPlayer player, final SchematicWorld world, @@ -24,8 +32,6 @@ public List getList(final EntityPlayer player, final Schematic return blockList; } - final MovingObjectPosition movingObjectPosition = new MovingObjectPosition(player); - for (int y = 0; y < world.getHeight(); y++) { for (int x = 0; x < world.getWidth(); x++) { for (int z = 0; z < world.getLength(); z++) { @@ -42,52 +48,140 @@ public List getList(final EntityPlayer player, final Schematic final int wx = world.position.x + x; final int wy = world.position.y + y; final int wz = world.position.z + z; + if (Mods.FORGE_MICROBLOCK && block.hasTileEntity(world.getBlockMetadata(x, y, z)) + && MicroblockSupport.addMaterials( + world.getTileEntity(x, y, z), + mcWorld.getTileEntity(wx, wy, wz), + (stack, placed) -> addMaterial(blockList, stack, stack.stackSize, placed))) { + continue; + } final Block mcBlock = mcWorld.getBlock(wx, wy, wz); - final boolean isPlaced = block == mcBlock - && world.getBlockMetadata(x, y, z) == mcWorld.getBlockMetadata(wx, wy, wz); - - ItemStack stack = null; - - try { - stack = block.getPickBlock(movingObjectPosition, world, x, y, z, player); - } catch (final Exception e) { - Reference.logger.debug("Could not get the pick block for: {}", block, e); + final boolean carpenter = Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block); + if (carpenter) { + CarpentersBlocksSupport.addMaterials( + world.getTileEntity(x, y, z), + block == mcBlock ? mcWorld.getTileEntity(wx, wy, wz) : null, + (material, placed) -> addMaterial(blockList, material, 1, placed)); } + final ItemStack stack = BlockToItemStack.getItemStack(player, block, world, x, y, z); if (stack == null || stack.getItem() == null) { Reference.logger.debug("Could not find the item for: {}", block); continue; } - final WrappedItemStack wrappedItemStack = findOrCreateWrappedItemStackFor(blockList, stack); - if (isPlaced) { - wrappedItemStack.placed++; + final ItemStack placed = block == mcBlock && (carpenter || BlockToItemStack + .matchesMetadata(block, mcWorld.getBlockMetadata(wx, wy, wz), world.getBlockMetadata(x, y, z))) + ? BlockToItemStack.getItemStack(player, mcBlock, mcWorld, wx, wy, wz) + : null; + addMaterial(blockList, stack, 1, placed != null && BlockToItemStack.matches(placed, stack)); + if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { + final ItemStack secondary = ArchitectureCraftSupport + .getSecondaryItem(world.getTileEntity(x, y, z)); + if (secondary != null) { + final ItemStack actual = block == mcBlock + ? ArchitectureCraftSupport.getSecondaryItem(mcWorld.getTileEntity(wx, wy, wz)) + : null; + addMaterial( + blockList, + secondary, + secondary.stackSize, + actual != null && BlockToItemStack.matches(actual, secondary)); + } + } + if (Mods.COOKING_FOR_BLOCKHEADS && block.hasTileEntity(world.getBlockMetadata(x, y, z))) { + final GameRegistry.UniqueIdentifier name = GameRegistry.findUniqueIdentifierFor(block); + if (name != null && Mods.COOKING_FOR_BLOCKHEADS_ID.equals(name.modId)) { + final int color = kitchenColor(world.getTileEntity(x, y, z)); + final boolean pairedFridge = "fridge".equals(name.name) && !world.isRenderingLayer + && y > 0 + && world.getBlock(x, y - 1, z) == block + && kitchenColor(world.getTileEntity(x, y - 1, z)) == color; + if (color > 0 && color <= 15 && !pairedFridge) { + final boolean dyed = block == mcBlock + && kitchenColor(mcWorld.getTileEntity(wx, wy, wz)) == color; + final WrappedItemStack dye = addMaterial( + blockList, + new ItemStack(Items.dye, 1, 15 - color), + 1, + dyed); + if (!dyed) { + dye.kitchenDyesNeeded++; + } + } + } } - wrappedItemStack.total++; } } } for (WrappedItemStack wrappedItemStack : blockList) { - if (player.capabilities.isCreativeMode) wrappedItemStack.inventory = -1; - else wrappedItemStack.inventory = EntityHelper.getItemCountInInventory( - player.inventory, - wrappedItemStack.itemStack.getItem(), - wrappedItemStack.itemStack.getItemDamage()); + final ItemStack target = wrappedItemStack.itemStack; + if (player.capabilities.isCreativeMode) { + wrappedItemStack.inventory = -1; + } else { + for (ItemStack stack : player.inventory.mainInventory) { + if (stack != null && BlockToItemStack.matches(stack, target)) { + wrappedItemStack.inventory += stack.stackSize; + } + } + } } + if (Mods.COOKING_FOR_BLOCKHEADS && !player.capabilities.isCreativeMode) { + addKitchenDyeSubstitutes(blockList, player.inventory.mainInventory); + } return blockList; } + private void addKitchenDyeSubstitutes(List materials, ItemStack[] inventory) { + for (WrappedItemStack dye : materials) { + if (dye.kitchenDyesNeeded == 0) { + continue; + } + final int damage = dye.itemStack.getItemDamage(); + int available = 0; + for (ItemStack stack : inventory) { + if (stack != null && !BlockToItemStack.matches(stack, dye.itemStack) + && DyeUtils.rawDyeDamageFromStack(stack) == damage) { + available += stack.stackSize; + } + } + // Reserve dyes that a different row needs as exact ingredients before counting substitutes. + for (WrappedItemStack material : materials) { + if (material != dye && DyeUtils.rawDyeDamageFromStack(material.itemStack) == damage) { + available -= Math.min(material.inventory, material.total - material.placed); + } + } + dye.inventory += Math.min(Math.max(available, 0), dye.kitchenDyesNeeded); + } + } + + private int kitchenColor(TileEntity tile) { + return tile == null ? 0 + : NBTHelper.writeTileEntityToCompound(tile) + .getByte("Color"); + } + + private WrappedItemStack addMaterial(List blockList, ItemStack stack, int count, boolean placed) { + final WrappedItemStack entry = findOrCreateWrappedItemStackFor(blockList, stack); + if (placed) { + entry.placed += count; + } + entry.total += count; + return entry; + } + private WrappedItemStack findOrCreateWrappedItemStackFor(final List blockList, final ItemStack itemStack) { for (final WrappedItemStack wrappedItemStack : blockList) { - if (wrappedItemStack.itemStack.isItemEqual(itemStack)) { + if (BlockToItemStack.matches(wrappedItemStack.itemStack, itemStack)) { return wrappedItemStack; } } final WrappedItemStack wrappedItemStack = new WrappedItemStack(itemStack.copy()); + wrappedItemStack.itemStack.stackSize = 1; blockList.add(wrappedItemStack); return wrappedItemStack; } @@ -98,6 +192,7 @@ public static class WrappedItemStack { public int placed; public int total; public int inventory; + private int kitchenDyesNeeded; public WrappedItemStack(final ItemStack itemStack) { this(itemStack, 0, 0); @@ -110,8 +205,14 @@ public WrappedItemStack(final ItemStack itemStack, final int placed, final int t } public String getItemStackDisplayName() { - return this.itemStack.getItem() - .getItemStackDisplayName(this.itemStack); + final String name = this.itemStack.getDisplayName(); + if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(this.itemStack)) { + final String material = ArchitectureCraftSupport.getMaterialName(this.itemStack); + if (!material.isEmpty()) { + return name + " (" + material + ")"; + } + } + return name; } public String getFormattedAmount() { diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 89931918..3ff5159c 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -2,26 +2,45 @@ import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; +import net.minecraft.world.World; -import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; public class BlockToItemStack { - public static ItemStack getItemStack(final EntityPlayer player, final Block block, final SchematicWorld world, - final int x, final int y, final int z) { + public static ItemStack getItemStack(final EntityPlayer player, final Block block, final World world, final int x, + final int y, final int z) { try { + if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { + final ItemStack shape = ArchitectureCraftSupport.getItem(world.getTileEntity(x, y, z), block); + if (shape != null) { + return shape; + } + } final ItemStack itemStack = block.getPickBlock( - new MovingObjectPosition(x, y, z, 0, Vec3.createVectorHelper(0, 0, 0)), + new MovingObjectPosition(x, y, z, 1, Vec3.createVectorHelper(x + 0.5, y + 1.0, z + 0.5)), world, x, y, z, player); - if (itemStack != null) { + if (itemStack != null && itemStack.getItem() != null) { + // Ignore facing damage when a non-subtyped item places the same metadata as its default stack. + if (itemStack.getItem() instanceof ItemBlock && !itemStack.getHasSubtypes() + && itemStack.getItem() + .getMetadata(itemStack.getItemDamage()) + == itemStack.getItem() + .getMetadata(0)) { + itemStack.setItemDamage(0); + } return itemStack; } } catch (final Exception e) { @@ -30,4 +49,35 @@ public static ItemStack getItemStack(final EntityPlayer player, final Block bloc return null; } + + public static boolean matches(ItemStack stack, ItemStack target) { + if (!stack.isItemEqual(target)) { + return false; + } + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMicroblockItem(target)) { + return MicroblockSupport.itemsMatch(stack, target); + } + if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(target)) { + return ArchitectureCraftSupport.itemsMatch(stack, target); + } + return ItemStack.areItemStackTagsEqual(stack, target) + || (hasOnlyCosmeticTags(stack) && hasOnlyCosmeticTags(target)); + } + + private static boolean hasOnlyCosmeticTags(ItemStack stack) { + final NBTTagCompound tag = stack.getTagCompound(); + if (tag == null) { + return true; + } + // The vanilla anvil writes RepairCost when renaming an item. + final int cosmeticKeys = (tag.hasKey("display", 10) ? 1 : 0) + (tag.hasKey("RepairCost", 3) ? 1 : 0); + return tag.func_150296_c() + .size() == cosmeticKeys; + } + + public static boolean matchesMetadata(Block block, int actual, int saved) { + return actual == saved || (block.getClass() + .getName() + .equals("gregtech.common.blocks.GTBlockOre") && block.damageDropped(actual) == block.damageDropped(saved)); + } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index 42c4f52f..12eea038 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -21,7 +21,9 @@ import com.github.lunatrius.core.util.vector.Vector3f; import com.github.lunatrius.core.util.vector.Vector3i; import com.github.lunatrius.schematica.api.ISchematic; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.world.chunk.ChunkProviderSchematic; import com.github.lunatrius.schematica.world.storage.SaveHandlerSchematic; @@ -310,6 +312,7 @@ public void flip(ForgeDirection direction) { } this.schematic = schematicFlipped; + transformShapeTiles(direction, true); refreshChests(); } @@ -439,6 +442,16 @@ public void rotate(ForgeDirection direction) { break; default: Reference.logger.debug("Incorrect direction given to rotate function!"); + return; + } + transformShapeTiles(direction, false); + } + + private void transformShapeTiles(ForgeDirection direction, boolean mirror) { + if (Mods.ARCHITECTURE_CRAFT) { + for (TileEntity tile : this.schematic.getTileEntities()) { + ArchitectureCraftSupport.transform(tile, direction, mirror); + } } } diff --git a/src/main/resources/META-INF/schematica_at.cfg b/src/main/resources/META-INF/schematica_at.cfg index e2ba0869..b612f28d 100644 --- a/src/main/resources/META-INF/schematica_at.cfg +++ b/src/main/resources/META-INF/schematica_at.cfg @@ -1,2 +1,4 @@ # Schematica public net.minecraft.nbt.NBTTagCompound func_150298_a(Ljava/lang/String;Lnet/minecraft/nbt/NBTBase;Ljava/io/DataOutput;)V # writeNamedTag +public net.minecraftforge.client.ForgeHooksClient worldRenderPass +public net.minecraft.client.multiplayer.PlayerControllerMP func_78750_j()V # syncCurrentPlayItem From 1c4e3c0a301ff4a570298338bd3e4871c461a642 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 05/64] fix: preserve metadata in schematic downloads Append the optional high bytes after the legacy fields to preserve older decoders and avoid Forge's signed-short NBT length limit. --- .../network/message/MessageDownloadChunk.java | 41 ++++++++++++++++--- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java index ea157427..0233b9f5 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java @@ -24,6 +24,8 @@ public class MessageDownloadChunk implements IMessage, IMessageHandler { public static final FMLControlledNamespacedRegistry BLOCK_REGISTRY = GameData.getBlockRegistry(); + private static final int CELL_COUNT = Constants.SchematicChunk.WIDTH * Constants.SchematicChunk.HEIGHT + * Constants.SchematicChunk.LENGTH; public int baseX; public int baseY; @@ -31,6 +33,7 @@ public class MessageDownloadChunk implements IMessage, IMessageHandler tileEntities; public List entities; @@ -46,13 +49,22 @@ public MessageDownloadChunk(ISchematic schematic, int baseX, int baseY, int base this.tileEntities = new ArrayList<>(); this.entities = new ArrayList<>(); + int index = 0; for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { + for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++, index++) { final Block block = schematic.getBlock(baseX + x, baseY + y, baseZ + z); final int id = BLOCK_REGISTRY.getId(block); this.blocks[x][y][z] = (short) id; - this.metadata[x][y][z] = (byte) schematic.getBlockMetadata(baseX + x, baseY + y, baseZ + z); + final int metadata = schematic.getBlockMetadata(baseX + x, baseY + y, baseZ + z); + this.metadata[x][y][z] = (byte) metadata; + final byte high = (byte) (metadata >>> 8); + if (high != 0) { + if (this.highMetadata == null) { + this.highMetadata = new byte[CELL_COUNT]; + } + this.highMetadata[index] = high; + } final TileEntity tileEntity = schematic.getTileEntity(baseX + x, baseY + y, baseZ + z); if (tileEntity != null) { this.tileEntities.add(tileEntity); @@ -63,12 +75,15 @@ public MessageDownloadChunk(ISchematic schematic, int baseX, int baseY, int base } private void copyToSchematic(final ISchematic schematic) { + int index = 0; for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { - short id = this.blocks[x][y][z]; - byte meta = this.metadata[x][y][z]; - Block block = BLOCK_REGISTRY.getObjectById(id); + for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++, index++) { + final Block block = BLOCK_REGISTRY.getObjectById(this.blocks[x][y][z] & 0xffff); + int meta = this.metadata[x][y][z] & 0xff; + if (this.highMetadata != null) { + meta |= (this.highMetadata[index] & 0xff) << 8; + } schematic.setBlock(this.baseX + x, this.baseY + y, this.baseZ + z, block, meta); } @@ -105,6 +120,15 @@ public void fromBytes(ByteBuf buf) { final NBTTagCompound compound2 = ByteBufUtils.readTag(buf); this.entities = NBTHelper.readEntitiesFromCompound(compound2, this.entities); + + this.highMetadata = null; + if (buf.isReadable()) { + if (buf.readableBytes() != CELL_COUNT) { + throw new IllegalArgumentException("Invalid schematic download metadata length"); + } + this.highMetadata = new byte[CELL_COUNT]; + buf.readBytes(this.highMetadata); + } } @Override @@ -127,6 +151,11 @@ public void toBytes(ByteBuf buf) { final NBTTagCompound compound1 = NBTHelper.writeEntitiesToCompound(this.entities); ByteBufUtils.writeTag(buf, compound1); + + // Append the high bytes after the original payload, outside NBT's signed-short length limit. + if (this.highMetadata != null) { + buf.writeBytes(this.highMetadata); + } } @Override From 6efed640e26066f3093d973883e30643d4e72361 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 06/64] fix: clear stale schematic byte arrays Rewriting a compound can omit high metadata or change the ID encoding. Clear the previous optional arrays before writing. --- .../lunatrius/schematica/world/schematic/SchematicAlpha.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java index f8547372..6f455473 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java @@ -190,6 +190,9 @@ private void loadTiles(NBTTagCompound tagCompound, ISchematic schematic) { @Override public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, World backupWorld) { + tagCompound.removeTag(Names.NBT.DATA_HIGH); + tagCompound.removeTag(Names.NBT.ADD_BLOCKS); + tagCompound.removeTag(Names.NBT.ADD_BLOCKS_SCHEMATICA); if (ConfigurationHandler.useSchematicplusFormat) { NBTTagCompound tagCompoundIcon = new NBTTagCompound(); ItemStack icon = schematic.getIcon(); From 48453fff45a7a56210bc4694dc6bbbdafb7ab827 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 07/64] fix: load mixed multipart tiles safely Keep the microblock render-bounds update while a schematic tile is detached. Other multipart implementations may need an attached world. --- .../github/lunatrius/schematica/nbt/ForgeMultipart.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java b/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java index 8547fe5d..e6a0d672 100644 --- a/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java +++ b/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java @@ -32,6 +32,7 @@ public class ForgeMultipart { private static Method methodLoadRegisteredPart; private static Method methodLoad; private static Method methodOnPartChanged; + private static Class microblockPart; private static Object instanceMultipartGenerator$; private static Method methodGenerateCompositeTile; private static Method methodLoadParts; @@ -71,6 +72,7 @@ public static void init() { final Class classMicroblockClass = ReflectionHelper .getClass(classLoader, "codechicken.microblock.MicroblockClass"); + microblockPart = ReflectionHelper.getClass(classLoader, "codechicken.microblock.Microblock"); methodCreatePart = ReflectionHelper .findMethod(classMicroblockClass, null, new String[] { "create" }, boolean.class, int.class); @@ -160,7 +162,10 @@ private static TileEntity createFromNBTClient(final NBTTagCompound tileEntityCom loadParts(tileEntity, parts); for (Object part : parts) { - onPartChanged(part, part); + // Microblocks recalculate render bounds here. Other parts may require an attached world. + if (microblockPart.isInstance(part)) { + onPartChanged(part, part); + } } return tileEntity; From d7f401214abc62f303800014da5643c531d3a44e Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 08/64] fix: restore bounds after microblock probes --- .../client/compat/MicroblockSupport.java | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java index 6f6184ca..b53a2069 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.function.BiConsumer; import java.util.function.Predicate; +import java.util.function.Supplier; import net.minecraft.block.Block; import net.minecraft.client.entity.EntityClientPlayerMP; @@ -238,7 +239,10 @@ private Click find() { if (visible != null && Math.abs(visible.blockX - x) + Math.abs(visible.blockY - y) + Math.abs(visible.blockZ - z) <= (expanding ? 0 : 1)) { - final Click click = tryAim(visible.blockX, visible.blockY, visible.blockZ, visible.sideHit); + final Block block = world.getBlock(visible.blockX, visible.blockY, visible.blockZ); + final Click click = withSavedBlockBounds( + block, + () -> tryAim(visible.blockX, visible.blockY, visible.blockZ, visible.sideHit)); if (click != null) { return click; } @@ -266,6 +270,10 @@ private Click tryBlock(int bx, int by, int bz, ForgeDirection face) { if (world.isAirBlock(bx, by, bz) || !canClick.test(block)) { return null; } + return withSavedBlockBounds(block, () -> tryBlockFaces(block, bx, by, bz, face)); + } + + private Click tryBlockFaces(Block block, int bx, int by, int bz, ForgeDirection face) { if (world.getTileEntity(bx, by, bz) instanceof TileMultipart multipart) { final Iterator parts = multipart.partList() .iterator(); @@ -386,6 +394,20 @@ private Click tryAim(int bx, int by, int bz, int face) { } } + private static Click withSavedBlockBounds(Block block, Supplier action) { + final float minX = (float) block.getBlockBoundsMinX(); + final float minY = (float) block.getBlockBoundsMinY(); + final float minZ = (float) block.getBlockBoundsMinZ(); + final float maxX = (float) block.getBlockBoundsMaxX(); + final float maxY = (float) block.getBlockBoundsMaxY(); + final float maxZ = (float) block.getBlockBoundsMaxZ(); + try { + return action.get(); + } finally { + block.setBlockBounds(minX, minY, minZ, maxX, maxY, maxZ); + } + } + private static ExecutablePlacement predictPlacement(EntityClientPlayerMP player, int x, int y, int z, PlacementRequest request, MovingObjectPosition hit, boolean expanding) { final int damage = request.item.getItemDamage(); From d954f13a8a6259e9e45d3164f24646255b4f418f Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 09/64] fix: preserve ArchitectureCraft shape state --- .../compat/ArchitectureCraftSupport.java | 14 ++++-- .../renderer/RendererSchematicChunk.java | 44 ++++++++++--------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index f362e4b3..85e066ce 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -10,11 +10,11 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import gcewing.architecture.ArchitectureCraft; import gcewing.architecture.common.block.BlockShape; import gcewing.architecture.common.shape.Shape; import gcewing.architecture.common.shape.ShapeItem; import gcewing.architecture.common.shape.ShapeSymmetry; +import gcewing.architecture.common.tile.TileArchitecture; import gcewing.architecture.common.tile.TileShape; import gcewing.architecture.compat.BlockCompatUtils; import gcewing.architecture.compat.BlockPos; @@ -51,13 +51,19 @@ public static ItemStack getSecondaryItem(TileEntity tile) { public static ItemStack getItem(TileEntity tile, Block block) { if (tile instanceof TileShape shape && shape.shape != null) { - return shape.shape.kind - .newStack(shape.shape, shape.baseBlockState, 1, block == ArchitectureCraft.content.blockShapeSE); + return TileArchitecture.blockStackWithTileEntity(block, 1, shape); } return null; } public static boolean itemsMatch(ItemStack stack, ItemStack target) { + return sameShape(stack, target) && stack.getTagCompound() + .getInteger("Disconnected") + == target.getTagCompound() + .getInteger("Disconnected"); + } + + private static boolean sameShape(ItemStack stack, ItemStack target) { final NBTTagCompound tag = stack.getTagCompound(); final NBTTagCompound expected = target.getTagCompound(); return tag != null && expected != null @@ -76,7 +82,7 @@ public static boolean matches(TileEntity placed, TileEntity target, Block block) final ItemStack actualItem = getItem(actual, block); final ItemStack expectedItem = getItem(expected, block); return actualItem != null && expectedItem != null - && itemsMatch(actualItem, expectedItem) + && sameShape(actualItem, expectedItem) && sameOrientation(actual, expected); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index df639d56..85fd977e 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -22,6 +22,7 @@ import com.github.lunatrius.core.util.vector.Vector3d; import com.github.lunatrius.core.util.vector.Vector3f; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.renderer.shader.ShaderProgram; @@ -249,7 +250,6 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, IBlockAccess mcWorld = this.minecraft.theWorld; RenderBlocks renderBlocks = RendererSchematicGlobal.INSTANCE.renderBlocks; final boolean renderMicroblocks = renderPass < 2 && Mods.FORGE_MICROBLOCK; - final boolean highlightCarpenters = renderPass == 2 && Mods.CARPENTERS_BLOCKS; int x, y, z, wx, wy, wz; int sides; @@ -349,26 +349,16 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, if (ConfigurationHandler.drawLines) { RenderHelper.drawCuboidOutline(zero, size, sides, 1.0f, 0.0f, 0.0f, 0.25f); } - } else if (highlightCarpenters && CarpentersBlocksSupport.isCoverable(block) - ? !CarpentersBlocksSupport.matches( - block, - this.schematic.getTileEntity(x, y, z), - mcWorld.getTileEntity(wx, wy, wz)) - : !BlockToItemStack.matchesMetadata( - block, - mcWorld.getBlockMetadata(wx, wy, wz), - this.schematic.getBlockMetadata(x, y, z))) { - zero.set(x, y, z); - size.set(x + 1, y + 1, z + 1); - if (ConfigurationHandler.drawQuads) { - RenderHelper - .drawCuboidSurface(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); - } - if (ConfigurationHandler.drawLines) { - RenderHelper - .drawCuboidOutline(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); - } - } + } else if (!matchesBlockState(block, mcWorld, x, y, z, wx, wy, wz)) { + zero.set(x, y, z); + size.set(x + 1, y + 1, z + 1); + if (ConfigurationHandler.drawQuads) { + RenderHelper.drawCuboidSurface(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); + } + if (ConfigurationHandler.drawLines) { + RenderHelper.drawCuboidOutline(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); + } + } } } else if (!isAirBlock) { if (ConfigurationHandler.highlight && renderPass == 2) { @@ -398,6 +388,18 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, this.minecraft.gameSettings.ambientOcclusion = ambientOcclusion; } + private boolean matchesBlockState(Block block, IBlockAccess world, int x, int y, int z, int wx, int wy, int wz) { + if (Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block)) { + return CarpentersBlocksSupport + .matches(block, this.schematic.getTileEntity(x, y, z), world.getTileEntity(wx, wy, wz)); + } + return BlockToItemStack + .matchesMetadata(block, world.getBlockMetadata(wx, wy, wz), this.schematic.getBlockMetadata(x, y, z)) + && (!Mods.ARCHITECTURE_CRAFT || !ArchitectureCraftSupport.isShapeBlock(block) + || ArchitectureCraftSupport + .matches(world.getTileEntity(wx, wy, wz), this.schematic.getTileEntity(x, y, z), block)); + } + public void renderTileEntities(int renderPass) { if (renderPass != 0) { return; From 0a280cda2f4ce581526cd073a5df7b77fda51111 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 10/64] fix: allow direct placement without support --- .../printer/ArchitectureCraftPrinter.java | 17 ++++++++++++----- .../client/printer/SchematicPrinter.java | 14 +++++++++----- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java index a74a7940..c0f89464 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java @@ -6,6 +6,7 @@ import net.minecraftforge.common.util.ForgeDirection; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.handler.ConfigurationHandler; final class ArchitectureCraftPrinter { @@ -15,12 +16,18 @@ static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEn if (!interaction.canSelectItem(item)) { return false; } - for (ForgeDirection support : interaction.findSupports(x, y, z)) { + final ForgeDirection[] supports = interaction.findSupports(x, y, z); + final boolean hasSupport = supports.length > 0; + if (!hasSupport && ConfigurationHandler.placeAdjacent) { + return false; + } + for (ForgeDirection support : hasSupport ? supports : ForgeDirection.VALID_DIRECTIONS) { for (boolean sneaking : new boolean[] { true, false }) { // A standing click on the support could activate it instead of placing the shape. - final int clickedX = x + (sneaking ? support.offsetX : 0); - final int clickedY = y + (sneaking ? support.offsetY : 0); - final int clickedZ = z + (sneaking ? support.offsetZ : 0); + final boolean clickSupport = hasSupport && sneaking; + final int clickedX = x + (clickSupport ? support.offsetX : 0); + final int clickedY = y + (clickSupport ? support.offsetY : 0); + final int clickedZ = z + (clickSupport ? support.offsetZ : 0); if (!PrinterInteraction .canClickForPlacement(interaction.world.getBlock(clickedX, clickedY, clickedZ), item, sneaking)) { continue; @@ -37,7 +44,7 @@ static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEn clickedZ, support.getOpposite() .ordinal(), - sneaking ? hit : hit.addVector(-support.offsetX, -support.offsetY, -support.offsetZ))); + clickSupport ? hit : hit.addVector(-support.offsetX, -support.offsetY, -support.offsetZ))); } } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index f25f4116..310855c8 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -1,7 +1,9 @@ package com.github.lunatrius.schematica.client.printer; import net.minecraft.block.Block; +import net.minecraft.block.BlockHopper; import net.minecraft.block.BlockPistonBase; +import net.minecraft.block.BlockRotatedPillar; import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; @@ -273,15 +275,17 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, final boolean adjacent = direction != ForgeDirection.UNKNOWN; if (!adjacent) { + final boolean needsMappedSupport = data != null && data.type == PlacementData.PlacementType.BLOCK + && !data.mapping.isEmpty() + && !(block instanceof BlockRotatedPillar || block instanceof BlockHopper); if ((ConfigurationHandler.placeAdjacent && solidSides.length == 0) - || (validSides.length == 0 && data != null - && data.type == PlacementData.PlacementType.BLOCK - && !data.mapping.isEmpty()) + || (needsMappedSupport && validSides.length == 0) || !(itemStack.getItem() instanceof ItemBlock)) { return false; } - final ForgeDirection[] valid = data == null ? ForgeDirection.VALID_DIRECTIONS - : data.getValidDirections(ForgeDirection.VALID_DIRECTIONS, metadata); + final ForgeDirection[] valid = needsMappedSupport ? validSides + : data == null ? ForgeDirection.VALID_DIRECTIONS + : data.getValidDirections(ForgeDirection.VALID_DIRECTIONS, metadata); for (ForgeDirection side : valid) { // ItemSlab checks the block across the clicked face before placing into the clicked cell. if (!slab From 2c0c0c72129a3e78012892d18f89c6c8a9a1ae6e Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 11/64] fix: avoid opening protected Carpenter's safes --- .../schematica/client/compat/CarpentersBlocksSupport.java | 8 ++++++++ .../schematica/client/printer/CarpentersPrinter.java | 3 +++ 2 files changed, 11 insertions(+) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index 66a22cb4..22d35a62 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -16,6 +16,7 @@ import com.carpentersblocks.block.BlockCarpentersBlock; import com.carpentersblocks.block.BlockCarpentersGarageDoor; +import com.carpentersblocks.block.BlockCarpentersSafe; import com.carpentersblocks.block.BlockCarpentersSlope; import com.carpentersblocks.block.BlockCarpentersStairs; import com.carpentersblocks.block.BlockCoverable; @@ -23,6 +24,7 @@ import com.carpentersblocks.data.Stairs; import com.carpentersblocks.tileentity.TEBase; import com.carpentersblocks.util.BlockProperties; +import com.carpentersblocks.util.protection.PlayerPermissions; import com.carpentersblocks.util.registry.FeatureRegistry; import com.github.lunatrius.schematica.client.util.BlockToItemStack; import com.github.lunatrius.schematica.client.world.SchematicWorld; @@ -48,6 +50,12 @@ public static boolean isGarageDoor(Block block) { return block instanceof BlockCarpentersGarageDoor; } + public static boolean canConfigure(Block block, TileEntity tile, EntityPlayer player) { + // A rejected configuration click can open a safe. A remote client cannot check operator status. + return tile instanceof TEBase carpenter && (!(block instanceof BlockCarpentersSafe) + || PlayerPermissions.hasElevatedPermission(carpenter, player, true)); + } + public static boolean passesThroughMicroblockClick(Block block) { return block instanceof BlockCarpentersBlock || isStairs(block); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 5aed6830..f946ca59 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -42,6 +42,9 @@ boolean configureBlock(PrinterInteraction interaction, SchematicWorld schematic, int x, int y, int z) { final World world = interaction.world; final TileEntity placed = world.getTileEntity(x, y, z); + if (!CarpentersBlocksSupport.canConfigure(block, placed, interaction.player)) { + return false; + } final CarpentersHammerSupport.Adjustment adjustment = CarpentersHammerSupport .findAdjustment(block, schematic, target, placed); if (adjustment != null && applyHammer(interaction, adjustment, x, y, z)) { From a5f08aae9fb5cfb891969e2f087f23119b42039c Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 12/64] fix: count both halves of double slabs --- .../client/printer/SchematicPrinter.java | 16 +++++----------- .../schematica/client/util/BlockList.java | 12 +++++++++++- .../schematica/client/util/BlockToItemStack.java | 6 ++++++ 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 310855c8..0869b6f7 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -186,7 +186,7 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { && !placedBlock.isOpaqueCube()) { final ItemStack slab = BlockToItemStack.getItemStack(player, block, this.schematic, x, y, z); if (slab != null && slab.getItem() instanceof ItemSlab - && isMatchingHalfSlab(world, worldX, worldY, worldZ, slab)) { + && BlockToItemStack.matchesHalfSlab(world, worldX, worldY, worldZ, slab)) { if (interaction.selectItem(slab) && mergeSlab(interaction, worldX, worldY, worldZ, player.getHeldItem())) { this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; @@ -288,8 +288,8 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, : data.getValidDirections(ForgeDirection.VALID_DIRECTIONS, metadata); for (ForgeDirection side : valid) { // ItemSlab checks the block across the clicked face before placing into the clicked cell. - if (!slab - || !isMatchingHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack)) { + if (!slab || !BlockToItemStack + .matchesHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack)) { direction = side; break; } @@ -306,19 +306,13 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, } private boolean wouldMergeSupportingSlab(World world, int x, int y, int z, ForgeDirection support, ItemStack slab) { - if (support.offsetY == 0 || !isMatchingHalfSlab(world, x, y + support.offsetY, z, slab)) { + if (support.offsetY == 0 || !BlockToItemStack.matchesHalfSlab(world, x, y + support.offsetY, z, slab)) { return false; } final boolean top = (world.getBlockMetadata(x, y + support.offsetY, z) & 8) != 0; return top ? support == ForgeDirection.UP : support == ForgeDirection.DOWN; } - private boolean isMatchingHalfSlab(World world, int x, int y, int z, ItemStack slab) { - final Block block = world.getBlock(x, y, z); - return block == Block.getBlockFromItem(slab.getItem()) && !block.isOpaqueCube() - && (world.getBlockMetadata(x, y, z) & 7) == slab.getItemDamage(); - } - private boolean mergeSlab(PrinterInteraction interaction, int x, int y, int z, ItemStack slab) { final boolean top = (interaction.world.getBlockMetadata(x, y, z) & 8) != 0; return interaction.place( @@ -384,7 +378,7 @@ private boolean placeAgainstSupport(PrinterInteraction interaction, int x, int y boolean placed = interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); for (int i = 0; placed && i < extraClicks; i++) { placed = itemStack.getItem() instanceof ItemSlab - ? isMatchingHalfSlab(interaction.world, x, y, z, itemStack) + ? BlockToItemStack.matchesHalfSlab(interaction.world, x, y, z, itemStack) && mergeSlab(interaction, x, y, z, itemStack) : interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 0467e307..bcf6680e 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -5,10 +5,12 @@ import net.blay09.mods.cookingforblockheads.utils.DyeUtils; import net.minecraft.block.Block; +import net.minecraft.block.BlockSlab; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; +import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -74,7 +76,15 @@ public List getList(final EntityPlayer player, final Schematic .matchesMetadata(block, mcWorld.getBlockMetadata(wx, wy, wz), world.getBlockMetadata(x, y, z))) ? BlockToItemStack.getItemStack(player, mcBlock, mcWorld, wx, wy, wz) : null; - addMaterial(blockList, stack, 1, placed != null && BlockToItemStack.matches(placed, stack)); + final boolean complete = placed != null && BlockToItemStack.matches(placed, stack); + addMaterial(blockList, stack, 1, complete); + if (block instanceof BlockSlab && block.isOpaqueCube() && stack.getItem() instanceof ItemSlab) { + addMaterial( + blockList, + stack, + 1, + complete || BlockToItemStack.matchesHalfSlab(mcWorld, wx, wy, wz, stack)); + } if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { final ItemStack secondary = ArchitectureCraftSupport .getSecondaryItem(world.getTileEntity(x, y, z)); diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 3ff5159c..1b94a59d 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -80,4 +80,10 @@ public static boolean matchesMetadata(Block block, int actual, int saved) { .getName() .equals("gregtech.common.blocks.GTBlockOre") && block.damageDropped(actual) == block.damageDropped(saved)); } + + public static boolean matchesHalfSlab(World world, int x, int y, int z, ItemStack slab) { + final Block block = world.getBlock(x, y, z); + return block == Block.getBlockFromItem(slab.getItem()) && !block.isOpaqueCube() + && (world.getBlockMetadata(x, y, z) & 7) == slab.getItemDamage(); + } } From b45218e3d03c5e717b2da44ae9ee31ae17c670fb Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 13/64] fix: count one item per garage door column --- .../schematica/client/compat/CarpentersBlocksSupport.java | 4 ++++ .../github/lunatrius/schematica/client/util/BlockList.java | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index 22d35a62..93107e3e 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -50,6 +50,10 @@ public static boolean isGarageDoor(Block block) { return block instanceof BlockCarpentersGarageDoor; } + public static boolean isGarageDoorPanel(TileEntity tile) { + return tile instanceof TEBase carpenter && !GarageDoor.INSTANCE.isHost(carpenter); + } + public static boolean canConfigure(Block block, TileEntity tile, EntityPlayer player) { // A rejected configuration click can open a safe. A remote client cannot check operator status. return tile instanceof TEBase carpenter && (!(block instanceof BlockCarpentersSafe) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index bcf6680e..6dba8d5e 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -64,6 +64,10 @@ public List getList(final EntityPlayer player, final Schematic world.getTileEntity(x, y, z), block == mcBlock ? mcWorld.getTileEntity(wx, wy, wz) : null, (material, placed) -> addMaterial(blockList, material, 1, placed)); + if (CarpentersBlocksSupport.isGarageDoor(block) + && CarpentersBlocksSupport.isGarageDoorPanel(world.getTileEntity(x, y, z))) { + continue; + } } final ItemStack stack = BlockToItemStack.getItemStack(player, block, world, x, y, z); From 152ead7b5f5c4d5044813b7b0b377c2e414fb1c4 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 14/64] fix: probe the optional kitchen dye API --- .../compat/CookingForBlockheadsSupport.java | 30 +++++++++++++++++++ .../schematica/client/util/BlockList.java | 9 +++--- 2 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java new file mode 100644 index 00000000..84c9ac6b --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java @@ -0,0 +1,30 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import net.blay09.mods.cookingforblockheads.utils.DyeUtils; +import net.minecraft.item.ItemStack; + +import com.github.lunatrius.schematica.reference.Reference; + +public final class CookingForBlockheadsSupport { + + public static final boolean SUPPORTS_DYE_SUBSTITUTES = supportsDyeSubstitutes(); + + private CookingForBlockheadsSupport() {} + + public static int getDyeDamage(ItemStack stack) { + return DyeUtils.rawDyeDamageFromStack(stack); + } + + private static boolean supportsDyeSubstitutes() { + try { + final Method method = DyeUtils.class.getMethod("rawDyeDamageFromStack", ItemStack.class); + return method.getReturnType() == int.class && Modifier.isStatic(method.getModifiers()); + } catch (ReflectiveOperationException | LinkageError e) { + Reference.logger.debug("Cooking for Blockheads dye substitutes are unavailable", e); + return false; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 6dba8d5e..ccc25126 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; -import net.blay09.mods.cookingforblockheads.utils.DyeUtils; import net.minecraft.block.Block; import net.minecraft.block.BlockSlab; import net.minecraft.client.multiplayer.WorldClient; @@ -16,6 +15,7 @@ import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.CookingForBlockheadsSupport; import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.nbt.NBTHelper; @@ -142,7 +142,8 @@ public List getList(final EntityPlayer player, final Schematic } } - if (Mods.COOKING_FOR_BLOCKHEADS && !player.capabilities.isCreativeMode) { + if (Mods.COOKING_FOR_BLOCKHEADS && !player.capabilities.isCreativeMode + && CookingForBlockheadsSupport.SUPPORTS_DYE_SUBSTITUTES) { addKitchenDyeSubstitutes(blockList, player.inventory.mainInventory); } return blockList; @@ -157,13 +158,13 @@ private void addKitchenDyeSubstitutes(List materials, ItemStac int available = 0; for (ItemStack stack : inventory) { if (stack != null && !BlockToItemStack.matches(stack, dye.itemStack) - && DyeUtils.rawDyeDamageFromStack(stack) == damage) { + && CookingForBlockheadsSupport.getDyeDamage(stack) == damage) { available += stack.stackSize; } } // Reserve dyes that a different row needs as exact ingredients before counting substitutes. for (WrappedItemStack material : materials) { - if (material != dye && DyeUtils.rawDyeDamageFromStack(material.itemStack) == damage) { + if (material != dye && CookingForBlockheadsSupport.getDyeDamage(material.itemStack) == damage) { available -= Math.min(material.inventory, material.total - material.placed); } } From f8a78c53f965c56c313563c4b8e16d8130ef9262 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:26:38 +0100 Subject: [PATCH 15/64] fix: verify dye on both fridge halves --- .../lunatrius/schematica/client/util/BlockList.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index ccc25126..2d337a88 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -112,8 +112,11 @@ public List getList(final EntityPlayer player, final Schematic && world.getBlock(x, y - 1, z) == block && kitchenColor(world.getTileEntity(x, y - 1, z)) == color; if (color > 0 && color <= 15 && !pairedFridge) { - final boolean dyed = block == mcBlock - && kitchenColor(mcWorld.getTileEntity(wx, wy, wz)) == color; + final boolean hasUpperFridge = "fridge".equals(name.name) && !world.isRenderingLayer + && world.getBlock(x, y + 1, z) == block + && kitchenColor(world.getTileEntity(x, y + 1, z)) == color; + final boolean dyed = hasKitchenColor(mcWorld, block, wx, wy, wz, color) + && (!hasUpperFridge || hasKitchenColor(mcWorld, block, wx, wy + 1, wz, color)); final WrappedItemStack dye = addMaterial( blockList, new ItemStack(Items.dye, 1, 15 - color), @@ -178,6 +181,10 @@ private int kitchenColor(TileEntity tile) { .getByte("Color"); } + private boolean hasKitchenColor(WorldClient world, Block block, int x, int y, int z, int color) { + return world.getBlock(x, y, z) == block && kitchenColor(world.getTileEntity(x, y, z)) == color; + } + private WrappedItemStack addMaterial(List blockList, ItemStack stack, int count, boolean placed) { final WrappedItemStack entry = findOrCreateWrappedItemStackFor(blockList, stack); if (placed) { From 10b63ccef3ac2b683159d2e0b720715ca54f2905 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:10:57 +0100 Subject: [PATCH 16/64] fix: guard automatic Carpenter edits --- .../compat/CarpentersBlocksSupport.java | 8 +++---- .../compat/CarpentersHammerSupport.java | 24 +++++++++++-------- .../client/printer/CarpentersPrinter.java | 6 +++-- 3 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index 93107e3e..b93ce7cb 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -16,7 +16,6 @@ import com.carpentersblocks.block.BlockCarpentersBlock; import com.carpentersblocks.block.BlockCarpentersGarageDoor; -import com.carpentersblocks.block.BlockCarpentersSafe; import com.carpentersblocks.block.BlockCarpentersSlope; import com.carpentersblocks.block.BlockCarpentersStairs; import com.carpentersblocks.block.BlockCoverable; @@ -54,10 +53,9 @@ public static boolean isGarageDoorPanel(TileEntity tile) { return tile instanceof TEBase carpenter && !GarageDoor.INSTANCE.isHost(carpenter); } - public static boolean canConfigure(Block block, TileEntity tile, EntityPlayer player) { - // A rejected configuration click can open a safe. A remote client cannot check operator status. - return tile instanceof TEBase carpenter && (!(block instanceof BlockCarpentersSafe) - || PlayerPermissions.hasElevatedPermission(carpenter, player, true)); + public static boolean canConfigure(TileEntity tile, EntityPlayer player) { + // A rejected edit can fall through to normal activation. Remote clients only know the synced owner. + return tile instanceof TEBase carpenter && PlayerPermissions.hasElevatedPermission(carpenter, player, true); } public static boolean passesThroughMicroblockClick(Block block) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java index cc00e132..9e9c2fa7 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -52,6 +52,7 @@ import com.carpentersblocks.data.Torch; import com.carpentersblocks.tileentity.TEBase; import com.carpentersblocks.util.handler.DesignHandler; +import com.carpentersblocks.util.registry.FeatureRegistry; import com.carpentersblocks.util.registry.ItemRegistry; import com.github.lunatrius.schematica.client.world.SchematicWorld; @@ -214,18 +215,21 @@ private static Collection affectedBlocks(Block block, TEBase actual, TEB .ordinal() < 2 || door.getDirection(actual) == ForgeDirection.UNKNOWN || !door.isVisible(actual)) { return Collections.emptyList(); } - final Collection pieces = door.getBlocks(actual, block); - final int type = door.getType(actual); - if (click == Click.RIGHT && door.isOpen(actual)) { - // An open door activates the bottommost panel, so every possible source must agree on the current - // style. - for (TEBase piece : pieces) { - if (door.getType(piece) != type) { - return Collections.emptyList(); - } + TEBase activation = actual; + if (click != Click.LEFT && door.isOpen(actual)) { + // Carpenter's Blocks redirects both right-click paths to the bottom of an open door. + activation = door.getBottommost(world, actual.xCoord, actual.yCoord, actual.zCoord); + if (activation == null || door.getDirection(activation) != door.getDirection(actual) + || (click == Click.RIGHT ? door.getType(activation) != door.getType(actual) + : door.getRigidity(activation) != door.getRigidity(actual))) { + return Collections.emptyList(); } } - return pieces; + final Collection pieces = door.getBlocks(activation, block); + // A capped client search can omit panels the server will change. + return pieces.size() > FeatureRegistry.multiBlockSizeLimit || !pieces.contains(actual) + ? Collections.emptyList() + : pieces; } if (block instanceof BlockCarpentersBed) { final TEBase other = Bed.getOppositeTE(actual); diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index f946ca59..6942fe8b 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -42,12 +42,14 @@ boolean configureBlock(PrinterInteraction interaction, SchematicWorld schematic, int x, int y, int z) { final World world = interaction.world; final TileEntity placed = world.getTileEntity(x, y, z); - if (!CarpentersBlocksSupport.canConfigure(block, placed, interaction.player)) { + if (!CarpentersBlocksSupport.canConfigure(placed, interaction.player)) { return false; } final CarpentersHammerSupport.Adjustment adjustment = CarpentersHammerSupport .findAdjustment(block, schematic, target, placed); - if (adjustment != null && applyHammer(interaction, adjustment, x, y, z)) { + if (adjustment != null && adjustment.affected.stream() + .allMatch(piece -> CarpentersBlocksSupport.canConfigure(piece, interaction.player)) + && applyHammer(interaction, adjustment, x, y, z)) { final PendingClick click = new PendingClick(world, this.currentPass, () -> adjustment.isConfirmed(world)); for (TileEntity piece : adjustment.affected) { this.pendingClicks.put(new ChunkPosition(piece.xCoord, piece.yCoord, piece.zCoord), click); From 4f01f87fbd4312e9e1fde4221984b956cff4b039 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:10:57 +0100 Subject: [PATCH 17/64] fix: match garage door hosts --- .../schematica/client/compat/CarpentersBlocksSupport.java | 7 ++++--- .../github/lunatrius/schematica/client/util/BlockList.java | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index b93ce7cb..754ac834 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -49,8 +49,8 @@ public static boolean isGarageDoor(Block block) { return block instanceof BlockCarpentersGarageDoor; } - public static boolean isGarageDoorPanel(TileEntity tile) { - return tile instanceof TEBase carpenter && !GarageDoor.INSTANCE.isHost(carpenter); + public static boolean isGarageDoorHost(TileEntity tile) { + return tile instanceof TEBase carpenter && GarageDoor.INSTANCE.isHost(carpenter); } public static boolean canConfigure(TileEntity tile, EntityPlayer player) { @@ -132,7 +132,8 @@ public static boolean matches(Block block, TileEntity target, TileEntity placed) private static boolean matchesShape(Block block, TEBase expected, TEBase actual) { if (isGarageDoor(block)) { - return GarageDoor.INSTANCE.getDirection(actual) == GarageDoor.INSTANCE.getDirection(expected); + return GarageDoor.INSTANCE.getDirection(actual) == GarageDoor.INSTANCE.getDirection(expected) + && GarageDoor.INSTANCE.isHost(actual) == GarageDoor.INSTANCE.isHost(expected); } return !(block instanceof BlockCarpentersBlock || block instanceof BlockCarpentersSlope || isStairs(block)) || actual.getData() == expected.getData(); diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 2d337a88..619eb21c 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -59,13 +59,13 @@ public List getList(final EntityPlayer player, final Schematic } final Block mcBlock = mcWorld.getBlock(wx, wy, wz); final boolean carpenter = Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block); + final boolean garageDoor = carpenter && CarpentersBlocksSupport.isGarageDoor(block); if (carpenter) { CarpentersBlocksSupport.addMaterials( world.getTileEntity(x, y, z), block == mcBlock ? mcWorld.getTileEntity(wx, wy, wz) : null, (material, placed) -> addMaterial(blockList, material, 1, placed)); - if (CarpentersBlocksSupport.isGarageDoor(block) - && CarpentersBlocksSupport.isGarageDoorPanel(world.getTileEntity(x, y, z))) { + if (garageDoor && !CarpentersBlocksSupport.isGarageDoorHost(world.getTileEntity(x, y, z))) { continue; } } @@ -80,7 +80,8 @@ public List getList(final EntityPlayer player, final Schematic .matchesMetadata(block, mcWorld.getBlockMetadata(wx, wy, wz), world.getBlockMetadata(x, y, z))) ? BlockToItemStack.getItemStack(player, mcBlock, mcWorld, wx, wy, wz) : null; - final boolean complete = placed != null && BlockToItemStack.matches(placed, stack); + final boolean complete = placed != null && BlockToItemStack.matches(placed, stack) + && (!garageDoor || CarpentersBlocksSupport.isGarageDoorHost(mcWorld.getTileEntity(wx, wy, wz))); addMaterial(blockList, stack, 1, complete); if (block instanceof BlockSlab && block.isOpaqueCube() && stack.getItem() instanceof ItemSlab) { addMaterial( From 9238d45bd064e336b55a1ad21468049e72068b78 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:10:57 +0100 Subject: [PATCH 18/64] fix: remap extended Carpenter item IDs --- .../schematica/nbt/CarpentersBlocksNBT.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java b/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java index 8ccfb86a..989e4829 100644 --- a/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java +++ b/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java @@ -1,6 +1,7 @@ package com.github.lunatrius.schematica.nbt; import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.Constants; @@ -21,10 +22,19 @@ public static void remapAttributeItems(NBTTagCompound tile) { final NBTTagCompound attribute = attributes.getCompoundTagAt(i); final String name = attribute.getString(ITEM_REGISTRY_NAME); if (!name.isEmpty()) { - // Carpenter's Blocks uses the registry name only when the numeric ID fails to resolve. final Item item = GameData.getItemRegistry() .getObject(name); - attribute.setShort("id", (short) (item == null ? 0 : Item.getIdFromItem(item))); + // EndlessIDs can prefer idExt over the vanilla id. Copy the current stack's ID encoding only. + attribute.removeTag("idExt"); + if (item == null) { + attribute.setShort("id", (short) 0); + continue; + } + final NBTTagCompound stack = new ItemStack(item).writeToNBT(new NBTTagCompound()); + attribute.setTag("id", stack.getTag("id")); + if (stack.hasKey("idExt")) { + attribute.setTag("idExt", stack.getTag("idExt")); + } } } } From 88deaafaafebee3db179b2a9e441200a66e14213 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:10:57 +0100 Subject: [PATCH 19/64] fix: mirror angled roof ridges --- .../schematica/client/compat/ArchitectureCraftSupport.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index 85e066ce..ec2aad24 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -168,7 +168,7 @@ public static void transform(TileEntity tile, ForgeDirection axis, boolean mirro shape.setOffsetX(-shape.getOffsetX()); // Placement symmetry differs from the mirrored geometry of these models. mirrorTurn = switch (shape.shape) { - case DoricTriglyphCorner -> 1; + case AngledRoofRidge, DoricTriglyphCorner -> 1; case IonicCapital, DoricCapital, CorinthianCapital -> 2; default -> shape.shape.symmetry == ShapeSymmetry.Unilateral ? 1 : 0; }; From eab3aacefbf1edcef6a6bb7b025f9280cb28c0f1 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:10:57 +0100 Subject: [PATCH 20/64] fix: compare ArchitectureCraft preview state --- .../client/compat/ArchitectureCraftSupport.java | 14 ++++++++++++++ .../client/renderer/RendererSchematicChunk.java | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index ec2aad24..36fb5529 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -18,6 +18,7 @@ import gcewing.architecture.common.tile.TileShape; import gcewing.architecture.compat.BlockCompatUtils; import gcewing.architecture.compat.BlockPos; +import gcewing.architecture.compat.IBlockState; import gcewing.architecture.compat.Trans3; import gcewing.architecture.compat.Vector3; import gcewing.architecture.util.Utils; @@ -86,6 +87,19 @@ && sameShape(actualItem, expectedItem) && sameOrientation(actual, expected); } + public static boolean matchesPreview(TileEntity placed, TileEntity target, Block block) { + return placed instanceof TileShape actual && target instanceof TileShape expected + && matches(actual, expected, block) + && actual.disabledConnections == expected.disabledConnections + && sameMaterial(actual.secondaryBlockState, expected.secondaryBlockState); + } + + private static boolean sameMaterial(IBlockState actual, IBlockState expected) { + return actual == expected || (actual != null && expected != null + && actual.getBlock() == expected.getBlock() + && BlockCompatUtils.getMetaFromBlockState(actual) == BlockCompatUtils.getMetaFromBlockState(expected)); + } + private static boolean sameOrientation(TileShape actual, TileShape expected) { return actual.side == expected.side && actual.getOffsetX() == expected.getOffsetX() && (actual.turn == expected.turn || expected.shape.symmetry == ShapeSymmetry.Quadrilateral); diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index 85fd977e..cc1b31a7 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -397,7 +397,7 @@ private boolean matchesBlockState(Block block, IBlockAccess world, int x, int y, .matchesMetadata(block, world.getBlockMetadata(wx, wy, wz), this.schematic.getBlockMetadata(x, y, z)) && (!Mods.ARCHITECTURE_CRAFT || !ArchitectureCraftSupport.isShapeBlock(block) || ArchitectureCraftSupport - .matches(world.getTileEntity(wx, wy, wz), this.schematic.getTileEntity(x, y, z), block)); + .matchesPreview(world.getTileEntity(wx, wy, wz), this.schematic.getTileEntity(x, y, z), block)); } public void renderTileEntities(int renderPass) { From fe0634852f31fac65ae4eb9983b88ae22160e9ac Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:10:57 +0100 Subject: [PATCH 21/64] fix: restore bounds after microblock rays --- .../client/compat/MicroblockSupport.java | 79 ++++++++++++++++--- src/main/resources/META-INF/schematica_at.cfg | 6 ++ 2 files changed, 74 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java index b53a2069..a886b5f4 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -11,6 +11,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; @@ -233,8 +234,9 @@ private PlacementSearch(EntityClientPlayerMP player, int x, int y, int z, List

action) { - final float minX = (float) block.getBlockBoundsMinX(); - final float minY = (float) block.getBlockBoundsMinY(); - final float minZ = (float) block.getBlockBoundsMinZ(); - final float maxX = (float) block.getBlockBoundsMaxX(); - final float maxY = (float) block.getBlockBoundsMaxY(); - final float maxZ = (float) block.getBlockBoundsMaxZ(); + private static MovingObjectPosition traceWithoutChangingBounds(World world, Vec3 origin, Vec3 end) { + final Vec3 start = origin.addVector(0, 0, 0); + final int endX = MathHelper.floor_double(end.xCoord); + final int endY = MathHelper.floor_double(end.yCoord); + final int endZ = MathHelper.floor_double(end.zCoord); + int x = MathHelper.floor_double(start.xCoord); + int y = MathHelper.floor_double(start.yCoord); + int z = MathHelper.floor_double(start.zCoord); + + // Match vanilla's voxel order, including its Z/Y/X tie order at grid boundaries. + for (int step = 0; step <= 201; step++) { + final Block block = world.getBlock(x, y, z); + if (block.canCollideCheck(world.getBlockMetadata(x, y, z), false)) { + final int bx = x; + final int by = y; + final int bz = z; + final MovingObjectPosition hit = withSavedBlockBounds( + block, + () -> block.collisionRayTrace(world, bx, by, bz, start, end)); + if (hit != null) { + return hit; + } + } + if (x == endX && y == endY && z == endZ) { + return null; + } + + final double boundaryX = x + (endX > x ? 1 : 0); + final double boundaryY = y + (endY > y ? 1 : 0); + final double boundaryZ = z + (endZ > z ? 1 : 0); + final double dx = end.xCoord - start.xCoord; + final double dy = end.yCoord - start.yCoord; + final double dz = end.zCoord - start.zCoord; + final double tx = x == endX ? Double.POSITIVE_INFINITY : (boundaryX - start.xCoord) / dx; + final double ty = y == endY ? Double.POSITIVE_INFINITY : (boundaryY - start.yCoord) / dy; + final double tz = z == endZ ? Double.POSITIVE_INFINITY : (boundaryZ - start.zCoord) / dz; + final boolean crossX = tx < ty && tx < tz; + final boolean crossY = !crossX && ty < tz; + final boolean crossZ = !crossX && !crossY; + final double t = crossX ? tx : crossY ? ty : tz; + start.xCoord = crossX ? boundaryX : start.xCoord + dx * t; + start.yCoord = crossY ? boundaryY : start.yCoord + dy * t; + start.zCoord = crossZ ? boundaryZ : start.zCoord + dz * t; + x = MathHelper.floor_double(start.xCoord) - (crossX && dx < 0 ? 1 : 0); + y = MathHelper.floor_double(start.yCoord) - (crossY && dy < 0 ? 1 : 0); + z = MathHelper.floor_double(start.zCoord) - (crossZ && dz < 0 ? 1 : 0); + } + return null; + } + + private static T withSavedBlockBounds(Block block, Supplier action) { + final double minX = block.minX; + final double minY = block.minY; + final double minZ = block.minZ; + final double maxX = block.maxX; + final double maxY = block.maxY; + final double maxZ = block.maxZ; try { return action.get(); } finally { - block.setBlockBounds(minX, minY, minZ, maxX, maxY, maxZ); + block.minX = minX; + block.minY = minY; + block.minZ = minZ; + block.maxX = maxX; + block.maxY = maxY; + block.maxZ = maxZ; } } diff --git a/src/main/resources/META-INF/schematica_at.cfg b/src/main/resources/META-INF/schematica_at.cfg index b612f28d..f013db93 100644 --- a/src/main/resources/META-INF/schematica_at.cfg +++ b/src/main/resources/META-INF/schematica_at.cfg @@ -1,4 +1,10 @@ # Schematica public net.minecraft.nbt.NBTTagCompound func_150298_a(Ljava/lang/String;Lnet/minecraft/nbt/NBTBase;Ljava/io/DataOutput;)V # writeNamedTag +public net.minecraft.block.Block field_149759_B # minX +public net.minecraft.block.Block field_149760_C # minY +public net.minecraft.block.Block field_149754_D # minZ +public net.minecraft.block.Block field_149755_E # maxX +public net.minecraft.block.Block field_149756_F # maxY +public net.minecraft.block.Block field_149757_G # maxZ public net.minecraftforge.client.ForgeHooksClient worldRenderPass public net.minecraft.client.multiplayer.PlayerControllerMP func_78750_j()V # syncCurrentPlayItem From df97d3133d8ac82ad2678f89e8d0adcd51cac39c Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:10:57 +0100 Subject: [PATCH 22/64] fix: copy pick stacks before normalization --- .../lunatrius/schematica/client/util/BlockToItemStack.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 1b94a59d..ff8b157d 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -34,12 +34,15 @@ public static ItemStack getItemStack(final EntityPlayer player, final Block bloc player); if (itemStack != null && itemStack.getItem() != null) { // Ignore facing damage when a non-subtyped item places the same metadata as its default stack. - if (itemStack.getItem() instanceof ItemBlock && !itemStack.getHasSubtypes() + if (itemStack.getItemDamage() != 0 && itemStack.getItem() instanceof ItemBlock + && !itemStack.getHasSubtypes() && itemStack.getItem() .getMetadata(itemStack.getItemDamage()) == itemStack.getItem() .getMetadata(0)) { - itemStack.setItemDamage(0); + final ItemStack normalized = itemStack.copy(); + normalized.setItemDamage(0); + return normalized; } return itemStack; } From e796271ab0894c61e22a66a53372e2b5f52a4675 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:40:25 +0100 Subject: [PATCH 23/64] fix: compare Carpenter torch and ladder directions --- .../schematica/client/compat/CarpentersHammerSupport.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java index 9e9c2fa7..df0eefa6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -108,6 +108,12 @@ public final class CarpentersHammerSupport { forwardCycle(PRESSURE_PLATE::getTriggerEntity, 4), toggle(PRESSURE_PLATE::getPolarity, Click.LEFT)), new BlockSettings(BlockCarpentersButton.class, toggle(BUTTON::getPolarity, Click.LEFT)), + if (block instanceof BlockCarpentersTorch && TORCH.getDirection(actual) != TORCH.getDirection(expected)) { + return false; + } + if (block instanceof BlockCarpentersLadder && LADDER.getDirection(actual) != LADDER.getDirection(expected)) { + return false; + } new BlockSettings(BlockCarpentersLever.class, toggle(LEVER::getPolarity, Click.LEFT)), new BlockSettings( BlockCarpentersSafe.class, From 7fe763b583ec2c2931b8e6394e9c2247c03f38e4 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:40:25 +0100 Subject: [PATCH 24/64] fix: validate garage door columns across layers --- .../schematica/client/compat/CarpentersBlocksSupport.java | 4 ++-- .../schematica/client/compat/CarpentersHammerSupport.java | 3 ++- .../lunatrius/schematica/client/world/SchematicWorld.java | 4 ++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index 754ac834..785623d5 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -160,7 +160,7 @@ public static Float findGarageDoorYaw(Block block, SchematicWorld schematic, Wor int worldY = wy - 1; while (worldY >= 0 && world.getBlock(wx, worldY, wz) .isReplaceable(world, wx, worldY, wz)) { - if (schematic.getBlock(x, panelY, z) != block + if (schematic.getBlockIncludingHiddenLayers(x, panelY, z) != block || !(schematic.getTileEntity(x, panelY, z) instanceof TEBase panel) || door.isHost(panel) || door.getDirection(panel) != direction) { @@ -169,7 +169,7 @@ public static Float findGarageDoorYaw(Block block, SchematicWorld schematic, Wor panelY--; worldY--; } - if (schematic.getBlock(x, panelY, z) == block && (world.getBlock(wx, worldY, wz) != block + if (schematic.getBlockIncludingHiddenLayers(x, panelY, z) == block && (world.getBlock(wx, worldY, wz) != block || !(world.getTileEntity(wx, worldY, wz) instanceof TEBase panel) || door.getDirection(panel) != direction)) { return null; diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java index df0eefa6..e8d04c76 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -205,7 +205,8 @@ && validIndex(actual.getData(), Slab.SLAB_Z_POS + 1)) { final int x = piece.xCoord - schematic.position.x; final int y = piece.yCoord - schematic.position.y; final int z = piece.zCoord - schematic.position.z; - if (schematic.getBlock(x, y, z) != block || !(schematic.getTileEntity(x, y, z) instanceof TEBase saved) + if (schematic.getBlockIncludingHiddenLayers(x, y, z) != block + || !(schematic.getTileEntity(x, y, z) instanceof TEBase saved) || settings.findClick(expected, saved) != null) { return null; } diff --git a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index 12eea038..35ec099f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -86,6 +86,10 @@ public Block getBlock(int x, int y, int z) { return Blocks.air; } + return getBlockIncludingHiddenLayers(x, y, z); + } + + public Block getBlockIncludingHiddenLayers(int x, int y, int z) { return this.schematic.getBlock(x, y, z); } From 7d66800a466be886d2767385fdc30829aa69389a Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:40:25 +0100 Subject: [PATCH 25/64] fix: mirror Double Roof Tile cladding --- .../schematica/client/compat/ArchitectureCraftSupport.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index 36fb5529..e694a6f0 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -183,7 +183,7 @@ public static void transform(TileEntity tile, ForgeDirection axis, boolean mirro // Placement symmetry differs from the mirrored geometry of these models. mirrorTurn = switch (shape.shape) { case AngledRoofRidge, DoricTriglyphCorner -> 1; - case IonicCapital, DoricCapital, CorinthianCapital -> 2; + case DoubleRoofTile, IonicCapital, DoricCapital, CorinthianCapital -> 2; default -> shape.shape.symmetry == ShapeSymmetry.Unilateral ? 1 : 0; }; } From 730e6248a0fe208c832b7f6caeac1345398c980c Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:47:31 +0100 Subject: [PATCH 26/64] fix: match ArchitectureCraft stock by shape material --- .../compat/ArchitectureCraftSupport.java | 10 ++++++---- .../client/printer/PrinterInteraction.java | 18 ++++++++++++++++-- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index e694a6f0..1eef7e9b 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -58,10 +58,12 @@ public static ItemStack getItem(TileEntity tile, Block block) { } public static boolean itemsMatch(ItemStack stack, ItemStack target) { - return sameShape(stack, target) && stack.getTagCompound() - .getInteger("Disconnected") - == target.getTagCompound() - .getInteger("Disconnected"); + return sameShape(stack, target); + } + + public static int getDisabledConnections(ItemStack stack) { + final NBTTagCompound tag = stack.getTagCompound(); + return tag == null ? 0 : tag.getInteger("Disconnected"); } private static boolean sameShape(ItemStack stack, ItemStack target) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java index 9a21c6fc..8f08cc06 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -23,6 +23,7 @@ import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fluids.IFluidBlock; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; import com.github.lunatrius.schematica.client.util.BlockToItemStack; import com.github.lunatrius.schematica.handler.ConfigurationHandler; @@ -80,13 +81,26 @@ && swapIntoHotbar(slot) } private int findItemSlot(ItemStack item) { + final boolean shape = Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(item); + final int connections = shape ? ArchitectureCraftSupport.getDisabledConnections(item) : 0; + final boolean canSwap = !ConfigurationHandler.swapSlotsQueue.isEmpty() + && this.player.openContainer == this.player.inventoryContainer; + int fallback = -1; for (int i = 0; i < this.inventory.mainInventory.length; i++) { final ItemStack stack = this.inventory.mainInventory[i]; if (stack != null && stack.stackSize > 0 && BlockToItemStack.matches(stack, item)) { - return i; + if (!shape || (ArchitectureCraftSupport.getDisabledConnections(stack) == connections + && (i < Constants.Inventory.Size.HOTBAR || canSwap))) { + return i; + } + if (fallback < 0) { + fallback = i; + } } } - return -1; + // Creative can make an exact stack. Survival can use the sawbench shape and adjust its connections by hand. + return shape && this.controller.isInCreativeMode() && !ConfigurationHandler.swapSlotsQueue.isEmpty() ? -1 + : fallback; } private boolean swapIntoHotbar(int sourceSlot) { From c31aaf247ed043841890154cbc172138f103789f Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:53:01 +0100 Subject: [PATCH 27/64] fix: place Carpenter shapes without mining clicks --- .../compat/CarpentersBlocksSupport.java | 85 ++++++- .../compat/CarpentersHammerSupport.java | 128 ++++------ .../client/printer/CarpentersPrinter.java | 220 ++++++++++++++---- .../client/printer/PrinterInteraction.java | 20 -- 4 files changed, 300 insertions(+), 153 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index 785623d5..ab7253a8 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -16,11 +16,16 @@ import com.carpentersblocks.block.BlockCarpentersBlock; import com.carpentersblocks.block.BlockCarpentersGarageDoor; +import com.carpentersblocks.block.BlockCarpentersLadder; import com.carpentersblocks.block.BlockCarpentersSlope; import com.carpentersblocks.block.BlockCarpentersStairs; +import com.carpentersblocks.block.BlockCarpentersTorch; import com.carpentersblocks.block.BlockCoverable; import com.carpentersblocks.data.GarageDoor; +import com.carpentersblocks.data.Ladder; +import com.carpentersblocks.data.Slope; import com.carpentersblocks.data.Stairs; +import com.carpentersblocks.data.Torch; import com.carpentersblocks.tileentity.TEBase; import com.carpentersblocks.util.BlockProperties; import com.carpentersblocks.util.protection.PlayerPermissions; @@ -34,6 +39,8 @@ public final class CarpentersBlocksSupport { private static final int BASE = 6; private static final byte[][] SURFACE_ATTRIBUTES = { TEBase.ATTR_COVER, TEBase.ATTR_DYE, TEBase.ATTR_OVERLAY }; private static final int[] TOP_BOTTOM_FACING = { 0, 3, 1, 2 }; + private static final Ladder LADDER = new Ladder(); + private static final Torch TORCH = new Torch(); private CarpentersBlocksSupport() {} @@ -53,6 +60,77 @@ public static boolean isGarageDoorHost(TileEntity tile) { return tile instanceof TEBase carpenter && GarageDoor.INSTANCE.isHost(carpenter); } + public static ForgeDirection getAttachmentDirection(Block block, TileEntity tile) { + if (block instanceof BlockCarpentersLadder) { + return tile instanceof TEBase carpenter ? LADDER.getDirection(carpenter) : ForgeDirection.UNKNOWN; + } + if (block instanceof BlockCarpentersTorch) { + return tile instanceof TEBase carpenter ? TORCH.getDirection(carpenter) : ForgeDirection.UNKNOWN; + } + return null; + } + + public static boolean isFreestandingLadder(Block block, ForgeDirection direction) { + return block instanceof BlockCarpentersLadder && direction.offsetY != 0; + } + + public static Float getWedgeYaw(Block block, TileEntity tile, ItemStack item) { + if (!(block instanceof BlockCarpentersSlope) || !(tile instanceof TEBase slope) + || item.getItemDamage() != BlockCarpentersSlope.META_WEDGE) { + return null; + } + return switch (slope.getData()) { + case Slope.ID_WEDGE_NEG_N, Slope.ID_WEDGE_POS_N -> 0f; + case Slope.ID_WEDGE_NEG_E, Slope.ID_WEDGE_POS_E -> 90f; + case Slope.ID_WEDGE_NEG_S, Slope.ID_WEDGE_POS_S -> 180f; + case Slope.ID_WEDGE_NEG_W, Slope.ID_WEDGE_POS_W -> 270f; + default -> null; + }; + } + + public static ForgeDirection getWedgeFace(TileEntity tile) { + return ((TEBase) tile).getData() <= Slope.ID_WEDGE_NEG_E ? ForgeDirection.DOWN : ForgeDirection.UP; + } + + public static ForgeDirection getWedgeWallFace(TileEntity tile) { + return ForgeDirection.getOrientation(2 + (((TEBase) tile).getData() & 3)); + } + + public static boolean canReshapeOppositeWedge(TileEntity tile) { + final int expected = ((TEBase) tile).getData(); + return CarpentersHammerSupport.canReshapeSlope(expected, expected ^ 12); + } + + public static boolean isSideWedge(Block block, TileEntity tile, ItemStack item) { + return block instanceof BlockCarpentersSlope && tile instanceof TEBase slope + && item.getItemDamage() == BlockCarpentersSlope.META_WEDGE + && slope.getData() >= Slope.ID_WEDGE_SE + && slope.getData() <= Slope.ID_WEDGE_SW; + } + + public static double getSideWedgeHit(TileEntity tile, ForgeDirection face) { + final int expected = ((TEBase) tile).getData(); + final int near = switch (face) { + case NORTH -> Slope.ID_WEDGE_NW; + case SOUTH -> Slope.ID_WEDGE_SE; + case WEST -> Slope.ID_WEDGE_SW; + case EAST -> Slope.ID_WEDGE_NE; + default -> -1; + }; + final int far = switch (face) { + case NORTH -> Slope.ID_WEDGE_NE; + case SOUTH -> Slope.ID_WEDGE_SW; + case WEST -> Slope.ID_WEDGE_NW; + case EAST -> Slope.ID_WEDGE_SE; + default -> -1; + }; + if (expected != near && expected != far) { + return 0; + } + final boolean reversed = face == ForgeDirection.NORTH || face == ForgeDirection.EAST; + return (expected == near) != reversed ? 0.125 : 0.875; + } + public static boolean canConfigure(TileEntity tile, EntityPlayer player) { // A rejected edit can fall through to normal activation. Remote clients only know the synced owner. return tile instanceof TEBase carpenter && PlayerPermissions.hasElevatedPermission(carpenter, player, true); @@ -178,15 +256,16 @@ public static Float findGarageDoorYaw(Block block, SchematicWorld schematic, Wor } public static boolean matchesStairPlacement(TileEntity tile, Block block, World world, int x, int y, int z, - int side, float hitX, float hitY, float hitZ, EntityPlayer player) { + int side, float hitX, float hitY, float hitZ, float yaw, boolean allowReshape) { if (!(tile instanceof TEBase expected)) { return false; } final int metadata = block.onBlockPlaced(world, x, y, z, side, hitX, hitY, hitZ, 0); - final int facing = MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; + final int facing = MathHelper.floor_double(yaw * 4.0F / 360.0F + 0.5D) & 3; final int data = metadata < 12 ? metadata : (metadata == 12 ? Stairs.ID_NORMAL_NEG_N : Stairs.ID_NORMAL_POS_N) + TOP_BOTTOM_FACING[facing]; - return data == expected.getData(); + return data == expected.getData() + || (allowReshape && CarpentersHammerSupport.canReshapeStair(expected.getData(), data)); } public static Interaction findAttachment(Block block, TileEntity target, TileEntity placed, EntityPlayer player, diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java index e8d04c76..b8a75c6b 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -1,6 +1,5 @@ package com.github.lunatrius.schematica.client.compat; -import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -58,7 +57,6 @@ public final class CarpentersHammerSupport { - private static final Click[] SHAPE_CLICKS = { Click.LEFT, Click.RIGHT }; private static final Slab SLAB = new Slab(); private static final Ladder LADDER = new Ladder(); private static final Torch TORCH = new Torch(); @@ -67,62 +65,55 @@ public final class CarpentersHammerSupport { private static final Button BUTTON = new Button(); private static final Lever LEVER = new Lever(); - // BlockCarpentersSlope's left click uses the UP row of Slope.ROTATION_Y. - private static final int[] SLOPE_ROTATIONS = { 3, 2, 0, 1, 7, 6, 4, 5, 11, 10, 8, 9, 15, 14, 12, 13, 19, 18, 16, 17, - 23, 22, 20, 21, 27, 26, 24, 25, 31, 30, 28, 29, 35, 34, 32, 33, 39, 38, 36, 37, 43, 42, 40, 41, 44, 45, 49, 48, - 46, 47, 51, 50, 55, 54, 52, 53, 59, 58, 56, 57, 60, 64, 63, 61, 62 }; - private static final BlockSettings NO_SETTINGS = new BlockSettings(Block.class); // Settings are ordered by the sequence in which the hammer should adjust them. private static final BlockSettings[] BLOCK_SETTINGS = { new BlockSettings( BlockCarpentersGarageDoor.class, - shortestCycle(GarageDoor.INSTANCE::getType, BlockCarpentersGarageDoor.type.length), + cycle(GarageDoor.INSTANCE::getType, BlockCarpentersGarageDoor.type.length), toggle(GarageDoor.INSTANCE::getRigidity, Click.SNEAK_RIGHT)), new BlockSettings( BlockCarpentersBarrier.class, new Setting<>(Barrier::getType, CarpentersHammerSupport::fenceClick), - toggle(Barrier::getPost, Click.LEFT)), + toggle(Barrier::getPost, Click.MANUAL)), new BlockSettings(BlockCarpentersGate.class, new Setting<>(Gate::getType, CarpentersHammerSupport::fenceClick)), new BlockSettings( BlockCarpentersDoor.class, - forwardCycle(Hinge::getType, BlockCarpentersDoor.type.length), - toggle(Hinge::getHinge, Click.LEFT)), + cycle(Hinge::getType, BlockCarpentersDoor.type.length), + toggle(Hinge::getHinge, Click.MANUAL)), new BlockSettings( BlockCarpentersHatch.class, - forwardCycle(Hatch::getType, Hatch.TYPE_PANEL + 1), + cycle(Hatch::getType, Hatch.TYPE_PANEL + 1), toggle(Hatch::getRigidity, Click.SNEAK_RIGHT), - toggle(Hatch::getDir, Click.LEFT)), - new BlockSettings( - BlockCarpentersLadder.class, - shortestCycle(LADDER::getType, BlockCarpentersLadder.type.length)), - new BlockSettings(BlockCarpentersTorch.class, forwardCycle(TORCH::getType, BlockCarpentersTorch.type.length)), + toggle(Hatch::getDir, Click.MANUAL)), + new BlockSettings(BlockCarpentersLadder.class, cycle(LADDER::getType, BlockCarpentersLadder.type.length)), + new BlockSettings(BlockCarpentersTorch.class, cycle(TORCH::getType, BlockCarpentersTorch.type.length)), new BlockSettings(BlockCarpentersBed.class, decoration("bed")), new BlockSettings(BlockCarpentersFlowerPot.class, decoration("flowerpot")), new BlockSettings( BlockCarpentersDaylightSensor.class, - forwardCycle(SENSOR::getSensitivity, 3), - toggle(SENSOR::getPolarity, Click.LEFT)), + cycle(SENSOR::getSensitivity, 3), + toggle(SENSOR::getPolarity, Click.MANUAL)), new BlockSettings( BlockCarpentersPressurePlate.class, - forwardCycle(PRESSURE_PLATE::getTriggerEntity, 4), - toggle(PRESSURE_PLATE::getPolarity, Click.LEFT)), - new BlockSettings(BlockCarpentersButton.class, toggle(BUTTON::getPolarity, Click.LEFT)), - if (block instanceof BlockCarpentersTorch && TORCH.getDirection(actual) != TORCH.getDirection(expected)) { - return false; - } - if (block instanceof BlockCarpentersLadder && LADDER.getDirection(actual) != LADDER.getDirection(expected)) { - return false; - } - new BlockSettings(BlockCarpentersLever.class, toggle(LEVER::getPolarity, Click.LEFT)), + cycle(PRESSURE_PLATE::getTriggerEntity, 4), + toggle(PRESSURE_PLATE::getPolarity, Click.MANUAL)), + new BlockSettings(BlockCarpentersButton.class, toggle(BUTTON::getPolarity, Click.MANUAL)), + new BlockSettings(BlockCarpentersLever.class, toggle(LEVER::getPolarity, Click.MANUAL)), new BlockSettings( BlockCarpentersSafe.class, toggle(Safe::isLocked, Click.SNEAK_RIGHT), - forwardCycle(Safe::getAutoPerm, 4)) }; + cycle(Safe::getAutoPerm, 4)) }; private CarpentersHammerSupport() {} static boolean matchesSettings(Block block, TEBase expected, TEBase actual) { + if (block instanceof BlockCarpentersTorch && TORCH.getDirection(actual) != TORCH.getDirection(expected)) { + return false; + } + if (block instanceof BlockCarpentersLadder && LADDER.getDirection(actual) != LADDER.getDirection(expected)) { + return false; + } return settingsFor(block).findClick(expected, actual) == null; } @@ -171,29 +162,11 @@ && validIndex(actual.getData(), Slab.SLAB_Z_POS + 1)) { expected.getData(), actual.getData(), Stairs.stairsList.length, - id -> (id & ~3) | ((id + 1) & 3), CarpentersHammerSupport::nextStairShape); } else if (block instanceof BlockCarpentersSlope) { - click = shapeClick( - expected.getData(), - actual.getData(), - SLOPE_ROTATIONS.length, - id -> SLOPE_ROTATIONS[id], - id -> { - final Slope slope = Slope.getSlopeById(id); - return slope.slopeType.getNextSlopeType(slope).slopeID; - }); - } - if (click == null) { - return null; + click = canReshapeSlope(expected.getData(), actual.getData()) ? Click.RIGHT : null; } - if (click == Click.LEFT && block instanceof BlockCarpentersHatch - && !block.canPlaceBlockOnSide( - actual.getWorldObj(), - actual.xCoord, - actual.yCoord, - actual.zCoord, - Hatch.getDir(expected) + 2)) { + if (click == null || click == Click.MANUAL) { return null; } @@ -223,7 +196,7 @@ private static Collection affectedBlocks(Block block, TEBase actual, TEB return Collections.emptyList(); } TEBase activation = actual; - if (click != Click.LEFT && door.isOpen(actual)) { + if (door.isOpen(actual)) { // Carpenter's Blocks redirects both right-click paths to the bottom of an open door. activation = door.getBottommost(world, actual.xCoord, actual.yCoord, actual.zCoord); if (activation == null || door.getDirection(activation) != door.getDirection(actual) @@ -270,14 +243,10 @@ private static Setting toggle(Function read, Click click) { return new Setting<>(read, (expected, actual) -> expected.equals(actual) ? null : click); } - private static Setting forwardCycle(Function read, int variants) { + private static Setting cycle(Function read, int variants) { return new Setting<>(read, (expected, actual) -> cycle(expected, actual, variants)); } - private static Setting shortestCycle(Function read, int variants) { - return new Setting<>(read, (expected, actual) -> bidirectionalCycle(expected, actual, variants)); - } - private static Setting decoration(String designType) { return new Setting<>(TEBase::getDesign, (expected, actual) -> { if (expected.equals(actual)) { @@ -302,14 +271,6 @@ private static Click cycle(int expected, int actual, int variants) { Click.RIGHT); } - private static Click bidirectionalCycle(int expected, int actual, int variants) { - if (cycle(expected, actual, variants) == null) { - return null; - } - final int forward = Math.floorMod(expected - actual, variants); - return forward < variants - forward ? Click.LEFT : Click.RIGHT; - } - private static Click toggle(boolean different, Click click) { return different ? click : null; } @@ -328,26 +289,29 @@ private static int nextStairShape(int id) { }; } - private static Click shapeClick(int expected, int actual, int variants, IntUnaryOperator turn, - IntUnaryOperator reshape) { + static boolean canReshapeStair(int expected, int actual) { + return shapeClick(expected, actual, Stairs.stairsList.length, CarpentersHammerSupport::nextStairShape) != null; + } + + static boolean canReshapeSlope(int expected, int actual) { + return shapeClick(expected, actual, Slope.ID_PRISM_WEDGE_POS_E + 1, id -> { + final Slope slope = Slope.getSlopeById(id); + return slope.slopeType.getNextSlopeType(slope).slopeID; + }) != null; + } + + private static Click shapeClick(int expected, int actual, int variants, IntUnaryOperator reshape) { if (expected == actual || !validIndex(expected, variants) || !validIndex(actual, variants)) { return null; } - final Click[] firstClicks = new Click[variants]; - final ArrayDeque remaining = new ArrayDeque<>(); - remaining.add(actual); - while (!remaining.isEmpty()) { - final int current = remaining.remove(); - for (Click click : SHAPE_CLICKS) { - final int next = (click == Click.LEFT ? turn : reshape).applyAsInt(current); - if (next == actual || firstClicks[next] != null) { - continue; - } - firstClicks[next] = current == actual ? click : firstClicks[current]; - if (next == expected) { - return firstClicks[next]; - } - remaining.add(next); + int next = actual; + for (int step = 0; step < variants; step++) { + next = reshape.applyAsInt(next); + if (next == expected) { + return Click.RIGHT; + } + if (next == actual) { + break; } } return null; @@ -418,7 +382,7 @@ private boolean matches(TEBase tile, Object[] values) { } public enum Click { - LEFT, + MANUAL, RIGHT, SNEAK_RIGHT } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 6942fe8b..28d241b2 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -78,19 +78,13 @@ private static boolean applyHammer(PrinterInteraction interaction, CarpentersHam || !CarpentersHammerSupport.canUseHammer(interaction.player, interaction.world)) { return false; } - if (adjustment.click != CarpentersHammerSupport.Click.LEFT) { - return useFace( - interaction, - x, - y, - z, - adjustment.face, - adjustment.click == CarpentersHammerSupport.Click.SNEAK_RIGHT); - } - return interaction.withSneaking( - false, - () -> CarpentersBlocksSupport.isCoverable(interaction.world.getBlock(x, y, z)) - && interaction.tapWithoutMining(x, y, z, adjustment.face)); + return useFace( + interaction, + x, + y, + z, + adjustment.face, + adjustment.click == CarpentersHammerSupport.Click.SNEAK_RIGHT); } private static boolean useFace(PrinterInteraction interaction, int x, int y, int z, int side, boolean sneaking) { @@ -115,14 +109,118 @@ static boolean place(PrinterInteraction interaction, SchematicWorld schematic, B .findGarageDoorYaw(block, schematic, interaction.world, localX, localY, localZ); return yaw != null && placeGarageDoor(interaction, x, y, z, block, item, yaw); } + final TileEntity tile = schematic.getTileEntity(localX, localY, localZ); if (CarpentersBlocksSupport.isStairs(block)) { - final TileEntity tile = schematic.getTileEntity(localX, localY, localZ); - return placeStairs(interaction, x, y, z, block, tile, item) - || (findHammer(interaction) != null && placeNormally.getAsBoolean()); + return placeStairs(interaction, x, y, z, block, tile, item); + } + final ForgeDirection face = CarpentersBlocksSupport.getAttachmentDirection(block, tile); + if (face != null) { + return placeSidedBlock(interaction, x, y, z, block, item, face); + } + if (CarpentersBlocksSupport.isSideWedge(block, tile, item)) { + return placeSideWedge(interaction, x, y, z, block, item, tile); + } + final Float wedgeYaw = CarpentersBlocksSupport.getWedgeYaw(block, tile, item); + if (wedgeYaw != null) { + final ForgeDirection verticalFace = CarpentersBlocksSupport.getWedgeFace(tile); + final ForgeDirection wallFace = CarpentersBlocksSupport.getWedgeWallFace(tile); + if (canUseSupport(interaction, x, y, z, verticalFace, item)) { + return placeFromFace(interaction, x, y, z, block, item, verticalFace, true, 0.5, 0.5, wedgeYaw); + } + if (canUseSupport(interaction, x, y, z, wallFace, item)) { + final double hitY = verticalFace == ForgeDirection.UP ? 0.25 : 0.75; + return placeFromFace(interaction, x, y, z, block, item, wallFace, true, 0.5, hitY, wedgeYaw); + } + if (!ConfigurationHandler.placeAdjacent) { + return placeFromFace(interaction, x, y, z, block, item, verticalFace, false, 0.5, 0.5, wedgeYaw); + } + final ForgeDirection opposite = verticalFace.getOpposite(); + return canUseSupport(interaction, x, y, z, opposite, item) + && CarpentersBlocksSupport.canReshapeOppositeWedge(tile) + && findHammer(interaction) != null + && placeFromFace(interaction, x, y, z, block, item, opposite, true, 0.5, 0.5, wedgeYaw); } return placeNormally.getAsBoolean(); } + private static boolean placeSideWedge(PrinterInteraction interaction, int x, int y, int z, Block block, + ItemStack item, TileEntity tile) { + final float yaw = interaction.player.rotationYaw; + ForgeDirection directFace = ForgeDirection.UNKNOWN; + for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) { + final double across = CarpentersBlocksSupport.getSideWedgeHit(tile, face); + if (across == 0) { + continue; + } + if (canUseSupport(interaction, x, y, z, face, item)) { + return placeFromFace(interaction, x, y, z, block, item, face, true, across, 0.5, yaw); + } + directFace = face; + } + return !ConfigurationHandler.placeAdjacent && directFace != ForgeDirection.UNKNOWN + && placeFromFace( + interaction, + x, + y, + z, + block, + item, + directFace, + false, + CarpentersBlocksSupport.getSideWedgeHit(tile, directFace), + 0.5, + yaw); + } + + private static boolean placeSidedBlock(PrinterInteraction interaction, int x, int y, int z, Block block, + ItemStack item, ForgeDirection face) { + if (face == ForgeDirection.UNKNOWN) { + return false; + } + if (CarpentersBlocksSupport.isFreestandingLadder(block, face)) { + final float yaw = face == ForgeDirection.UP ? 90 : 0; + for (ForgeDirection vertical : new ForgeDirection[] { ForgeDirection.UP, ForgeDirection.DOWN }) { + if (block.canPlaceBlockOnSide(interaction.world, x, y, z, vertical.ordinal()) + && canUseSupport(interaction, x, y, z, vertical, item)) { + return placeFromFace(interaction, x, y, z, block, item, vertical, true, 0.5, 0.5, yaw); + } + } + return false; + } + return block.canPlaceBlockOnSide(interaction.world, x, y, z, face.ordinal()) + && canUseSupport(interaction, x, y, z, face, item) + && placeFromFace(interaction, x, y, z, block, item, face, true, 0.5, 0.5, interaction.player.rotationYaw); + } + + private static boolean canUseSupport(PrinterInteraction interaction, int x, int y, int z, ForgeDirection face, + ItemStack item) { + final int sx = x - face.offsetX; + final int sy = y - face.offsetY; + final int sz = z - face.offsetZ; + final Block support = interaction.world.getBlock(sx, sy, sz); + return !support.isAir(interaction.world, sx, sy, sz) && !support.isReplaceable(interaction.world, sx, sy, sz) + && PrinterInteraction.canClickForPlacement(support, item, true); + } + + private static boolean placeFromFace(PrinterInteraction interaction, int x, int y, int z, Block block, + ItemStack item, ForgeDirection face, boolean adjacent, double across, double hitY, float yaw) { + if (PrinterInteraction.isBlacklisted(block, item) || !interaction.selectItem(item)) { + return false; + } + final int sx = adjacent ? x - face.offsetX : x; + final int sy = adjacent ? y - face.offsetY : y; + final int sz = adjacent ? z - face.offsetZ : z; + final Vec3 hit = Vec3.createVectorHelper( + sx + (face.offsetX == 0 ? across : (1 + face.offsetX) * 0.5), + sy + hitY + face.offsetY * 0.5, + sz + (face.offsetZ == 0 ? across : (1 + face.offsetZ) * 0.5)); + final BooleanSupplier click = () -> interaction.withSneaking( + true, + () -> interaction.place(interaction.player.getHeldItem(), sx, sy, sz, face.ordinal(), hit)); + return yaw == interaction.player.rotationYaw ? click.getAsBoolean() + : interaction.withLook(yaw, interaction.player.rotationPitch, click); + } + private static ItemStack findHammer(PrinterInteraction interaction) { return CarpentersHammerSupport .findHammer(interaction.player.inventory.mainInventory, interaction::canSelectItem); @@ -157,45 +255,71 @@ private static boolean placeStairs(PrinterInteraction interaction, int x, int y, if (!hasSupport && ConfigurationHandler.placeAdjacent) { return false; } - for (ForgeDirection support : hasSupport ? supports : ForgeDirection.VALID_DIRECTIONS) { - final ForgeDirection face = support.getOpposite(); - final int clickedX = hasSupport ? x + support.offsetX : x; - final int clickedY = hasSupport ? y + support.offsetY : y; - final int clickedZ = hasSupport ? z + support.offsetZ : z; - for (float across : STAIR_HIT_OFFSETS) { - for (float height : STAIR_HIT_OFFSETS) { - final float hitX = face.offsetX == 0 ? across : (1 + face.offsetX) * 0.5f; - final float hitY = face.offsetY == 0 ? height : (1 + face.offsetY) * 0.5f; - final float hitZ = face.offsetZ == 0 ? across : (1 + face.offsetZ) * 0.5f; - if (CarpentersBlocksSupport.matchesStairPlacement( - tile, - block, - interaction.world, - x, - y, - z, - face.ordinal(), - hitX, - hitY, - hitZ, - interaction.player)) { - final Vec3 hit = Vec3.createVectorHelper(clickedX + hitX, clickedY + hitY, clickedZ + hitZ); - return interaction.withSneaking( - true, - () -> interaction.selectItem(item) && interaction.place( - interaction.player.getHeldItem(), - clickedX, - clickedY, - clickedZ, - face.ordinal(), - hit)); + final float originalYaw = interaction.player.rotationYaw; + final float pitch = interaction.player.rotationPitch; + final float[] yaws = { originalYaw, 0, 90, 180, 270 }; + for (boolean allowReshape : new boolean[] { false, true }) { + if (allowReshape && findHammer(interaction) == null) { + return false; + } + for (float yaw : yaws) { + for (ForgeDirection support : hasSupport ? supports : ForgeDirection.VALID_DIRECTIONS) { + final ForgeDirection face = support.getOpposite(); + final int clickedX = hasSupport ? x + support.offsetX : x; + final int clickedY = hasSupport ? y + support.offsetY : y; + final int clickedZ = hasSupport ? z + support.offsetZ : z; + if (!PrinterInteraction + .canClickForPlacement(interaction.world.getBlock(clickedX, clickedY, clickedZ), item, true)) { + continue; } + final Vec3 hit = findStairHit(interaction.world, x, y, z, block, tile, yaw, allowReshape, face); + if (hit == null) { + continue; + } + final BooleanSupplier click = () -> interaction.withSneaking( + true, + () -> interaction.place( + interaction.player.getHeldItem(), + clickedX, + clickedY, + clickedZ, + face.ordinal(), + hit.addVector(clickedX, clickedY, clickedZ))); + return interaction.selectItem(item) + && (yaw == originalYaw ? click.getAsBoolean() : interaction.withLook(yaw, pitch, click)); } } } return false; } + private static Vec3 findStairHit(World world, int x, int y, int z, Block block, TileEntity tile, float yaw, + boolean allowReshape, ForgeDirection face) { + for (float across : STAIR_HIT_OFFSETS) { + for (float height : STAIR_HIT_OFFSETS) { + final float hitX = face.offsetX == 0 ? across : (1 + face.offsetX) * 0.5f; + final float hitY = face.offsetY == 0 ? height : (1 + face.offsetY) * 0.5f; + final float hitZ = face.offsetZ == 0 ? across : (1 + face.offsetZ) * 0.5f; + if (CarpentersBlocksSupport.matchesStairPlacement( + tile, + block, + world, + x, + y, + z, + face.ordinal(), + hitX, + hitY, + hitZ, + yaw, + allowReshape)) { + return Vec3.createVectorHelper(hitX, hitY, hitZ); + } + } + } + return null; + } + private static final class PendingClick { private final World world; diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java index 8f08cc06..547a3e93 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -13,7 +13,6 @@ import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.C03PacketPlayer.C05PacketPlayerLook; -import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C0BPacketEntityAction; import net.minecraft.util.Vec3; import net.minecraft.world.World; @@ -168,25 +167,6 @@ boolean useBlock(ItemStack held, int x, int y, int z, int side, Vec3 hit) { return success; } - boolean tapWithoutMining(int x, int y, int z, int side) { - final ItemStack held = this.player.getHeldItem(); - final Block block = this.world.getBlock(x, y, z); - if (!isStillHolding(held) || block.getPlayerRelativeBlockHardness(this.player, this.world, x, y, z) >= 0) { - return false; - } - this.controller.syncCurrentPlayItem(); - if (ForgeEventFactory.onPlayerInteract(this.player, Action.LEFT_CLICK_BLOCK, x, y, z, side, this.world) - .isCanceled() || held != this.player.getHeldItem() - || this.world.getBlock(x, y, z) != block) { - return false; - } - // Send the initial hit and cancel mining so the mod can handle the tool without client-side block removal. - this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(0, x, y, z, side)); - this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(1, x, y, z, side)); - this.player.swingItem(); - return true; - } - private boolean isStillHolding(ItemStack item) { return item != null && item.stackSize > 0 && item == this.player.getHeldItem(); } From e87b6e4966d9fc80bc6bba885bb76e5b5691cbe8 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:53:01 +0100 Subject: [PATCH 28/64] fix: rotate capitals through server hammer clicks --- .../compat/ArchitectureCraftSupport.java | 34 ++++++++++++-- .../printer/ArchitectureCraftPrinter.java | 36 ++++++++++++++- .../client/printer/PrinterInteraction.java | 46 +++++++++++++++---- .../client/printer/SchematicPrinter.java | 9 ++++ 4 files changed, 112 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index 1eef7e9b..055b9f4c 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -10,6 +10,7 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import gcewing.architecture.ArchitectureCraft; import gcewing.architecture.common.block.BlockShape; import gcewing.architecture.common.shape.Shape; import gcewing.architecture.common.shape.ShapeItem; @@ -104,11 +105,37 @@ private static boolean sameMaterial(IBlockState actual, IBlockState expected) { private static boolean sameOrientation(TileShape actual, TileShape expected) { return actual.side == expected.side && actual.getOffsetX() == expected.getOffsetX() - && (actual.turn == expected.turn || expected.shape.symmetry == ShapeSymmetry.Quadrilateral); + && (actual.turn == expected.turn + || (expected.shape.symmetry == ShapeSymmetry.Quadrilateral && !requiresCapitalTurn(expected.shape))); + } + + private static boolean requiresCapitalTurn(Shape shape) { + return shape == Shape.DoricCapital || shape == Shape.CorinthianCapital; + } + + public static boolean isTurnableCapital(TileEntity tile) { + return tile instanceof TileShape shape && requiresCapitalTurn(shape.shape) && shape.getOffsetX() == 0; + } + + public static ItemStack getHammer() { + return new ItemStack(ArchitectureCraft.content.itemHammer); + } + + public static boolean needsHammerTurn(TileEntity placed, TileEntity target) { + return placed instanceof TileShape actual && target instanceof TileShape expected + && canHammerTurn(actual, expected) + && sameMaterial(actual.baseBlockState, expected.baseBlockState); + } + + private static boolean canHammerTurn(TileShape actual, TileShape expected) { + return isTurnableCapital(expected) && actual.shape == expected.shape + && actual.side == expected.side + && actual.getOffsetX() == 0 + && actual.turn != expected.turn; } public static Vec3 findHit(EntityClientPlayerMP player, World world, TileEntity target, ItemStack stack, int x, - int y, int z, ForgeDirection support, boolean sneaking) { + int y, int z, ForgeDirection support, boolean sneaking, boolean allowHammerTurn) { if (!(target instanceof TileShape expected) || expected.shape == null) { return null; } @@ -146,7 +173,8 @@ public static Vec3 findHit(EntityClientPlayerMP player, World world, TileEntity neighborTile, EnumFacing.values()[face.ordinal()], relative); - if (sameOrientation(candidate, expected)) { + if (sameOrientation(candidate, expected) + || (allowHammerTurn && canHammerTurn(candidate, expected))) { return Vec3.createVectorHelper(neighbor.x + hitX, neighbor.y + hitY, neighbor.z + hitZ); } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java index c0f89464..49ae6737 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java @@ -21,6 +21,29 @@ static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEn if (!hasSupport && ConfigurationHandler.placeAdjacent) { return false; } + if (placeAgainstSupports(interaction, x, y, z, tile, item, supports, false)) { + return true; + } + return ArchitectureCraftSupport.isTurnableCapital(tile) + && interaction.canSelectItem(ArchitectureCraftSupport.getHammer()) + && placeAgainstSupports(interaction, x, y, z, tile, item, supports, true); + } + + static boolean rotateCapital(PrinterInteraction interaction, int x, int y, int z) { + return interaction.selectItem(ArchitectureCraftSupport.getHammer()) && interaction.withSneaking( + false, + () -> interaction.useBlockOnServer( + interaction.player.getHeldItem(), + x, + y, + z, + ForgeDirection.UP.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 1, z + 0.5))); + } + + private static boolean placeAgainstSupports(PrinterInteraction interaction, int x, int y, int z, TileEntity tile, + ItemStack item, ForgeDirection[] supports, boolean allowHammerTurn) { + final boolean hasSupport = supports.length > 0; for (ForgeDirection support : hasSupport ? supports : ForgeDirection.VALID_DIRECTIONS) { for (boolean sneaking : new boolean[] { true, false }) { // A standing click on the support could activate it instead of placing the shape. @@ -32,8 +55,17 @@ static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEn .canClickForPlacement(interaction.world.getBlock(clickedX, clickedY, clickedZ), item, sneaking)) { continue; } - final Vec3 hit = ArchitectureCraftSupport - .findHit(interaction.player, interaction.world, tile, item, x, y, z, support, sneaking); + final Vec3 hit = ArchitectureCraftSupport.findHit( + interaction.player, + interaction.world, + tile, + item, + x, + y, + z, + support, + sneaking, + allowHammerTurn); if (hit != null) { return interaction.selectItem(item) && interaction.withSneaking( sneaking, diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java index 547a3e93..20607bcc 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -13,11 +13,13 @@ import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.C03PacketPlayer.C05PacketPlayerLook; +import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.network.play.client.C0BPacketEntityAction; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fluids.IFluidBlock; @@ -30,6 +32,8 @@ import com.github.lunatrius.schematica.reference.Constants; import com.github.lunatrius.schematica.reference.Mods; +import cpw.mods.fml.common.eventhandler.Event.Result; + final class PrinterInteraction { final World world; @@ -47,7 +51,8 @@ final class PrinterInteraction { boolean canSelectItem(ItemStack item) { final int slot = findItemSlot(item); return (slot >= 0 && slot < Constants.Inventory.Size.HOTBAR) - || (!ConfigurationHandler.swapSlotsQueue.isEmpty() && (slot >= 0 || this.controller.isInCreativeMode())); + || (!ConfigurationHandler.swapSlotsQueue.isEmpty() && (this.controller.isInCreativeMode() + || (slot >= 0 && this.player.openContainer == this.player.inventoryContainer))); } boolean selectItem(ItemStack item) { @@ -151,13 +156,7 @@ boolean place(ItemStack held, int x, int y, int z, int side, Vec3 hit) { } boolean useBlock(ItemStack held, int x, int y, int z, int side, Vec3 hit) { - if (!isStillHolding(held)) { - return false; - } - // Interaction listeners can send packets before PlayerControllerMP handles the vanilla click. - this.controller.syncCurrentPlayItem(); - if (ForgeEventFactory.onPlayerInteract(this.player, Action.RIGHT_CLICK_BLOCK, x, y, z, side, this.world) - .isCanceled() || !isStillHolding(held)) { + if (prepareBlockUse(held, x, y, z, side) == null) { return false; } final boolean success = this.controller.onPlayerRightClick(this.player, this.world, held, x, y, z, side, hit); @@ -167,6 +166,37 @@ boolean useBlock(ItemStack held, int x, int y, int z, int side, Vec3 hit) { return success; } + boolean useBlockOnServer(ItemStack held, int x, int y, int z, int side, Vec3 hit) { + final PlayerInteractEvent event = prepareBlockUse(held, x, y, z, side); + if (event == null || event.useItem == Result.DENY) { + return false; + } + // The hammer changes tile orientation locally even when the server subsequently denies the click. + this.player.sendQueue.addToSendQueue( + new C08PacketPlayerBlockPlacement( + x, + y, + z, + side, + held, + (float) (hit.xCoord - x), + (float) (hit.yCoord - y), + (float) (hit.zCoord - z))); + this.player.swingItem(); + return true; + } + + private PlayerInteractEvent prepareBlockUse(ItemStack held, int x, int y, int z, int side) { + if (!isStillHolding(held)) { + return null; + } + // Interaction listeners can send packets before PlayerControllerMP handles the vanilla click. + this.controller.syncCurrentPlayItem(); + final PlayerInteractEvent event = ForgeEventFactory + .onPlayerInteract(this.player, Action.RIGHT_CLICK_BLOCK, x, y, z, side, this.world); + return event.isCanceled() || !isStillHolding(held) ? null : event; + } + private boolean isStillHolding(ItemStack item) { return item != null && item.stackSize > 0 && item == this.player.getHeldItem(); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 0869b6f7..11594c19 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -175,6 +175,15 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { final boolean architectureShape = Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block); final TileEntity architectureTile = architectureShape ? this.schematic.getTileEntity(x, y, z) : null; + if (architectureShape && block == placedBlock + && ArchitectureCraftSupport + .needsHammerTurn(world.getTileEntity(worldX, worldY, worldZ), architectureTile)) { + if (ArchitectureCraftPrinter.rotateCapital(interaction, worldX, worldY, worldZ)) { + this.retryDelay[x][y][z] = (byte) Math.max(20, ConfigurationHandler.timeout); + return !ConfigurationHandler.placeInstantly; + } + return false; + } if (block == placedBlock && BlockToItemStack.matchesMetadata(block, placedMetadata, metadata) && (!architectureShape || ArchitectureCraftSupport .matches(world.getTileEntity(worldX, worldY, worldZ), architectureTile, block))) { From b7d7e20f544a024a972832c56d6738e500070eaf Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:53:01 +0100 Subject: [PATCH 29/64] fix: match and merge painted EnderIO slabs --- dependencies.gradle | 2 ++ .../client/compat/EnderIOSlabSupport.java | 36 +++++++++++++++++++ .../client/printer/SchematicPrinter.java | 4 ++- .../renderer/RendererSchematicChunk.java | 1 + .../schematica/client/util/BlockList.java | 3 +- .../client/util/BlockToItemStack.java | 15 ++++++++ .../lunatrius/schematica/reference/Mods.java | 1 + 7 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java diff --git a/dependencies.gradle b/dependencies.gradle index 96977d96..439405b3 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -8,6 +8,8 @@ dependencies { compileOnly('com.github.GTNewHorizons:ArchitectureCraft:1.12.19:dev') { transitive = false } compileOnly('com.github.GTNewHorizons:CarpentersBlocks:3.7.3-GTNH:dev') { transitive = false } compileOnly('com.github.GTNewHorizons:CookingForBlockheads:1.4.14-GTNH:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:EnderIO:2.10.49:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:EnderCore:0.5.15:dev') { transitive = false } compileOnly('com.github.GTNewHorizons:Postea:1.2.7:dev') { transitive = false } // Optional mods and their dependencies for the compatibility test client. diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java new file mode 100644 index 00000000..7ab14e9a --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java @@ -0,0 +1,36 @@ +package com.github.lunatrius.schematica.client.compat; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +import crazypants.enderio.machine.painter.BlockPaintedSlab; +import crazypants.enderio.machine.painter.PainterUtil; +import crazypants.enderio.machine.painter.TileEntityPaintedBlock; + +public final class EnderIOSlabSupport { + + private EnderIOSlabSupport() {} + + public static boolean isPaintedSlab(Block block) { + return block instanceof BlockPaintedSlab; + } + + public static ItemStack getItem(TileEntity tile) { + if (tile instanceof TileEntityPaintedBlock painted) { + return BlockPaintedSlab + .createItemStackForSourceBlock(painted.getSourceBlock(), painted.getSourceBlockMetadata()); + } + return null; + } + + public static boolean itemsMatch(ItemStack actual, ItemStack expected) { + return PainterUtil.isMetadataEquivelent(actual, expected); + } + + public static boolean matchesPaint(TileEntity actual, TileEntity expected) { + return actual instanceof TileEntityPaintedBlock placed && expected instanceof TileEntityPaintedBlock saved + && placed.getSourceBlock() == saved.getSourceBlock() + && placed.getSourceBlockMetadata() == saved.getSourceBlockMetadata(); + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 11594c19..155a46c6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -185,6 +185,7 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { return false; } if (block == placedBlock && BlockToItemStack.matchesMetadata(block, placedMetadata, metadata) + && BlockToItemStack.matchesPaint(block, world, worldX, worldY, worldZ, this.schematic, x, y, z) && (!architectureShape || ArchitectureCraftSupport .matches(world.getTileEntity(worldX, worldY, worldZ), architectureTile, block))) { return false; @@ -195,7 +196,8 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { && !placedBlock.isOpaqueCube()) { final ItemStack slab = BlockToItemStack.getItemStack(player, block, this.schematic, x, y, z); if (slab != null && slab.getItem() instanceof ItemSlab - && BlockToItemStack.matchesHalfSlab(world, worldX, worldY, worldZ, slab)) { + && BlockToItemStack.matchesHalfSlab(world, worldX, worldY, worldZ, slab) + && BlockToItemStack.matchesPaint(block, world, worldX, worldY, worldZ, this.schematic, x, y, z)) { if (interaction.selectItem(slab) && mergeSlab(interaction, worldX, worldY, worldZ, player.getHeldItem())) { this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index cc1b31a7..b323377a 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -395,6 +395,7 @@ private boolean matchesBlockState(Block block, IBlockAccess world, int x, int y, } return BlockToItemStack .matchesMetadata(block, world.getBlockMetadata(wx, wy, wz), this.schematic.getBlockMetadata(x, y, z)) + && BlockToItemStack.matchesPaint(block, world, wx, wy, wz, this.schematic, x, y, z) && (!Mods.ARCHITECTURE_CRAFT || !ArchitectureCraftSupport.isShapeBlock(block) || ArchitectureCraftSupport .matchesPreview(world.getTileEntity(wx, wy, wz), this.schematic.getTileEntity(x, y, z), block)); diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 619eb21c..fd5af39e 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -88,7 +88,8 @@ public List getList(final EntityPlayer player, final Schematic blockList, stack, 1, - complete || BlockToItemStack.matchesHalfSlab(mcWorld, wx, wy, wz, stack)); + complete || (BlockToItemStack.matchesHalfSlab(mcWorld, wx, wy, wz, stack) + && BlockToItemStack.matchesPaint(block, mcWorld, wx, wy, wz, world, x, y, z))); } if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { final ItemStack secondary = ArchitectureCraftSupport diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index ff8b157d..811359ae 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -7,9 +7,11 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; +import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.EnderIOSlabSupport; import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; @@ -19,6 +21,9 @@ public class BlockToItemStack { public static ItemStack getItemStack(final EntityPlayer player, final Block block, final World world, final int x, final int y, final int z) { try { + if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(block)) { + return EnderIOSlabSupport.getItem(world.getTileEntity(x, y, z)); + } if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { final ItemStack shape = ArchitectureCraftSupport.getItem(world.getTileEntity(x, y, z), block); if (shape != null) { @@ -63,6 +68,9 @@ public static boolean matches(ItemStack stack, ItemStack target) { if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(target)) { return ArchitectureCraftSupport.itemsMatch(stack, target); } + if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(Block.getBlockFromItem(target.getItem()))) { + return EnderIOSlabSupport.itemsMatch(stack, target); + } return ItemStack.areItemStackTagsEqual(stack, target) || (hasOnlyCosmeticTags(stack) && hasOnlyCosmeticTags(target)); } @@ -84,6 +92,13 @@ public static boolean matchesMetadata(Block block, int actual, int saved) { .equals("gregtech.common.blocks.GTBlockOre") && block.damageDropped(actual) == block.damageDropped(saved)); } + public static boolean matchesPaint(Block block, IBlockAccess world, int x, int y, int z, IBlockAccess schematic, + int localX, int localY, int localZ) { + return !Mods.ENDER_IO || !EnderIOSlabSupport.isPaintedSlab(block) + || EnderIOSlabSupport + .matchesPaint(world.getTileEntity(x, y, z), schematic.getTileEntity(localX, localY, localZ)); + } + public static boolean matchesHalfSlab(World world, int x, int y, int z, ItemStack slab) { final Block block = world.getBlock(x, y, z); return block == Block.getBlockFromItem(slab.getItem()) && !block.isOpaqueCube() diff --git a/src/main/java/com/github/lunatrius/schematica/reference/Mods.java b/src/main/java/com/github/lunatrius/schematica/reference/Mods.java index b4167ae2..9753e6f8 100644 --- a/src/main/java/com/github/lunatrius/schematica/reference/Mods.java +++ b/src/main/java/com/github/lunatrius/schematica/reference/Mods.java @@ -10,6 +10,7 @@ public final class Mods { public static final boolean ARCHITECTURE_CRAFT = Loader.isModLoaded("ArchitectureCraft"); public static final boolean CARPENTERS_BLOCKS = Loader.isModLoaded("CarpentersBlocks"); public static final boolean COOKING_FOR_BLOCKHEADS = Loader.isModLoaded(COOKING_FOR_BLOCKHEADS_ID); + public static final boolean ENDER_IO = Loader.isModLoaded("EnderIO"); public static final boolean FORGE_MICROBLOCK = Loader.isModLoaded("ForgeMicroblock"); public static final boolean FORGE_MULTIPART = Loader.isModLoaded("ForgeMultipart"); public static final boolean GTNH = Loader.isModLoaded("dreamcraft"); From d9c000389b1dd852e48e15e547620c17bdc16a65 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:53:01 +0100 Subject: [PATCH 30/64] fix: choose the correct half for slab placement --- .../schematica/client/printer/SchematicPrinter.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 155a46c6..0e13d3c2 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -273,9 +273,10 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, final ForgeDirection[] solidSides = interaction.findSupports(x, y, z); final ForgeDirection[] validSides = data == null ? solidSides : data.getValidDirections(solidSides, metadata); final boolean slab = block instanceof BlockSlab && itemStack.getItem() instanceof ItemSlab; + final boolean halfSlab = slab && !block.isOpaqueCube(); ForgeDirection direction = ForgeDirection.UNKNOWN; for (ForgeDirection support : validSides) { - if (PrinterInteraction.canClickForPlacement( + if ((!halfSlab || placesSlabHalf(metadata, support)) && PrinterInteraction.canClickForPlacement( world.getBlock(x + support.offsetX, y + support.offsetY, z + support.offsetZ), itemStack, true) && (!slab || !wouldMergeSupportingSlab(world, x, y, z, support, itemStack))) { @@ -299,8 +300,8 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, : data.getValidDirections(ForgeDirection.VALID_DIRECTIONS, metadata); for (ForgeDirection side : valid) { // ItemSlab checks the block across the clicked face before placing into the clicked cell. - if (!slab || !BlockToItemStack - .matchesHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack)) { + if ((!halfSlab || placesSlabHalf(metadata, side)) && (!slab || !BlockToItemStack + .matchesHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack))) { direction = side; break; } @@ -316,6 +317,11 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, && placeAgainstSupport(interaction, x, y, z, direction, adjacent, offsetY, extraClicks); } + static boolean placesSlabHalf(int metadata, ForgeDirection support) { + return support.offsetY == 0 + || ((metadata & 8) != 0 ? support == ForgeDirection.UP : support == ForgeDirection.DOWN); + } + private boolean wouldMergeSupportingSlab(World world, int x, int y, int z, ForgeDirection support, ItemStack slab) { if (support.offsetY == 0 || !BlockToItemStack.matchesHalfSlab(world, x, y + support.offsetY, z, slab)) { return false; From ee13cad9e11a677f33be31bb955cfbaee665ed5d Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:05:41 +0100 Subject: [PATCH 31/64] fix: wait for capital turns and retry rejected clicks --- .../compat/ArchitectureCraftSupport.java | 4 ++ .../printer/ArchitectureCraftPrinter.java | 53 +++++++++++++++++-- .../client/printer/SchematicPrinter.java | 18 ++++--- 3 files changed, 63 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index 055b9f4c..8723e25c 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -127,6 +127,10 @@ && canHammerTurn(actual, expected) && sameMaterial(actual.baseBlockState, expected.baseBlockState); } + public static int getTurn(TileEntity tile) { + return ((TileShape) tile).turn; + } + private static boolean canHammerTurn(TileShape actual, TileShape expected) { return isTurnableCapital(expected) && actual.shape == expected.shape && actual.side == expected.side diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java index 49ae6737..5557976f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java @@ -1,8 +1,13 @@ package com.github.lunatrius.schematica.client.printer; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; +import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; @@ -10,7 +15,25 @@ final class ArchitectureCraftPrinter { - private ArchitectureCraftPrinter() {} + private static final long TURN_ACK_TIMEOUT = TimeUnit.SECONDS.toNanos(5); + private final Map pendingTurns = new IdentityHashMap<>(); + + void reset() { + this.pendingTurns.clear(); + } + + void beginPass(World world) { + final long now = System.nanoTime(); + this.pendingTurns.entrySet() + .removeIf(entry -> { + final TileEntity tile = entry.getKey(); + final PendingTurn pending = entry.getValue(); + return tile.getWorldObj() != world || !world.blockExists(tile.xCoord, tile.yCoord, tile.zCoord) + || world.getTileEntity(tile.xCoord, tile.yCoord, tile.zCoord) != tile + || ArchitectureCraftSupport.getTurn(tile) != pending.turn + || now - pending.sentAt >= TURN_ACK_TIMEOUT; + }); + } static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEntity tile, ItemStack item) { if (!interaction.canSelectItem(item)) { @@ -29,16 +52,36 @@ static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEn && placeAgainstSupports(interaction, x, y, z, tile, item, supports, true); } - static boolean rotateCapital(PrinterInteraction interaction, int x, int y, int z) { - return interaction.selectItem(ArchitectureCraftSupport.getHammer()) && interaction.withSneaking( + boolean rotateCapital(PrinterInteraction interaction, TileEntity tile, int x, int y, int z) { + if (this.pendingTurns.containsKey(tile) || !interaction.selectItem(ArchitectureCraftSupport.getHammer())) { + return false; + } + final int previousTurn = ArchitectureCraftSupport.getTurn(tile); + final boolean sent = interaction.withSneaking( false, () -> interaction.useBlockOnServer( interaction.player.getHeldItem(), x, y, z, - ForgeDirection.UP.ordinal(), - Vec3.createVectorHelper(x + 0.5, y + 1, z + 0.5))); + ForgeDirection.NORTH.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 0.5, z))); + if (sent) { + // A turn is relative. Wait for a tile update before sending another click. + this.pendingTurns.put(tile, new PendingTurn(previousTurn, System.nanoTime())); + } + return sent; + } + + private static final class PendingTurn { + + private final int turn; + private final long sentAt; + + private PendingTurn(int turn, long sentAt) { + this.turn = turn; + this.sentAt = sentAt; + } } private static boolean placeAgainstSupports(PrinterInteraction interaction, int x, int y, int z, TileEntity tile, diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 0e13d3c2..12e09b44 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -39,6 +39,7 @@ public class SchematicPrinter { private final Minecraft minecraft = Minecraft.getMinecraft(); private final MicroblockPrinter microblocks = new MicroblockPrinter(); private final CarpentersPrinter carpenters = new CarpentersPrinter(); + private final ArchitectureCraftPrinter architectureCraft = new ArchitectureCraftPrinter(); private boolean isEnabled; private boolean isPrinting; @@ -79,6 +80,7 @@ public void setSchematic(SchematicWorld schematic) { public void refresh() { this.microblocks.reset(); this.carpenters.reset(); + this.architectureCraft.reset(); if (this.schematic != null) { this.retryDelay = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic .getLength()]; @@ -92,6 +94,7 @@ public boolean print() { final World world = this.minecraft.theWorld; final PrinterInteraction interaction = new PrinterInteraction(world, player, this.minecraft.playerController); this.carpenters.beginPass(world); + this.architectureCraft.beginPass(world); final Vector3i trans = ClientProxy.playerPosition.clone() .sub(this.schematic.position.x, this.schematic.position.y, this.schematic.position.z) @@ -175,19 +178,20 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { final boolean architectureShape = Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block); final TileEntity architectureTile = architectureShape ? this.schematic.getTileEntity(x, y, z) : null; - if (architectureShape && block == placedBlock - && ArchitectureCraftSupport - .needsHammerTurn(world.getTileEntity(worldX, worldY, worldZ), architectureTile)) { - if (ArchitectureCraftPrinter.rotateCapital(interaction, worldX, worldY, worldZ)) { - this.retryDelay[x][y][z] = (byte) Math.max(20, ConfigurationHandler.timeout); + final TileEntity placedArchitectureTile = architectureShape && block == placedBlock + ? world.getTileEntity(worldX, worldY, worldZ) + : null; + if (architectureShape && ArchitectureCraftSupport.needsHammerTurn(placedArchitectureTile, architectureTile)) { + if (this.architectureCraft.rotateCapital(interaction, placedArchitectureTile, worldX, worldY, worldZ)) { + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; return !ConfigurationHandler.placeInstantly; } return false; } if (block == placedBlock && BlockToItemStack.matchesMetadata(block, placedMetadata, metadata) && BlockToItemStack.matchesPaint(block, world, worldX, worldY, worldZ, this.schematic, x, y, z) - && (!architectureShape || ArchitectureCraftSupport - .matches(world.getTileEntity(worldX, worldY, worldZ), architectureTile, block))) { + && (!architectureShape + || ArchitectureCraftSupport.matches(placedArchitectureTile, architectureTile, block))) { return false; } From 96c17a68063f6512466c558b3757716f68eb61a4 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:05:41 +0100 Subject: [PATCH 32/64] fix: plan Carpenter shapes from native placement --- .../compat/CarpentersBlocksSupport.java | 116 +++++++----- .../client/printer/CarpentersPrinter.java | 173 ++++++++---------- .../client/util/BlockToItemStack.java | 4 + 3 files changed, 148 insertions(+), 145 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index ab7253a8..f21ca223 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -39,6 +39,11 @@ public final class CarpentersBlocksSupport { private static final int BASE = 6; private static final byte[][] SURFACE_ATTRIBUTES = { TEBase.ATTR_COVER, TEBase.ATTR_DYE, TEBase.ATTR_OVERLAY }; private static final int[] TOP_BOTTOM_FACING = { 0, 3, 1, 2 }; + private static final int[] SLOPE_CORNERS = { 2, 0, 3, 1 }; + private static final int[] WEDGE_NEAR = { Slope.ID_WEDGE_NW, Slope.ID_WEDGE_SE, Slope.ID_WEDGE_SW, + Slope.ID_WEDGE_NE }; + private static final int[] WEDGE_FAR = { Slope.ID_WEDGE_NE, Slope.ID_WEDGE_SW, Slope.ID_WEDGE_NW, + Slope.ID_WEDGE_SE }; private static final Ladder LADDER = new Ladder(); private static final Torch TORCH = new Torch(); @@ -74,61 +79,82 @@ public static boolean isFreestandingLadder(Block block, ForgeDirection direction return block instanceof BlockCarpentersLadder && direction.offsetY != 0; } - public static Float getWedgeYaw(Block block, TileEntity tile, ItemStack item) { - if (!(block instanceof BlockCarpentersSlope) || !(tile instanceof TEBase slope) - || item.getItemDamage() != BlockCarpentersSlope.META_WEDGE) { - return null; - } - return switch (slope.getData()) { - case Slope.ID_WEDGE_NEG_N, Slope.ID_WEDGE_POS_N -> 0f; - case Slope.ID_WEDGE_NEG_E, Slope.ID_WEDGE_POS_E -> 90f; - case Slope.ID_WEDGE_NEG_S, Slope.ID_WEDGE_POS_S -> 180f; - case Slope.ID_WEDGE_NEG_W, Slope.ID_WEDGE_POS_W -> 270f; - default -> null; - }; + public static boolean isSlope(Block block) { + return block instanceof BlockCarpentersSlope; } - public static ForgeDirection getWedgeFace(TileEntity tile) { - return ((TEBase) tile).getData() <= Slope.ID_WEDGE_NEG_E ? ForgeDirection.DOWN : ForgeDirection.UP; - } - - public static ForgeDirection getWedgeWallFace(TileEntity tile) { - return ForgeDirection.getOrientation(2 + (((TEBase) tile).getData() & 3)); - } - - public static boolean canReshapeOppositeWedge(TileEntity tile) { - final int expected = ((TEBase) tile).getData(); - return CarpentersHammerSupport.canReshapeSlope(expected, expected ^ 12); + public static ItemStack getSlopeItem(Block block, TileEntity tile) { + if (!(tile instanceof TEBase slope) || slope.getData() < 0 || slope.getData() > Slope.ID_PRISM_WEDGE_POS_E) { + return null; + } + final int data = slope.getData(); + final int subtype; + if (data >= Slope.ID_PRISM_WEDGE_POS_N) { + subtype = BlockCarpentersSlope.META_PRISM_SLOPE; + } else if (data >= Slope.ID_PRISM_NEG) { + subtype = BlockCarpentersSlope.META_PRISM; + } else if (data >= Slope.ID_OBL_EXT_NEG_SE) { + subtype = BlockCarpentersSlope.META_OBLIQUE_EXT; + } else if (data >= Slope.ID_OBL_INT_NEG_SE) { + subtype = BlockCarpentersSlope.META_OBLIQUE_INT; + } else { + subtype = BlockCarpentersSlope.META_WEDGE; + } + return new ItemStack(block, 1, subtype); } - public static boolean isSideWedge(Block block, TileEntity tile, ItemStack item) { - return block instanceof BlockCarpentersSlope && tile instanceof TEBase slope - && item.getItemDamage() == BlockCarpentersSlope.META_WEDGE - && slope.getData() >= Slope.ID_WEDGE_SE - && slope.getData() <= Slope.ID_WEDGE_SW; + public static ItemStack getWedgeItem(ItemStack slope) { + return new ItemStack(slope.getItem(), 1, BlockCarpentersSlope.META_WEDGE); } - public static double getSideWedgeHit(TileEntity tile, ForgeDirection face) { - final int expected = ((TEBase) tile).getData(); - final int near = switch (face) { - case NORTH -> Slope.ID_WEDGE_NW; - case SOUTH -> Slope.ID_WEDGE_SE; - case WEST -> Slope.ID_WEDGE_SW; - case EAST -> Slope.ID_WEDGE_NE; + public static boolean matchesSlopePlacement(TileEntity tile, ItemStack item, ForgeDirection face, float hitX, + float hitY, float hitZ, float yaw, boolean allowReshape) { + if (!(tile instanceof TEBase expected)) { + return false; + } + final int facing = MathHelper.floor_double(yaw * 4.0F / 360.0F + 0.5D) & 3; + final int corner = SLOPE_CORNERS[MathHelper.floor_double(yaw * 4.0F / 360.0F) & 3]; + final boolean positive = face == ForgeDirection.UP || (face.offsetY == 0 && hitY < 0.5f); + // Sneaking disables native neighbor reshaping during placement. + final int initial = switch (item.getItemDamage()) { + case BlockCarpentersSlope.META_WEDGE -> wedgePlacement(face, hitX, hitY, hitZ, facing); + case BlockCarpentersSlope.META_OBLIQUE_INT -> (positive ? Slope.ID_OBL_INT_POS_SE : Slope.ID_OBL_INT_NEG_SE) + + corner; + case BlockCarpentersSlope.META_OBLIQUE_EXT -> (positive ? Slope.ID_OBL_EXT_POS_SE : Slope.ID_OBL_EXT_NEG_SE) + + corner; + case BlockCarpentersSlope.META_PRISM -> positive ? Slope.ID_PRISM_POS : Slope.ID_PRISM_NEG; + case BlockCarpentersSlope.META_PRISM_SLOPE -> Slope.ID_PRISM_WEDGE_POS_N + TOP_BOTTOM_FACING[facing]; default -> -1; }; - final int far = switch (face) { - case NORTH -> Slope.ID_WEDGE_NE; - case SOUTH -> Slope.ID_WEDGE_SW; - case WEST -> Slope.ID_WEDGE_NW; - case EAST -> Slope.ID_WEDGE_SE; - default -> -1; + return initial >= 0 && (initial == expected.getData() + || (allowReshape && CarpentersHammerSupport.canReshapeSlope(expected.getData(), initial))); + } + + private static int wedgePlacement(ForgeDirection face, float hitX, float hitY, float hitZ, int facing) { + if (face.offsetY != 0) { + final int base = face == ForgeDirection.UP ? Slope.ID_WEDGE_POS_N : Slope.ID_WEDGE_NEG_N; + return base + TOP_BOTTOM_FACING[facing]; + } + final float across = switch (face) { + case NORTH -> 1 - hitX; + case WEST -> hitZ; + case EAST -> 1 - hitZ; + default -> hitX; }; - if (expected != near && expected != far) { - return 0; + final int side = face.ordinal(); + if (hitY > 0.5f && across > 1 - hitY && across < hitY) { + return side + 2; + } + if (hitY < 0.5f && across < 1 - hitY && across > hitY) { + return side + 6; + } + if (across < 0.2f) { + return WEDGE_NEAR[side - 2]; + } + if (across > 0.8f) { + return WEDGE_FAR[side - 2]; } - final boolean reversed = face == ForgeDirection.NORTH || face == ForgeDirection.EAST; - return (expected == near) != reversed ? 0.125 : 0.875; + return side + (hitY > 0.5f ? 2 : 6); } public static boolean canConfigure(TileEntity tile, EntityPlayer player) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 28d241b2..6c8ef274 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -5,6 +5,7 @@ import java.util.function.BooleanSupplier; import net.minecraft.block.Block; +import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; @@ -19,7 +20,7 @@ final class CarpentersPrinter { - private static final float[] STAIR_HIT_OFFSETS = { 0.5f, 0.125f, 0.875f, 0.25f, 0.75f }; + private static final float[] SHAPE_HIT_OFFSETS = { 0.5f, 0.125f, 0.875f, 0.25f, 0.75f }; private final Map pendingClicks = new HashMap<>(); private long currentPass; @@ -110,68 +111,19 @@ static boolean place(PrinterInteraction interaction, SchematicWorld schematic, B return yaw != null && placeGarageDoor(interaction, x, y, z, block, item, yaw); } final TileEntity tile = schematic.getTileEntity(localX, localY, localZ); - if (CarpentersBlocksSupport.isStairs(block)) { - return placeStairs(interaction, x, y, z, block, tile, item); + if (CarpentersBlocksSupport.isSlope(block) && !interaction.canSelectItem(item)) { + return placeShape(interaction, x, y, z, block, tile, CarpentersBlocksSupport.getWedgeItem(item)); + } + if (CarpentersBlocksSupport.isStairs(block) || CarpentersBlocksSupport.isSlope(block)) { + return placeShape(interaction, x, y, z, block, tile, item); } final ForgeDirection face = CarpentersBlocksSupport.getAttachmentDirection(block, tile); if (face != null) { return placeSidedBlock(interaction, x, y, z, block, item, face); } - if (CarpentersBlocksSupport.isSideWedge(block, tile, item)) { - return placeSideWedge(interaction, x, y, z, block, item, tile); - } - final Float wedgeYaw = CarpentersBlocksSupport.getWedgeYaw(block, tile, item); - if (wedgeYaw != null) { - final ForgeDirection verticalFace = CarpentersBlocksSupport.getWedgeFace(tile); - final ForgeDirection wallFace = CarpentersBlocksSupport.getWedgeWallFace(tile); - if (canUseSupport(interaction, x, y, z, verticalFace, item)) { - return placeFromFace(interaction, x, y, z, block, item, verticalFace, true, 0.5, 0.5, wedgeYaw); - } - if (canUseSupport(interaction, x, y, z, wallFace, item)) { - final double hitY = verticalFace == ForgeDirection.UP ? 0.25 : 0.75; - return placeFromFace(interaction, x, y, z, block, item, wallFace, true, 0.5, hitY, wedgeYaw); - } - if (!ConfigurationHandler.placeAdjacent) { - return placeFromFace(interaction, x, y, z, block, item, verticalFace, false, 0.5, 0.5, wedgeYaw); - } - final ForgeDirection opposite = verticalFace.getOpposite(); - return canUseSupport(interaction, x, y, z, opposite, item) - && CarpentersBlocksSupport.canReshapeOppositeWedge(tile) - && findHammer(interaction) != null - && placeFromFace(interaction, x, y, z, block, item, opposite, true, 0.5, 0.5, wedgeYaw); - } return placeNormally.getAsBoolean(); } - private static boolean placeSideWedge(PrinterInteraction interaction, int x, int y, int z, Block block, - ItemStack item, TileEntity tile) { - final float yaw = interaction.player.rotationYaw; - ForgeDirection directFace = ForgeDirection.UNKNOWN; - for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) { - final double across = CarpentersBlocksSupport.getSideWedgeHit(tile, face); - if (across == 0) { - continue; - } - if (canUseSupport(interaction, x, y, z, face, item)) { - return placeFromFace(interaction, x, y, z, block, item, face, true, across, 0.5, yaw); - } - directFace = face; - } - return !ConfigurationHandler.placeAdjacent && directFace != ForgeDirection.UNKNOWN - && placeFromFace( - interaction, - x, - y, - z, - block, - item, - directFace, - false, - CarpentersBlocksSupport.getSideWedgeHit(tile, directFace), - 0.5, - yaw); - } - private static boolean placeSidedBlock(PrinterInteraction interaction, int x, int y, int z, Block block, ItemStack item, ForgeDirection face) { if (face == ForgeDirection.UNKNOWN) { @@ -245,74 +197,95 @@ private static boolean placeGarageDoor(PrinterInteraction interaction, int x, in Vec3.createVectorHelper(x + 0.5, y + 1, z + 0.5)))); } - private static boolean placeStairs(PrinterInteraction interaction, int x, int y, int z, Block block, - TileEntity tile, ItemStack item) { + private static boolean placeShape(PrinterInteraction interaction, int x, int y, int z, Block block, TileEntity tile, + ItemStack item) { if (PrinterInteraction.isBlacklisted(block, item) || !interaction.canSelectItem(item)) { return false; } final ForgeDirection[] supports = interaction.findSupports(x, y, z); - final boolean hasSupport = supports.length > 0; - if (!hasSupport && ConfigurationHandler.placeAdjacent) { + if (supports.length == 0 && ConfigurationHandler.placeAdjacent) { return false; } final float originalYaw = interaction.player.rotationYaw; final float pitch = interaction.player.rotationPitch; final float[] yaws = { originalYaw, 0, 90, 180, 270 }; + final boolean[] clickModes = ConfigurationHandler.placeAdjacent ? new boolean[] { true } + : new boolean[] { true, false }; for (boolean allowReshape : new boolean[] { false, true }) { if (allowReshape && findHammer(interaction) == null) { return false; } - for (float yaw : yaws) { - for (ForgeDirection support : hasSupport ? supports : ForgeDirection.VALID_DIRECTIONS) { - final ForgeDirection face = support.getOpposite(); - final int clickedX = hasSupport ? x + support.offsetX : x; - final int clickedY = hasSupport ? y + support.offsetY : y; - final int clickedZ = hasSupport ? z + support.offsetZ : z; - if (!PrinterInteraction - .canClickForPlacement(interaction.world.getBlock(clickedX, clickedY, clickedZ), item, true)) { - continue; + for (boolean adjacent : clickModes) { + final ForgeDirection[] candidates = adjacent ? supports : ForgeDirection.VALID_DIRECTIONS; + for (float yaw : yaws) { + for (ForgeDirection support : candidates) { + final ForgeDirection face = support.getOpposite(); + final int clickedX = adjacent ? x + support.offsetX : x; + final int clickedY = adjacent ? y + support.offsetY : y; + final int clickedZ = adjacent ? z + support.offsetZ : z; + final Block clicked = interaction.world.getBlock(clickedX, clickedY, clickedZ); + if (!PrinterInteraction.canClickForPlacement(clicked, item, true) + || (!adjacent && clicked == Blocks.snow_layer + && face != ForgeDirection.UP + && (interaction.world.getBlockMetadata(clickedX, clickedY, clickedZ) & 7) == 0)) { + continue; + } + final Vec3 hit = findShapeHit( + interaction.world, + x, + y, + z, + block, + tile, + item, + yaw, + allowReshape, + face); + if (hit == null) { + continue; + } + final BooleanSupplier click = () -> interaction.withSneaking( + true, + () -> interaction.place( + interaction.player.getHeldItem(), + clickedX, + clickedY, + clickedZ, + face.ordinal(), + hit.addVector(clickedX, clickedY, clickedZ))); + return interaction.selectItem(item) + && (yaw == originalYaw ? click.getAsBoolean() : interaction.withLook(yaw, pitch, click)); } - final Vec3 hit = findStairHit(interaction.world, x, y, z, block, tile, yaw, allowReshape, face); - if (hit == null) { - continue; - } - final BooleanSupplier click = () -> interaction.withSneaking( - true, - () -> interaction.place( - interaction.player.getHeldItem(), - clickedX, - clickedY, - clickedZ, - face.ordinal(), - hit.addVector(clickedX, clickedY, clickedZ))); - return interaction.selectItem(item) - && (yaw == originalYaw ? click.getAsBoolean() : interaction.withLook(yaw, pitch, click)); } } } return false; } - private static Vec3 findStairHit(World world, int x, int y, int z, Block block, TileEntity tile, float yaw, - boolean allowReshape, ForgeDirection face) { - for (float across : STAIR_HIT_OFFSETS) { - for (float height : STAIR_HIT_OFFSETS) { + private static Vec3 findShapeHit(World world, int x, int y, int z, Block block, TileEntity tile, ItemStack item, + float yaw, boolean allowReshape, ForgeDirection face) { + for (float across : SHAPE_HIT_OFFSETS) { + for (float height : SHAPE_HIT_OFFSETS) { final float hitX = face.offsetX == 0 ? across : (1 + face.offsetX) * 0.5f; final float hitY = face.offsetY == 0 ? height : (1 + face.offsetY) * 0.5f; final float hitZ = face.offsetZ == 0 ? across : (1 + face.offsetZ) * 0.5f; - if (CarpentersBlocksSupport.matchesStairPlacement( - tile, - block, - world, - x, - y, - z, - face.ordinal(), - hitX, - hitY, - hitZ, - yaw, - allowReshape)) { + final boolean matches = CarpentersBlocksSupport.isSlope(block) + ? CarpentersBlocksSupport + .matchesSlopePlacement(tile, item, face, hitX, hitY, hitZ, yaw, allowReshape) + : CarpentersBlocksSupport.matchesStairPlacement( + tile, + block, + world, + x, + y, + z, + face.ordinal(), + hitX, + hitY, + hitZ, + yaw, + allowReshape); + if (matches) { return Vec3.createVectorHelper(hitX, hitY, hitZ); } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 811359ae..e52ce2ee 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -11,6 +11,7 @@ import net.minecraft.world.World; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; import com.github.lunatrius.schematica.client.compat.EnderIOSlabSupport; import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.reference.Mods; @@ -21,6 +22,9 @@ public class BlockToItemStack { public static ItemStack getItemStack(final EntityPlayer player, final Block block, final World world, final int x, final int y, final int z) { try { + if (Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isSlope(block)) { + return CarpentersBlocksSupport.getSlopeItem(block, world.getTileEntity(x, y, z)); + } if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(block)) { return EnderIOSlabSupport.getItem(world.getTileEntity(x, y, z)); } From aaea8bbd727c67ac8a1f7acd46f33f7a4a782ba0 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:05:41 +0100 Subject: [PATCH 33/64] fix: protect slab placement over snow and seamless slabs --- .../schematica/client/printer/SchematicPrinter.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 12e09b44..22c7db3c 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -8,6 +8,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; @@ -195,6 +196,11 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { return false; } + // Native slab merges cannot recreate the seamless double-stone-slab variant. + if (block == Blocks.double_stone_slab && (metadata & 8) != 0) { + return false; + } + if (block instanceof BlockSlab && block.isOpaqueCube() && placedBlock instanceof BlockSlab && !placedBlock.isOpaqueCube()) { @@ -291,6 +297,12 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, final boolean adjacent = direction != ForgeDirection.UNKNOWN; if (!adjacent) { + if (halfSlab && (metadata & 8) != 0 + && world.getBlock(x, y, z) == Blocks.snow_layer + && (world.getBlockMetadata(x, y, z) & 7) == 0) { + // ItemBlock forces an upward placement click when replacing a snow layer. + return false; + } final boolean needsMappedSupport = data != null && data.type == PlacementData.PlacementType.BLOCK && !data.mapping.isEmpty() && !(block instanceof BlockRotatedPillar || block instanceof BlockHopper); From 3981b0a0e2555e7ace6316ec88cc8409f89a6ccb Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:05:41 +0100 Subject: [PATCH 34/64] fix: identify slab paint in material exports --- .../schematica/client/compat/EnderIOSlabSupport.java | 4 ++++ .../client/gui/control/GuiSchematicMaterials.java | 4 ++-- .../lunatrius/schematica/client/util/BlockList.java | 9 +++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java index 7ab14e9a..4cb27038 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java @@ -28,6 +28,10 @@ public static boolean itemsMatch(ItemStack actual, ItemStack expected) { return PainterUtil.isMetadataEquivelent(actual, expected); } + public static String getPaintName(ItemStack stack) { + return PainterUtil.getTooltTipText(stack); + } + public static boolean matchesPaint(TileEntity actual, TileEntity expected) { return actual instanceof TileEntityPaintedBlock placed && expected instanceof TileEntityPaintedBlock saved && placed.getSourceBlock() == saved.getSourceBlock() diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java b/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java index 1f135b1b..95e44add 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java @@ -128,7 +128,7 @@ private void dumpMaterialList(final List blockList) for (final BlockList.WrappedItemStack wrappedItemStack : blockList) { maxLengthName = Math.max( maxLengthName, - wrappedItemStack.getItemStackDisplayName() + wrappedItemStack.getExportDisplayName() .length()); maxSize = Math.max(maxSize, wrappedItemStack.total); } @@ -141,7 +141,7 @@ private void dumpMaterialList(final List blockList) final StringBuilder stringBuilder = new StringBuilder((maxLengthName + 1 + maxLengthSize) * blockList.size()); final Formatter formatter = new Formatter(stringBuilder); for (final BlockList.WrappedItemStack wrappedItemStack : blockList) { - formatter.format(formatName, wrappedItemStack.getItemStackDisplayName()); + formatter.format(formatName, wrappedItemStack.getExportDisplayName()); stringBuilder.append(" "); formatter.format(formatSize, wrappedItemStack.total); stringBuilder.append(System.lineSeparator()); diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index fd5af39e..d2b56c23 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -16,6 +16,7 @@ import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; import com.github.lunatrius.schematica.client.compat.CookingForBlockheadsSupport; +import com.github.lunatrius.schematica.client.compat.EnderIOSlabSupport; import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.nbt.NBTHelper; @@ -239,6 +240,14 @@ public String getItemStackDisplayName() { return name; } + public String getExportDisplayName() { + final String name = getItemStackDisplayName(); + if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(Block.getBlockFromItem(this.itemStack.getItem()))) { + return name + " (" + EnderIOSlabSupport.getPaintName(this.itemStack) + ")"; + } + return name; + } + public String getFormattedAmount() { final char color = this.placed < this.total ? 'c' : 'a'; return String.format( From 647208d04b807a0e083d74379315c22038301eeb Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:10:21 +0100 Subject: [PATCH 35/64] fix: retain pending capital turns across refreshes --- .../client/printer/ArchitectureCraftPrinter.java | 9 +++------ .../schematica/client/printer/SchematicPrinter.java | 1 - 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java index 5557976f..f14ab8a6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java @@ -1,7 +1,7 @@ package com.github.lunatrius.schematica.client.printer; -import java.util.IdentityHashMap; import java.util.Map; +import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; import net.minecraft.item.ItemStack; @@ -16,11 +16,8 @@ final class ArchitectureCraftPrinter { private static final long TURN_ACK_TIMEOUT = TimeUnit.SECONDS.toNanos(5); - private final Map pendingTurns = new IdentityHashMap<>(); - - void reset() { - this.pendingTurns.clear(); - } + // An outstanding click belongs to the live tile, even when the schematic is refreshed. + private final Map pendingTurns = new WeakHashMap<>(); void beginPass(World world) { final long now = System.nanoTime(); diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 22c7db3c..b70f561e 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -81,7 +81,6 @@ public void setSchematic(SchematicWorld schematic) { public void refresh() { this.microblocks.reset(); this.carpenters.reset(); - this.architectureCraft.reset(); if (this.schematic != null) { this.retryDelay = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic .getLength()]; From dc5991e4de41c9f8d5d2acf579b6e021fa76eeb8 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:10:21 +0100 Subject: [PATCH 36/64] fix: try wedge stock when native slope placement cannot finish --- .../client/printer/CarpentersPrinter.java | 121 +++++++++++------- 1 file changed, 75 insertions(+), 46 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 6c8ef274..43a09aa8 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -111,9 +111,6 @@ static boolean place(PrinterInteraction interaction, SchematicWorld schematic, B return yaw != null && placeGarageDoor(interaction, x, y, z, block, item, yaw); } final TileEntity tile = schematic.getTileEntity(localX, localY, localZ); - if (CarpentersBlocksSupport.isSlope(block) && !interaction.canSelectItem(item)) { - return placeShape(interaction, x, y, z, block, tile, CarpentersBlocksSupport.getWedgeItem(item)); - } if (CarpentersBlocksSupport.isStairs(block) || CarpentersBlocksSupport.isSlope(block)) { return placeShape(interaction, x, y, z, block, tile, item); } @@ -199,15 +196,23 @@ private static boolean placeGarageDoor(PrinterInteraction interaction, int x, in private static boolean placeShape(PrinterInteraction interaction, int x, int y, int z, Block block, TileEntity tile, ItemStack item) { - if (PrinterInteraction.isBlacklisted(block, item) || !interaction.canSelectItem(item)) { + if (PrinterInteraction.isBlacklisted(block, item)) { + return false; + } + final ItemStack wedge = CarpentersBlocksSupport.isSlope(block) ? CarpentersBlocksSupport.getWedgeItem(item) + : item; + final boolean usePreferred = interaction.canSelectItem(item); + final boolean useWedge = !wedge.isItemEqual(item) && interaction.canSelectItem(wedge); + if (!usePreferred && !useWedge) { return false; } + final ItemStack[] items = usePreferred ? (useWedge ? new ItemStack[] { item, wedge } : new ItemStack[] { item }) + : new ItemStack[] { wedge }; final ForgeDirection[] supports = interaction.findSupports(x, y, z); if (supports.length == 0 && ConfigurationHandler.placeAdjacent) { return false; } final float originalYaw = interaction.player.rotationYaw; - final float pitch = interaction.player.rotationPitch; final float[] yaws = { originalYaw, 0, 90, 180, 270 }; final boolean[] clickModes = ConfigurationHandler.placeAdjacent ? new boolean[] { true } : new boolean[] { true, false }; @@ -215,53 +220,77 @@ private static boolean placeShape(PrinterInteraction interaction, int x, int y, if (allowReshape && findHammer(interaction) == null) { return false; } - for (boolean adjacent : clickModes) { - final ForgeDirection[] candidates = adjacent ? supports : ForgeDirection.VALID_DIRECTIONS; - for (float yaw : yaws) { - for (ForgeDirection support : candidates) { - final ForgeDirection face = support.getOpposite(); - final int clickedX = adjacent ? x + support.offsetX : x; - final int clickedY = adjacent ? y + support.offsetY : y; - final int clickedZ = adjacent ? z + support.offsetZ : z; - final Block clicked = interaction.world.getBlock(clickedX, clickedY, clickedZ); - if (!PrinterInteraction.canClickForPlacement(clicked, item, true) - || (!adjacent && clicked == Blocks.snow_layer - && face != ForgeDirection.UP - && (interaction.world.getBlockMetadata(clickedX, clickedY, clickedZ) & 7) == 0)) { - continue; - } - final Vec3 hit = findShapeHit( - interaction.world, - x, - y, - z, - block, - tile, - item, - yaw, - allowReshape, - face); - if (hit == null) { - continue; - } - final BooleanSupplier click = () -> interaction.withSneaking( - true, - () -> interaction.place( - interaction.player.getHeldItem(), - clickedX, - clickedY, - clickedZ, - face.ordinal(), - hit.addVector(clickedX, clickedY, clickedZ))); - return interaction.selectItem(item) - && (yaw == originalYaw ? click.getAsBoolean() : interaction.withLook(yaw, pitch, click)); - } + for (ItemStack candidate : items) { + final BooleanSupplier click = findShapeClick( + interaction, + x, + y, + z, + block, + tile, + candidate, + supports, + yaws, + clickModes, + allowReshape); + if (click != null) { + return interaction.selectItem(candidate) && click.getAsBoolean(); } } } return false; } + private static BooleanSupplier findShapeClick(PrinterInteraction interaction, int x, int y, int z, Block block, + TileEntity tile, ItemStack item, ForgeDirection[] supports, float[] yaws, boolean[] clickModes, + boolean allowReshape) { + final float originalYaw = interaction.player.rotationYaw; + final float pitch = interaction.player.rotationPitch; + for (boolean adjacent : clickModes) { + final ForgeDirection[] candidates = adjacent ? supports : ForgeDirection.VALID_DIRECTIONS; + for (float yaw : yaws) { + for (ForgeDirection support : candidates) { + final ForgeDirection face = support.getOpposite(); + final int clickedX = adjacent ? x + support.offsetX : x; + final int clickedY = adjacent ? y + support.offsetY : y; + final int clickedZ = adjacent ? z + support.offsetZ : z; + final Block clicked = interaction.world.getBlock(clickedX, clickedY, clickedZ); + if (!PrinterInteraction.canClickForPlacement(clicked, item, true) + || (!adjacent && clicked == Blocks.snow_layer + && face != ForgeDirection.UP + && (interaction.world.getBlockMetadata(clickedX, clickedY, clickedZ) & 7) == 0)) { + continue; + } + final Vec3 hit = findShapeHit( + interaction.world, + x, + y, + z, + block, + tile, + item, + yaw, + allowReshape, + face); + if (hit == null) { + continue; + } + final BooleanSupplier click = () -> interaction.withSneaking( + true, + () -> interaction.place( + interaction.player.getHeldItem(), + clickedX, + clickedY, + clickedZ, + face.ordinal(), + hit.addVector(clickedX, clickedY, clickedZ))); + return yaw == originalYaw ? click : () -> interaction.withLook(yaw, pitch, click); + } + } + } + return null; + } + private static Vec3 findShapeHit(World world, int x, int y, int z, Block block, TileEntity tile, ItemStack item, float yaw, boolean allowReshape, ForgeDirection face) { for (float across : SHAPE_HIT_OFFSETS) { From e7a34d981acd5afab382353d0fa532d972ee6ad1 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:41:49 +0100 Subject: [PATCH 37/64] fix: skip non-multipart tile lookups --- .../schematica/client/compat/MicroblockSupport.java | 5 +++++ .../schematica/client/printer/SchematicPrinter.java | 2 +- .../schematica/client/renderer/RendererSchematicChunk.java | 3 +-- .../github/lunatrius/schematica/client/util/BlockList.java | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java index a886b5f4..a151174e 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -31,6 +31,7 @@ import codechicken.microblock.ItemMicroPart; import codechicken.microblock.Microblock; import codechicken.microblock.MicroblockPlacement; +import codechicken.multipart.BlockMultipart; import codechicken.multipart.TMultiPart; import codechicken.multipart.TileMultipart; import scala.collection.Iterator; @@ -42,6 +43,10 @@ public final class MicroblockSupport { private MicroblockSupport() {} + public static boolean isMultipartBlock(Block block) { + return block instanceof BlockMultipart; + } + public static boolean isMicroblockItem(ItemStack stack) { return stack.getItem() instanceof ItemMicroPart; } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index b70f561e..d8b26c56 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -156,7 +156,7 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { final int metadata = this.schematic.getBlockMetadata(x, y, z); final int placedMetadata = world.getBlockMetadata(worldX, worldY, worldZ); - if (block.hasTileEntity(metadata) && Mods.FORGE_MICROBLOCK) { + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block)) { final TileEntity tile = this.schematic.getTileEntity(x, y, z); if (MicroblockSupport.hasMicroblocks(tile)) { return this.microblocks.place(interaction, tile, x, y, z, worldX, worldY, worldZ) diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index b323377a..66f850c5 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -306,8 +306,7 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, || ConfigurationHandler.isExtraAirBlock(mcBlock); if (!isMcAirBlock) { - if (renderMicroblocks && block == mcBlock - && block.hasTileEntity(this.schematic.getBlockMetadata(x, y, z))) { + if (renderMicroblocks && block == mcBlock && MicroblockSupport.isMultipartBlock(block)) { MicroblockSupport.renderMissingParts( this.schematic, mcWorld.getTileEntity(wx, wy, wz), diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index d2b56c23..220a2d86 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -51,7 +51,7 @@ public List getList(final EntityPlayer player, final Schematic final int wx = world.position.x + x; final int wy = world.position.y + y; final int wz = world.position.z + z; - if (Mods.FORGE_MICROBLOCK && block.hasTileEntity(world.getBlockMetadata(x, y, z)) + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block) && MicroblockSupport.addMaterials( world.getTileEntity(x, y, z), mcWorld.getTileEntity(wx, wy, wz), From 6406bb2a62341b709a09f5e2edb973fee4776678 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:45:10 +0100 Subject: [PATCH 38/64] fix: match saved player head owners --- .../client/util/BlockToItemStack.java | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index e52ce2ee..693b46e3 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -1,10 +1,17 @@ package com.github.lunatrius.schematica.client.util; +import java.util.Objects; + import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; @@ -16,9 +23,16 @@ import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; +import com.google.common.collect.Iterables; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.minecraft.MinecraftProfileTexture; +import com.mojang.authlib.properties.Property; public class BlockToItemStack { + private static final int PLAYER_SKULL = 3; + private static final String SKULL_OWNER = "SkullOwner"; + public static ItemStack getItemStack(final EntityPlayer player, final Block block, final World world, final int x, final int y, final int z) { try { @@ -34,6 +48,16 @@ public static ItemStack getItemStack(final EntityPlayer player, final Block bloc return shape; } } + if (block == Blocks.skull && world.getTileEntity(x, y, z) instanceof TileEntitySkull skull) { + final ItemStack item = new ItemStack(Items.skull, 1, skull.func_145904_a()); + final GameProfile owner = skull.func_152108_a(); + if (isPlayerHead(item) && owner != null) { + final NBTTagCompound ownerTag = new NBTTagCompound(); + NBTUtil.func_152460_a(ownerTag, owner); + item.setTagInfo(SKULL_OWNER, ownerTag); + } + return item; + } final ItemStack itemStack = block.getPickBlock( new MovingObjectPosition(x, y, z, 1, Vec3.createVectorHelper(x + 0.5, y + 1.0, z + 0.5)), world, @@ -66,6 +90,13 @@ public static boolean matches(ItemStack stack, ItemStack target) { if (!stack.isItemEqual(target)) { return false; } + if (isPlayerHead(target)) { + try { + return matchesHeadOwner(getHeadOwner(stack), getHeadOwner(target)); + } catch (IllegalArgumentException e) { + return false; + } + } if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMicroblockItem(target)) { return MicroblockSupport.itemsMatch(stack, target); } @@ -79,6 +110,63 @@ public static boolean matches(ItemStack stack, ItemStack target) { || (hasOnlyCosmeticTags(stack) && hasOnlyCosmeticTags(target)); } + private static boolean isPlayerHead(ItemStack stack) { + return stack.getItem() == Items.skull && stack.getItemDamage() == PLAYER_SKULL; + } + + private static GameProfile getHeadOwner(ItemStack stack) { + final NBTTagCompound tag = stack.getTagCompound(); + if (tag == null) { + return null; + } + if (tag.hasKey(SKULL_OWNER, 10)) { + return NBTUtil.func_152459_a(tag.getCompoundTag(SKULL_OWNER)); + } + final String name = tag.hasKey(SKULL_OWNER, 8) ? tag.getString(SKULL_OWNER) : ""; + return name.isEmpty() ? null : new GameProfile(null, name); + } + + private static boolean matchesHeadOwner(GameProfile actual, GameProfile expected) { + if (actual == null || expected == null) { + return actual == expected; + } + // A legacy name cannot identify a saved UUID, particularly on heads with custom textures. + if (!Objects.equals(actual.getId(), expected.getId()) || (actual.getId() == null && !actual.getName() + .equalsIgnoreCase(expected.getName()))) { + return false; + } + // Vanilla renders the first texture property. Its timestamp and cape can change independently of the skin. + final Property actualTexture = Iterables.getFirst( + actual.getProperties() + .get("textures"), + null); + final Property expectedTexture = Iterables.getFirst( + expected.getProperties() + .get("textures"), + null); + if (actualTexture == null || expectedTexture == null) { + return actualTexture == expectedTexture; + } + if (actualTexture.getValue() + .equals(expectedTexture.getValue())) { + return true; + } + try { + return Objects.equals(getSkinUrl(actual), getSkinUrl(expected)); + } catch (RuntimeException e) { + // Some malformed texture payloads make Authlib throw instead of returning an empty map. + return false; + } + } + + private static String getSkinUrl(GameProfile owner) { + final MinecraftProfileTexture skin = Minecraft.getMinecraft() + .func_152347_ac() + .getTextures(owner, false) + .get(MinecraftProfileTexture.Type.SKIN); + return skin == null ? null : skin.getUrl(); + } + private static boolean hasOnlyCosmeticTags(ItemStack stack) { final NBTTagCompound tag = stack.getTagCompound(); if (tag == null) { From 880e53c67b75850a97d7e741991cc5dad94e4c6a Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:45:10 +0100 Subject: [PATCH 39/64] fix: guard extended downloads for older clients --- .../command/CommandSchematicaDownload.java | 3 +- .../schematica/handler/DownloadHandler.java | 63 +++++++++++++++---- .../schematica/handler/PlayerHandler.java | 4 +- .../network/message/MessageDownloadBegin.java | 21 ++++++- .../message/MessageDownloadBeginAck.java | 21 ++++--- .../message/MessageDownloadChunkAck.java | 6 +- .../network/transfer/SchematicTransfer.java | 20 ++++++ .../lunatrius/schematica/reference/Names.java | 1 + .../assets/schematica/lang/en_US.lang | 1 + 9 files changed, 111 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java index a3dd2ef8..5c223fd6 100644 --- a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java +++ b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java @@ -18,7 +18,6 @@ import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.handler.DownloadHandler; -import com.github.lunatrius.schematica.network.transfer.SchematicTransfer; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.util.FileUtils; @@ -86,7 +85,7 @@ public void processCommand(ICommandSender sender, String[] args) { final ISchematic schematic = SchematicFormat.readFromFile(directory, filename); if (schematic != null) { - DownloadHandler.INSTANCE.transferMap.put(player, new SchematicTransfer(schematic, filename)); + DownloadHandler.INSTANCE.startDownload(player, schematic, filename); sender.addChatMessage( new ChatComponentTranslation(Names.Command.Download.Message.DOWNLOAD_STARTED, filename)); } else { diff --git a/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java index 8070088c..16281c55 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java @@ -4,6 +4,8 @@ import java.util.Map; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.StatCollector; import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.network.PacketHandler; @@ -12,6 +14,7 @@ import com.github.lunatrius.schematica.network.message.MessageDownloadEnd; import com.github.lunatrius.schematica.network.transfer.SchematicTransfer; import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @@ -23,7 +26,7 @@ public class DownloadHandler { public ISchematic schematic = null; - public final Map transferMap = new LinkedHashMap<>(); + private final Map transferMap = new LinkedHashMap<>(); private DownloadHandler() {} @@ -36,7 +39,33 @@ public void onServerTick(TickEvent.ServerTickEvent event) { processQueue(); } - private void processQueue() { + public void startDownload(EntityPlayerMP player, ISchematic schematic, String name) { + final SchematicTransfer transfer = new SchematicTransfer(schematic, name); + synchronized (this) { + this.transferMap.put(player, transfer); + } + } + + public synchronized void cancelDownload(EntityPlayerMP player) { + this.transferMap.remove(player); + } + + public synchronized void confirmBegin(EntityPlayerMP player, boolean supportsExtendedBlockData) { + final SchematicTransfer transfer = this.transferMap.get(player); + if (transfer != null && transfer.state == SchematicTransfer.State.BEGIN) { + transfer.supportsExtendedBlockData = supportsExtendedBlockData; + transfer.setState(SchematicTransfer.State.CHUNK_WAIT); + } + } + + public synchronized void confirmChunk(EntityPlayerMP player, int x, int y, int z) { + final SchematicTransfer transfer = this.transferMap.get(player); + if (transfer != null && transfer.state == SchematicTransfer.State.CHUNK) { + transfer.confirmChunk(x, y, z); + } + } + + private synchronized void processQueue() { if (this.transferMap.isEmpty()) { return; } @@ -49,42 +78,54 @@ private void processQueue() { if (transfer == null) { return; } + this.transferMap.put(player, transfer); if (!transfer.state.isWaiting()) { if (++transfer.timeout >= Constants.Network.TIMEOUT) { if (++transfer.retries >= Constants.Network.RETRIES) { Reference.logger.warn("{}'s download was dropped!", player.getDisplayName()); + this.transferMap.remove(player); return; } Reference.logger .warn("{}'s download timed out, retrying (#{})", player.getDisplayName(), transfer.retries); - sendChunk(player, transfer); + if (transfer.state == SchematicTransfer.State.BEGIN) { + sendBegin(player, transfer); + } else { + sendChunk(player, transfer); + } transfer.timeout = 0; } } else if (transfer.state == SchematicTransfer.State.BEGIN_WAIT) { + transfer.setState(SchematicTransfer.State.BEGIN); sendBegin(player, transfer); } else if (transfer.state == SchematicTransfer.State.CHUNK_WAIT) { + if (transfer.requiresExtendedBlockData && !transfer.supportsExtendedBlockData) { + // Translate on the server because old clients do not have this key. + player.addChatMessage( + new ChatComponentText( + StatCollector.translateToLocalFormatted( + Names.Command.Download.Message.DOWNLOAD_REQUIRES_UPDATE, + transfer.name))); + this.transferMap.remove(player); + return; + } + transfer.setState(SchematicTransfer.State.CHUNK); sendChunk(player, transfer); } else if (transfer.state == SchematicTransfer.State.END_WAIT) { + this.transferMap.remove(player); sendEnd(player, transfer); - return; } - - this.transferMap.put(player, transfer); } private void sendBegin(EntityPlayerMP player, SchematicTransfer transfer) { - transfer.setState(SchematicTransfer.State.BEGIN); - - MessageDownloadBegin message = new MessageDownloadBegin(transfer.schematic); + MessageDownloadBegin message = new MessageDownloadBegin(transfer.schematic, transfer.requiresExtendedBlockData); PacketHandler.INSTANCE.sendTo(message, player); } private void sendChunk(EntityPlayerMP player, SchematicTransfer transfer) { - transfer.setState(SchematicTransfer.State.CHUNK); - Reference.logger.trace("Sending chunk {},{},{}", transfer.baseX, transfer.baseY, transfer.baseZ); MessageDownloadChunk message = new MessageDownloadChunk( transfer.schematic, diff --git a/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java index 8cfb4a37..b01bcfb8 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java @@ -33,8 +33,8 @@ public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { @SubscribeEvent public void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) { - if (event.player instanceof EntityPlayerMP) { - DownloadHandler.INSTANCE.transferMap.remove(event.player); + if (event.player instanceof EntityPlayerMP player) { + DownloadHandler.INSTANCE.cancelDownload(player); } } } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBegin.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBegin.java index b121f337..044a5c34 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBegin.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBegin.java @@ -18,14 +18,16 @@ public class MessageDownloadBegin implements IMessage, IMessageHandler { + private boolean supportsExtendedBlockData; + + public MessageDownloadBeginAck() {} + + MessageDownloadBeginAck(boolean supportsExtendedBlockData) { + this.supportsExtendedBlockData = supportsExtendedBlockData; + } + @Override public void fromBytes(ByteBuf buf) { - // NOOP + // Older clients acknowledge with an empty payload. + this.supportsExtendedBlockData = buf.readableBytes() == 1 && buf.readUnsignedByte() == 1; } @Override public void toBytes(ByteBuf buf) { - // NOOP + if (this.supportsExtendedBlockData) { + buf.writeByte(1); + } } @Override public IMessage onMessage(MessageDownloadBeginAck message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; - SchematicTransfer transfer = DownloadHandler.INSTANCE.transferMap.get(player); - if (transfer != null) { - transfer.setState(SchematicTransfer.State.CHUNK_WAIT); - } + DownloadHandler.INSTANCE.confirmBegin(player, message.supportsExtendedBlockData); return null; } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java index a6a3b703..6d409271 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java @@ -3,7 +3,6 @@ import net.minecraft.entity.player.EntityPlayerMP; import com.github.lunatrius.schematica.handler.DownloadHandler; -import com.github.lunatrius.schematica.network.transfer.SchematicTransfer; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; @@ -41,10 +40,7 @@ public void toBytes(ByteBuf buf) { @Override public IMessage onMessage(MessageDownloadChunkAck message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; - SchematicTransfer transfer = DownloadHandler.INSTANCE.transferMap.get(player); - if (transfer != null) { - transfer.confirmChunk(message.baseX, message.baseY, message.baseZ); - } + DownloadHandler.INSTANCE.confirmChunk(player, message.baseX, message.baseY, message.baseZ); return null; } diff --git a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java index 604afbe2..3bf2c139 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java +++ b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java @@ -1,5 +1,7 @@ package com.github.lunatrius.schematica.network.transfer; +import net.minecraft.block.Block; + import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.reference.Constants; @@ -33,10 +35,12 @@ public boolean isWaiting() { public final int width; public final int height; public final int length; + public final boolean requiresExtendedBlockData; public State state = State.BEGIN_WAIT; public int timeout = 0; public int retries = 0; + public boolean supportsExtendedBlockData; public int baseX = 0; public int baseY = 0; @@ -49,6 +53,7 @@ public SchematicTransfer(final ISchematic schematic, String name) { this.width = schematic.getWidth(); this.height = schematic.getHeight(); this.length = schematic.getLength(); + this.requiresExtendedBlockData = requiresExtendedBlockData(); } public boolean confirmChunk(final int chunkX, final int chunkY, final int chunkZ) { @@ -75,6 +80,21 @@ public boolean confirmChunk(final int chunkX, final int chunkY, final int chunkZ return true; } + private boolean requiresExtendedBlockData() { + for (int x = 0; x < this.width; x++) { + for (int y = 0; y < this.height; y++) { + for (int z = 0; z < this.length; z++) { + // Older clients keep four metadata bits and may save IDs in packed AddBlocks nibbles. + if (this.schematic.getBlockMetadata(x, y, z) > 0xF + || Block.getIdFromBlock(this.schematic.getBlock(x, y, z)) > 0xFFF) { + return true; + } + } + } + } + return false; + } + public void setState(State state) { this.state = state; this.timeout = 0; diff --git a/src/main/java/com/github/lunatrius/schematica/reference/Names.java b/src/main/java/com/github/lunatrius/schematica/reference/Names.java index 33e9c6b3..941c3a15 100644 --- a/src/main/java/com/github/lunatrius/schematica/reference/Names.java +++ b/src/main/java/com/github/lunatrius/schematica/reference/Names.java @@ -144,6 +144,7 @@ public static final class Message { public static final String DOWNLOAD_STARTED = "schematica.command.download.started"; public static final String DOWNLOAD_SUCCEEDED = "schematica.command.download.downloadSucceeded"; public static final String DOWNLOAD_FAILED = "schematica.command.download.downloadFail"; + public static final String DOWNLOAD_REQUIRES_UPDATE = "schematica.command.download.requiresUpdate"; } public static final String NAME = "schematicaDownload"; diff --git a/src/main/resources/assets/schematica/lang/en_US.lang b/src/main/resources/assets/schematica/lang/en_US.lang index b850fad2..d400b855 100644 --- a/src/main/resources/assets/schematica/lang/en_US.lang +++ b/src/main/resources/assets/schematica/lang/en_US.lang @@ -158,3 +158,4 @@ schematica.command.download.usage=/schematicaDownload schematica.command.download.started=Started downloading %s... schematica.command.download.downloadSucceeded=Successfully downloaded %s. schematica.command.download.downloadFail=Download failed. +schematica.command.download.requiresUpdate=Update Schematica to download %s. This schematic contains block data your client cannot preserve. From eba1580820646cde0c0e12e8f6beab8727f9e209 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:09:31 +0100 Subject: [PATCH 40/64] fix: keep highlights outside Forge render passes --- .../schematica/client/renderer/RendererSchematicChunk.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index 66f850c5..2b75b5c1 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -154,7 +154,9 @@ public void updateRenderer() { final int previousPass = ForgeHooksClient.getWorldRenderPass(); try { // Multipart uses Forge's chunk-building pass to choose the parts to render. - ForgeHooksClient.worldRenderPass = pass; + if (pass < 2) { + ForgeHooksClient.worldRenderPass = pass; + } renderBlocks(pass, minX, minY, minZ, maxX, maxY, maxZ); } finally { ForgeHooksClient.worldRenderPass = previousPass; @@ -371,7 +373,7 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, } } - if (block != null && block.canRenderInPass(renderPass)) { + if (renderPass < 2 && block != null && block.canRenderInPass(renderPass)) { renderBlocks.renderBlockByRenderType(block, x, y, z); } } From fefdf7cfec0583c1b11e13e245b09910fedb5c50 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:09:31 +0100 Subject: [PATCH 41/64] fix: preserve hidden schematic layers during transforms --- .../client/world/SchematicWorld.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index 35ec099f..991548ae 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -236,6 +236,24 @@ public void refreshChests() { } public void flip(ForgeDirection direction) { + transformAllLayers(() -> flipSchematic(direction)); + } + + public void rotate(ForgeDirection direction) { + transformAllLayers(() -> rotateSchematic(direction)); + } + + private void transformAllLayers(Runnable transform) { + final boolean wasRenderingLayer = this.isRenderingLayer; + this.isRenderingLayer = false; + try { + transform.run(); + } finally { + this.isRenderingLayer = wasRenderingLayer; + } + } + + private void flipSchematic(ForgeDirection direction) { final ItemStack icon = this.schematic.getIcon(); final int width = this.schematic.getWidth(); final int height = this.schematic.getHeight(); @@ -320,7 +338,7 @@ public void flip(ForgeDirection direction) { refreshChests(); } - public void rotate(ForgeDirection direction) { + private void rotateSchematic(ForgeDirection direction) { final ItemStack icon = this.schematic.getIcon(); final int width = this.schematic.getWidth(); final int height = this.schematic.getHeight(); From 2aead716386699d8ed147d4eb08859318c75acde Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:09:32 +0100 Subject: [PATCH 42/64] fix: retain Carpenter clicks across printer refreshes --- .../lunatrius/schematica/client/printer/SchematicPrinter.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index d8b26c56..c97455db 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -75,12 +75,14 @@ public SchematicWorld getSchematic() { public void setSchematic(SchematicWorld schematic) { this.isPrinting = false; this.schematic = schematic; + if (schematic == null) { + this.carpenters.reset(); + } refresh(); } public void refresh() { this.microblocks.reset(); - this.carpenters.reset(); if (this.schematic != null) { this.retryDelay = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic .getLength()]; From 177a6a1766565e561f358dc8d850dd7a30054561 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:09:32 +0100 Subject: [PATCH 43/64] fix: preserve placement direction and finish split slab stacks --- .../client/printer/SchematicPrinter.java | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index c97455db..c814f675 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -298,12 +298,6 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, final boolean adjacent = direction != ForgeDirection.UNKNOWN; if (!adjacent) { - if (halfSlab && (metadata & 8) != 0 - && world.getBlock(x, y, z) == Blocks.snow_layer - && (world.getBlockMetadata(x, y, z) & 7) == 0) { - // ItemBlock forces an upward placement click when replacing a snow layer. - return false; - } final boolean needsMappedSupport = data != null && data.type == PlacementData.PlacementType.BLOCK && !data.mapping.isEmpty() && !(block instanceof BlockRotatedPillar || block instanceof BlockHopper); @@ -315,10 +309,14 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, final ForgeDirection[] valid = needsMappedSupport ? validSides : data == null ? ForgeDirection.VALID_DIRECTIONS : data.getValidDirections(ForgeDirection.VALID_DIRECTIONS, metadata); + // ItemBlock forces an upward click when replacing a single layer of snow. + final boolean snowForcesUp = world.getBlock(x, y, z) == Blocks.snow_layer + && (world.getBlockMetadata(x, y, z) & 7) == 0; for (ForgeDirection side : valid) { // ItemSlab checks the block across the clicked face before placing into the clicked cell. - if ((!halfSlab || placesSlabHalf(metadata, side)) && (!slab || !BlockToItemStack - .matchesHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack))) { + if ((!snowForcesUp || side == ForgeDirection.DOWN) && (!halfSlab || placesSlabHalf(metadata, side)) + && (!slab || !BlockToItemStack + .matchesHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack))) { direction = side; break; } @@ -394,6 +392,7 @@ private boolean placeAgainstSupport(PrinterInteraction interaction, int x, int y final ItemStack itemStack = player.getCurrentEquippedItem(); if (!this.minecraft.playerController.isInCreativeMode() && itemStack != null + && !(itemStack.getItem() instanceof ItemSlab) && itemStack.stackSize <= extraClicks) { return false; } @@ -410,11 +409,16 @@ private boolean placeAgainstSupport(PrinterInteraction interaction, int x, int y final boolean success = interaction.withSneaking(true, () -> { boolean placed = interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); + if (placed && extraClicks > 0 && itemStack.getItem() instanceof ItemSlab) { + // The existing-half path can finish on a later pass when the remaining slab is in another slot. + if (itemStack.stackSize > 0 + && BlockToItemStack.matchesHalfSlab(interaction.world, x, y, z, itemStack)) { + mergeSlab(interaction, x, y, z, itemStack); + } + return true; + } for (int i = 0; placed && i < extraClicks; i++) { - placed = itemStack.getItem() instanceof ItemSlab - ? BlockToItemStack.matchesHalfSlab(interaction.world, x, y, z, itemStack) - && mergeSlab(interaction, x, y, z, itemStack) - : interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); + placed = interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); } return placed; }); From 33f61992b7fb07c45834d4d4d87ca509fafa7bc7 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:09:32 +0100 Subject: [PATCH 44/64] fix: match survival stock to schematic block picks --- .../client/printer/PrinterInteraction.java | 31 +++++++++---- .../client/printer/SchematicPrinter.java | 2 +- .../schematica/client/util/BlockList.java | 7 ++- .../client/util/BlockToItemStack.java | 44 +++++++++++++++++-- 4 files changed, 70 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java index 20607bcc..c9dd0500 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -49,19 +49,30 @@ final class PrinterInteraction { } boolean canSelectItem(ItemStack item) { - final int slot = findItemSlot(item); + final int slot = findItemSlot(item, false); return (slot >= 0 && slot < Constants.Inventory.Size.HOTBAR) || (!ConfigurationHandler.swapSlotsQueue.isEmpty() && (this.controller.isInCreativeMode() || (slot >= 0 && this.player.openContainer == this.player.inventoryContainer))); } boolean selectItem(ItemStack item) { - return selectItem(item, true) && this.inventory.getCurrentItem() != null - && BlockToItemStack.matches(this.inventory.getCurrentItem(), item); + return selectItem(item, false); } - private boolean selectItem(ItemStack item, boolean allowInventorySwap) { - final int slot = findItemSlot(item); + boolean selectBlockItem(ItemStack item) { + return selectItem(item, true); + } + + private boolean selectItem(ItemStack item, boolean blockStock) { + if (!selectItem(item, blockStock, true)) { + return false; + } + final ItemStack selected = this.inventory.getCurrentItem(); + return selected != null && matchesSelection(selected, item, blockStock); + } + + private boolean selectItem(ItemStack item, boolean blockStock, boolean allowInventorySwap) { + final int slot = findItemSlot(item, blockStock); final boolean inHotbar = slot >= Constants.Inventory.InventoryOffset.HOTBAR && slot < Constants.Inventory.InventoryOffset.HOTBAR + Constants.Inventory.Size.HOTBAR; @@ -81,10 +92,10 @@ private boolean selectItem(ItemStack item, boolean allowInventorySwap) { return allowInventorySwap && slot >= Constants.Inventory.InventoryOffset.INVENTORY && slot < Constants.Inventory.InventoryOffset.INVENTORY + Constants.Inventory.Size.INVENTORY && swapIntoHotbar(slot) - && selectItem(item, false); + && selectItem(item, blockStock, false); } - private int findItemSlot(ItemStack item) { + private int findItemSlot(ItemStack item, boolean blockStock) { final boolean shape = Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(item); final int connections = shape ? ArchitectureCraftSupport.getDisabledConnections(item) : 0; final boolean canSwap = !ConfigurationHandler.swapSlotsQueue.isEmpty() @@ -92,7 +103,7 @@ private int findItemSlot(ItemStack item) { int fallback = -1; for (int i = 0; i < this.inventory.mainInventory.length; i++) { final ItemStack stack = this.inventory.mainInventory[i]; - if (stack != null && stack.stackSize > 0 && BlockToItemStack.matches(stack, item)) { + if (stack != null && stack.stackSize > 0 && matchesSelection(stack, item, blockStock)) { if (!shape || (ArchitectureCraftSupport.getDisabledConnections(stack) == connections && (i < Constants.Inventory.Size.HOTBAR || canSwap))) { return i; @@ -107,6 +118,10 @@ private int findItemSlot(ItemStack item) { : fallback; } + private static boolean matchesSelection(ItemStack stack, ItemStack target, boolean blockStock) { + return blockStock ? BlockToItemStack.matchesBlockStock(stack, target) : BlockToItemStack.matches(stack, target); + } + private boolean swapIntoHotbar(int sourceSlot) { if (this.player.openContainer != this.player.inventoryContainer || ConfigurationHandler.swapSlotsQueue.isEmpty()) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index c814f675..415ac9c5 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -328,7 +328,7 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, final float offsetY = data == null || data.maskOffset == 0 ? 0.5f : data.getOffsetFromMetadata(metadata); final int extraClicks = data == null ? 0 : data.getExtraClicks(block, metadata); - return interaction.selectItem(itemStack) + return interaction.selectBlockItem(itemStack) && placeAgainstSupport(interaction, x, y, z, direction, adjacent, offsetY, extraClicks); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 220a2d86..665658ff 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -83,7 +83,7 @@ public List getList(final EntityPlayer player, final Schematic : null; final boolean complete = placed != null && BlockToItemStack.matches(placed, stack) && (!garageDoor || CarpentersBlocksSupport.isGarageDoorHost(mcWorld.getTileEntity(wx, wy, wz))); - addMaterial(blockList, stack, 1, complete); + addMaterial(blockList, stack, 1, complete).pickedBlock = true; if (block instanceof BlockSlab && block.isOpaqueCube() && stack.getItem() instanceof ItemSlab) { addMaterial( blockList, @@ -141,7 +141,9 @@ public List getList(final EntityPlayer player, final Schematic wrappedItemStack.inventory = -1; } else { for (ItemStack stack : player.inventory.mainInventory) { - if (stack != null && BlockToItemStack.matches(stack, target)) { + if (stack != null + && (wrappedItemStack.pickedBlock ? BlockToItemStack.matchesBlockStock(stack, target) + : BlockToItemStack.matches(stack, target))) { wrappedItemStack.inventory += stack.stackSize; } } @@ -218,6 +220,7 @@ public static class WrappedItemStack { public int total; public int inventory; private int kitchenDyesNeeded; + private boolean pickedBlock; public WrappedItemStack(final ItemStack itemStack) { this(itemStack, 0, 0); diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 693b46e3..2e53ebdd 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -10,12 +10,14 @@ import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTUtil; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; @@ -28,6 +30,8 @@ import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.properties.Property; +import cpw.mods.fml.common.registry.GameRegistry; + public class BlockToItemStack { private static final int PLAYER_SKULL = 3; @@ -87,7 +91,22 @@ public static ItemStack getItemStack(final EntityPlayer player, final Block bloc } public static boolean matches(ItemStack stack, ItemStack target) { - if (!stack.isItemEqual(target)) { + return matches(stack, target, false); + } + + public static boolean matchesBlockStock(ItemStack stack, ItemStack target) { + return matches(stack, target, true); + } + + private static boolean matches(ItemStack stack, ItemStack target, boolean blockStock) { + if (stack.getItem() != target.getItem()) { + return false; + } + if ((stack.hasTagCompound() || target.hasTagCompound()) + && target.getItem() == GameRegistry.findItem("etfuturum", "banner")) { + return matchesBanner(stack, target); + } + if (stack.getItemDamage() != target.getItemDamage()) { return false; } if (isPlayerHead(target)) { @@ -106,8 +125,27 @@ public static boolean matches(ItemStack stack, ItemStack target) { if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(Block.getBlockFromItem(target.getItem()))) { return EnderIOSlabSupport.itemsMatch(stack, target); } - return ItemStack.areItemStackTagsEqual(stack, target) - || (hasOnlyCosmeticTags(stack) && hasOnlyCosmeticTags(target)); + // Ordinary block picks can omit per-item data from stock, such as a dropped machine's configuration. + return ItemStack.areItemStackTagsEqual(stack, target) || (hasOnlyCosmeticTags(target) + && (hasOnlyCosmeticTags(stack) || (blockStock && target.getItem() instanceof ItemBlock))); + } + + private static boolean matchesBanner(ItemStack stack, ItemStack target) { + final NBTTagCompound actual = stack.hasTagCompound() ? stack.getTagCompound() + .getCompoundTag("BlockEntityTag") : new NBTTagCompound(); + final NBTTagCompound expected = target.hasTagCompound() ? target.getTagCompound() + .getCompoundTag("BlockEntityTag") : new NBTTagCompound(); + if (bannerColor(stack, actual) != bannerColor(target, expected)) { + return false; + } + final NBTTagList patterns = actual.getTagList("Patterns", Constants.NBT.TAG_COMPOUND); + final NBTTagList expectedPatterns = expected.getTagList("Patterns", Constants.NBT.TAG_COMPOUND); + return patterns.equals(expectedPatterns) || (patterns.tagCount() == 0 && expectedPatterns.tagCount() == 0); + } + + private static int bannerColor(ItemStack stack, NBTTagCompound tile) { + return tile.hasKey("Base", Constants.NBT.TAG_ANY_NUMERIC) ? tile.getInteger("Base") + : stack.getItemDamage() & 15; } private static boolean isPlayerHead(ItemStack stack) { From 3038f1fb0e6726cba176b16a578749c5be59b1d8 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:09:32 +0100 Subject: [PATCH 45/64] fix: identify cladding materials in material lists --- .../client/compat/ArchitectureCraftSupport.java | 9 +++++++++ .../lunatrius/schematica/client/util/BlockList.java | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index 8723e25c..377e3715 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -12,6 +12,7 @@ import gcewing.architecture.ArchitectureCraft; import gcewing.architecture.common.block.BlockShape; +import gcewing.architecture.common.item.ItemCladding; import gcewing.architecture.common.shape.Shape; import gcewing.architecture.common.shape.ShapeItem; import gcewing.architecture.common.shape.ShapeSymmetry; @@ -39,6 +40,14 @@ public static boolean isShapeItem(ItemStack stack) { } public static String getMaterialName(ItemStack stack) { + if (stack.getItem() instanceof ItemCladding cladding) { + final IBlockState material = cladding.blockStateFromStack(stack); + return material == null ? "" + : Utils.displayNameOfBlock(material.getBlock(), BlockCompatUtils.getMetaFromBlockState(material)); + } + if (!isShapeItem(stack)) { + return ""; + } final NBTTagCompound tag = stack.getTagCompound(); final Block base = tag == null ? null : Block.getBlockFromName(tag.getString("BaseName")); return base == null ? "" : Utils.displayNameOfBlock(base, tag.getInteger("BaseData")); diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 665658ff..3dcdc519 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -234,7 +234,7 @@ public WrappedItemStack(final ItemStack itemStack, final int placed, final int t public String getItemStackDisplayName() { final String name = this.itemStack.getDisplayName(); - if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(this.itemStack)) { + if (Mods.ARCHITECTURE_CRAFT) { final String material = ArchitectureCraftSupport.getMaterialName(this.itemStack); if (!material.isEmpty()) { return name + " (" + material + ")"; From f6f1de965d1c1be2f2158208ff111d8b08631e56 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:18:46 +0100 Subject: [PATCH 46/64] Extract NBT strings as constants --- .../compat/ArchitectureCraftSupport.java | 19 +++++++++++-------- .../client/compat/MicroblockSupport.java | 5 +++-- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java index 377e3715..59ed9f34 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -28,6 +28,9 @@ public final class ArchitectureCraftSupport { private static final double[] HIT_OFFSETS = { 0.5, 0.125, 0.875 }; + public static final String NBT_SHAPE = "Shape"; + public static final String NBT_BASE_DATA = "BaseData"; + public static final String NBT_BASE_NAME = "BaseName"; private ArchitectureCraftSupport() {} @@ -49,8 +52,8 @@ public static String getMaterialName(ItemStack stack) { return ""; } final NBTTagCompound tag = stack.getTagCompound(); - final Block base = tag == null ? null : Block.getBlockFromName(tag.getString("BaseName")); - return base == null ? "" : Utils.displayNameOfBlock(base, tag.getInteger("BaseData")); + final Block base = tag == null ? null : Block.getBlockFromName(tag.getString(NBT_BASE_NAME)); + return base == null ? "" : Utils.displayNameOfBlock(base, tag.getInteger(NBT_BASE_DATA)); } public static ItemStack getSecondaryItem(TileEntity tile) { @@ -80,12 +83,12 @@ private static boolean sameShape(ItemStack stack, ItemStack target) { final NBTTagCompound tag = stack.getTagCompound(); final NBTTagCompound expected = target.getTagCompound(); return tag != null && expected != null - && tag.hasKey("Shape") - && expected.hasKey("Shape") - && tag.getInteger("Shape") == expected.getInteger("Shape") - && tag.getInteger("BaseData") == expected.getInteger("BaseData") - && tag.getString("BaseName") - .equals(expected.getString("BaseName")); + && tag.hasKey(NBT_SHAPE) + && expected.hasKey(NBT_SHAPE) + && tag.getInteger(NBT_SHAPE) == expected.getInteger(NBT_SHAPE) + && tag.getInteger(NBT_BASE_DATA) == expected.getInteger(NBT_BASE_DATA) + && tag.getString(NBT_BASE_NAME) + .equals(expected.getString(NBT_BASE_NAME)); } public static boolean matches(TileEntity placed, TileEntity target, Block block) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java index a151174e..2d7eae32 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -40,6 +40,7 @@ public final class MicroblockSupport { private static final double[] FACE_SAMPLES = { 0.5, 0.125, 0.875, 0.03125, 0.96875 }; private static final double SERVER_SNEAK_EYE_OFFSET = 0.08; + public static final String NBT_MAT = "mat"; private MicroblockSupport() {} @@ -55,10 +56,10 @@ public static boolean itemsMatch(ItemStack stack, ItemStack target) { return stack.isItemEqual(target) && stack.hasTagCompound() && target.hasTagCompound() && stack.getTagCompound() - .getString("mat") + .getString(NBT_MAT) .equals( target.getTagCompound() - .getString("mat")); + .getString(NBT_MAT)); } public static boolean hasMicroblocks(TileEntity tile) { From 8c5ce1dbe4ac4885e315b1a62b2f71a671a8048f Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:45:18 +0100 Subject: [PATCH 47/64] fix: preserve pending microblock placements across refreshes --- .../client/compat/MicroblockSupport.java | 15 ++------ .../client/printer/MicroblockPrinter.java | 35 +++++++++++-------- .../client/printer/SchematicPrinter.java | 6 ++-- 3 files changed, 26 insertions(+), 30 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java index 2d7eae32..a824863f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -391,9 +391,6 @@ private Click tryAim(int bx, int by, int bz, int face) { player.rotationYaw, player.rotationPitch, player.isSneaking(), - x, - y, - z, placement.part()); } return null; @@ -561,26 +558,18 @@ public static final class Click { public final float pitch; public final boolean sneaking; - private final int x, y, z; private final Microblock result; - private Click(ItemStack item, MovingObjectPosition hit, float yaw, float pitch, boolean sneaking, int x, int y, - int z, Microblock result) { + private Click(ItemStack item, MovingObjectPosition hit, float yaw, float pitch, boolean sneaking, + Microblock result) { this.item = item; this.hit = hit; this.yaw = yaw; this.pitch = pitch; this.sneaking = sneaking; - this.x = x; - this.y = y; - this.z = z; this.result = result; } - public boolean targets(int x, int y, int z) { - return this.x == x && this.y == y && this.z == z; - } - public boolean isConfirmed(TileEntity tile) { for (Microblock part : getParts(tile)) { if (part.getSize() == result.getSize() && sameOrientation(part, result)) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java index 7395ae94..796cb3f3 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java @@ -1,7 +1,9 @@ package com.github.lunatrius.schematica.client.printer; +import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.TimeUnit; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MovingObjectPosition; @@ -9,38 +11,42 @@ import net.minecraft.world.World; import com.github.lunatrius.schematica.client.compat.MicroblockSupport; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; final class MicroblockPrinter { + private static final long ACK_TIMEOUT = TimeUnit.SECONDS.toNanos(5); + private final Map pendingPlacements = new HashMap<>(); + private WeakReference pendingWorld = new WeakReference<>(null); - void reset() { - this.pendingPlacements.clear(); + void beginPass(World world) { + if (this.pendingWorld.get() != world) { + this.pendingPlacements.clear(); + this.pendingWorld = new WeakReference<>(world); + } else if (!this.pendingPlacements.isEmpty()) { + final long now = System.nanoTime(); + this.pendingPlacements.values() + .removeIf(pending -> now - pending.sentAt >= ACK_TIMEOUT); + } } - boolean isWaiting(World world, int localX, int localY, int localZ, int x, int y, int z) { + boolean isWaiting(World world, int x, int y, int z) { if (this.pendingPlacements.isEmpty()) { return false; } - final ChunkPosition cell = new ChunkPosition(localX, localY, localZ); + final ChunkPosition cell = new ChunkPosition(x, y, z); final PendingPlacement pending = this.pendingPlacements.get(cell); if (pending == null) { return false; } - if (!pending.click.targets(x, y, z) || pending.click.isConfirmed(world.getTileEntity(x, y, z))) { + if (world.blockExists(x, y, z) && pending.click.isConfirmed(world.getTileEntity(x, y, z))) { this.pendingPlacements.remove(cell); return false; } - pending.remainingDelay -= Math.max(1, ConfigurationHandler.placeDelay); - if (pending.remainingDelay <= 0) { - this.pendingPlacements.remove(cell); - } return true; } - boolean place(PrinterInteraction interaction, TileEntity tile, int localX, int localY, int localZ, int x, int y, - int z) { + boolean place(PrinterInteraction interaction, TileEntity tile, int x, int y, int z) { final MicroblockSupport.Click click = MicroblockSupport .findPlacement(interaction.player, tile, x, y, z, interaction::canSelectItem); if (click == null || !interaction.selectItem(click.item)) { @@ -62,14 +68,15 @@ boolean place(PrinterInteraction interaction, TileEntity tile, int localX, int l hit.hitVec)))) { return false; } - this.pendingPlacements.put(new ChunkPosition(localX, localY, localZ), new PendingPlacement(click)); + // ForgeMultipart expands on the server. Keep the click pending across schematic moves and refreshes. + this.pendingPlacements.put(new ChunkPosition(x, y, z), new PendingPlacement(click)); return true; } private static final class PendingPlacement { private final MicroblockSupport.Click click; - private int remainingDelay = Math.max(1, ConfigurationHandler.timeout); + private final long sentAt = System.nanoTime(); private PendingPlacement(MicroblockSupport.Click click) { this.click = click; diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 415ac9c5..a92cbae1 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -82,7 +82,6 @@ public void setSchematic(SchematicWorld schematic) { } public void refresh() { - this.microblocks.reset(); if (this.schematic != null) { this.retryDelay = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic .getLength()]; @@ -95,6 +94,7 @@ public boolean print() { final EntityClientPlayerMP player = this.minecraft.thePlayer; final World world = this.minecraft.theWorld; final PrinterInteraction interaction = new PrinterInteraction(world, player, this.minecraft.playerController); + this.microblocks.beginPass(world); this.carpenters.beginPass(world); this.architectureCraft.beginPass(world); @@ -145,7 +145,7 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { final int worldZ = this.schematic.position.z + z; if (this.carpenters.isWaiting(worldX, worldY, worldZ) - || this.microblocks.isWaiting(world, x, y, z, worldX, worldY, worldZ)) { + || this.microblocks.isWaiting(world, worldX, worldY, worldZ)) { return false; } if (this.retryDelay[x][y][z] > 0) { @@ -161,7 +161,7 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block)) { final TileEntity tile = this.schematic.getTileEntity(x, y, z); if (MicroblockSupport.hasMicroblocks(tile)) { - return this.microblocks.place(interaction, tile, x, y, z, worldX, worldY, worldZ) + return this.microblocks.place(interaction, tile, worldX, worldY, worldZ) && !ConfigurationHandler.placeInstantly; } } From 1e9757b1a47b47a04906719bc26da7497d6d0743 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:45:18 +0100 Subject: [PATCH 48/64] fix: let the server place Carpenter garage columns --- .../printer/ArchitectureCraftPrinter.java | 1 + .../client/printer/CarpentersPrinter.java | 25 ++++++++++++++----- .../client/printer/PrinterInteraction.java | 1 - .../client/printer/SchematicPrinter.java | 2 +- 4 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java index f14ab8a6..8032f4c4 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java @@ -54,6 +54,7 @@ boolean rotateCapital(PrinterInteraction interaction, TileEntity tile, int x, in return false; } final int previousTurn = ArchitectureCraftSupport.getTurn(tile); + // Native hammer prediction changes the tile even when the server denies the click. final boolean sent = interaction.withSneaking( false, () -> interaction.useBlockOnServer( diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 43a09aa8..6454f55f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -100,7 +100,7 @@ private static boolean useFace(PrinterInteraction interaction, int x, int y, int return used || sneaking; } - static boolean place(PrinterInteraction interaction, SchematicWorld schematic, Block block, int localX, int localY, + boolean place(PrinterInteraction interaction, SchematicWorld schematic, Block block, int localX, int localY, int localZ, ItemStack item, BooleanSupplier placeNormally) { final int x = schematic.position.x + localX; final int y = schematic.position.y + localY; @@ -175,23 +175,36 @@ private static ItemStack findHammer(PrinterInteraction interaction) { .findHammer(interaction.player.inventory.mainInventory, interaction::canSelectItem); } - private static boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, int z, Block block, - ItemStack item, float yaw) { - if (PrinterInteraction.isBlacklisted(block, item) || !interaction.selectItem(item)) { + private boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, int z, Block block, ItemStack item, + float yaw) { + final World world = interaction.world; + if (PrinterInteraction.isBlacklisted(block, item) + || !PrinterInteraction.canClickForPlacement(world.getBlock(x, y + 1, z), item, true) + || !interaction.selectItem(item)) { return false; } - return interaction.withSneaking( + // Client prediction creates the whole column, but a rejected server click only corrects the host cell. + final boolean sent = interaction.withSneaking( true, () -> interaction.withLook( yaw, interaction.player.rotationPitch, - () -> interaction.place( + () -> interaction.useBlockOnServer( interaction.player.getHeldItem(), x, y + 1, z, ForgeDirection.DOWN.ordinal(), Vec3.createVectorHelper(x + 0.5, y + 1, z + 0.5)))); + if (sent) { + this.pendingClicks.put( + new ChunkPosition(x, y, z), + new PendingClick( + world, + this.currentPass, + () -> world.blockExists(x, y, z) && world.getBlock(x, y, z) == block)); + } + return sent; } private static boolean placeShape(PrinterInteraction interaction, int x, int y, int z, Block block, TileEntity tile, diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java index c9dd0500..9b0dcf27 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -186,7 +186,6 @@ boolean useBlockOnServer(ItemStack held, int x, int y, int z, int side, Vec3 hit if (event == null || event.useItem == Result.DENY) { return false; } - // The hammer changes tile orientation locally even when the server subsequently denies the click. this.player.sendQueue.addToSendQueue( new C08PacketPlayerBlockPlacement( x, diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index a92cbae1..77c3b903 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -245,7 +245,7 @@ && mergeSlab(interaction, worldX, worldY, worldZ, player.getHeldItem())) { if (architectureShape) { success = ArchitectureCraftPrinter.place(interaction, worldX, worldY, worldZ, architectureTile, itemStack); } else if (carpenterBlock) { - success = CarpentersPrinter.place( + success = this.carpenters.place( interaction, this.schematic, block, From e0bac4d56fc0ab1bc1b1f8ad727cd482e4d69fff Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:46:06 +0100 Subject: [PATCH 49/64] fix: count white dye for kitchen recoloring --- .../lunatrius/schematica/client/util/BlockList.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 3dcdc519..8780feab 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -114,12 +114,16 @@ public List getList(final EntityPlayer player, final Schematic && y > 0 && world.getBlock(x, y - 1, z) == block && kitchenColor(world.getTileEntity(x, y - 1, z)) == color; - if (color > 0 && color <= 15 && !pairedFridge) { + if (color >= 0 && color <= 15 && !pairedFridge) { final boolean hasUpperFridge = "fridge".equals(name.name) && !world.isRenderingLayer && world.getBlock(x, y + 1, z) == block && kitchenColor(world.getTileEntity(x, y + 1, z)) == color; final boolean dyed = hasKitchenColor(mcWorld, block, wx, wy, wz, color) && (!hasUpperFridge || hasKitchenColor(mcWorld, block, wx, wy + 1, wz, color)); + if (color == 0 && !hasColoredKitchenBlock(mcWorld, block, wx, wy, wz) + && (!hasUpperFridge || !hasColoredKitchenBlock(mcWorld, block, wx, wy + 1, wz))) { + continue; + } final WrappedItemStack dye = addMaterial( blockList, new ItemStack(Items.dye, 1, 15 - color), @@ -190,6 +194,10 @@ private boolean hasKitchenColor(WorldClient world, Block block, int x, int y, in return world.getBlock(x, y, z) == block && kitchenColor(world.getTileEntity(x, y, z)) == color; } + private boolean hasColoredKitchenBlock(WorldClient world, Block block, int x, int y, int z) { + return world.getBlock(x, y, z) == block && kitchenColor(world.getTileEntity(x, y, z)) != 0; + } + private WrappedItemStack addMaterial(List blockList, ItemStack stack, int count, boolean placed) { final WrappedItemStack entry = findOrCreateWrappedItemStackFor(blockList, stack); if (placed) { From 6fea3f22fcee35f534d3bcc03593c54c68cb1cb8 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:46:06 +0100 Subject: [PATCH 50/64] fix: include banner patterns in material exports --- .../lunatrius/schematica/client/util/BlockList.java | 8 ++++++++ .../schematica/client/util/BlockToItemStack.java | 7 +++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 8780feab..976ab1d5 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -256,6 +256,14 @@ public String getExportDisplayName() { if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(Block.getBlockFromItem(this.itemStack.getItem()))) { return name + " (" + EnderIOSlabSupport.getPaintName(this.itemStack) + ")"; } + if (this.itemStack.hasTagCompound() && BlockToItemStack.isBanner(this.itemStack)) { + final List patterns = new ArrayList<>(); + this.itemStack.getItem() + .addInformation(this.itemStack, null, patterns, false); + if (!patterns.isEmpty()) { + return name + " (" + String.join(", ", patterns) + ")"; + } + } return name; } diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 2e53ebdd..1e48ed1c 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -102,8 +102,7 @@ private static boolean matches(ItemStack stack, ItemStack target, boolean blockS if (stack.getItem() != target.getItem()) { return false; } - if ((stack.hasTagCompound() || target.hasTagCompound()) - && target.getItem() == GameRegistry.findItem("etfuturum", "banner")) { + if ((stack.hasTagCompound() || target.hasTagCompound()) && isBanner(target)) { return matchesBanner(stack, target); } if (stack.getItemDamage() != target.getItemDamage()) { @@ -130,6 +129,10 @@ private static boolean matches(ItemStack stack, ItemStack target, boolean blockS && (hasOnlyCosmeticTags(stack) || (blockStock && target.getItem() instanceof ItemBlock))); } + static boolean isBanner(ItemStack stack) { + return stack.getItem() == GameRegistry.findItem("etfuturum", "banner"); + } + private static boolean matchesBanner(ItemStack stack, ItemStack target) { final NBTTagCompound actual = stack.hasTagCompound() ? stack.getTagCompound() .getCompoundTag("BlockEntityTag") : new NBTTagCompound(); From 18b36786933b74302e9ce43b8de8eb1f1eb97811 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:46:06 +0100 Subject: [PATCH 51/64] fix: reserve exact ingredients before counting block stock --- .../schematica/client/util/BlockList.java | 61 ++++++++++++++----- 1 file changed, 47 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 976ab1d5..0053345a 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -9,6 +9,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; +import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -83,14 +84,18 @@ public List getList(final EntityPlayer player, final Schematic : null; final boolean complete = placed != null && BlockToItemStack.matches(placed, stack) && (!garageDoor || CarpentersBlocksSupport.isGarageDoorHost(mcWorld.getTileEntity(wx, wy, wz))); - addMaterial(blockList, stack, 1, complete).pickedBlock = true; + final WrappedItemStack blockMaterial = addMaterial(blockList, stack, 1, complete); + if (!complete) { + blockMaterial.pickedBlocksNeeded++; + } if (block instanceof BlockSlab && block.isOpaqueCube() && stack.getItem() instanceof ItemSlab) { - addMaterial( - blockList, - stack, - 1, - complete || (BlockToItemStack.matchesHalfSlab(mcWorld, wx, wy, wz, stack) - && BlockToItemStack.matchesPaint(block, mcWorld, wx, wy, wz, world, x, y, z))); + if (complete || (BlockToItemStack.matchesHalfSlab(mcWorld, wx, wy, wz, stack) + && BlockToItemStack.matchesPaint(block, mcWorld, wx, wy, wz, world, x, y, z))) { + blockMaterial.placed++; + } else { + blockMaterial.pickedBlocksNeeded++; + } + blockMaterial.total++; } if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { final ItemStack secondary = ArchitectureCraftSupport @@ -145,22 +150,50 @@ public List getList(final EntityPlayer player, final Schematic wrappedItemStack.inventory = -1; } else { for (ItemStack stack : player.inventory.mainInventory) { - if (stack != null - && (wrappedItemStack.pickedBlock ? BlockToItemStack.matchesBlockStock(stack, target) - : BlockToItemStack.matches(stack, target))) { + if (stack != null && BlockToItemStack.matches(stack, target)) { wrappedItemStack.inventory += stack.stackSize; } } } } - if (Mods.COOKING_FOR_BLOCKHEADS && !player.capabilities.isCreativeMode - && CookingForBlockheadsSupport.SUPPORTS_DYE_SUBSTITUTES) { - addKitchenDyeSubstitutes(blockList, player.inventory.mainInventory); + if (!player.capabilities.isCreativeMode) { + addLooseBlockStock(blockList, player.inventory.mainInventory); + if (Mods.COOKING_FOR_BLOCKHEADS && CookingForBlockheadsSupport.SUPPORTS_DYE_SUBSTITUTES) { + addKitchenDyeSubstitutes(blockList, player.inventory.mainInventory); + } } return blockList; } + private void addLooseBlockStock(List materials, ItemStack[] inventory) { + for (WrappedItemStack row : materials) { + if (row.pickedBlocksNeeded == 0 || !(row.itemStack.getItem() instanceof ItemBlock)) { + continue; + } + int available = 0; + for (ItemStack stack : inventory) { + if (stack != null && matchesOnlyBlockStock(stack, row.itemStack)) { + available += stack.stackSize; + } + } + if (available == 0) { + continue; + } + // Tagged stock may be required as an exact ingredient in another row. + for (WrappedItemStack material : materials) { + if (matchesOnlyBlockStock(material.itemStack, row.itemStack)) { + available -= Math.min(material.inventory, material.total - material.placed); + } + } + row.inventory += Math.min(Math.max(available, 0), row.pickedBlocksNeeded); + } + } + + private static boolean matchesOnlyBlockStock(ItemStack candidate, ItemStack target) { + return BlockToItemStack.matchesBlockStock(candidate, target) && !BlockToItemStack.matches(candidate, target); + } + private void addKitchenDyeSubstitutes(List materials, ItemStack[] inventory) { for (WrappedItemStack dye : materials) { if (dye.kitchenDyesNeeded == 0) { @@ -228,7 +261,7 @@ public static class WrappedItemStack { public int total; public int inventory; private int kitchenDyesNeeded; - private boolean pickedBlock; + private int pickedBlocksNeeded; public WrappedItemStack(final ItemStack itemStack) { this(itemStack, 0, 0); From 20771337af6f578a2c585193f3ff182a53cde281 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:46:06 +0100 Subject: [PATCH 52/64] fix: guard downloads against legacy schemplus ID truncation --- .../schematica/network/transfer/SchematicTransfer.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java index 3bf2c139..6b7b910a 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java +++ b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java @@ -84,9 +84,11 @@ private boolean requiresExtendedBlockData() { for (int x = 0; x < this.width; x++) { for (int y = 0; y < this.height; y++) { for (int z = 0; z < this.length; z++) { - // Older clients keep four metadata bits and may save IDs in packed AddBlocks nibbles. - if (this.schematic.getBlockMetadata(x, y, z) > 0xF - || Block.getIdFromBlock(this.schematic.getBlock(x, y, z)) > 0xFFF) { + final int blockId = Block.getIdFromBlock(this.schematic.getBlock(x, y, z)); + // Legacy clients truncate metadata and standard IDs. Their schemplus writer misencodes 256 + // multiples. + if (this.schematic.getBlockMetadata(x, y, z) > 0xF || blockId > 0xFFF + || (blockId != 0 && (blockId & 0xFF) == 0)) { return true; } } From 59a08ee40ed2b9ff609d651f2578ac4551f99bf6 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:51:56 +0100 Subject: [PATCH 53/64] fix: wait for garage door inventory updates --- .../client/printer/CarpentersPrinter.java | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 6454f55f..4d0a5c05 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -1,10 +1,12 @@ package com.github.lunatrius.schematica.client.printer; +import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import java.util.function.BooleanSupplier; import net.minecraft.block.Block; +import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -23,6 +25,7 @@ final class CarpentersPrinter { private static final float[] SHAPE_HIT_OFFSETS = { 0.5f, 0.125f, 0.875f, 0.25f, 0.75f }; private final Map pendingClicks = new HashMap<>(); + private PendingClick pendingGarageStock; private long currentPass; void reset() { @@ -33,6 +36,9 @@ void beginPass(World world) { final long pass = ++this.currentPass; this.pendingClicks.values() .removeIf(click -> click.allowsNextClick(world, pass)); + if (this.pendingGarageStock != null && this.pendingGarageStock.allowsNextClick(world, pass)) { + this.pendingGarageStock = null; + } } boolean isWaiting(int x, int y, int z) { @@ -178,11 +184,16 @@ private static ItemStack findHammer(PrinterInteraction interaction) { private boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, int z, Block block, ItemStack item, float yaw) { final World world = interaction.world; - if (PrinterInteraction.isBlacklisted(block, item) + final boolean consumesItem = !interaction.player.capabilities.isCreativeMode; + if ((consumesItem && this.pendingGarageStock != null) || PrinterInteraction.isBlacklisted(block, item) || !PrinterInteraction.canClickForPlacement(world.getBlock(x, y + 1, z), item, true) || !interaction.selectItem(item)) { return false; } + final InventoryPlayer inventory = interaction.player.inventory; + final int slot = inventory.currentItem; + final ItemStack held = inventory.getCurrentItem(); + final int count = held.stackSize; // Client prediction creates the whole column, but a rejected server click only corrects the host cell. final boolean sent = interaction.withSneaking( true, @@ -203,6 +214,15 @@ private boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, in world, this.currentPass, () -> world.blockExists(x, y, z) && world.getBlock(x, y, z) == block)); + if (consumesItem) { + // A block update can arrive before the consumed item is removed from the selected slot. + final WeakReference inventoryRef = new WeakReference<>(inventory); + this.pendingGarageStock = new PendingClick(world, this.currentPass, () -> { + final InventoryPlayer current = inventoryRef.get(); + final ItemStack stack = current == null ? null : current.getStackInSlot(slot); + return stack == null || !stack.isItemEqual(item) || stack.stackSize < count; + }); + } } return sent; } @@ -337,7 +357,7 @@ private static Vec3 findShapeHit(World world, int x, int y, int z, Block block, private static final class PendingClick { - private final World world; + private final WeakReference world; private final long retryPass; private final BooleanSupplier confirmed; private long lastChecked = Long.MIN_VALUE; @@ -346,14 +366,14 @@ private static final class PendingClick { private PendingClick(World world, long pass, BooleanSupplier confirmed) { final int delay = Math.max(1, ConfigurationHandler.placeDelay); final int timeout = Math.max(20, ConfigurationHandler.timeout); - this.world = world; + this.world = new WeakReference<>(world); // Keep the original retry interval in printer passes for clicks without a server update. this.retryPass = pass + 2 + (timeout - 1) / delay; this.confirmed = confirmed; } private boolean allowsNextClick(World world, long pass) { - if (world != this.world || pass >= this.retryPass) { + if (world != this.world.get() || pass >= this.retryPass) { return true; } // Connected panels share a click. Check all of them once per printer pass. From 739fe3fe0105ce8bb1b6a888b3b7576887e61220 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:51:56 +0100 Subject: [PATCH 54/64] fix: export every saved banner pattern --- .../schematica/client/util/BlockList.java | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 0053345a..04f752cf 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -12,7 +12,10 @@ import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.Constants; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; @@ -290,9 +293,7 @@ public String getExportDisplayName() { return name + " (" + EnderIOSlabSupport.getPaintName(this.itemStack) + ")"; } if (this.itemStack.hasTagCompound() && BlockToItemStack.isBanner(this.itemStack)) { - final List patterns = new ArrayList<>(); - this.itemStack.getItem() - .addInformation(this.itemStack, null, patterns, false); + final List patterns = getBannerPatternNames(); if (!patterns.isEmpty()) { return name + " (" + String.join(", ", patterns) + ")"; } @@ -300,6 +301,27 @@ public String getExportDisplayName() { return name; } + private List getBannerPatternNames() { + final List names = new ArrayList<>(); + final ItemStack sample = this.itemStack.copy(); + final NBTTagCompound tile = sample.getTagCompound() + .getCompoundTag("BlockEntityTag"); + final NBTTagList patterns = tile.getTagList("Patterns", Constants.NBT.TAG_COMPOUND); + // Et Futurum's tooltip lists six patterns, but imported banners can render more layers. + final int tooltipLimit = 6; + for (int start = 0; start < patterns.tagCount(); start += tooltipLimit) { + final NBTTagList batch = new NBTTagList(); + final int end = Math.min(start + tooltipLimit, patterns.tagCount()); + for (int i = start; i < end; i++) { + batch.appendTag(patterns.getCompoundTagAt(i)); + } + tile.setTag("Patterns", batch); + sample.getItem() + .addInformation(sample, null, names, false); + } + return names; + } + public String getFormattedAmount() { final char color = this.placed < this.total ? 'c' : 'a'; return String.format( From a7ce89d0335515789de5deb4f095082ad3813281 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:57:20 +0100 Subject: [PATCH 55/64] fix: retry denied garage doors after other columns --- .../client/printer/CarpentersPrinter.java | 28 +++++++++++++++++-- .../client/printer/SchematicPrinter.java | 1 + 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 4d0a5c05..c1271196 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -2,7 +2,9 @@ import java.lang.ref.WeakReference; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.function.BooleanSupplier; import net.minecraft.block.Block; @@ -25,19 +27,38 @@ final class CarpentersPrinter { private static final float[] SHAPE_HIT_OFFSETS = { 0.5f, 0.125f, 0.875f, 0.25f, 0.75f }; private final Map pendingClicks = new HashMap<>(); + private final Set deferredGarageHosts = new HashSet<>(); + private WeakReference garageWorld = new WeakReference<>(null); private PendingClick pendingGarageStock; + private ChunkPosition pendingGarageHost; private long currentPass; void reset() { this.pendingClicks.clear(); + this.deferredGarageHosts.clear(); } void beginPass(World world) { final long pass = ++this.currentPass; this.pendingClicks.values() .removeIf(click -> click.allowsNextClick(world, pass)); + if (this.garageWorld.get() != world) { + this.deferredGarageHosts.clear(); + this.garageWorld = new WeakReference<>(world); + } if (this.pendingGarageStock != null && this.pendingGarageStock.allowsNextClick(world, pass)) { + if (this.pendingGarageStock.world.get() == world && pass >= this.pendingGarageStock.retryPass) { + // Let the current scan try the other garage hosts before retrying this one. + this.deferredGarageHosts.add(this.pendingGarageHost); + } this.pendingGarageStock = null; + this.pendingGarageHost = null; + } + } + + void finishPass() { + if (this.pendingGarageStock == null) { + this.deferredGarageHosts.clear(); } } @@ -185,7 +206,9 @@ private boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, in float yaw) { final World world = interaction.world; final boolean consumesItem = !interaction.player.capabilities.isCreativeMode; - if ((consumesItem && this.pendingGarageStock != null) || PrinterInteraction.isBlacklisted(block, item) + final ChunkPosition host = new ChunkPosition(x, y, z); + if ((consumesItem && (this.pendingGarageStock != null || this.deferredGarageHosts.contains(host))) + || PrinterInteraction.isBlacklisted(block, item) || !PrinterInteraction.canClickForPlacement(world.getBlock(x, y + 1, z), item, true) || !interaction.selectItem(item)) { return false; @@ -209,7 +232,7 @@ private boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, in Vec3.createVectorHelper(x + 0.5, y + 1, z + 0.5)))); if (sent) { this.pendingClicks.put( - new ChunkPosition(x, y, z), + host, new PendingClick( world, this.currentPass, @@ -217,6 +240,7 @@ private boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, in if (consumesItem) { // A block update can arrive before the consumed item is removed from the selected slot. final WeakReference inventoryRef = new WeakReference<>(inventory); + this.pendingGarageHost = host; this.pendingGarageStock = new PendingClick(world, this.currentPass, () -> { final InventoryPlayer current = inventoryRef.get(); final ItemStack stack = current == null ? null : current.getStackInSlot(slot); diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 77c3b903..787d5eae 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -126,6 +126,7 @@ public boolean print() { } } } + this.carpenters.finishPass(); return true; } catch (Exception e) { Reference.logger.error("Could not place block!", e); From bdd4dc112ca2cba0d4fa4359561ff47723b54d52 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:36:10 +0100 Subject: [PATCH 56/64] fix: preserve Et Futurum chain orientation --- .../schematica/client/printer/SchematicPrinter.java | 6 ++---- .../client/printer/registry/PlacementData.java | 11 +++++++++++ .../client/printer/registry/PlacementRegistry.java | 11 +++++++++-- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 787d5eae..9b858738 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -1,9 +1,7 @@ package com.github.lunatrius.schematica.client.printer; import net.minecraft.block.Block; -import net.minecraft.block.BlockHopper; import net.minecraft.block.BlockPistonBase; -import net.minecraft.block.BlockRotatedPillar; import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; @@ -276,7 +274,7 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, return false; } - PlacementData data = PlacementRegistry.INSTANCE.getPlacementData(block, itemStack); + final PlacementData data = PlacementRegistry.INSTANCE.getPlacementData(block, itemStack); if (!isValidOrientation(interaction.player, x, y, z, data, metadata)) { return false; @@ -301,7 +299,7 @@ private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, if (!adjacent) { final boolean needsMappedSupport = data != null && data.type == PlacementData.PlacementType.BLOCK && !data.mapping.isEmpty() - && !(block instanceof BlockRotatedPillar || block instanceof BlockHopper); + && !data.allowsDirectClick(); if ((ConfigurationHandler.placeAdjacent && solidSides.length == 0) || (needsMappedSupport && validSides.length == 0) || !(itemStack.getItem() instanceof ItemBlock)) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java index 43fd6301..2c8ba16f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java @@ -24,6 +24,7 @@ public enum PlacementType { public float offsetHighY = 1.0f; public int maskMeta = 0xF; public final Map mapping = new HashMap<>(); + private boolean directClick; private IExtraClick extraClick; public PlacementData(PlacementType type, int... metadata) { @@ -52,6 +53,16 @@ public float getOffsetFromMetadata(int metadata) { return (metadata & this.maskOffset) == 0 ? this.offsetLowY : this.offsetHighY; } + /** Lets a mapped face set orientation through a click on the target cell itself. */ + public PlacementData allowDirectClick() { + this.directClick = true; + return this; + } + + public boolean allowsDirectClick() { + return this.directClick; + } + public ForgeDirection[] getValidDirections(ForgeDirection[] solidSides, int metadata) { List list = new ArrayList<>(); diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java index 17bcc463..a1931ea2 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java @@ -22,6 +22,8 @@ import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; +import cpw.mods.fml.common.registry.GameRegistry; + public class PlacementRegistry { public static final PlacementRegistry INSTANCE = new PlacementRegistry(); @@ -56,7 +58,8 @@ public void populatePlacementMaps() { new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 3, 2, 5, 4)); addPlacementMapping( BlockHopper.class, - new PlacementData(PlacementData.PlacementType.BLOCK, 0, 1, 2, 3, 4, 5).setMaskMeta(0x7)); + new PlacementData(PlacementData.PlacementType.BLOCK, 0, 1, 2, 3, 4, 5).setMaskMeta(0x7) + .allowDirectClick()); addPlacementMapping( BlockPistonBase.class, new PlacementData(PlacementData.PlacementType.PISTON, 0, 1, 2, 3, 4, 5).setMaskMeta(0x7)); @@ -65,7 +68,8 @@ public void populatePlacementMaps() { new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 0, 2, 3, 1).setMaskMeta(0xF)); addPlacementMapping( BlockRotatedPillar.class, - new PlacementData(PlacementData.PlacementType.BLOCK, 0, 0, 8, 8, 4, 4).setMaskMeta(0xC)); + new PlacementData(PlacementData.PlacementType.BLOCK, 0, 0, 8, 8, 4, 4).setMaskMeta(0xC) + .allowDirectClick()); addPlacementMapping( BlockStairs.class, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 3, 2, 1, 0).setOffset(0x4, 0.0f, 1.0f) @@ -105,6 +109,9 @@ public void populatePlacementMaps() { addPlacementMapping(Blocks.stained_hardened_clay, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.carpet, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.stained_glass_pane, new PlacementData(PlacementData.PlacementType.BLOCK)); + addPlacementMapping( + GameRegistry.findBlock("etfuturum", "chain"), + new PlacementData(PlacementData.PlacementType.BLOCK, 0, 0, 2, 2, 1, 1).allowDirectClick()); addPlacementMapping( Items.wooden_door, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 3, 1, 2, 0).setMaskMeta(0x7)); From 59fe4b49c635b86390bac7c81e7fcee39775f453 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:36:23 +0100 Subject: [PATCH 57/64] fix: print Carpenter's collapsible blocks and posts --- .../compat/CarpentersBlocksSupport.java | 15 +- .../compat/CarpentersHammerSupport.java | 139 +++++++++++++++++- .../client/printer/CarpentersPrinter.java | 49 +++++- .../client/printer/PrinterInteraction.java | 23 +++ 4 files changed, 218 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index f21ca223..88823187 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -15,12 +15,14 @@ import net.minecraftforge.common.util.ForgeDirection; import com.carpentersblocks.block.BlockCarpentersBlock; +import com.carpentersblocks.block.BlockCarpentersCollapsibleBlock; import com.carpentersblocks.block.BlockCarpentersGarageDoor; import com.carpentersblocks.block.BlockCarpentersLadder; import com.carpentersblocks.block.BlockCarpentersSlope; import com.carpentersblocks.block.BlockCarpentersStairs; import com.carpentersblocks.block.BlockCarpentersTorch; import com.carpentersblocks.block.BlockCoverable; +import com.carpentersblocks.data.Collapsible; import com.carpentersblocks.data.GarageDoor; import com.carpentersblocks.data.Ladder; import com.carpentersblocks.data.Slope; @@ -57,6 +59,14 @@ public static boolean isStairs(Block block) { return block instanceof BlockCarpentersStairs; } + public static boolean isCollapsible(Block block) { + return block instanceof BlockCarpentersCollapsibleBlock; + } + + public static ForgeDirection getCollapsibleDirection(TileEntity tile) { + return tile instanceof TEBase carpenter ? Collapsible.INSTANCE.getDirection(carpenter) : ForgeDirection.UNKNOWN; + } + public static boolean isGarageDoor(Block block) { return block instanceof BlockCarpentersGarageDoor; } @@ -163,7 +173,7 @@ public static boolean canConfigure(TileEntity tile, EntityPlayer player) { } public static boolean passesThroughMicroblockClick(Block block) { - return block instanceof BlockCarpentersBlock || isStairs(block); + return block instanceof BlockCarpentersBlock || isStairs(block) || isCollapsible(block); } public static boolean allowsPlacementClick(Block clicked, ItemStack stack, boolean sneaking) { @@ -239,6 +249,9 @@ private static boolean matchesShape(Block block, TEBase expected, TEBase actual) return GarageDoor.INSTANCE.getDirection(actual) == GarageDoor.INSTANCE.getDirection(expected) && GarageDoor.INSTANCE.isHost(actual) == GarageDoor.INSTANCE.isHost(expected); } + if (isCollapsible(block)) { + return getCollapsibleDirection(actual) == getCollapsibleDirection(expected); + } return !(block instanceof BlockCarpentersBlock || block instanceof BlockCarpentersSlope || isStairs(block)) || actual.getData() == expected.getData(); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java index b8a75c6b..315dc3df 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -1,5 +1,6 @@ package com.github.lunatrius.schematica.client.compat; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -12,6 +13,8 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; @@ -20,6 +23,7 @@ import com.carpentersblocks.block.BlockCarpentersBed; import com.carpentersblocks.block.BlockCarpentersBlock; import com.carpentersblocks.block.BlockCarpentersButton; +import com.carpentersblocks.block.BlockCarpentersCollapsibleBlock; import com.carpentersblocks.block.BlockCarpentersDaylightSensor; import com.carpentersblocks.block.BlockCarpentersDoor; import com.carpentersblocks.block.BlockCarpentersFlowerPot; @@ -36,6 +40,7 @@ import com.carpentersblocks.data.Barrier; import com.carpentersblocks.data.Bed; import com.carpentersblocks.data.Button; +import com.carpentersblocks.data.Collapsible; import com.carpentersblocks.data.DaylightSensor; import com.carpentersblocks.data.GarageDoor; import com.carpentersblocks.data.Gate; @@ -50,6 +55,7 @@ import com.carpentersblocks.data.Stairs; import com.carpentersblocks.data.Torch; import com.carpentersblocks.tileentity.TEBase; +import com.carpentersblocks.util.collapsible.CollapsibleUtil; import com.carpentersblocks.util.handler.DesignHandler; import com.carpentersblocks.util.registry.FeatureRegistry; import com.carpentersblocks.util.registry.ItemRegistry; @@ -64,6 +70,8 @@ public final class CarpentersHammerSupport { private static final PressurePlate PRESSURE_PLATE = new PressurePlate(); private static final Button BUTTON = new Button(); private static final Lever LEVER = new Lever(); + private static final double[] CORNER_SAMPLES = { 0.5, 0.0625, 0.9375 }; + private static final double[] CORNER_HEIGHTS = { 0.5, 1, 0 }; private static final BlockSettings NO_SETTINGS = new BlockSettings(Block.class); // Settings are ordered by the sequence in which the hammer should adjust them. @@ -100,6 +108,7 @@ public final class CarpentersHammerSupport { toggle(PRESSURE_PLATE::getPolarity, Click.MANUAL)), new BlockSettings(BlockCarpentersButton.class, toggle(BUTTON::getPolarity, Click.MANUAL)), new BlockSettings(BlockCarpentersLever.class, toggle(LEVER::getPolarity, Click.MANUAL)), + new BlockSettings(BlockCarpentersCollapsibleBlock.class, toggle(TEBase::getData, Click.MANUAL)), new BlockSettings( BlockCarpentersSafe.class, toggle(Safe::isLocked, Click.SNEAK_RIGHT), @@ -141,13 +150,16 @@ public static boolean canUseHammer(EntityPlayer player, World world) { && hammer.canUseHammer(world, player); } - public static Adjustment findAdjustment(Block block, SchematicWorld schematic, TileEntity target, - TileEntity placed) { + public static Adjustment findAdjustment(Block block, SchematicWorld schematic, TileEntity target, TileEntity placed, + EntityPlayer player, double reach) { if (!(target instanceof TEBase expected) || !(placed instanceof TEBase actual)) { return null; } final BlockSettings settings = settingsFor(block); + if (CarpentersBlocksSupport.isCollapsible(block)) { + return findCollapsibleAdjustment(block, schematic, expected, actual, player, Math.min(5, reach), settings); + } Click click = settings.findClick(expected, actual); ForgeDirection face = ForgeDirection.UP; if (block instanceof BlockCarpentersBlock && expected.getData() != actual.getData() @@ -184,7 +196,97 @@ && validIndex(actual.getData(), Slab.SLAB_Z_POS + 1)) { return null; } } - return new Adjustment(click, face.ordinal(), affected, block, actual, settings); + return new Adjustment(click, face.ordinal(), affected, block, actual, settings, null); + } + + private static Adjustment findCollapsibleAdjustment(Block block, SchematicWorld schematic, TEBase expected, + TEBase actual, EntityPlayer player, double reach, BlockSettings settings) { + if (CarpentersBlocksSupport.getCollapsibleDirection(expected) + != CarpentersBlocksSupport.getCollapsibleDirection(actual)) { + return null; + } + final boolean positive = Collapsible.INSTANCE.isPositive(actual); + for (int quad = 0; quad < 4; quad++) { + final int goal = Collapsible.getQuadDepth(expected, quad); + final int depth = Collapsible.getQuadDepth(actual, quad); + if (depth == goal) { + continue; + } + final int nextDepth = depth + Integer.signum(goal - depth); + final Collection affected = collapsibleNeighbors(block, schematic, actual, quad, goal, nextDepth); + if (affected.isEmpty()) { + continue; + } + final CornerHit hit = findCornerHit(actual, player, reach, quad, nextDepth); + if (hit != null) { + final Click click = (goal > depth) == positive ? Click.RIGHT : Click.LEFT; + return new Adjustment(click, hit.hit.sideHit, affected, block, actual, settings, hit); + } + } + return null; + } + + private static Collection collapsibleNeighbors(Block block, SchematicWorld schematic, TEBase actual, + int quad, int goal, int nextDepth) { + final World world = actual.getWorldObj(); + final Collection affected = new ArrayList<>(); + affected.add(actual); + // Carpenter's smooths this corner into the three neighbors that share it. + for (int neighbor = 1; neighbor < 4; neighbor++) { + final int x = actual.xCoord + ((neighbor & 2) == 0 ? 0 : (quad & 2) == 0 ? -1 : 1); + final int y = actual.yCoord; + final int z = actual.zCoord + ((neighbor & 1) == 0 ? 0 : (quad & 1) == 0 ? -1 : 1); + final int neighborQuad = quad ^ neighbor; + if (world.getBlock(x, y, z) != block || !(world.getTileEntity(x, y, z) instanceof TEBase other) + || !Collapsible.INSTANCE.match(actual, other) + || Collapsible.getQuadDepth(other, neighborQuad) == nextDepth) { + continue; + } + final int sx = x - schematic.position.x; + final int sy = y - schematic.position.y; + final int sz = z - schematic.position.z; + if (schematic.getBlockIncludingHiddenLayers(sx, sy, sz) != block + || !(schematic.getTileEntity(sx, sy, sz) instanceof TEBase saved) + || !Collapsible.INSTANCE.match(other, saved) + || Collapsible.getQuadDepth(saved, neighborQuad) != goal) { + return Collections.emptyList(); + } + affected.add(other); + } + return affected; + } + + private static CornerHit findCornerHit(TEBase tile, EntityPlayer player, double reach, int quad, int nextDepth) { + final World world = tile.getWorldObj(); + final float[] bounds = CollapsibleUtil.genBounds(tile, quad); + // Carpenter's gets the quadrant from a fresh server-side trace of the player's normal click. + final Vec3 eye = Vec3.createVectorHelper(player.posX, player.boundingBox.minY + 1.62F, player.posZ); + for (double u : CORNER_SAMPLES) { + for (double v : CORNER_SAMPLES) { + for (double h : CORNER_HEIGHTS) { + final double dx = tile.xCoord + bounds[0] + (bounds[3] - bounds[0]) * u - eye.xCoord; + final double dy = tile.yCoord + bounds[1] + (bounds[4] - bounds[1]) * h - eye.yCoord; + final double dz = tile.zCoord + bounds[2] + (bounds[5] - bounds[2]) * v - eye.zCoord; + final double distance = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (distance == 0 || distance > reach) { + continue; + } + final double scale = reach / distance; + final MovingObjectPosition hit = world + .rayTraceBlocks(eye.addVector(0, 0, 0), eye.addVector(dx * scale, dy * scale, dz * scale)); + if (hit != null && hit.blockX == tile.xCoord + && hit.blockY == tile.yCoord + && hit.blockZ == tile.zCoord + && Collapsible.getQuad(hit.hitVec.xCoord - tile.xCoord, hit.hitVec.zCoord - tile.zCoord) + == quad) { + final float yaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + final float pitch = (float) -Math.toDegrees(Math.atan2(dy, Math.hypot(dx, dz))); + return new CornerHit(hit, yaw, pitch, quad, nextDepth); + } + } + } + } + return null; } private static Collection affectedBlocks(Block block, TEBase actual, TEBase expected, Click click) { @@ -383,15 +485,40 @@ private boolean matches(TEBase tile, Object[] values) { public enum Click { MANUAL, + LEFT, RIGHT, SNEAK_RIGHT } + public static final class CornerHit { + + public final MovingObjectPosition hit; + public final float yaw; + public final float pitch; + private final int quad; + private final int nextDepth; + + private CornerHit(MovingObjectPosition hit, float yaw, float pitch, int quad, int nextDepth) { + this.hit = hit; + this.yaw = yaw; + this.pitch = pitch; + this.quad = quad; + this.nextDepth = nextDepth; + } + + private boolean matches(TEBase clicked, TEBase actual) { + final int quad = this.quad ^ (actual.xCoord == clicked.xCoord ? 0 : 2) + ^ (actual.zCoord == clicked.zCoord ? 0 : 1); + return Collapsible.getQuadDepth(actual, quad) == this.nextDepth; + } + } + public static final class Adjustment { public final Click click; public final int face; public final Collection affected; + public final CornerHit corner; private final Block block; private final TEBase clicked; @@ -399,7 +526,7 @@ public static final class Adjustment { private final Object[] previousState; private Adjustment(Click click, int face, Collection affected, Block block, TEBase clicked, - BlockSettings settings) { + BlockSettings settings, CornerHit corner) { this.click = click; this.face = face; this.affected = affected; @@ -407,6 +534,7 @@ private Adjustment(Click click, int face, Collection affected, Block blo this.clicked = clicked; this.settings = settings; this.previousState = settings.snapshot(clicked); + this.corner = corner; } public boolean isConfirmed(World world) { @@ -423,7 +551,8 @@ public boolean isConfirmed(World world) { for (TileEntity piece : this.affected) { if (world.getBlock(piece.xCoord, piece.yCoord, piece.zCoord) != this.block || !(world.getTileEntity(piece.xCoord, piece.yCoord, piece.zCoord) instanceof TEBase updated) - || !this.settings.matches(updated, state)) { + || !(this.corner == null ? this.settings.matches(updated, state) + : this.corner.matches(this.clicked, updated))) { return false; } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index c1271196..43f9eb30 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -12,6 +12,7 @@ import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; @@ -74,9 +75,11 @@ boolean configureBlock(PrinterInteraction interaction, SchematicWorld schematic, return false; } final CarpentersHammerSupport.Adjustment adjustment = CarpentersHammerSupport - .findAdjustment(block, schematic, target, placed); + .findAdjustment(block, schematic, target, placed, interaction.player, interaction.blockReach()); if (adjustment != null && adjustment.affected.stream() - .allMatch(piece -> CarpentersBlocksSupport.canConfigure(piece, interaction.player)) + .allMatch( + piece -> !isWaiting(piece.xCoord, piece.yCoord, piece.zCoord) + && CarpentersBlocksSupport.canConfigure(piece, interaction.player)) && applyHammer(interaction, adjustment, x, y, z)) { final PendingClick click = new PendingClick(world, this.currentPass, () -> adjustment.isConfirmed(world)); for (TileEntity piece : adjustment.affected) { @@ -106,6 +109,19 @@ private static boolean applyHammer(PrinterInteraction interaction, CarpentersHam || !CarpentersHammerSupport.canUseHammer(interaction.player, interaction.world)) { return false; } + if (adjustment.corner != null) { + final CarpentersHammerSupport.CornerHit corner = adjustment.corner; + final MovingObjectPosition hit = corner.hit; + final ItemStack held = interaction.player.getHeldItem(); + return interaction.withSneaking( + false, + () -> interaction.withLook( + corner.yaw, + corner.pitch, + () -> adjustment.click == CarpentersHammerSupport.Click.LEFT + ? interaction.tapBlock(held, x, y, z, hit.sideHit) + : interaction.useBlock(held, x, y, z, hit.sideHit, hit.hitVec))); + } return useFace( interaction, x, @@ -141,6 +157,9 @@ boolean place(PrinterInteraction interaction, SchematicWorld schematic, Block bl if (CarpentersBlocksSupport.isStairs(block) || CarpentersBlocksSupport.isSlope(block)) { return placeShape(interaction, x, y, z, block, tile, item); } + if (CarpentersBlocksSupport.isCollapsible(block)) { + return placeCollapsible(interaction, x, y, z, block, tile, item); + } final ForgeDirection face = CarpentersBlocksSupport.getAttachmentDirection(block, tile); if (face != null) { return placeSidedBlock(interaction, x, y, z, block, item, face); @@ -148,6 +167,32 @@ boolean place(PrinterInteraction interaction, SchematicWorld schematic, Block bl return placeNormally.getAsBoolean(); } + private static boolean placeCollapsible(PrinterInteraction interaction, int x, int y, int z, Block block, + TileEntity tile, ItemStack item) { + final ForgeDirection face = CarpentersBlocksSupport.getCollapsibleDirection(tile); + if (face != ForgeDirection.UP && face != ForgeDirection.DOWN) { + return false; + } + final float yaw = interaction.player.rotationYaw; + if (canUseSupport(interaction, x, y, z, face, item)) { + return placeFromFace(interaction, x, y, z, block, item, face, true, 0.5, 0.5, yaw); + } + final ForgeDirection[] supports = interaction.findSupports(x, y, z); + for (ForgeDirection support : supports) { + final ForgeDirection side = support.getOpposite(); + if (side.offsetY == 0 && canUseSupport(interaction, x, y, z, side, item)) { + final double height = face == ForgeDirection.UP ? 0.25 : 0.75; + return placeFromFace(interaction, x, y, z, block, item, side, true, 0.5, height, yaw); + } + } + final World world = interaction.world; + final boolean snowForcesUp = world.getBlock(x, y, z) == Blocks.snow_layer + && (world.getBlockMetadata(x, y, z) & 7) == 0; + return (!ConfigurationHandler.placeAdjacent || supports.length > 0) + && (face == ForgeDirection.UP || !snowForcesUp) + && placeFromFace(interaction, x, y, z, block, item, face, false, 0.5, 0.5, yaw); + } + private static boolean placeSidedBlock(PrinterInteraction interaction, int x, int y, int z, Block block, ItemStack item, ForgeDirection face) { if (face == ForgeDirection.UNKNOWN) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java index 9b0dcf27..eb8f365f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -13,6 +13,7 @@ import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.C03PacketPlayer.C05PacketPlayerLook; +import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.network.play.client.C0BPacketEntityAction; import net.minecraft.util.Vec3; @@ -48,6 +49,10 @@ final class PrinterInteraction { this.inventory = player.inventory; } + double blockReach() { + return this.controller.getBlockReachDistance(); + } + boolean canSelectItem(ItemStack item) { final int slot = findItemSlot(item, false); return (slot >= 0 && slot < Constants.Inventory.Size.HOTBAR) @@ -200,6 +205,24 @@ boolean useBlockOnServer(ItemStack held, int x, int y, int z, int side, Vec3 hit return true; } + boolean tapBlock(ItemStack held, int x, int y, int z, int side) { + if (!isStillHolding(held) || (!this.controller.isInCreativeMode() && this.world.getBlock(x, y, z) + .getPlayerRelativeBlockHardness(this.player, this.world, x, y, z) >= 1)) { + return false; + } + this.controller.syncCurrentPlayItem(); + final PlayerInteractEvent event = ForgeEventFactory + .onPlayerInteract(this.player, Action.LEFT_CLICK_BLOCK, x, y, z, side, this.world); + if (event.isCanceled() || event.useBlock == Result.DENY || !isStillHolding(held)) { + return false; + } + // Carpenter's handles the hammer on the first click. Abort before mining can progress. + this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(0, x, y, z, side)); + this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(1, x, y, z, side)); + this.player.swingItem(); + return true; + } + private PlayerInteractEvent prepareBlockUse(ItemStack held, int x, int y, int z, int side) { if (!isStillHolding(held)) { return null; From aaf7003ea6b3ca9ec98ae3bc9870c67f5958beb8 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:23:15 +0100 Subject: [PATCH 58/64] fix: preserve wide IDs in schematic files and downloads --- dependencies.gradle | 2 + .../schematica/FileFilterSchematic.java | 66 ++- .../api/event/PreSchematicSaveEvent.java | 8 +- .../client/gui/load/GuiSchematicLoadSlot.java | 3 +- .../client/gui/save/GuiSchematicSave.java | 8 +- .../client/world/SchematicWorld.java | 8 +- .../command/CommandSchematicaDownload.java | 17 +- .../command/CommandSchematicaRemove.java | 9 +- .../handler/ConfigurationHandler.java | 2 + .../schematica/handler/DownloadHandler.java | 13 +- .../network/message/MessageCapabilities.java | 6 + .../network/message/MessageDownloadBegin.java | 33 +- .../message/MessageDownloadBeginAck.java | 16 +- .../network/message/MessageDownloadChunk.java | 81 +-- .../network/transfer/SchematicTransfer.java | 23 +- .../schematica/proxy/ClientProxy.java | 3 + .../lunatrius/schematica/reference/Names.java | 5 +- .../world/schematic/BlockIdCodec.java | 177 ++++++ .../world/schematic/SchematicAlpha.java | 507 +++++++----------- .../world/schematic/SchematicFormat.java | 5 + .../schematica/world/storage/Schematic.java | 8 +- .../assets/schematica/lang/en_US.lang | 3 +- .../world/schematic/BlockIdCodecTest.java | 117 ++++ .../world/schematic/SchematicAlphaTest.java | 179 +++++++ 24 files changed, 821 insertions(+), 478 deletions(-) create mode 100644 src/main/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodec.java create mode 100644 src/test/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodecTest.java create mode 100644 src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java diff --git a/dependencies.gradle b/dependencies.gradle index 439405b3..604b25d6 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -23,4 +23,6 @@ dependencies { runtimeOnlyNonPublishable('ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.65-GTNH:dev') { transitive = false } runtimeOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.11.48:dev') { transitive = false } runtimeOnlyNonPublishable('io.github.legacymoddingmc:unimixins:0.3.1:dev') { transitive = false } + + testImplementation('junit:junit:4.13.2') } diff --git a/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java b/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java index 04db84c3..3ef18c9f 100644 --- a/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java +++ b/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java @@ -2,11 +2,15 @@ import java.io.File; import java.io.FileFilter; +import java.util.Locale; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.util.FileUtils; public class FileFilterSchematic implements FileFilter { + public static final String EXTENSION_SCHEMATIC = ".schematic"; + public static final String EXTENSION_SCHEMPLUS = ".schemplus"; + private final boolean directory; public FileFilterSchematic(boolean dir) { @@ -18,14 +22,58 @@ public boolean accept(File file) { if (this.directory) { return file.isDirectory(); } - if (ConfigurationHandler.useSchematicplusFormat) { - return file.getName() - .toLowerCase() - .endsWith(".schemplus"); - } else { - return file.getName() - .toLowerCase() - .endsWith(".schematic"); + return isSchematicName(file.getName()); + } + + public static boolean isSchematicName(String name) { + String lower = name.toLowerCase(Locale.ROOT); + return lower.endsWith(EXTENSION_SCHEMATIC) || lower.endsWith(EXTENSION_SCHEMPLUS); + } + + public static boolean isSchemplusName(String name) { + return name.toLowerCase(Locale.ROOT) + .endsWith(EXTENSION_SCHEMPLUS); + } + + public static String stripExtension(String filename) { + if (filename == null) { + return null; + } + String lower = filename.toLowerCase(Locale.ROOT); + if (lower.endsWith(EXTENSION_SCHEMPLUS)) { + return filename.substring(0, filename.length() - EXTENSION_SCHEMPLUS.length()); + } + if (lower.endsWith(EXTENSION_SCHEMATIC)) { + return filename.substring(0, filename.length() - EXTENSION_SCHEMATIC.length()); + } + return filename; + } + + /** + * Finds {@code name}, {@code name.schematic}, or {@code name.schemplus} inside {@code directory}. + * A bare name prefers {@code .schematic} when both files exist. + */ + public static File resolve(File directory, String name) { + if (directory == null || name == null || name.isEmpty()) { + return null; + } + + File direct = new File(directory, name); + if (isSchematicName(name) && FileUtils.contains(directory, direct) && direct.isFile()) { + return direct; + } + if (isSchematicName(name)) { + return null; + } + + File schematic = new File(directory, name + EXTENSION_SCHEMATIC); + if (FileUtils.contains(directory, schematic) && schematic.isFile()) { + return schematic; + } + File schemplus = new File(directory, name + EXTENSION_SCHEMPLUS); + if (FileUtils.contains(directory, schemplus) && schemplus.isFile()) { + return schemplus; } + return null; } } diff --git a/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java b/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java index 8ea10b00..2184c398 100644 --- a/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java +++ b/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java @@ -14,7 +14,7 @@ */ public class PreSchematicSaveEvent extends Event { - private final Map mappings; + private final Map mappings; /** * The schematic that will be saved. @@ -27,11 +27,11 @@ public class PreSchematicSaveEvent extends Event { public final NBTTagCompound extendedMetadata; @Deprecated - public PreSchematicSaveEvent(Map mappings) { + public PreSchematicSaveEvent(Map mappings) { this(null, mappings); } - public PreSchematicSaveEvent(ISchematic schematic, Map mappings) { + public PreSchematicSaveEvent(ISchematic schematic, Map mappings) { this.schematic = schematic; this.mappings = mappings; this.extendedMetadata = new NBTTagCompound(); @@ -59,7 +59,7 @@ public boolean replaceMapping(String oldName, String newName) throws DuplicateMa newName)); } - Short id = this.mappings.get(oldName); + Integer id = this.mappings.get(oldName); if (id != null) { this.mappings.remove(oldName); this.mappings.put(newName, id); diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java b/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java index a51185fd..462bc81f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java @@ -4,6 +4,7 @@ import net.minecraft.client.gui.GuiSlot; import net.minecraft.client.renderer.Tessellator; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.client.gui.GuiHelper; public class GuiSchematicLoadSlot extends GuiSlot { @@ -64,7 +65,7 @@ protected void drawSlot(int index, int x, int y, int par4, Tessellator tessellat if (schematic.isDirectory()) { schematicName += "/"; } else { - schematicName = schematicName.replaceAll("(?i)\\.schematic$", ""); + schematicName = FileFilterSchematic.stripExtension(schematicName); } GuiHelper diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java b/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java index 2b4c513c..7af640de 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java @@ -8,6 +8,7 @@ import com.github.lunatrius.core.client.gui.GuiNumericField; import com.github.lunatrius.core.client.gui.GuiScreenBase; import com.github.lunatrius.core.util.vector.Vector3i; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; @@ -168,12 +169,7 @@ protected void actionPerformed(GuiButton guiButton) { this.btnEnable.displayString = ClientProxy.isRenderingGuide ? this.strOn : this.strOff; this.btnSave.enabled = ClientProxy.isRenderingGuide; } else if (guiButton.id == this.btnSave.id) { - String path; - if (ConfigurationHandler.useSchematicplusFormat) { - path = this.tfFilename.getText() + ".schemplus"; - } else { - path = this.tfFilename.getText() + ".schematic"; - } + String path = this.tfFilename.getText() + FileFilterSchematic.EXTENSION_SCHEMATIC; if (Schematica.proxy.saveSchematic( this.mc.thePlayer, ConfigurationHandler.schematicDirectory, diff --git a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index 991548ae..6f0ff99f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -20,9 +20,9 @@ import com.github.lunatrius.core.util.vector.Vector3f; import com.github.lunatrius.core.util.vector.Vector3i; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.world.chunk.ChunkProviderSchematic; @@ -73,11 +73,7 @@ public SchematicWorld(ISchematic schematic) { public SchematicWorld(ISchematic schematic, String filename) { this(schematic); - if (ConfigurationHandler.useSchematicplusFormat) { - this.name = filename.replace(".schemplus", ""); - } else { - this.name = filename.replace(".schematic", ""); - } + this.name = FileFilterSchematic.stripExtension(filename); } @Override diff --git a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java index 5c223fd6..b2f8f872 100644 --- a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java +++ b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java @@ -16,11 +16,9 @@ import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.api.ISchematic; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.handler.DownloadHandler; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; -import com.github.lunatrius.schematica.util.FileUtils; import com.github.lunatrius.schematica.world.schematic.SchematicFormat; public class CommandSchematicaDownload extends CommandSchematicaBase { @@ -69,20 +67,15 @@ public void processCommand(ICommandSender sender, String[] args) { throw new CommandException(Names.Command.Download.Message.PLAYERS_ONLY); } - final String filename; - if (ConfigurationHandler.useSchematicplusFormat) { - filename = args[0] + ".schemplus"; - } else { - filename = args[0] + ".schematic"; - } - final File directory = Schematica.proxy.getPlayerSchematicDirectory(player, true); - if (!FileUtils.contains(directory, filename)) { - Reference.logger.error("{} has tried to download the file {}", player.getDisplayName(), filename); + final File schematicFile = FileFilterSchematic.resolve(directory, args[0]); + if (schematicFile == null) { + Reference.logger.error("{} has tried to download the file {}", player.getDisplayName(), args[0]); throw new CommandException(Names.Command.Download.Message.DOWNLOAD_FAILED); } - final ISchematic schematic = SchematicFormat.readFromFile(directory, filename); + final String filename = schematicFile.getName(); + final ISchematic schematic = SchematicFormat.readFromFile(schematicFile); if (schematic != null) { DownloadHandler.INSTANCE.startDownload(player, schematic, filename); diff --git a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java index e8dd49de..d3c2d0d2 100644 --- a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java +++ b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java @@ -14,10 +14,10 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; -import com.github.lunatrius.schematica.util.FileUtils; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; @@ -67,11 +67,10 @@ public void processCommand(ICommandSender sender, String[] arguments) { } } - String filename = String.format("%s.schematic", name); File schematicDirectory = Schematica.proxy.getPlayerSchematicDirectory(player, true); - File file = new File(schematicDirectory, filename); - if (!FileUtils.contains(schematicDirectory, file)) { - Reference.logger.error("{} has tried to download the file {}", player.getDisplayName(), filename); + File file = FileFilterSchematic.resolve(schematicDirectory, name); + if (file == null) { + Reference.logger.error("{} has tried to remove the file {}", player.getDisplayName(), name); throw new CommandException(Names.Command.Remove.Message.SCHEMATIC_NOT_FOUND); } diff --git a/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java index 1d16f873..80263242 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java @@ -58,6 +58,7 @@ public class ConfigurationHandler { public static final boolean SERVERSIDE_SCHEMATICS_ENABLED_DEFAULT = true; public static boolean showDebugInfo = SHOW_DEBUG_INFO_DEFAULT; + /** Loaded for old configs. Saving and loading no longer branch on this flag. */ public static boolean useSchematicplusFormat = EXTENDED_ID_FORMAT_DEFAULT; public static boolean enableAlpha = ENABLE_ALPHA_DEFAULT; public static float alpha = (float) ALPHA_DEFAULT; @@ -293,6 +294,7 @@ public static void loadConfiguration() { EXTENDED_ID_FORMAT_DEFAULT, Names.Config.EXTENDED_ID_FORMAT_DESC); propUseSchematicplusFormat.setLanguageKey(Names.Config.LANG_PREFIX + "." + Names.Config.EXTENDED_ID_FORMAT); + propUseSchematicplusFormat.setShowInGui(false); useSchematicplusFormat = propUseSchematicplusFormat.getBoolean(EXTENDED_ID_FORMAT_DEFAULT); propSortType = configuration diff --git a/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java index 16281c55..108486d4 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java @@ -22,9 +22,12 @@ public class DownloadHandler { + public static final int PROTOCOL_VERSION = 2; public static final DownloadHandler INSTANCE = new DownloadHandler(); - public ISchematic schematic = null; + // Version advertised by the connected server via MessageCapabilities. + public int serverProtocolVersion; + public ISchematic schematic; private final Map transferMap = new LinkedHashMap<>(); @@ -50,10 +53,10 @@ public synchronized void cancelDownload(EntityPlayerMP player) { this.transferMap.remove(player); } - public synchronized void confirmBegin(EntityPlayerMP player, boolean supportsExtendedBlockData) { + public synchronized void confirmBegin(EntityPlayerMP player, int protocolVersion) { final SchematicTransfer transfer = this.transferMap.get(player); if (transfer != null && transfer.state == SchematicTransfer.State.BEGIN) { - transfer.supportsExtendedBlockData = supportsExtendedBlockData; + transfer.clientProtocolVersion = protocolVersion; transfer.setState(SchematicTransfer.State.CHUNK_WAIT); } } @@ -102,7 +105,7 @@ private synchronized void processQueue() { transfer.setState(SchematicTransfer.State.BEGIN); sendBegin(player, transfer); } else if (transfer.state == SchematicTransfer.State.CHUNK_WAIT) { - if (transfer.requiresExtendedBlockData && !transfer.supportsExtendedBlockData) { + if (transfer.clientProtocolVersion != PROTOCOL_VERSION) { // Translate on the server because old clients do not have this key. player.addChatMessage( new ChatComponentText( @@ -121,7 +124,7 @@ private synchronized void processQueue() { } private void sendBegin(EntityPlayerMP player, SchematicTransfer transfer) { - MessageDownloadBegin message = new MessageDownloadBegin(transfer.schematic, transfer.requiresExtendedBlockData); + MessageDownloadBegin message = new MessageDownloadBegin(transfer.schematic); PacketHandler.INSTANCE.sendTo(message, player); } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java index 08797ce6..d1c47ca9 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java @@ -2,6 +2,7 @@ import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.client.printer.SchematicPrinter; +import com.github.lunatrius.schematica.handler.DownloadHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; import com.github.lunatrius.schematica.reference.Reference; @@ -15,6 +16,7 @@ public class MessageCapabilities implements IMessage, IMessageHandler minecraft.ingameGUI.getChatGUI() + .printChatMessageWithOptionalDeletion( + new ChatComponentTranslation(messageKey), + messageKey.hashCode())); + return null; + } - return new MessageDownloadBeginAck(true); + DownloadHandler.INSTANCE.schematic = new Schematic(message.icon, message.width, message.height, message.length); + return new MessageDownloadBeginAck(DownloadHandler.PROTOCOL_VERSION); } } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java index c8f04d6c..f6b0f956 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java @@ -11,31 +11,29 @@ public class MessageDownloadBeginAck implements IMessage, IMessageHandler { - private boolean supportsExtendedBlockData; + private int protocolVersion; public MessageDownloadBeginAck() {} - MessageDownloadBeginAck(boolean supportsExtendedBlockData) { - this.supportsExtendedBlockData = supportsExtendedBlockData; + MessageDownloadBeginAck(int protocolVersion) { + this.protocolVersion = protocolVersion; } @Override public void fromBytes(ByteBuf buf) { - // Older clients acknowledge with an empty payload. - this.supportsExtendedBlockData = buf.readableBytes() == 1 && buf.readUnsignedByte() == 1; + // The original acknowledgment has no payload. + this.protocolVersion = buf.readableBytes() == 1 ? buf.readUnsignedByte() : 0; } @Override public void toBytes(ByteBuf buf) { - if (this.supportsExtendedBlockData) { - buf.writeByte(1); - } + buf.writeByte(this.protocolVersion); } @Override public IMessage onMessage(MessageDownloadBeginAck message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; - DownloadHandler.INSTANCE.confirmBegin(player, message.supportsExtendedBlockData); + DownloadHandler.INSTANCE.confirmBegin(player, message.protocolVersion); return null; } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java index 0233b9f5..833f671e 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java @@ -31,11 +31,10 @@ public class MessageDownloadChunk implements IMessage, IMessageHandler tileEntities; - public List entities; + private final int[] blockIds = new int[CELL_COUNT]; + private final char[] metadata = new char[CELL_COUNT]; + private List tileEntities = new ArrayList<>(); + private List entities = new ArrayList<>(); public MessageDownloadChunk() {} @@ -44,27 +43,13 @@ public MessageDownloadChunk(ISchematic schematic, int baseX, int baseY, int base this.baseY = baseY; this.baseZ = baseZ; - this.blocks = new short[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.metadata = new byte[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.tileEntities = new ArrayList<>(); - this.entities = new ArrayList<>(); - int index = 0; for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++, index++) { final Block block = schematic.getBlock(baseX + x, baseY + y, baseZ + z); - final int id = BLOCK_REGISTRY.getId(block); - this.blocks[x][y][z] = (short) id; - final int metadata = schematic.getBlockMetadata(baseX + x, baseY + y, baseZ + z); - this.metadata[x][y][z] = (byte) metadata; - final byte high = (byte) (metadata >>> 8); - if (high != 0) { - if (this.highMetadata == null) { - this.highMetadata = new byte[CELL_COUNT]; - } - this.highMetadata[index] = high; - } + this.blockIds[index] = BLOCK_REGISTRY.getId(block); + this.metadata[index] = (char) schematic.getBlockMetadata(baseX + x, baseY + y, baseZ + z); final TileEntity tileEntity = schematic.getTileEntity(baseX + x, baseY + y, baseZ + z); if (tileEntity != null) { this.tileEntities.add(tileEntity); @@ -79,13 +64,8 @@ private void copyToSchematic(final ISchematic schematic) { for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++, index++) { - final Block block = BLOCK_REGISTRY.getObjectById(this.blocks[x][y][z] & 0xffff); - int meta = this.metadata[x][y][z] & 0xff; - if (this.highMetadata != null) { - meta |= (this.highMetadata[index] & 0xff) << 8; - } - - schematic.setBlock(this.baseX + x, this.baseY + y, this.baseZ + z, block, meta); + final Block block = BLOCK_REGISTRY.getObjectById(this.blockIds[index]); + schematic.setBlock(this.baseX + x, this.baseY + y, this.baseZ + z, block, this.metadata[index]); } } } @@ -101,18 +81,9 @@ public void fromBytes(ByteBuf buf) { this.baseY = buf.readShort(); this.baseZ = buf.readShort(); - this.blocks = new short[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.metadata = new byte[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.tileEntities = new ArrayList<>(); - this.entities = new ArrayList<>(); - - for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { - for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { - this.blocks[x][y][z] = buf.readShort(); - this.metadata[x][y][z] = buf.readByte(); - } - } + for (int index = 0; index < CELL_COUNT; index++) { + this.blockIds[index] = buf.readInt(); + this.metadata[index] = (char) buf.readUnsignedShort(); } final NBTTagCompound compound = ByteBufUtils.readTag(buf); @@ -120,15 +91,6 @@ public void fromBytes(ByteBuf buf) { final NBTTagCompound compound2 = ByteBufUtils.readTag(buf); this.entities = NBTHelper.readEntitiesFromCompound(compound2, this.entities); - - this.highMetadata = null; - if (buf.isReadable()) { - if (buf.readableBytes() != CELL_COUNT) { - throw new IllegalArgumentException("Invalid schematic download metadata length"); - } - this.highMetadata = new byte[CELL_COUNT]; - buf.readBytes(this.highMetadata); - } } @Override @@ -137,13 +99,9 @@ public void toBytes(ByteBuf buf) { buf.writeShort(this.baseY); buf.writeShort(this.baseZ); - for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { - for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { - buf.writeShort(this.blocks[x][y][z]); - buf.writeByte(this.metadata[x][y][z]); - } - } + for (int index = 0; index < CELL_COUNT; index++) { + buf.writeInt(this.blockIds[index]); + buf.writeShort(this.metadata[index]); } final NBTTagCompound compound = NBTHelper.writeTileEntitiesToCompound(this.tileEntities); @@ -151,16 +109,15 @@ public void toBytes(ByteBuf buf) { final NBTTagCompound compound1 = NBTHelper.writeEntitiesToCompound(this.entities); ByteBufUtils.writeTag(buf, compound1); - - // Append the high bytes after the original payload, outside NBT's signed-short length limit. - if (this.highMetadata != null) { - buf.writeBytes(this.highMetadata); - } } @Override public IMessage onMessage(MessageDownloadChunk message, MessageContext ctx) { - message.copyToSchematic(DownloadHandler.INSTANCE.schematic); + final ISchematic schematic = DownloadHandler.INSTANCE.schematic; + if (schematic == null) { + return null; + } + message.copyToSchematic(schematic); return new MessageDownloadChunkAck(message.baseX, message.baseY, message.baseZ); } diff --git a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java index 6b7b910a..9db2a449 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java +++ b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java @@ -1,7 +1,5 @@ package com.github.lunatrius.schematica.network.transfer; -import net.minecraft.block.Block; - import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.reference.Constants; @@ -35,12 +33,11 @@ public boolean isWaiting() { public final int width; public final int height; public final int length; - public final boolean requiresExtendedBlockData; public State state = State.BEGIN_WAIT; public int timeout = 0; public int retries = 0; - public boolean supportsExtendedBlockData; + public int clientProtocolVersion; public int baseX = 0; public int baseY = 0; @@ -53,7 +50,6 @@ public SchematicTransfer(final ISchematic schematic, String name) { this.width = schematic.getWidth(); this.height = schematic.getHeight(); this.length = schematic.getLength(); - this.requiresExtendedBlockData = requiresExtendedBlockData(); } public boolean confirmChunk(final int chunkX, final int chunkY, final int chunkZ) { @@ -80,23 +76,6 @@ public boolean confirmChunk(final int chunkX, final int chunkY, final int chunkZ return true; } - private boolean requiresExtendedBlockData() { - for (int x = 0; x < this.width; x++) { - for (int y = 0; y < this.height; y++) { - for (int z = 0; z < this.length; z++) { - final int blockId = Block.getIdFromBlock(this.schematic.getBlock(x, y, z)); - // Legacy clients truncate metadata and standard IDs. Their schemplus writer misencodes 256 - // multiples. - if (this.schematic.getBlockMetadata(x, y, z) > 0xF || blockId > 0xFFF - || (blockId != 0 && (blockId & 0xFF) == 0)) { - return true; - } - } - } - } - return false; - } - public void setState(State state) { this.state = state; this.timeout = 0; diff --git a/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java b/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java index 8087a0ec..7c0f48e2 100644 --- a/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java +++ b/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java @@ -30,6 +30,7 @@ import com.github.lunatrius.schematica.compat.ILOTRPresent; import com.github.lunatrius.schematica.compat.NoLOTRProxy; import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.handler.DownloadHandler; import com.github.lunatrius.schematica.handler.client.ChatEventHandler; import com.github.lunatrius.schematica.handler.client.InputHandler; import com.github.lunatrius.schematica.handler.client.OverlayHandler; @@ -372,6 +373,8 @@ public File getDataDirectory() { @Override public void resetSettings() { super.resetSettings(); + DownloadHandler.INSTANCE.serverProtocolVersion = 0; + DownloadHandler.INSTANCE.schematic = null; ChatEventHandler.INSTANCE.chatLines = 0; diff --git a/src/main/java/com/github/lunatrius/schematica/reference/Names.java b/src/main/java/com/github/lunatrius/schematica/reference/Names.java index 941c3a15..f860cb52 100644 --- a/src/main/java/com/github/lunatrius/schematica/reference/Names.java +++ b/src/main/java/com/github/lunatrius/schematica/reference/Names.java @@ -19,7 +19,7 @@ public static final class Category { public static final String SHOW_DEBUG_INFO = "showDebugInfo"; public static final String SHOW_DEBUG_INFO_DESC = "Display extra information on the debug screen (F3)."; public static final String EXTENDED_ID_FORMAT = "useSchematicplusFormat"; - public static final String EXTENDED_ID_FORMAT_DESC = "Save and load schematics with a different format that supports a much higher number of block ids. Only schematics in schemplus format will be loaded."; + public static final String EXTENDED_ID_FORMAT_DESC = "Unused. Block ids are stored automatically: classic 12-bit data when every id is below 4096, otherwise up to 24 bits. Both .schematic and .schemplus files are loaded."; public static final String ALPHA_ENABLED = "alphaEnabled"; public static final String ALPHA_ENABLED_DESC = "Enable transparent textures."; public static final String ALPHA = "alpha"; @@ -144,6 +144,7 @@ public static final class Message { public static final String DOWNLOAD_STARTED = "schematica.command.download.started"; public static final String DOWNLOAD_SUCCEEDED = "schematica.command.download.downloadSucceeded"; public static final String DOWNLOAD_FAILED = "schematica.command.download.downloadFail"; + public static final String DOWNLOAD_SERVER_REQUIRES_UPDATE = "schematica.command.download.serverRequiresUpdate"; public static final String DOWNLOAD_REQUIRES_UPDATE = "schematica.command.download.requiresUpdate"; } @@ -234,6 +235,8 @@ public static final class NBT { public static final String DATA = "Data"; public static final String DATA_HIGH = "SchematicaDataHigh"; public static final String ADD_BLOCKS = "AddBlocks"; + public static final String ADD_BLOCKS_HIGH = "AddBlocksHigh"; + public static final String BLOCK_ID_BYTES = "BlockIdBytes"; public static final String ADD_BLOCKS_SCHEMATICA = "Add"; public static final String WIDTH = "Width"; public static final String LENGTH = "Length"; diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodec.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodec.java new file mode 100644 index 00000000..bdc3fb8d --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodec.java @@ -0,0 +1,177 @@ +package com.github.lunatrius.schematica.world.schematic; + +/** + * Block ids stored in a schematic, up to 24 bits. + * + *

+ * Classic files keep the low 8 bits in {@code Blocks} and the next 4 bits as nibbles in {@code AddBlocks}. That + * covers ids below 4096. Wider files store a full second byte per block in {@code AddBlocks} and, when any id is above + * 65535, a third byte in {@code AddBlocksHigh}. {@code BlockIdBytes} is 2 or 3 on those files so a one-block schematic + * is not read back as nibbles. + * + *

+ * Older {@code .schemplus} files use the full-byte {@code AddBlocks} layout and have no {@code BlockIdBytes} tag. A + * one-block file of that kind is only recognized when {@code schemplusFile} is true. Ids already saved by the old + * schemplus writer that were divisible by 256 dropped a byte on the way in; those files do not contain the missing + * bits, so loading them gives the value that was actually written. + */ +public final class BlockIdCodec { + + public static final int MAX_SAVED_ID = 0xFFFFFF; + public static final int CLASSIC_MAX_ID = 0xFFF; + public static final int TWO_BYTE_MAX_ID = 0xFFFF; + + private BlockIdCodec() {} + + public static final class Encoded { + + public final byte[] blocks; + public final byte[] addBlocks; + public final byte[] addBlocksHigh; + /** 1 = classic 8/12-bit, 2 = 16-bit, 3 = 24-bit. Classic files omit the tag. */ + public final int blockIdBytes; + + Encoded(byte[] blocks, byte[] addBlocks, byte[] addBlocksHigh, int blockIdBytes) { + this.blocks = blocks; + this.addBlocks = addBlocks; + this.addBlocksHigh = addBlocksHigh; + this.blockIdBytes = blockIdBytes; + } + } + + public static Encoded encode(int[] ids) { + int[] stored = new int[ids.length]; + int max = 0; + for (int i = 0; i < ids.length; i++) { + int id = ids[i]; + if (id < 0) { + id = 0; + } else if (id > MAX_SAVED_ID) { + id &= MAX_SAVED_ID; + } + stored[i] = id; + if (id > max) { + max = id; + } + } + + if (max <= CLASSIC_MAX_ID) { + return encodeClassic(stored); + } + return encodeWide(stored, max <= TWO_BYTE_MAX_ID ? 2 : 3); + } + + /** + * @param blockIdBytes value of the {@code BlockIdBytes} tag, or 0 when the tag is absent + * @param schemplusFile true when the file name ends in {@code .schemplus} + */ + public static int[] decode(byte[] blocks, byte[] addBlocks, byte[] legacyAdd, byte[] addHigh, int blockIdBytes, + boolean schemplusFile) { + if (blocks == null) { + throw new IllegalArgumentException("Blocks array is missing"); + } + int count = blocks.length; + if (count == 0) { + return new int[0]; + } + if (addHigh != null || blockIdBytes >= 3) { + return combine(blocks, addBlocks, addHigh); + } + if (blockIdBytes == 2) { + return combine(blocks, addBlocks != null ? addBlocks : legacyAdd, null); + } + if (blockIdBytes == 1) { + return addBlocks == null ? lowByte(blocks) : decodeNibbles(blocks, addBlocks); + } + // The former compatibility branch wrote Add alongside a packed preview in AddBlocks. + if (legacyAdd != null) { + return combine(blocks, legacyAdd, null); + } + if (addBlocks == null) { + return lowByte(blocks); + } + if (addBlocks.length == count && (count != 1 || schemplusFile)) { + return combine(blocks, addBlocks, null); + } + return decodeNibbles(blocks, addBlocks); + } + + private static Encoded encodeClassic(int[] ids) { + byte[] blocks = new byte[ids.length]; + boolean extra = false; + byte[] nibbles = new byte[ids.length]; + for (int i = 0; i < ids.length; i++) { + blocks[i] = (byte) ids[i]; + int high = (ids[i] >> 8) & 0xF; + nibbles[i] = (byte) high; + if (high != 0) { + extra = true; + } + } + if (!extra) { + return new Encoded(blocks, null, null, 1); + } + + byte[] packed = new byte[(ids.length + 1) / 2]; + for (int i = 0; i < packed.length; i++) { + int even = nibbles[i * 2] & 0xF; + int odd = (i * 2 + 1 < nibbles.length) ? (nibbles[i * 2 + 1] & 0xF) : 0; + packed[i] = (byte) ((even << 4) | odd); + } + return new Encoded(blocks, packed, null, 1); + } + + private static Encoded encodeWide(int[] ids, int blockIdBytes) { + byte[] blocks = new byte[ids.length]; + byte[] addBlocks = new byte[ids.length]; + byte[] addHigh = blockIdBytes == 3 ? new byte[ids.length] : null; + for (int i = 0; i < ids.length; i++) { + blocks[i] = (byte) ids[i]; + addBlocks[i] = (byte) (ids[i] >> 8); + if (addHigh != null) { + addHigh[i] = (byte) (ids[i] >> 16); + } + } + return new Encoded(blocks, addBlocks, addHigh, blockIdBytes); + } + + private static int[] lowByte(byte[] blocks) { + int[] ids = new int[blocks.length]; + for (int i = 0; i < blocks.length; i++) { + ids[i] = blocks[i] & 0xFF; + } + return ids; + } + + private static int[] decodeNibbles(byte[] blocks, byte[] packed) { + int[] ids = new int[blocks.length]; + for (int i = 0; i < blocks.length; i++) { + int packedIndex = i >>> 1; + int high = 0; + if (packedIndex < packed.length) { + int value = packed[packedIndex] & 0xFF; + high = (i & 1) == 0 ? (value >> 4) & 0xF : value & 0xF; + } + ids[i] = (blocks[i] & 0xFF) | (high << 8); + } + return ids; + } + + private static int[] combine(byte[] blocks, byte[] mid, byte[] high) { + if (mid == null || mid.length < blocks.length) { + throw new IllegalArgumentException("AddBlocks does not cover every block"); + } + if (high != null && high.length < blocks.length) { + throw new IllegalArgumentException("AddBlocksHigh does not cover every block"); + } + int[] ids = new int[blocks.length]; + for (int i = 0; i < blocks.length; i++) { + int id = (blocks[i] & 0xFF) | ((mid[i] & 0xFF) << 8); + if (high != null) { + id |= (high[i] & 0xFF) << 16; + } + ids[i] = id; + } + return ids; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java index 6f455473..ee5a89ac 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java @@ -3,14 +3,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagShort; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; @@ -18,7 +19,6 @@ import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.api.event.PreSchematicSaveEvent; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.nbt.CarpentersBlocksNBT; import com.github.lunatrius.schematica.nbt.LegacyGregTechOre; import com.github.lunatrius.schematica.nbt.NBTHelper; @@ -36,116 +36,56 @@ public class SchematicAlpha extends SchematicFormat { @Override public ISchematic readFromNBT(NBTTagCompound tagCompound) { - if (ConfigurationHandler.useSchematicplusFormat) { - ItemStack icon = SchematicUtil.getIconFromNBT(tagCompound); - - byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); - byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); - byte[] highMetadata = readHighMetadata(tagCompound, localMetadata.length); - byte[] extraBlocks = tagCompound.getByteArray(Names.NBT.ADD_BLOCKS); - if (extraBlocks.length != localBlocks.length) { - throw new IllegalArgumentException("Invalid schemplus AddBlocks length"); - } - - short width = tagCompound.getShort(Names.NBT.WIDTH); - short length = tagCompound.getShort(Names.NBT.LENGTH); - short height = tagCompound.getShort(Names.NBT.HEIGHT); - - Integer id; - Map oldToNew = new HashMap<>(); - if (tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { - NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); - Set names = mapping.func_150296_c(); - for (String name : names) { - oldToNew.put(mapping.getShort(name), BLOCK_REGISTRY.getId(name)); - } - } - - ISchematic schematic = new Schematic(icon, width, height, length); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - for (int z = 0; z < length; z++) { - int index = x + (y * length + z) * width; - int blockID = (localBlocks[index] & 0xFF) | ((extraBlocks[index] & 0xFF) << 8); - int meta = localMetadata[index] & 0xFF; - if (highMetadata != null) { - meta |= (highMetadata[index] & 0xFF) << 8; - } + return readFromNBT(tagCompound, false); + } - if ((id = oldToNew.get((short) blockID)) != null) { - blockID = id; - } + public ISchematic readFromNBT(NBTTagCompound tagCompound, boolean schemplusFile) { + ItemStack icon = SchematicUtil.getIconFromNBT(tagCompound); + + byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); + byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); + byte[] addBlocks = byteArrayOrNull(tagCompound, Names.NBT.ADD_BLOCKS); + byte[] legacyAdd = byteArrayOrNull(tagCompound, Names.NBT.ADD_BLOCKS_SCHEMATICA); + byte[] addBlocksHigh = byteArrayOrNull(tagCompound, Names.NBT.ADD_BLOCKS_HIGH); + int blockIdBytes = tagCompound.hasKey(Names.NBT.BLOCK_ID_BYTES) + ? tagCompound.getByte(Names.NBT.BLOCK_ID_BYTES) & 0xFF + : 0; + + int width = tagCompound.getShort(Names.NBT.WIDTH); + int length = tagCompound.getShort(Names.NBT.LENGTH); + int height = tagCompound.getShort(Names.NBT.HEIGHT); + int size = width * length * height; + if (localBlocks.length < size || localMetadata.length < size) { + throw new IllegalArgumentException( + "Schematic block arrays have " + localBlocks.length + " entries, expected at least " + size); + } - schematic.setBlock(x, y, z, BLOCK_REGISTRY.getObjectById(blockID), meta); + byte[] highMetadata = readHighMetadata(tagCompound, localMetadata.length); + int[] blockIds = BlockIdCodec + .decode(localBlocks, addBlocks, legacyAdd, addBlocksHigh, blockIdBytes, schemplusFile); + Map oldToNew = readMapping(tagCompound); + + ISchematic schematic = new Schematic(icon, width, height, length); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + for (int z = 0; z < length; z++) { + int index = index(x, y, z, width, length); + int blockId = blockIds[index]; + Integer mapped = oldToNew.get(blockId); + if (mapped != null) { + blockId = mapped; } - } - } - - loadTiles(tagCompound, schematic); - - return schematic; - } else { - ItemStack icon = SchematicUtil.getIconFromNBT(tagCompound); - - byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); - byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); - byte[] highMetadata = readHighMetadata(tagCompound, localMetadata.length); - - boolean extra = false; - byte[] extraBlocks = null; - byte[] extraBlocksNibble; - if (tagCompound.hasKey(Names.NBT.ADD_BLOCKS)) { - extra = true; - extraBlocksNibble = tagCompound.getByteArray(Names.NBT.ADD_BLOCKS); - extraBlocks = new byte[extraBlocksNibble.length * 2]; - for (int i = 0; i < extraBlocksNibble.length; i++) { - extraBlocks[i * 2 + 0] = (byte) ((extraBlocksNibble[i] >> 4) & 0xF); - extraBlocks[i * 2 + 1] = (byte) (extraBlocksNibble[i] & 0xF); - } - } else if (tagCompound.hasKey(Names.NBT.ADD_BLOCKS_SCHEMATICA)) { - extra = true; - extraBlocks = tagCompound.getByteArray(Names.NBT.ADD_BLOCKS_SCHEMATICA); - } - - short width = tagCompound.getShort(Names.NBT.WIDTH); - short length = tagCompound.getShort(Names.NBT.LENGTH); - short height = tagCompound.getShort(Names.NBT.HEIGHT); - - Integer id; - Map oldToNew = new HashMap<>(); - if (tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { - NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); - Set names = mapping.func_150296_c(); - for (String name : names) { - oldToNew.put(mapping.getShort(name), BLOCK_REGISTRY.getId(name)); - } - } - - ISchematic schematic = new Schematic(icon, width, height, length); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - for (int z = 0; z < length; z++) { - int index = x + (y * length + z) * width; - int blockID = (localBlocks[index] & 0xFF) | (extra ? ((extraBlocks[index] & 0xFF) << 8) : 0); - int meta = localMetadata[index] & 0xFF; - if (highMetadata != null) { - meta |= (highMetadata[index] & 0xFF) << 8; - } - - if ((id = oldToNew.get((short) blockID)) != null) { - blockID = id; - } - - schematic.setBlock(x, y, z, BLOCK_REGISTRY.getObjectById(blockID), meta); + int meta = localMetadata[index] & 0xFF; + if (highMetadata != null) { + meta |= (highMetadata[index] & 0xFF) << 8; } + schematic.setBlock(x, y, z, BLOCK_REGISTRY.getObjectById(blockId), meta); } } - - loadTiles(tagCompound, schematic); - - return schematic; } + loadTiles(tagCompound, schematic); + return schematic; } private static byte[] readHighMetadata(NBTTagCompound tag, int length) { @@ -162,7 +102,7 @@ private static byte[] readHighMetadata(NBTTagCompound tag, int length) { return metadata; } - private void loadTiles(NBTTagCompound tagCompound, ISchematic schematic) { + private static void loadTiles(NBTTagCompound tagCompound, ISchematic schematic) { final NBTTagList tiles = tagCompound.getTagList(Names.NBT.TILE_ENTITIES, Constants.NBT.TAG_COMPOUND); for (int i = 0; i < tiles.tagCount(); i++) { final NBTTagCompound tag = tiles.getCompoundTagAt(i); @@ -190,245 +130,174 @@ private void loadTiles(NBTTagCompound tagCompound, ISchematic schematic) { @Override public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, World backupWorld) { - tagCompound.removeTag(Names.NBT.DATA_HIGH); - tagCompound.removeTag(Names.NBT.ADD_BLOCKS); - tagCompound.removeTag(Names.NBT.ADD_BLOCKS_SCHEMATICA); - if (ConfigurationHandler.useSchematicplusFormat) { - NBTTagCompound tagCompoundIcon = new NBTTagCompound(); - ItemStack icon = schematic.getIcon(); - icon.writeToNBT(tagCompoundIcon); - tagCompound.setTag(Names.NBT.ICON, tagCompoundIcon); - - tagCompound.setShort(Names.NBT.WIDTH, (short) schematic.getWidth()); - tagCompound.setShort(Names.NBT.LENGTH, (short) schematic.getLength()); - tagCompound.setShort(Names.NBT.HEIGHT, (short) schematic.getHeight()); - - int size = schematic.getWidth() * schematic.getLength() * schematic.getHeight(); - byte[] localBlocks = new byte[size]; - byte[] localMetadata = new byte[size]; - byte[] highMetadata = null; - byte[] extraBlocks = new byte[size]; - - Map mappings = new HashMap<>(); - for (int x = 0; x < schematic.getWidth(); x++) { - for (int y = 0; y < schematic.getHeight(); y++) { - for (int z = 0; z < schematic.getLength(); z++) { - final int index = x + (y * schematic.getLength() + z) * schematic.getWidth(); - final Block block = schematic.getBlock(x, y, z); - int blockId = BLOCK_REGISTRY.getId(block); - localBlocks[index] = (byte) blockId; - extraBlocks[index] = (byte) (blockId >>> 8); - final int metadata = schematic.getBlockMetadata(x, y, z); - localMetadata[index] = (byte) metadata; - if ((metadata >>> 8) != 0) { - if (highMetadata == null) { - highMetadata = new byte[size]; - } - highMetadata[index] = (byte) (metadata >>> 8); + NBTTagCompound tagCompoundIcon = new NBTTagCompound(); + ItemStack icon = schematic.getIcon(); + icon.writeToNBT(tagCompoundIcon); + tagCompound.setTag(Names.NBT.ICON, tagCompoundIcon); + + int width = schematic.getWidth(); + int length = schematic.getLength(); + int height = schematic.getHeight(); + tagCompound.setShort(Names.NBT.WIDTH, (short) width); + tagCompound.setShort(Names.NBT.LENGTH, (short) length); + tagCompound.setShort(Names.NBT.HEIGHT, (short) height); + + int size = width * length * height; + int[] blockIds = new int[size]; + byte[] localMetadata = new byte[size]; + byte[] highMetadata = null; + Map mappings = new HashMap<>(); + boolean loggedTruncation = false; + + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + for (int z = 0; z < length; z++) { + int index = index(x, y, z, width, length); + Block block = schematic.getBlock(x, y, z); + int rawId = block == null ? -1 : BLOCK_REGISTRY.getId(block); + int blockId = rawId; + if (rawId < 0) { + blockId = 0; + } else if (rawId > BlockIdCodec.MAX_SAVED_ID) { + blockId = rawId & BlockIdCodec.MAX_SAVED_ID; + if (!loggedTruncation) { + Reference.logger.error( + "Block {} has id {}, above the 24-bit schematic limit. The saved id will be truncated.", + BLOCK_REGISTRY.getNameForObject(block), + rawId); + loggedTruncation = true; + } + } + blockIds[index] = blockId; + int metadata = schematic.getBlockMetadata(x, y, z); + localMetadata[index] = (byte) metadata; + if ((metadata >>> 8) != 0) { + if (highMetadata == null) { + highMetadata = new byte[size]; } + highMetadata[index] = (byte) (metadata >>> 8); + } + if (block != null) { String name = BLOCK_REGISTRY.getNameForObject(block); if (!mappings.containsKey(name)) { - mappings.put(name, (short) blockId); + mappings.put(name, blockId); } } } } + } - int count = 20; - NBTTagList tileEntitiesList = new NBTTagList(); - for (TileEntity tileEntity : schematic.getTileEntities()) { - try { - if (!tileEntity.hasWorldObj()) { - tileEntity.setWorldObj(backupWorld); - } - NBTTagCompound tileEntityTagCompound = NBTHelper.writeTileEntityToCompound(tileEntity); - tileEntitiesList.appendTag(tileEntityTagCompound); - } catch (Exception e) { - int pos = tileEntity.xCoord - + (tileEntity.yCoord * schematic.getLength() + tileEntity.zCoord) * schematic.getWidth(); - if (--count > 0) { - Block block = schematic.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - Reference.logger.error( - "Block {}[{}] with TileEntity %s failed to save! Replacing with bedrock...", - block, - block != null ? BLOCK_REGISTRY.getNameForObject(block) : "?", - tileEntity.getClass() - .getName(), - e); - } - localBlocks[pos] = (byte) BLOCK_REGISTRY.getId(Blocks.bedrock); + int count = 20; + NBTTagList tileEntitiesList = new NBTTagList(); + for (TileEntity tileEntity : schematic.getTileEntities()) { + try { + if (!tileEntity.hasWorldObj()) { + tileEntity.setWorldObj(backupWorld); + } + tileEntitiesList.appendTag(NBTHelper.writeTileEntityToCompound(tileEntity)); + } catch (Exception e) { + int pos = index(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, width, length); + if (--count > 0) { + Block block = schematic.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + Reference.logger.error( + "Block {}[{}] with TileEntity %s failed to save! Replacing with bedrock...", + block, + block != null ? BLOCK_REGISTRY.getNameForObject(block) : "?", + tileEntity.getClass() + .getName(), + e); + } + if (pos >= 0 && pos < blockIds.length) { + int bedrockId = BLOCK_REGISTRY.getId(Blocks.bedrock); + blockIds[pos] = bedrockId < 0 ? 0 : bedrockId; localMetadata[pos] = 0; if (highMetadata != null) { highMetadata[pos] = 0; } - extraBlocks[pos] = 0; } } + } - final NBTTagList entityList = new NBTTagList(); - final List entities = schematic.getEntities(); - for (Entity entity : entities) { - try { - final NBTTagCompound entityCompound = NBTHelper.writeEntityToCompound(entity); - if (entityCompound != null) { - entityList.appendTag(entityCompound); - } - } catch (Throwable t) { - Reference.logger.error("Entity {} failed to save, skipping!", entity, t); + NBTTagList entityList = new NBTTagList(); + List entities = schematic.getEntities(); + for (Entity entity : entities) { + try { + NBTTagCompound entityCompound = NBTHelper.writeEntityToCompound(entity); + if (entityCompound != null) { + entityList.appendTag(entityCompound); } + } catch (Throwable t) { + Reference.logger.error("Entity {} failed to save, skipping!", entity, t); } + } - PreSchematicSaveEvent event = new PreSchematicSaveEvent(schematic, mappings); - MinecraftForge.EVENT_BUS.post(event); - - NBTTagCompound nbtMapping = new NBTTagCompound(); - for (Map.Entry entry : mappings.entrySet()) { - nbtMapping.setShort(entry.getKey(), entry.getValue()); - } + PreSchematicSaveEvent event = new PreSchematicSaveEvent(schematic, mappings); + MinecraftForge.EVENT_BUS.post(event); - tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); - tagCompound.setByteArray(Names.NBT.BLOCKS, localBlocks); - tagCompound.setByteArray(Names.NBT.DATA, localMetadata); - if (highMetadata != null) { - tagCompound.setByteArray(Names.NBT.DATA_HIGH, highMetadata); - } - tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, extraBlocks); - tagCompound.setTag(Names.NBT.ENTITIES, entityList); - tagCompound.setTag(Names.NBT.TILE_ENTITIES, tileEntitiesList); - tagCompound.setTag(Names.NBT.MAPPING_SCHEMATICA, nbtMapping); - final NBTTagCompound extendedMetadata = event.extendedMetadata; - if (!extendedMetadata.hasNoTags()) { - tagCompound.setTag(Names.NBT.EXTENDED_METADATA, extendedMetadata); - } - - return true; + BlockIdCodec.Encoded encoded = BlockIdCodec.encode(blockIds); + tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); + tagCompound.setByteArray(Names.NBT.BLOCKS, encoded.blocks); + tagCompound.setByteArray(Names.NBT.DATA, localMetadata); + if (highMetadata != null) { + tagCompound.setByteArray(Names.NBT.DATA_HIGH, highMetadata); } else { - NBTTagCompound tagCompoundIcon = new NBTTagCompound(); - ItemStack icon = schematic.getIcon(); - icon.writeToNBT(tagCompoundIcon); - tagCompound.setTag(Names.NBT.ICON, tagCompoundIcon); - - tagCompound.setShort(Names.NBT.WIDTH, (short) schematic.getWidth()); - tagCompound.setShort(Names.NBT.LENGTH, (short) schematic.getLength()); - tagCompound.setShort(Names.NBT.HEIGHT, (short) schematic.getHeight()); - - int size = schematic.getWidth() * schematic.getLength() * schematic.getHeight(); - byte[] localBlocks = new byte[size]; - byte[] localMetadata = new byte[size]; - byte[] highMetadata = null; - byte[] extraBlocks = new byte[size]; - byte[] extraBlocksNibble = new byte[(int) Math.ceil(size / 2.0)]; - boolean extra = false; - boolean extendedIds = false; - - Map mappings = new HashMap<>(); - for (int x = 0; x < schematic.getWidth(); x++) { - for (int y = 0; y < schematic.getHeight(); y++) { - for (int z = 0; z < schematic.getLength(); z++) { - final int index = x + (y * schematic.getLength() + z) * schematic.getWidth(); - final Block block = schematic.getBlock(x, y, z); - final int blockId = BLOCK_REGISTRY.getId(block); - localBlocks[index] = (byte) blockId; - final int metadata = schematic.getBlockMetadata(x, y, z); - localMetadata[index] = (byte) metadata; - if ((metadata >>> 8) != 0) { - if (highMetadata == null) { - highMetadata = new byte[size]; - } - highMetadata[index] = (byte) (metadata >>> 8); - } - extraBlocks[index] = (byte) (blockId >>> 8); - extra |= blockId > 0xFF; - extendedIds |= blockId > 0xFFF; - - String name = BLOCK_REGISTRY.getNameForObject(block); - if (!mappings.containsKey(name)) { - mappings.put(name, (short) blockId); - } - } - } - } - - int count = 20; - NBTTagList tileEntitiesList = new NBTTagList(); - for (TileEntity tileEntity : schematic.getTileEntities()) { - try { - if (!tileEntity.hasWorldObj()) { - tileEntity.setWorldObj(backupWorld); - } - NBTTagCompound tileEntityTagCompound = NBTHelper.writeTileEntityToCompound(tileEntity); - tileEntitiesList.appendTag(tileEntityTagCompound); - } catch (Exception e) { - int pos = tileEntity.xCoord - + (tileEntity.yCoord * schematic.getLength() + tileEntity.zCoord) * schematic.getWidth(); - if (--count > 0) { - Block block = schematic.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - Reference.logger.error( - "Block {}[{}] with TileEntity %s failed to save! Replacing with bedrock...", - block, - block != null ? BLOCK_REGISTRY.getNameForObject(block) : "?", - tileEntity.getClass() - .getName(), - e); - } - localBlocks[pos] = (byte) BLOCK_REGISTRY.getId(Blocks.bedrock); - localMetadata[pos] = 0; - if (highMetadata != null) { - highMetadata[pos] = 0; - } - extraBlocks[pos] = 0; - } - } + tagCompound.removeTag(Names.NBT.DATA_HIGH); + } + tagCompound.removeTag(Names.NBT.ADD_BLOCKS_SCHEMATICA); + tagCompound.removeTag(Names.NBT.BLOCK_ID_BYTES); + tagCompound.removeTag(Names.NBT.ADD_BLOCKS); + tagCompound.removeTag(Names.NBT.ADD_BLOCKS_HIGH); + // A one-cell packed array otherwise looks like a legacy .schemplus high byte. + if (encoded.blockIdBytes > 1 || (size == 1 && encoded.addBlocks != null)) { + tagCompound.setByte(Names.NBT.BLOCK_ID_BYTES, (byte) encoded.blockIdBytes); + } + if (encoded.addBlocks != null) { + tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, encoded.addBlocks); + } + if (encoded.addBlocksHigh != null) { + tagCompound.setByteArray(Names.NBT.ADD_BLOCKS_HIGH, encoded.addBlocksHigh); + } + tagCompound.setTag(Names.NBT.ENTITIES, entityList); + tagCompound.setTag(Names.NBT.TILE_ENTITIES, tileEntitiesList); + tagCompound.setTag(Names.NBT.MAPPING_SCHEMATICA, writeMapping(mappings)); + NBTTagCompound extendedMetadata = event.extendedMetadata; + if (!extendedMetadata.hasNoTags()) { + tagCompound.setTag(Names.NBT.EXTENDED_METADATA, extendedMetadata); + } else { + tagCompound.removeTag(Names.NBT.EXTENDED_METADATA); + } - for (int i = 0; i < extraBlocksNibble.length; i++) { - if (i * 2 + 1 < extraBlocks.length) { - extraBlocksNibble[i] = (byte) ((extraBlocks[i * 2 + 0] << 4) | extraBlocks[i * 2 + 1]); - } else { - extraBlocksNibble[i] = (byte) (extraBlocks[i * 2 + 0] << 4); - } - } + return true; + } - final NBTTagList entityList = new NBTTagList(); - final List entities = schematic.getEntities(); - for (Entity entity : entities) { - try { - final NBTTagCompound entityCompound = NBTHelper.writeEntityToCompound(entity); - if (entityCompound != null) { - entityList.appendTag(entityCompound); - } - } catch (Throwable t) { - Reference.logger.error("Entity {} failed to save, skipping!", entity, t); - } - } + private static Map readMapping(NBTTagCompound tagCompound) { + Map oldToNew = new HashMap<>(); + if (!tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { + return oldToNew; + } - PreSchematicSaveEvent event = new PreSchematicSaveEvent(schematic, mappings); - MinecraftForge.EVENT_BUS.post(event); + NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); + for (String name : mapping.func_150296_c()) { + NBTBase stored = mapping.getTag(name); + int oldId = stored instanceof NBTTagShort ? mapping.getShort(name) & 0xFFFF : mapping.getInteger(name); + oldToNew.put(oldId, BLOCK_REGISTRY.getId(name)); + } + return oldToNew; + } - NBTTagCompound nbtMapping = new NBTTagCompound(); - for (Map.Entry entry : mappings.entrySet()) { - nbtMapping.setShort(entry.getKey(), entry.getValue()); - } + private static NBTTagCompound writeMapping(Map mappings) { + NBTTagCompound nbtMapping = new NBTTagCompound(); + for (Map.Entry entry : mappings.entrySet()) { + nbtMapping.setInteger(entry.getKey(), entry.getValue()); + } + return nbtMapping; + } - tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); - tagCompound.setByteArray(Names.NBT.BLOCKS, localBlocks); - tagCompound.setByteArray(Names.NBT.DATA, localMetadata); - if (highMetadata != null) { - tagCompound.setByteArray(Names.NBT.DATA_HIGH, highMetadata); - } - if (extendedIds) { - tagCompound.setByteArray(Names.NBT.ADD_BLOCKS_SCHEMATICA, extraBlocks); - } else if (extra) { - tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, extraBlocksNibble); - } - tagCompound.setTag(Names.NBT.ENTITIES, entityList); - tagCompound.setTag(Names.NBT.TILE_ENTITIES, tileEntitiesList); - tagCompound.setTag(Names.NBT.MAPPING_SCHEMATICA, nbtMapping); - final NBTTagCompound extendedMetadata = event.extendedMetadata; - if (!extendedMetadata.hasNoTags()) { - tagCompound.setTag(Names.NBT.EXTENDED_METADATA, extendedMetadata); - } + private static byte[] byteArrayOrNull(NBTTagCompound tagCompound, String key) { + return tagCompound.hasKey(key) ? tagCompound.getByteArray(key) : null; + } - return true; - } + private static int index(int x, int y, int z, int width, int length) { + return x + (y * length + z) * width; } } diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java index 1e75cae1..dfd5e701 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java @@ -11,6 +11,7 @@ import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.api.event.PostSchematicCaptureEvent; import com.github.lunatrius.schematica.reference.Names; @@ -35,6 +36,10 @@ public static ISchematic readFromFile(File file) { throw new UnsupportedFormatException(format); } + if (schematicFormat instanceof SchematicAlpha alphaFormat + && FileFilterSchematic.isSchemplusName(file.getName())) { + return alphaFormat.readFromNBT(tagCompound, true); + } return schematicFormat.readFromNBT(tagCompound); } catch (Exception ex) { Reference.logger.error("Failed to read schematic!", ex); diff --git a/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java b/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java index 7705975e..6e6bf1a6 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java +++ b/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java @@ -21,7 +21,7 @@ public class Schematic implements ISchematic { private static final FMLControlledNamespacedRegistry BLOCK_REGISTRY = GameData.getBlockRegistry(); private ItemStack icon; - private final short[][][] blocks; + private final int[][][] blocks; private final char[][][] metadata; private final List tileEntities = new ArrayList<>(); private final List entities = new ArrayList<>(); @@ -31,7 +31,7 @@ public class Schematic implements ISchematic { public Schematic(final ItemStack icon, final int width, final int height, final int length) { this.icon = icon; - this.blocks = new short[width][height][length]; + this.blocks = new int[width][height][length]; this.metadata = new char[width][height][length]; this.width = width; @@ -45,7 +45,7 @@ public Block getBlock(final int x, final int y, final int z) { return Blocks.air; } - return BLOCK_REGISTRY.getObjectById(this.blocks[x][y][z] & 0xffff); + return BLOCK_REGISTRY.getObjectById(this.blocks[x][y][z]); } @Override @@ -64,7 +64,7 @@ public boolean setBlock(final int x, final int y, final int z, final Block block return false; } - this.blocks[x][y][z] = (short) id; + this.blocks[x][y][z] = id; setBlockMetadata(x, y, z, metadata); return true; } diff --git a/src/main/resources/assets/schematica/lang/en_US.lang b/src/main/resources/assets/schematica/lang/en_US.lang index d400b855..132defb5 100644 --- a/src/main/resources/assets/schematica/lang/en_US.lang +++ b/src/main/resources/assets/schematica/lang/en_US.lang @@ -158,4 +158,5 @@ schematica.command.download.usage=/schematicaDownload schematica.command.download.started=Started downloading %s... schematica.command.download.downloadSucceeded=Successfully downloaded %s. schematica.command.download.downloadFail=Download failed. -schematica.command.download.requiresUpdate=Update Schematica to download %s. This schematic contains block data your client cannot preserve. +schematica.command.download.requiresUpdate=Update Schematica to download %s. Your client uses a different download format. +schematica.command.download.serverRequiresUpdate=The server uses a different Schematica download format. Update the server to download schematics. diff --git a/src/test/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodecTest.java b/src/test/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodecTest.java new file mode 100644 index 00000000..2aafac80 --- /dev/null +++ b/src/test/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodecTest.java @@ -0,0 +1,117 @@ +package com.github.lunatrius.schematica.world.schematic; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.github.lunatrius.schematica.world.schematic.BlockIdCodec.Encoded; + +public class BlockIdCodecTest { + + private static final int[] SAMPLE_IDS = { 0, 255, 256, 4095, 4096, 11277, 32767, 32768, 65535, 65536, 16777215 }; + + @Test + public void classicFilesRoundTripWithoutTheWidthTag() { + int[] ids = { 0, 255, 256, 4095 }; + Encoded encoded = BlockIdCodec.encode(ids); + assertEquals(1, encoded.blockIdBytes); + int[] decoded = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, 0, false); + assertArrayEquals(ids, decoded); + } + + @Test + public void roundTripsUpTo24Bits() { + assertRoundTrip(SAMPLE_IDS, 3); + } + + @Test + public void keepsClassicLayoutWhenEveryIdFitsIn12Bits() { + int[] ids = { 0, 255, 256, 512, 4095 }; + Encoded encoded = assertRoundTrip(ids, 1); + assertNull(encoded.addBlocksHigh); + assertEquals(3, encoded.addBlocks.length); + assertEquals(0x00, encoded.blocks[2] & 0xFF); + assertEquals(0x12, encoded.addBlocks[1] & 0xFF); + } + + @Test + public void omitsAddBlocksWhenEveryIdFitsIn8Bits() { + Encoded encoded = assertRoundTrip(new int[] { 0, 1, 255 }, 1); + assertNull(encoded.addBlocks); + assertNull(encoded.addBlocksHigh); + } + + @Test + public void legacyTwelveBitFileDropsBitsAbove4095() { + byte[] blocks = { (byte) 0x0D }; + byte[] addBlocks = { (byte) 0xC0 }; + int[] ids = BlockIdCodec.decode(blocks, addBlocks, null, null, 0, false); + assertArrayEquals(new int[] { 3085 }, ids); + } + + @Test + public void writesTheReportedConcreteIdAsTwoBytes() { + Encoded encoded = assertRoundTrip(new int[] { 11277 }, 2); + assertEquals(0x0D, encoded.blocks[0] & 0xFF); + assertEquals(0x2C, encoded.addBlocks[0] & 0xFF); + assertNull(encoded.addBlocksHigh); + } + + @Test + public void oneBlockExtendedFileIsNotReadAsNibbles() { + Encoded encoded = BlockIdCodec.encode(new int[] { 4096 }); + assertEquals(2, encoded.blockIdBytes); + + int[] withTag = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, encoded.blockIdBytes, false); + assertArrayEquals(new int[] { 4096 }, withTag); + + int[] asClassicNibble = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, 0, false); + assertArrayEquals(new int[] { 256 }, asClassicNibble); + } + + @Test + public void readsLegacySchemplusBytesIncludingASingleBlock() { + byte[] blocks = { (byte) 0x0D }; + byte[] addBlocks = { (byte) 0x2C }; + int[] ids = BlockIdCodec.decode(blocks, addBlocks, null, null, 0, true); + assertArrayEquals(new int[] { 11277 }, ids); + } + + @Test + public void readsTheLegacyFullByteAddKey() { + byte[] blocks = { 0x00 }; + byte[] legacyAdd = { 0x02 }; + int[] ids = BlockIdCodec.decode(blocks, null, legacyAdd, null, 0, false); + assertArrayEquals(new int[] { 512 }, ids); + } + + @Test + public void readsAMultipleOf256ThatTheOldSchemplusWriterTruncated() { + byte[] blocks = { 0x00 }; + byte[] addBlocks = { 0x01 }; + int[] ids = BlockIdCodec.decode(blocks, addBlocks, null, null, 0, true); + assertArrayEquals(new int[] { 256 }, ids); + } + + @Test + public void omitsTheHighByteWhenNoIdNeedsIt() { + Encoded encoded = assertRoundTrip(new int[] { 1, 4096, 65535 }, 2); + assertNull(encoded.addBlocksHigh); + assertEquals(3, encoded.addBlocks.length); + } + + private static Encoded assertRoundTrip(int[] ids, int blockIdBytes) { + Encoded encoded = BlockIdCodec.encode(ids); + assertEquals(blockIdBytes, encoded.blockIdBytes); + int[] decoded = BlockIdCodec + .decode(encoded.blocks, encoded.addBlocks, null, encoded.addBlocksHigh, encoded.blockIdBytes, false); + assertArrayEquals(ids, decoded); + if (encoded.blockIdBytes == 1) { + int[] untagged = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, 0, false); + assertArrayEquals(ids, untagged); + } + return encoded; + } +} diff --git a/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java b/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java new file mode 100644 index 00000000..b0bf85b3 --- /dev/null +++ b/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java @@ -0,0 +1,179 @@ +package com.github.lunatrius.schematica.world.schematic; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.Collections; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.init.Blocks; +import net.minecraft.init.Bootstrap; +import net.minecraft.item.ItemStack; +import net.minecraft.launchwrapper.Launch; +import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraft.nbt.NBTTagCompound; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import com.github.lunatrius.schematica.Schematica; +import com.github.lunatrius.schematica.api.ISchematic; +import com.github.lunatrius.schematica.handler.DownloadHandler; +import com.github.lunatrius.schematica.network.message.MessageCapabilities; +import com.github.lunatrius.schematica.network.message.MessageDownloadBegin; +import com.github.lunatrius.schematica.network.message.MessageDownloadChunk; +import com.github.lunatrius.schematica.proxy.ServerProxy; +import com.github.lunatrius.schematica.reference.Names; +import com.github.lunatrius.schematica.world.storage.Schematic; + +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.network.ByteBufUtils; +import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; +import cpw.mods.fml.common.registry.GameData; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +public class SchematicAlphaTest { + + @Rule + public final TemporaryFolder temp = new TemporaryFolder(); + + @Test + public void legacyFilesAndCurrentDownloadsPreserveWideBlockData() throws Exception { + runFixture("wideBlockData"); + } + + private void runFixture(String name) throws Exception { + // Forge's registry expects to be loaded by LaunchWrapper, including when no game is running. + final String[] entries = System.getProperty("java.class.path") + .split(File.pathSeparator); + final URL[] classpath = new URL[entries.length]; + for (int i = 0; i < entries.length; i++) { + classpath[i] = new File(entries[i]).toURI() + .toURL(); + } + final LaunchClassLoader previous = Launch.classLoader; + try (LaunchClassLoader loader = new LaunchClassLoader(classpath)) { + Launch.classLoader = loader; + loader.loadClass(Fixture.class.getName()) + .getMethod(name, File.class) + .invoke(null, this.temp.getRoot()); + } finally { + Launch.classLoader = previous; + } + } + + public static class Fixture { + + private static void bootstrap(File gameDir) throws ReflectiveOperationException { + Loader.injectData("7", "10", "99", "99", "1.7.10", "9.05", gameDir, Collections.emptyList()); + // Simulate a discovered mod list for compatibility checks in the headless fixture. + final Field namedMods = Loader.class.getDeclaredField("namedMods"); + namedMods.setAccessible(true); + namedMods.set(Loader.instance(), Collections.emptyMap()); + Bootstrap.func_151354_b(); + Schematica.proxy = new ServerProxy() { + + @Override + public File getDataDirectory() { + return gameDir; + } + }; + } + + public static void wideBlockData(File gameDir) throws Exception { + bootstrap(gameDir); + final Method register = FMLControlledNamespacedRegistry.class + .getDeclaredMethod("addObjectRaw", int.class, String.class, Object.class); + register.setAccessible(true); + final int[] ids = { 0x10C, 0xFEBA, 0x20D, 0x1000, 0xFFFF, 0x10006 }; + final int[] metadata = { 3, 0xFF, 0x100, 0xABCD, 0xFFFF, 0xFE01 }; + final Block[] blocks = new Block[ids.length]; + final Schematic source = new Schematic(new ItemStack(Blocks.stone), ids.length, 1, 1); + for (int x = 0; x < ids.length; x++) { + blocks[x] = new Block(Material.rock) {}; + register.invoke(GameData.getBlockRegistry(), ids[x], "fixture:block" + x, blocks[x]); + assertTrue(source.setBlock(x, 0, 0, blocks[x], metadata[x])); + } + final SchematicAlpha format = new SchematicAlpha(); + final NBTTagCompound tags = new NBTTagCompound(); + + assertTrue(format.writeToNBT(tags, source, null)); + assertEquals(3, tags.getByte(Names.NBT.BLOCK_ID_BYTES)); + assertCells(format.readFromNBT(tags), blocks, metadata); + + // Older compatibility builds wrote Add with one high byte per cell and a packed preview. + final NBTTagCompound branchTags = new NBTTagCompound(); + branchTags.setShort(Names.NBT.WIDTH, (short) 2); + branchTags.setShort(Names.NBT.HEIGHT, (short) 1); + branchTags.setShort(Names.NBT.LENGTH, (short) 1); + branchTags.setByteArray(Names.NBT.BLOCKS, new byte[] { 0x0C, (byte) 0xBA }); + branchTags.setByteArray(Names.NBT.ADD_BLOCKS, new byte[] { 0x1E }); + branchTags.setByteArray(Names.NBT.ADD_BLOCKS_SCHEMATICA, new byte[] { 1, (byte) 0xFE }); + branchTags.setByteArray(Names.NBT.DATA, new byte[] { 3, (byte) 0xFF }); + assertCells(format.readFromNBT(branchTags), new Block[] { blocks[0], blocks[1] }, new int[] { 3, 0xFF }); + + final File download = new File(gameDir, "download.schemplus"); + final Schematic single = new Schematic(source.getIcon(), 1, 1, 1); + assertTrue(single.setBlock(0, 0, 0, blocks[0], 3)); + assertTrue(SchematicFormat.writeToFile(download, single, null)); + assertCells(SchematicFormat.readFromFile(download), new Block[] { blocks[0] }, new int[] { 3 }); + + assertTrue(format.writeToNBT(tags, single, null)); + assertEquals(1, tags.getByte(Names.NBT.BLOCK_ID_BYTES)); + assertFalse(tags.hasKey(Names.NBT.DATA_HIGH)); + assertFalse(tags.hasKey(Names.NBT.ADD_BLOCKS_HIGH)); + assertCells(format.readFromNBT(tags, true), new Block[] { blocks[0] }, new int[] { 3 }); + + assertDownloadRoundTrip(source, blocks, metadata); + } + + private static void assertDownloadRoundTrip(Schematic source, Block[] blocks, int[] metadata) throws Exception { + final ByteBuf packet = Unpooled.buffer(); + try { + new MessageCapabilities(true, true, true).toBytes(packet); + packet.skipBytes(3); + assertEquals(DownloadHandler.PROTOCOL_VERSION, packet.readUnsignedByte()); + packet.clear(); + new MessageDownloadBegin(source).toBytes(packet); + final ByteBuf legacyReader = packet.duplicate(); + ByteBufUtils.readItemStack(legacyReader); + assertEquals(0, legacyReader.readShort()); + assertEquals(0, legacyReader.readShort()); + assertEquals(0, legacyReader.readShort()); + final MessageDownloadBegin begin = new MessageDownloadBegin(); + begin.fromBytes(packet); + assertEquals(source.getWidth(), begin.width); + assertFalse(packet.isReadable()); + + packet.clear(); + new MessageDownloadChunk(source, 0, 0, 0).toBytes(packet); + final MessageDownloadChunk chunk = new MessageDownloadChunk(); + chunk.fromBytes(packet); + assertFalse(packet.isReadable()); + final Schematic result = new Schematic(source.getIcon(), begin.width, begin.height, begin.length); + final Method copy = MessageDownloadChunk.class.getDeclaredMethod("copyToSchematic", ISchematic.class); + copy.setAccessible(true); + copy.invoke(chunk, result); + assertCells(result, blocks, metadata); + } finally { + packet.release(); + } + } + + private static void assertCells(ISchematic schematic, Block[] blocks, int[] metadata) { + for (int x = 0; x < blocks.length; x++) { + assertSame(blocks[x], schematic.getBlock(x, 0, 0)); + assertEquals(metadata[x], schematic.getBlockMetadata(x, 0, 0)); + } + } + } +} From fab39950eed108aefda6d139118b412af8dc9464 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:23:31 +0100 Subject: [PATCH 59/64] fix: compare saved skull and banner state --- .../client/printer/SchematicPrinter.java | 5 ++- .../renderer/RendererSchematicChunk.java | 11 +++---- .../schematica/client/util/BlockList.java | 4 +-- .../client/util/BlockToItemStack.java | 22 +++++++++++++ .../world/schematic/SchematicAlphaTest.java | 31 +++++++++++++++++++ 5 files changed, 62 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 9b858738..b5e331f1 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -155,7 +155,6 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { final Block block = this.schematic.getBlock(x, y, z); final Block placedBlock = world.getBlock(worldX, worldY, worldZ); final int metadata = this.schematic.getBlockMetadata(x, y, z); - final int placedMetadata = world.getBlockMetadata(worldX, worldY, worldZ); if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block)) { final TileEntity tile = this.schematic.getTileEntity(x, y, z); @@ -189,8 +188,8 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { } return false; } - if (block == placedBlock && BlockToItemStack.matchesMetadata(block, placedMetadata, metadata) - && BlockToItemStack.matchesPaint(block, world, worldX, worldY, worldZ, this.schematic, x, y, z) + if (block == placedBlock + && BlockToItemStack.matchesSavedState(block, player, world, worldX, worldY, worldZ, this.schematic, x, y, z) && (!architectureShape || ArchitectureCraftSupport.matches(placedArchitectureTile, architectureTile, block))) { return false; diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index 2b75b5c1..e252646d 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -14,7 +14,7 @@ import net.minecraft.profiler.Profiler; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; -import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; import net.minecraftforge.client.ForgeHooksClient; import org.lwjgl.opengl.GL11; @@ -249,7 +249,7 @@ public void render(int renderPass) { } public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - IBlockAccess mcWorld = this.minecraft.theWorld; + World mcWorld = this.minecraft.theWorld; RenderBlocks renderBlocks = RendererSchematicGlobal.INSTANCE.renderBlocks; final boolean renderMicroblocks = renderPass < 2 && Mods.FORGE_MICROBLOCK; @@ -389,14 +389,13 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, this.minecraft.gameSettings.ambientOcclusion = ambientOcclusion; } - private boolean matchesBlockState(Block block, IBlockAccess world, int x, int y, int z, int wx, int wy, int wz) { + private boolean matchesBlockState(Block block, World world, int x, int y, int z, int wx, int wy, int wz) { if (Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block)) { return CarpentersBlocksSupport .matches(block, this.schematic.getTileEntity(x, y, z), world.getTileEntity(wx, wy, wz)); } return BlockToItemStack - .matchesMetadata(block, world.getBlockMetadata(wx, wy, wz), this.schematic.getBlockMetadata(x, y, z)) - && BlockToItemStack.matchesPaint(block, world, wx, wy, wz, this.schematic, x, y, z) + .matchesSavedState(block, this.minecraft.thePlayer, world, wx, wy, wz, this.schematic, x, y, z) && (!Mods.ARCHITECTURE_CRAFT || !ArchitectureCraftSupport.isShapeBlock(block) || ArchitectureCraftSupport .matchesPreview(world.getTileEntity(wx, wy, wz), this.schematic.getTileEntity(x, y, z), block)); @@ -407,7 +406,7 @@ public void renderTileEntities(int renderPass) { return; } - IBlockAccess mcWorld = this.minecraft.theWorld; + World mcWorld = this.minecraft.theWorld; int x, y, z; diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 04f752cf..573612e7 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -81,8 +81,8 @@ public List getList(final EntityPlayer player, final Schematic continue; } - final ItemStack placed = block == mcBlock && (carpenter || BlockToItemStack - .matchesMetadata(block, mcWorld.getBlockMetadata(wx, wy, wz), world.getBlockMetadata(x, y, z))) + final ItemStack placed = block == mcBlock && (carpenter + || BlockToItemStack.matchesSavedState(block, player, mcWorld, wx, wy, wz, world, x, y, z)) ? BlockToItemStack.getItemStack(player, mcBlock, mcWorld, wx, wy, wz) : null; final boolean complete = placed != null && BlockToItemStack.matches(placed, stack) diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 1e48ed1c..c1202701 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -7,6 +7,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; +import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -225,6 +226,27 @@ public static boolean matchesMetadata(Block block, int actual, int saved) { .equals("gregtech.common.blocks.GTBlockOre") && block.damageDropped(actual) == block.damageDropped(saved)); } + /** Compares base placement state once both locations have the same block. */ + public static boolean matchesSavedState(Block block, EntityPlayer player, World world, int x, int y, int z, + World schematic, int localX, int localY, int localZ) { + final int savedMetadata = schematic.getBlockMetadata(localX, localY, localZ); + if (!matchesMetadata(block, world.getBlockMetadata(x, y, z), savedMetadata) + || !matchesPaint(block, world, x, y, z, schematic, localX, localY, localZ)) { + return false; + } + if (block != Blocks.skull && (!block.hasTileEntity(savedMetadata) || !isBannerBlock(block))) { + return true; + } + final ItemStack actual = getItemStack(player, block, world, x, y, z); + final ItemStack expected = getItemStack(player, block, schematic, localX, localY, localZ); + return actual != null && expected != null && matches(actual, expected); + } + + private static boolean isBannerBlock(Block block) { + final Item banner = GameRegistry.findItem("etfuturum", "banner"); + return banner != null && block == Block.getBlockFromItem(banner); + } + public static boolean matchesPaint(Block block, IBlockAccess world, int x, int y, int z, IBlockAccess schematic, int localX, int localY, int localZ) { return !Mods.ENDER_IO || !EnderIOSlabSupport.isPaintedSlab(block) diff --git a/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java b/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java index b0bf85b3..87a0d39c 100644 --- a/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java +++ b/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java @@ -19,6 +19,7 @@ import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntitySkull; import org.junit.Rule; import org.junit.Test; @@ -26,6 +27,8 @@ import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.api.ISchematic; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; +import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.handler.DownloadHandler; import com.github.lunatrius.schematica.network.message.MessageCapabilities; import com.github.lunatrius.schematica.network.message.MessageDownloadBegin; @@ -51,6 +54,11 @@ public void legacyFilesAndCurrentDownloadsPreserveWideBlockData() throws Excepti runFixture("wideBlockData"); } + @Test + public void savedSkullOwnerMattersEvenWhenBlockMetadataMatches() throws Exception { + runFixture("skullOwners"); + } + private void runFixture(String name) throws Exception { // Forge's registry expects to be loaded by LaunchWrapper, including when no game is running. final String[] entries = System.getProperty("java.class.path") @@ -89,6 +97,29 @@ public File getDataDirectory() { }; } + public static void skullOwners(File gameDir) throws ReflectiveOperationException { + bootstrap(gameDir); + final SchematicWorld expected = skullWorld("Builder"); + final SchematicWorld different = skullWorld("Other"); + final SchematicWorld same = skullWorld("builder"); + assertFalse(BlockToItemStack.matchesSavedState(Blocks.skull, null, different, 0, 0, 0, expected, 0, 0, 0)); + assertTrue(BlockToItemStack.matchesSavedState(Blocks.skull, null, same, 0, 0, 0, expected, 0, 0, 0)); + } + + private static SchematicWorld skullWorld(String owner) { + final Schematic schematic = new Schematic(new ItemStack(Blocks.stone), 1, 1, 1); + assertTrue(schematic.setBlock(0, 0, 0, Blocks.skull, 1)); + final TileEntitySkull skull = new TileEntitySkull(); + final NBTTagCompound data = new NBTTagCompound(); + data.setByte("SkullType", (byte) 3); + final NBTTagCompound profile = new NBTTagCompound(); + profile.setString("Name", owner); + data.setTag("Owner", profile); + skull.readFromNBT(data); + schematic.setTileEntity(0, 0, 0, skull); + return new SchematicWorld(schematic); + } + public static void wideBlockData(File gameDir) throws Exception { bootstrap(gameDir); final Method register = FMLControlledNamespacedRegistry.class From 4054d80d60a859a7a909f2b7ea3354ebcbd0d6e9 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:23:33 +0100 Subject: [PATCH 60/64] fix: guard Carpenter's printer interactions --- .../compat/CarpentersBlocksSupport.java | 63 ++++++++++++++----- .../compat/CarpentersHammerSupport.java | 5 +- .../client/printer/CarpentersPrinter.java | 11 ++-- .../client/printer/PrinterInteraction.java | 57 +++++++++++++++-- .../client/printer/SchematicPrinter.java | 35 +++++------ 5 files changed, 125 insertions(+), 46 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java index 88823187..339e12b0 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -14,6 +14,8 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import com.carpentersblocks.api.ICarpentersChisel; +import com.carpentersblocks.api.ICarpentersHammer; import com.carpentersblocks.block.BlockCarpentersBlock; import com.carpentersblocks.block.BlockCarpentersCollapsibleBlock; import com.carpentersblocks.block.BlockCarpentersGarageDoor; @@ -28,8 +30,10 @@ import com.carpentersblocks.data.Slope; import com.carpentersblocks.data.Stairs; import com.carpentersblocks.data.Torch; +import com.carpentersblocks.network.PacketActivateBlock; import com.carpentersblocks.tileentity.TEBase; import com.carpentersblocks.util.BlockProperties; +import com.carpentersblocks.util.handler.PacketHandler; import com.carpentersblocks.util.protection.PlayerPermissions; import com.carpentersblocks.util.registry.FeatureRegistry; import com.github.lunatrius.schematica.client.util.BlockToItemStack; @@ -176,12 +180,24 @@ public static boolean passesThroughMicroblockClick(Block block) { return block instanceof BlockCarpentersBlock || isStairs(block) || isCollapsible(block); } + public static boolean isCarpenterTool(ItemStack stack) { + return stack.getItem() instanceof ICarpentersHammer || stack.getItem() instanceof ICarpentersChisel; + } + + public static boolean usesActivationPacket(ItemStack stack) { + return !(stack.getItem() instanceof ItemBlock) || BlockProperties.isOverlay(stack); + } + + public static void sendActivation(int x, int y, int z, int side) { + PacketHandler.sendPacketToServer(new PacketActivateBlock(x, y, z, side)); + } + public static boolean allowsPlacementClick(Block clicked, ItemStack stack, boolean sneaking) { if (!isCoverable(clicked)) { return true; } if (sneaking) { - return stack.getItem() instanceof ItemBlock && !BlockProperties.isOverlay(stack); + return !usesActivationPacket(stack); } return Mods.FORGE_MICROBLOCK && MicroblockSupport.isMicroblockItem(stack) && passesThroughMicroblockClick(clicked); @@ -272,28 +288,41 @@ public static Float findGarageDoorYaw(Block block, SchematicWorld schematic, Wor return null; } - // A single use creates every panel below the host until the first non-replaceable block. - int panelY = y - 1; - int worldY = wy - 1; - while (worldY >= 0 && world.getBlock(wx, worldY, wz) - .isReplaceable(world, wx, worldY, wz)) { - if (schematic.getBlockIncludingHiddenLayers(x, panelY, z) != block - || !(schematic.getTileEntity(x, panelY, z) instanceof TEBase panel) - || door.isHost(panel) - || door.getDirection(panel) != direction) { + // Native placement fills the replaceable prefix. Every remaining saved panel must already exist. + boolean fillsPanel = true; + for (int panelY = y - 1, worldY = wy - 1;; panelY--, worldY--) { + fillsPanel = fillsPanel && worldY >= 0 + && world.getBlock(wx, worldY, wz) + .isReplaceable(world, wx, worldY, wz); + if (schematic.getBlockIncludingHiddenLayers(x, panelY, z) != block) { + if (fillsPanel) { + return null; + } + break; + } + if (!(schematic.getTileEntity(x, panelY, z) instanceof TEBase savedPanel)) { + return null; + } + if (door.isHost(savedPanel)) { + if (fillsPanel) { + return null; + } + break; + } + if (door.getDirection(savedPanel) != direction + || (!fillsPanel && (worldY < 0 || world.getBlock(wx, worldY, wz) != block + || !isGaragePanel(world.getTileEntity(wx, worldY, wz), direction)))) { return null; } - panelY--; - worldY--; - } - if (schematic.getBlockIncludingHiddenLayers(x, panelY, z) == block && (world.getBlock(wx, worldY, wz) != block - || !(world.getTileEntity(wx, worldY, wz) instanceof TEBase panel) - || door.getDirection(panel) != direction)) { - return null; } return Direction.facingToDirection[direction.ordinal()] * 90.0f; } + private static boolean isGaragePanel(TileEntity tile, ForgeDirection direction) { + return tile instanceof TEBase panel && !GarageDoor.INSTANCE.isHost(panel) + && GarageDoor.INSTANCE.getDirection(panel) == direction; + } + public static boolean matchesStairPlacement(TileEntity tile, Block block, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, float yaw, boolean allowReshape) { if (!(tile instanceof TEBase expected)) { diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java index 315dc3df..8eb79477 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -109,10 +109,11 @@ public final class CarpentersHammerSupport { new BlockSettings(BlockCarpentersButton.class, toggle(BUTTON::getPolarity, Click.MANUAL)), new BlockSettings(BlockCarpentersLever.class, toggle(LEVER::getPolarity, Click.MANUAL)), new BlockSettings(BlockCarpentersCollapsibleBlock.class, toggle(TEBase::getData, Click.MANUAL)), + // An unlock click also enables insertion and extraction. Only compare safe access settings for preview. new BlockSettings( BlockCarpentersSafe.class, - toggle(Safe::isLocked, Click.SNEAK_RIGHT), - cycle(Safe::getAutoPerm, 4)) }; + toggle(Safe::isLocked, Click.MANUAL), + toggle(Safe::getAutoPerm, Click.MANUAL)) }; private CarpentersHammerSupport() {} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java index 43f9eb30..2505b5b1 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -137,10 +137,13 @@ private static boolean useFace(PrinterInteraction interaction, int x, int y, int x + 0.5 + face.offsetX * 0.5, y + 0.5 + face.offsetY * 0.5, z + 0.5 + face.offsetZ * 0.5); - final boolean used = interaction - .withSneaking(sneaking, () -> interaction.useBlock(interaction.player.getHeldItem(), x, y, z, side, hit)); - // Carpenter's Blocks cancels its sneak interaction after dispatching a separate activation packet. - return used || sneaking; + return interaction.withSneaking(sneaking, () -> { + final ItemStack held = interaction.player.getHeldItem(); + if (sneaking && held != null && CarpentersBlocksSupport.usesActivationPacket(held)) { + return interaction.activateCarpenterBlock(held, x, y, z, side); + } + return interaction.useBlock(held, x, y, z, side, hit); + }); } boolean place(PrinterInteraction interaction, SchematicWorld schematic, Block block, int localX, int localY, diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java index eb8f365f..40fa55f1 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -12,6 +12,7 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemSword; import net.minecraft.network.play.client.C03PacketPlayer.C05PacketPlayerLook; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; @@ -205,6 +206,51 @@ boolean useBlockOnServer(ItemStack held, int x, int y, int z, int side, Vec3 hit return true; } + boolean breakBlock(int x, int y, int z) { + if (!this.controller.isInCreativeMode()) { + return false; + } + final int originalSlot = this.inventory.currentItem; + int breakSlot = originalSlot; + if (!canBreakWith(this.inventory.getCurrentItem())) { + for (breakSlot = 0; breakSlot < Constants.Inventory.Size.HOTBAR; breakSlot++) { + if (canBreakWith(this.inventory.getStackInSlot(breakSlot))) { + break; + } + } + if (breakSlot == Constants.Inventory.Size.HOTBAR) { + return false; + } + } + this.inventory.currentItem = breakSlot; + try { + return withSneaking(false, () -> { + this.controller.syncCurrentPlayItem(); + this.controller.clickBlock(x, y, z, ForgeDirection.DOWN.ordinal()); + return true; + }); + } finally { + this.inventory.currentItem = originalSlot; + } + } + + private static boolean canBreakWith(ItemStack held) { + return held == null || (!(held.getItem() instanceof ItemSword) + && (!Mods.CARPENTERS_BLOCKS || !CarpentersBlocksSupport.isCarpenterTool(held))); + } + + boolean activateCarpenterBlock(ItemStack held, int x, int y, int z, int side) { + if (!isStillHolding(held) || !CarpentersBlocksSupport.isCoverable(this.world.getBlock(x, y, z)) + || !CarpentersBlocksSupport.canConfigure(this.world.getTileEntity(x, y, z), this.player)) { + return false; + } + this.controller.syncCurrentPlayItem(); + // Carpenter's activation packet runs a Forge interaction check on the server before changing the tile. + CarpentersBlocksSupport.sendActivation(x, y, z, side); + this.player.swingItem(); + return true; + } + boolean tapBlock(ItemStack held, int x, int y, int z, int side) { if (!isStillHolding(held) || (!this.controller.isInCreativeMode() && this.world.getBlock(x, y, z) .getPlayerRelativeBlockHardness(this.player, this.world, x, y, z) >= 1)) { @@ -238,23 +284,24 @@ private boolean isStillHolding(ItemStack item) { return item != null && item.stackSize > 0 && item == this.player.getHeldItem(); } - void syncSneaking(boolean sneaking) { + private void syncSneaking(boolean sneaking) { this.player.setSneaking(sneaking); this.player.sendQueue.addToSendQueue(new C0BPacketEntityAction(this.player, sneaking ? 1 : 2)); } boolean withSneaking(boolean sneaking, BooleanSupplier action) { final boolean previousInput = this.player.movementInput.sneak; + final boolean wasSneaking = this.player.isSneaking(); this.player.movementInput.sneak = sneaking; - if (!sneaking) { - syncSneaking(false); + if (sneaking != wasSneaking) { + syncSneaking(sneaking); } try { return action.getAsBoolean(); } finally { this.player.movementInput.sneak = previousInput; - if (!sneaking) { - syncSneaking(true); + if (sneaking != wasSneaking) { + syncSneaking(wasSneaking); } } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index b5e331f1..53d0b561 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -106,9 +106,6 @@ public boolean print() { final int minZ = Math.max(0, trans.z - 3); final int maxZ = Math.min(this.schematic.getLength(), trans.z + 4); - final int slot = player.inventory.currentItem; - final boolean wasSneaking = player.isSneaking(); - interaction.syncSneaking(true); try { final boolean isRenderingLayer = this.schematic.isRenderingLayer; final int renderingLayer = this.schematic.renderingLayer; @@ -118,8 +115,13 @@ public boolean print() { } for (int x = minX; x < maxX; x++) { for (int z = minZ; z < maxZ; z++) { - if (printCell(interaction, x, y, z)) { - return true; + final int selectedSlot = player.inventory.currentItem; + try { + if (printCell(interaction, x, y, z)) { + return true; + } + } finally { + player.inventory.currentItem = selectedSlot; } } } @@ -129,9 +131,6 @@ public boolean print() { } catch (Exception e) { Reference.logger.error("Could not place block!", e); return false; - } finally { - player.inventory.currentItem = slot; - interaction.syncSneaking(wasSneaking); } } @@ -217,9 +216,7 @@ && mergeSlab(interaction, worldX, worldY, worldZ, player.getHeldItem())) { } if (ConfigurationHandler.destroyBlocks && !world.isAirBlock(worldX, worldY, worldZ) - && this.minecraft.playerController.isInCreativeMode()) { - this.minecraft.playerController.clickBlock(worldX, worldY, worldZ, 0); - + && interaction.breakBlock(worldX, worldY, worldZ)) { this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; return !ConfigurationHandler.destroyInstantly; @@ -345,13 +342,15 @@ private boolean wouldMergeSupportingSlab(World world, int x, int y, int z, Forge private boolean mergeSlab(PrinterInteraction interaction, int x, int y, int z, ItemStack slab) { final boolean top = (interaction.world.getBlockMetadata(x, y, z) & 8) != 0; - return interaction.place( - slab, - x, - y, - z, - top ? ForgeDirection.DOWN.ordinal() : ForgeDirection.UP.ordinal(), - Vec3.createVectorHelper(x + 0.5, y + 0.5, z + 0.5)); + return interaction.withSneaking( + true, + () -> interaction.place( + slab, + x, + y, + z, + top ? ForgeDirection.DOWN.ordinal() : ForgeDirection.UP.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 0.5, z + 0.5))); } private boolean isValidOrientation(EntityPlayer player, int x, int y, int z, PlacementData data, int metadata) { From 09ccfb01a59f4c4edde2438a904425edcaa5a8a8 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:23:37 +0100 Subject: [PATCH 61/64] fix: handle mixed multipart blocks --- .../client/compat/MicroblockSupport.java | 51 +++++++++++++++++-- .../client/printer/SchematicPrinter.java | 10 +++- .../renderer/RendererSchematicChunk.java | 5 ++ 3 files changed, 60 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java index a824863f..1c8a546a 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -33,6 +33,7 @@ import codechicken.microblock.MicroblockPlacement; import codechicken.multipart.BlockMultipart; import codechicken.multipart.TMultiPart; +import codechicken.multipart.TSlottedPart; import codechicken.multipart.TileMultipart; import scala.collection.Iterator; @@ -96,10 +97,19 @@ public static void renderMissingParts(IBlockAccess schematic, TileEntity placed, public static boolean addMaterials(TileEntity schematic, TileEntity world, BiConsumer add) { final List expected = getParts(schematic); - if (expected.isEmpty()) { + final List otherParts = getOtherParts(schematic); + if (expected.isEmpty() && otherParts.isEmpty()) { return false; } + final List unmatchedOtherParts = getOtherParts(world); + for (TMultiPart part : otherParts) { + final boolean placed = removeOtherPartMatch(unmatchedOtherParts, part); + for (ItemStack stack : part.getDrops()) { + add.accept(stack, placed); + } + } + final List unmatched = getParts(world); for (Microblock part : expected) { if (removeMatch(unmatched, part)) { @@ -496,14 +506,47 @@ private static void aimAt(EntityClientPlayerMP player, Vec3 eye, double x, doubl player.rotationPitch = (float) -Math.toDegrees(Math.atan2(dy, Math.hypot(dx, dz))); } + public static boolean hasMissingOtherParts(TileEntity schematic, TileEntity world) { + final List unmatched = getOtherParts(world); + return getOtherParts(schematic).stream() + .anyMatch(part -> !removeOtherPartMatch(unmatched, part)); + } + + private static boolean removeOtherPartMatch(List placed, TMultiPart expected) { + for (int i = 0; i < placed.size(); i++) { + final TMultiPart actual = placed.get(i); + if (expected.getType() + .equals(actual.getType()) && slotMask(expected) == slotMask(actual)) { + placed.remove(i); + return true; + } + } + return false; + } + + private static int slotMask(TMultiPart part) { + return part instanceof TSlottedPart slotted ? slotted.getSlotMask() : 0; + } + + private static List getOtherParts(TileEntity tile) { + final List parts = getParts(tile, TMultiPart.class); + parts.removeIf(Microblock.class::isInstance); + return parts; + } + private static List getParts(TileEntity tile) { - final List parts = new ArrayList<>(); + return getParts(tile, Microblock.class); + } + + private static List getParts(TileEntity tile, Class type) { + final List parts = new ArrayList<>(); if (tile instanceof TileMultipart multipart) { final Iterator iterator = multipart.partList() .iterator(); while (iterator.hasNext()) { - if (iterator.next() instanceof Microblock part) { - parts.add(part); + final TMultiPart part = iterator.next(); + if (type.isInstance(part)) { + parts.add(type.cast(part)); } } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 53d0b561..0d7a883d 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -158,8 +158,14 @@ private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block)) { final TileEntity tile = this.schematic.getTileEntity(x, y, z); if (MicroblockSupport.hasMicroblocks(tile)) { - return this.microblocks.place(interaction, tile, worldX, worldY, worldZ) - && !ConfigurationHandler.placeInstantly; + if (this.microblocks.place(interaction, tile, worldX, worldY, worldZ)) { + return !ConfigurationHandler.placeInstantly; + } + // Preserve existing parts and leave room for placements that need stock or support. + if (MicroblockSupport.isMultipartBlock(placedBlock) || world.isAirBlock(worldX, worldY, worldZ) + || placedBlock.isReplaceable(world, worldX, worldY, worldZ)) { + return false; + } } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index e252646d..8bfe92f6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -394,6 +394,11 @@ private boolean matchesBlockState(Block block, World world, int x, int y, int z, return CarpentersBlocksSupport .matches(block, this.schematic.getTileEntity(x, y, z), world.getTileEntity(wx, wy, wz)); } + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block) + && MicroblockSupport + .hasMissingOtherParts(this.schematic.getTileEntity(x, y, z), world.getTileEntity(wx, wy, wz))) { + return false; + } return BlockToItemStack .matchesSavedState(block, this.minecraft.thePlayer, world, wx, wy, wz, this.schematic, x, y, z) && (!Mods.ARCHITECTURE_CRAFT || !ArchitectureCraftSupport.isShapeBlock(block) From 26f52f618747e18c82fd9d90c88447724b3d646f Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:23:39 +0100 Subject: [PATCH 62/64] fix: read dye colors from kitchen tiles --- .../compat/CookingForBlockheadsSupport.java | 47 +++++++++++++++++++ .../schematica/client/util/BlockList.java | 47 ++----------------- 2 files changed, 51 insertions(+), 43 deletions(-) diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java index 84c9ac6b..d7e48888 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java @@ -2,10 +2,20 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.function.BiConsumer; +import net.blay09.mods.cookingforblockheads.tile.BaseKitchenTileWithInventory; +import net.blay09.mods.cookingforblockheads.tile.TileCookingTable; +import net.blay09.mods.cookingforblockheads.tile.TileFridge; +import net.blay09.mods.cookingforblockheads.tile.TileSink; import net.blay09.mods.cookingforblockheads.utils.DyeUtils; +import net.minecraft.block.Block; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.reference.Reference; public final class CookingForBlockheadsSupport { @@ -18,6 +28,43 @@ public static int getDyeDamage(ItemStack stack) { return DyeUtils.rawDyeDamageFromStack(stack); } + public static void addDyeRequirement(SchematicWorld schematic, int x, int y, int z, World world, int wx, int wy, + int wz, BiConsumer add) { + final TileEntity tile = schematic.getTileEntity(x, y, z); + final int color = getColor(tile); + if (color < 0 || color > 15) { + return; + } + final Block block = schematic.getBlock(x, y, z); + final boolean pairFridges = tile instanceof TileFridge && !schematic.isRenderingLayer; + if (pairFridges && colorAt(schematic, block, x, y - 1, z) == color) { + return; + } + final boolean hasUpperFridge = pairFridges && colorAt(schematic, block, x, y + 1, z) == color; + final int currentColor = colorAt(world, block, wx, wy, wz); + final int upperColor = hasUpperFridge ? colorAt(world, block, wx, wy + 1, wz) : -1; + if (color == 0 && currentColor <= 0 && upperColor <= 0) { + return; + } + add.accept( + new ItemStack(Items.dye, 1, 15 - color), + currentColor == color && (!hasUpperFridge || upperColor == color)); + } + + private static int colorAt(World world, Block block, int x, int y, int z) { + return world.getBlock(x, y, z) == block ? getColor(world.getTileEntity(x, y, z)) : -1; + } + + private static int getColor(TileEntity tile) { + if (tile instanceof BaseKitchenTileWithInventory kitchen) { + return kitchen.getColor(); + } + if (tile instanceof TileCookingTable table) { + return table.getColor(); + } + return tile instanceof TileSink sink ? sink.getColor() : -1; + } + private static boolean supportsDyeSubstitutes() { try { final Method method = DyeUtils.class.getMethod("rawDyeDamageFromStack", ItemStack.class); diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index 573612e7..617fb0d6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -8,13 +8,11 @@ import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; -import net.minecraft.init.Items; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.Constants; import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; @@ -23,12 +21,9 @@ import com.github.lunatrius.schematica.client.compat.EnderIOSlabSupport; import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.world.SchematicWorld; -import com.github.lunatrius.schematica.nbt.NBTHelper; import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; -import cpw.mods.fml.common.registry.GameRegistry; - public class BlockList { public List getList(final EntityPlayer player, final SchematicWorld world, @@ -115,33 +110,13 @@ public List getList(final EntityPlayer player, final Schematic } } if (Mods.COOKING_FOR_BLOCKHEADS && block.hasTileEntity(world.getBlockMetadata(x, y, z))) { - final GameRegistry.UniqueIdentifier name = GameRegistry.findUniqueIdentifierFor(block); - if (name != null && Mods.COOKING_FOR_BLOCKHEADS_ID.equals(name.modId)) { - final int color = kitchenColor(world.getTileEntity(x, y, z)); - final boolean pairedFridge = "fridge".equals(name.name) && !world.isRenderingLayer - && y > 0 - && world.getBlock(x, y - 1, z) == block - && kitchenColor(world.getTileEntity(x, y - 1, z)) == color; - if (color >= 0 && color <= 15 && !pairedFridge) { - final boolean hasUpperFridge = "fridge".equals(name.name) && !world.isRenderingLayer - && world.getBlock(x, y + 1, z) == block - && kitchenColor(world.getTileEntity(x, y + 1, z)) == color; - final boolean dyed = hasKitchenColor(mcWorld, block, wx, wy, wz, color) - && (!hasUpperFridge || hasKitchenColor(mcWorld, block, wx, wy + 1, wz, color)); - if (color == 0 && !hasColoredKitchenBlock(mcWorld, block, wx, wy, wz) - && (!hasUpperFridge || !hasColoredKitchenBlock(mcWorld, block, wx, wy + 1, wz))) { - continue; - } - final WrappedItemStack dye = addMaterial( - blockList, - new ItemStack(Items.dye, 1, 15 - color), - 1, - dyed); + CookingForBlockheadsSupport + .addDyeRequirement(world, x, y, z, mcWorld, wx, wy, wz, (stackDye, dyed) -> { + final WrappedItemStack dye = addMaterial(blockList, stackDye, 1, dyed); if (!dyed) { dye.kitchenDyesNeeded++; } - } - } + }); } } } @@ -220,20 +195,6 @@ private void addKitchenDyeSubstitutes(List materials, ItemStac } } - private int kitchenColor(TileEntity tile) { - return tile == null ? 0 - : NBTHelper.writeTileEntityToCompound(tile) - .getByte("Color"); - } - - private boolean hasKitchenColor(WorldClient world, Block block, int x, int y, int z, int color) { - return world.getBlock(x, y, z) == block && kitchenColor(world.getTileEntity(x, y, z)) == color; - } - - private boolean hasColoredKitchenBlock(WorldClient world, Block block, int x, int y, int z) { - return world.getBlock(x, y, z) == block && kitchenColor(world.getTileEntity(x, y, z)) != 0; - } - private WrappedItemStack addMaterial(List blockList, ItemStack stack, int count, boolean placed) { final WrappedItemStack entry = findOrCreateWrappedItemStackFor(blockList, stack); if (placed) { From 2f812eace48f59fd4d187feab42666f54690d9b5 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:23:43 +0100 Subject: [PATCH 63/64] docs: explain schematic compatibility --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index e82d0074..6254a287 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,10 @@ Changes from Original: - Store Coordinates & rotation of schematics per world/server. No more re-entering coordinates for large builds! - Fix heavy lag when having lotr armor stands/weapon racks in loaded schematic - Updated Chinese translation + +### Schematic compatibility + +- Schematica reads `.schematic` and `.schemplus` files automatically. New saves use classic block ID encoding up to 4095 and support IDs up to 24 bits when needed. Older readers may truncate wide IDs or extended metadata. +- Schematic downloads require matching download protocol versions on the client and server. +- The preview compares Carpenter's Safe locks and automation permissions, which you set manually when building. +- The printer places ArchitectureCraft shapes with their saved base material and orientation. The preview also compares cladding and connections, which you apply manually. From d94a572b675d0dd13df17eda6fecd03114a23e50 Mon Sep 17 00:00:00 2001 From: Worive <13164341+Worive@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:21:52 +0100 Subject: [PATCH 64/64] docs: trim schematic compatibility notes --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 6254a287..4218f239 100644 --- a/README.md +++ b/README.md @@ -9,5 +9,3 @@ Changes from Original: - Schematica reads `.schematic` and `.schemplus` files automatically. New saves use classic block ID encoding up to 4095 and support IDs up to 24 bits when needed. Older readers may truncate wide IDs or extended metadata. - Schematic downloads require matching download protocol versions on the client and server. -- The preview compares Carpenter's Safe locks and automation permissions, which you set manually when building. -- The printer places ArchitectureCraft shapes with their saved base material and orientation. The preview also compares cladding and connections, which you apply manually.