Compare commits

...
29 Commits
Author SHA1 Message Date
Martin Robertz 1b7fe15299 Merge remote-tracking branch 'ReignOfFROZE/master' into dev 2025-04-20 21:58:47 +02:00
ReignOfFROZE bbcf3a8669 Moved keybind to CommonProxy 2025-04-20 11:52:25 -04:00
ReignOfFROZE f1473bbb3a Bapy-ized textures 2025-04-20 11:49:45 -04:00
ReignOfFROZE 086b0a00ff Spotless 2025-04-20 11:48:23 -04:00
ReignOfFROZE 6a4886796a Switched to using SyncedKeybind instead of vanilla keybind implementation 2025-04-20 11:46:35 -04:00
ReignOfFROZE e6c82d422d Revert file mode changes 2025-04-20 11:24:25 -04:00
Martin Robertz 3cbd6cf581 update 2025-04-12 23:09:52 +02:00
Martin Robertz 9d06da9b3b fix 2025-04-12 11:22:49 +02:00
Martin Robertz 88d5991161 update 2025-04-12 11:17:31 +02:00
Martin Robertz cce7372675 Merge remote-tracking branch 'origin/feature/channel-desc' into dev
# Conflicts:
#	dependencies.gradle
#	src/main/java/com/gtnewhorizon/structurelib/StructureLib.java
#	src/main/java/com/gtnewhorizon/structurelib/StructureLibAPI.java
#	src/main/java/com/gtnewhorizon/structurelib/gui/GuiScreenConfigureChannels.java
#	src/main/java/com/gtnewhorizon/structurelib/structure/IStructureDefinition.java
#	src/main/resources/assets/structurelib/lang/en_US.lang
#	src/main/resources/assets/structurelib/lang/zh_CN.lang
#	src/main/resources/assets/structurelib/textures/gui/channels.png
2025-04-12 11:16:46 +02:00
ReignOfFROZE b4b6f4e5eb Spotless apply 2025-04-11 18:45:17 -04:00
reign dfe910ebd3 Fix a few bugs, add removal checking 2025-04-11 18:39:15 -04:00
Glease 24403a82ce spotless
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-04-11 17:15:54 +08:00
Glease b775c1068d add gui tutorial and remove debug code
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-04-11 17:11:00 +08:00
reign 5b0b9ba3c5 Streamline codepaths and add SU compat for permission checking 2025-04-09 21:35:01 -04:00
reign bd76be4f6f Comment out GT5U Dependency 2025-04-08 10:58:39 -04:00
reign d3e258dd30 Remove logs and found workaround for updating mode bug 2025-04-08 10:56:50 -04:00
Glease 6a557c9aa0 bruh
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-04-08 14:53:47 +08:00
Glease 14d7219b41 change NEI to a implementation dependency
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-04-08 14:46:12 +08:00
Glease faa3e75ed1 spotless
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-04-08 14:34:32 +08:00
Glease df96277bd7 add channel desc and channel indicator item
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-04-08 14:32:10 +08:00
reign 0999964f1a Add removing and updating modes to ItemConstructableTrigger 2025-04-07 21:03:28 -04:00
538459eab5 channel configure ui tweaks (#35)
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
Co-authored-by: Martin Robertz <dream-master@gmx.net>
Co-authored-by: Maya <10861407+serenibyss@users.noreply.github.com>
2025-03-11 09:41:57 -05:00
Maya 3a9ec8b6ac update 2025-03-10 16:27:58 -05:00
Glease 330a13271b fix unbreakable warded glass (#37)
fix
https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/18849

@Ruling-0 since your glass refactor is slightly related to this

---------

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-03-10 16:26:36 -05:00
glowredmanandGlease bf5dd5566b Add Localization (#36)
This adds some missing localizations for unlocalized names returned by
the ItemStack-insensitive version of `Item.getUnlocalizedName()`.
Relevant for the Item/Block stats introduced in
https://github.com/GTNewHorizons/Hodgepodge/pull/398.

---------

Co-authored-by: Glease <4586901+Glease@users.noreply.github.com>
2025-01-02 11:40:59 +08:00
Martin Robertz b9d0143245 update 2024-12-14 20:12:25 +01:00
43fc39c99b Add error hint when block is invalid (#31)
Co-authored-by: kstvr32 <kstvr32@gmail.com>
Co-authored-by: Martin Robertz <dream-master@gmx.net>
2024-12-14 19:13:34 +01:00
Lyft 6337536dc3 Send correct identifier when instrumenting (#34) 2024-11-19 10:20:47 +08:00
36 changed files with 1464 additions and 215 deletions

No files matched your search

+1
View File
@@ -27,3 +27,4 @@ whitelist.json
*.iws
src/main/resources/mixins.*.json
*.bat
layout.json
+1 -2
View File
@@ -1,7 +1,7 @@
javadoc {
javadocTool = javaToolchains.javadocToolFor {
// Last version with frames, but it also has search
languageVersion = JavaLanguageVersion.of(11)
languageVersion = JavaLanguageVersion.of(21)
vendor = JvmVendorSpec.ADOPTIUM
}
@@ -20,7 +20,6 @@ javadoc {
overview "src/main/javadoc/overview.html"
links 'https://docs.oracle.com/javase/8/docs/api/'
links 'https://skmedix.github.io/ForgeJavaDocs/javadoc/forge/1.7.10-10.13.4.1614/'
addBooleanOption("-frames", true)
}
}
+8 -2
View File
@@ -1,9 +1,15 @@
// Add your dependencies here
dependencies {
api("com.github.GTNewHorizons:GTNHLib:0.5.19:dev")
runtimeOnly("com.github.GTNewHorizons:NotEnoughItems:2.6.44-GTNH:dev")
api("com.github.GTNewHorizons:GTNHLib:0.6.19:dev")
implementation("com.github.GTNewHorizons:NotEnoughItems:2.7.38-GTNH:dev")
compileOnly("com.github.GTNewHorizons:ServerUtilities:2.1.41-pre")
testImplementation(platform('org.junit:junit-bom:5.9.2'))
testImplementation('org.junit.jupiter:junit-jupiter')
// runtimeOnlyNonPublishable("com.github.GTNewHorizons:GT5-Unofficial:5.09.51.234:dev") {
// exclude group: "com.github.GTNewHorizons", module: "StructureLib"
// }
}
+1 -1
View File
@@ -14,7 +14,7 @@ modId = structurelib
modGroup = com.gtnewhorizon.structurelib
# Whether to use modGroup as the maven publishing group.
# Due to a history of using JitPack, the default is com.github.GTNewHorizons for all mods.
# When false, com.github.GTNewHorizons is used.
useModGroupForPublishing = false
# Updates your build.gradle and settings.gradle automatically whenever an update is available.
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+2 -3
View File
@@ -86,8 +86,7 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -206,7 +205,7 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
+1 -1
View File
@@ -17,7 +17,7 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.29'
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.38'
}
@@ -0,0 +1,94 @@
package com.gtnewhorizon.structurelib;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraft.item.ItemStack;
import com.gtnewhorizon.gtnhlib.util.map.ItemStackMap;
import cpw.mods.fml.common.Loader;
// this is not an API! go check StructureLibAPI instead!
public class ChannelDescription {
private static final ItemStackMap<Set<ChannelDescription>> itemToChannels = new ItemStackMap<>(true);
private static final Map<String, ChannelDescription> registry = new HashMap<>();
private final String channel;
private final Map<String, String> descriptions = new HashMap<>();
private final ItemStackMap<Integer> items = new ItemStackMap<>(true);
public static ChannelDescription get(final String channel) {
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY");
return registry.computeIfAbsent(channel, ChannelDescription::new);
}
public static boolean has(final String channel) {
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY");
return registry.containsKey(channel);
}
public static Collection<Map.Entry<String, Integer>> iterate(final ItemStack block) {
Set<ChannelDescription> channels = itemToChannels.get(block);
if (channels == null) return Collections.emptySet();
return channels.stream().map(d -> new AbstractMap.SimpleImmutableEntry<>(d.channel, d.items.get(block)))
.collect(Collectors.toList());
}
public static void set(final String channel, final String modid, final String description) {
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY");
registry.computeIfAbsent(channel, ChannelDescription::new).add(modid, description);
}
public static void item(final String channel, int channelValue, ItemStack stack) {
if (StructureLibAPI.isDebugEnabled()) {
if (!channel.toLowerCase(Locale.ROOT).equals(channel)) {
throw new IllegalArgumentException("Channel name can be lower case ONLY");
}
if (channelValue <= 0) {
throw new IllegalArgumentException("Channel value must be greater than 0");
}
}
ChannelDescription inst = registry.computeIfAbsent(channel, ChannelDescription::new);
inst.items.put(stack, channelValue);
itemToChannels.computeIfAbsent(stack, s -> new HashSet<>()).add(inst);
}
public static Map<String, ChannelDescription> getAll() {
return Collections.unmodifiableMap(registry);
}
private ChannelDescription(String channel) {
this.channel = channel;
}
public String getChannel() {
return channel;
}
public ChannelDescription add(String modid, String description) {
if (Loader.instance().getIndexedModList().get(modid) == null) {
throw new IllegalArgumentException("Mod not found: " + modid);
}
descriptions.put(modid, description);
return this;
}
public Map<String, String> getDescriptions() {
return Collections.unmodifiableMap(descriptions);
}
public Map<ItemStack, Integer> getItems() {
return Collections.unmodifiableMap(items);
}
}
@@ -46,6 +46,7 @@ import com.gtnewhorizon.structurelib.net.SetChannelDataMessage;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.EventPriority;
@@ -259,6 +260,11 @@ public class ClientProxy extends CommonProxy {
MinecraftForge.EVENT_BUS.register(new ForgeEventHandler());
}
@Override
public void init(FMLInitializationEvent e) {
super.init(e);
}
static void markTextureUsed(IIcon icon) {
if (StructureLib.COMPAT instanceof IStructureCompat)
((IStructureCompat) StructureLib.COMPAT).markTextureUsed(icon);
@@ -14,9 +14,12 @@ import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import com.gtnewhorizon.gtnhlib.keybind.SyncedKeybind;
import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger;
import com.gtnewhorizon.structurelib.net.ErrorHintParticleMessage;
import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@@ -64,6 +67,8 @@ public class CommonProxy {
public void preInit(FMLPreInitializationEvent e) {}
public void init(FMLInitializationEvent e) {}
public long getOverworldTime() {
return MinecraftServer.getServer().getEntityWorld().getTotalWorldTime();
}
@@ -108,6 +113,16 @@ public class CommonProxy {
}
}
private static final SyncedKeybind MODE_SWAP_KEY = SyncedKeybind.createConfigurable(
"item.structurelib.constructableTrigger.keys.cycleMode",
"item.structurelib.constructableTrigger.keyCategory",
0).registerGlobalListener((entityPlayerMP, syncedKeybind) -> {
final ItemStack held = entityPlayerMP.getHeldItem();
if (held != null && held.getItem() instanceof ItemConstructableTrigger) {
ItemConstructableTrigger.cycleMode(held);
}
});
public void displayConfigGUI(String category) {}
public static class ForgeEventHandler {
@@ -0,0 +1,48 @@
package com.gtnewhorizon.structurelib;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import cpw.mods.fml.common.event.FMLInterModComms;
public class DevelopHelper {
private static final boolean DEBUG = Boolean.getBoolean("structurelib.develop_helper");
public static void onPreInit() {
if (!DEBUG) return;
StructureLib.LOGGER.info("Running develop helper");
StructureLibAPI.registerChannelDescription("sandstone", StructureLibAPI.MOD_ID, "variants of Sandstone");
StructureLibAPI.registerChannelItem("sandstone", StructureLibAPI.MOD_ID, 1, new ItemStack(Blocks.sandstone));
StructureLibAPI
.registerChannelItem("sandstone", StructureLibAPI.MOD_ID, 2, new ItemStack(Blocks.sandstone, 1, 1));
StructureLibAPI
.registerChannelItem("sandstone", StructureLibAPI.MOD_ID, 3, new ItemStack(Blocks.sandstone, 1, 2));
StructureLibAPI.registerChannelDescription("sandbricks", StructureLibAPI.MOD_ID, "variants of Sandbricks");
StructureLibAPI.registerChannelDescription("apple", StructureLibAPI.MOD_ID, "apple");
StructureLibAPI.registerChannelDescription("bright", StructureLibAPI.MOD_ID, "bright");
StructureLibAPI.registerChannelDescription("apple_blight", StructureLibAPI.MOD_ID, "apple_blight");
StructureLibAPI.registerChannelDescription("app_eagle", StructureLibAPI.MOD_ID, "app_eagle");
}
public void x() {
NBTTagCompound command = new NBTTagCompound();
NBTTagList items = new NBTTagList();
int[] metas = { 0, 1, 2 };
for (int meta : metas) {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag("Item", new ItemStack(Blocks.sandstone, 1, meta).writeToNBT(new NBTTagCompound()));
NBTTagList channels = new NBTTagList();
NBTTagCompound channel = new NBTTagCompound();
channel.setString("Channel", "sandstone");
channel.setInteger("Value", meta + 1);
channels.appendTag(channel);
tag.setTag("Channels", channels);
items.appendTag(tag);
}
command.setTag("Items", items);
FMLInterModComms.sendMessage("structurelib", "register_channel_item", command);
}
}
@@ -3,6 +3,7 @@ package com.gtnewhorizon.structurelib;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.gui.EmptyContainer;
import com.gtnewhorizon.structurelib.gui.GuiScreenConfigureChannels;
import cpw.mods.fml.common.network.IGuiHandler;
@@ -11,14 +12,19 @@ public class GuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return null;
switch (ID) {
case 0:
return new EmptyContainer(player);
default:
return null;
}
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
switch (ID) {
case 0:
return new GuiScreenConfigureChannels(player.inventory.getStackInSlot(x));
return new GuiScreenConfigureChannels(new EmptyContainer(player), player.inventory.getStackInSlot(x));
default:
return null;
}
@@ -1,11 +1,18 @@
package com.gtnewhorizon.structurelib;
import static com.gtnewhorizon.structurelib.StructureLibAPI.CHANNEL_SHOW_ERROR;
import static com.gtnewhorizon.structurelib.StructureLibAPI.MOD_ID;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -24,9 +31,10 @@ import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage;
import com.gtnewhorizon.structurelib.util.InventoryUtility;
import com.gtnewhorizon.structurelib.util.XSTR;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
@@ -40,7 +48,7 @@ import cpw.mods.fml.relauncher.SideOnly;
* This class does not contain a stable API. Refrain from using this class.
*/
@Mod(
modid = StructureLibAPI.MOD_ID,
modid = MOD_ID,
name = "StructureLib",
version = Tags.VERSION,
acceptableRemoteVersions = "*",
@@ -57,7 +65,7 @@ public class StructureLib {
clientSide = "com.gtnewhorizon.structurelib.ClientProxy")
static CommonProxy proxy;
static final SimpleNetworkWrapper net = NetworkRegistry.INSTANCE.newSimpleChannel(StructureLibAPI.MOD_ID);
static final SimpleNetworkWrapper net = NetworkRegistry.INSTANCE.newSimpleChannel(MOD_ID);
static {
net.registerMessage(
@@ -84,7 +92,7 @@ public class StructureLib {
@Mod.Instance
static StructureLib INSTANCE;
@Mod.Instance(STRUCTURECOMPAT_MODID)
static Object COMPAT;
static Block blockHint;
@@ -115,9 +123,15 @@ public class StructureLib {
NetworkRegistry.INSTANCE.registerGuiHandler(instance(), new GuiHandler());
InventoryUtility.init();
if (Loader.isModLoaded(STRUCTURECOMPAT_MODID)) {
COMPAT = Loader.instance().getIndexedModList().get(STRUCTURECOMPAT_MODID).getMod();
}
ChannelDescription.set(CHANNEL_SHOW_ERROR, MOD_ID, "channels.structurelib.show_errors");
DevelopHelper.onPreInit();
}
@Mod.EventHandler
public void init(FMLInitializationEvent e) {
proxy.init(e);
}
@Mod.EventHandler
@@ -131,6 +145,48 @@ public class StructureLib {
e.registerServerCommand(new CommandRegistryDebug());
}
@Mod.EventHandler
public void handleIMC(FMLInterModComms.IMCEvent event) {
for (FMLInterModComms.IMCMessage message : event.getMessages()) {
switch (message.key) {
case "register_channel":
processRegisterChannel(message);
break;
case "register_channel_item":
processRegisterChannelItem(message);
break;
}
}
}
private void processRegisterChannel(FMLInterModComms.IMCMessage message) {
NBTTagList tags = message.getNBTValue().getTagList("Channels", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tags.tagCount(); i++) {
NBTTagCompound tag = tags.getCompoundTagAt(i);
StructureLibAPI.registerChannelDescription(
tag.getString("Channel"),
message.getSender(),
tag.getString("Description"));
}
}
private void processRegisterChannelItem(FMLInterModComms.IMCMessage message) {
NBTTagList items = message.getNBTValue().getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < items.tagCount(); i++) {
NBTTagCompound itemTag = items.getCompoundTagAt(i);
ItemStack item = ItemStack.loadItemStackFromNBT(itemTag.getCompoundTag("Item"));
NBTTagList tags = itemTag.getTagList("Channels", Constants.NBT.TAG_COMPOUND);
for (int j = 0; j < tags.tagCount(); j++) {
NBTTagCompound tag = tags.getCompoundTagAt(j);
StructureLibAPI.registerChannelItem(
tag.getString("Channel"),
message.getSender(),
tag.getInteger("Value"),
item);
}
}
}
public static void addClientSideChatMessages(String... messages) {
proxy.addClientSideChatMessages(messages);
}
@@ -11,6 +11,7 @@ import net.minecraft.util.IChatComponent;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import com.gtnewhorizon.gtnhlib.util.AnimatedTooltipHandler;
import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.IAlignmentProvider;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
@@ -43,6 +44,7 @@ public class StructureLibAPI {
public static final int HINT_BLOCK_META_AIR = 13;
public static final int HINT_BLOCK_META_NOT_AIR = 14;
public static final int HINT_BLOCK_META_ERROR = 15;
public static final String CHANNEL_SHOW_ERROR = "show_error";
static final ThreadLocal<Object> instrument = new ThreadLocal<>();
/**
@@ -72,7 +74,7 @@ public class StructureLibAPI {
*/
public static void enableInstrument(Object identifier) {
if (isInstrumentEnabled()) throw new IllegalStateException();
instrument.set(instrument);
instrument.set(identifier);
}
/**
@@ -350,4 +352,37 @@ public class StructureLibAPI {
short intervalRequired, boolean forceUpdateLastSend) {
proxy.addThrottledChat(throttleKey, player, text, intervalRequired, forceUpdateLastSend);
}
/**
* Register a channel description here. The description should describe how a channel will be used inside your mod.
*
* @param channel channel key
* @param modid your modid
* @param description localization key for your description
*/
public static void registerChannelDescription(final String channel, final String modid, final String description) {
ChannelDescription.set(channel, modid, description);
}
/**
* Register an item stack as an indicator for a (channel, value) pair.
*
* @param channel channel key
* @param modid your modid
* @param channelValue value
* @param stack item stack. having a metadata of
* {@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE} will match without comparing
* NBT or metadata value. having a tag with {@code tag.getBoolean("*") == true} will match
* without comparing NBT.
*/
public static void registerChannelItem(final String channel, final String modid, final int channelValue,
final ItemStack stack) {
ChannelDescription.item(channel, channelValue, stack);
AnimatedTooltipHandler.addItemTooltip(
stack,
AnimatedTooltipHandler.translatedText("structurelib.tooltip.channelvalue", channelValue, channel));
AnimatedTooltipHandler.addItemTooltip(
stack,
AnimatedTooltipHandler.translatedText("structurelib.tooltip.indicator_dnd", channelValue, channel));
}
}
@@ -57,12 +57,12 @@ public class ConstructableUtility {
}
IConstructable constructable = null;
if (tTileEntity instanceof IConstructableProvider)
constructable = ((IConstructableProvider) tTileEntity).getConstructable();
else if (tTileEntity instanceof IConstructable) {
constructable = (IConstructable) tTileEntity;
if (tTileEntity instanceof IConstructableProvider aConstructableProvider)
constructable = aConstructableProvider.getConstructable();
else if (tTileEntity instanceof IConstructable aConstructable) {
constructable = aConstructable;
} else if (IMultiblockInfoContainer.contains(tTileEntity.getClass())) {
ExtendedFacing facing = tTileEntity instanceof IAlignment ? ((IAlignment) tTileEntity).getExtendedFacing()
ExtendedFacing facing = tTileEntity instanceof IAlignment alignment ? alignment.getExtendedFacing()
: ExtendedFacing.of(ForgeDirection.getOrientation(aSide));
constructable = IMultiblockInfoContainer.<TileEntity>get(tTileEntity.getClass())
.toConstructable(tTileEntity, facing);
@@ -70,14 +70,13 @@ public class ConstructableUtility {
if (constructable == null) return false;
if (aPlayer instanceof EntityPlayerMP) {
EntityPlayerMP playerMP = (EntityPlayerMP) aPlayer;
if (aPlayer instanceof EntityPlayerMP playerMP) {
// server side and sneaking (already checked above)
// do construct
if (aPlayer.capabilities.isCreativeMode) {
constructable.construct(aStack, false);
} else if (constructable instanceof ISurvivalConstructable) {
int built = ((ISurvivalConstructable) constructable).survivalConstruct(
} else if (constructable instanceof ISurvivalConstructable aConstructable) {
int built = aConstructable.survivalConstruct(
aStack,
ConfigurationHandler.INSTANCE.getAutoPlaceBudget(),
ISurvivalBuildEnvironment.create(IItemSource.fromPlayer(playerMP), playerMP));
@@ -0,0 +1,18 @@
package com.gtnewhorizon.structurelib.gui;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
public class EmptyContainer extends Container {
private final EntityPlayer player;
public EmptyContainer(EntityPlayer player) {
this.player = player;
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return player == this.player;
}
}
@@ -1,45 +1,82 @@
package com.gtnewhorizon.structurelib.gui;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import com.google.common.base.Splitter;
import com.gtnewhorizon.structurelib.ChannelDescription;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.gui.GuiScrollableList.IGuiScreen;
public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen {
import codechicken.nei.VisiblityData;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.TaggedInventoryArea;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Optional;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
@Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems")
public class GuiScreenConfigureChannels extends GuiContainer implements IGuiScreen, INEIGuiHandler {
private static final String I18N_PREFIX = "item.structurelib.constructableTrigger.gui.";
private static final int ADD_BTN = 0;
private static final int UNSET_BTN = 1;
private static final int WIPE_BTN = 2;
private static final int KEY_MAX_WIDTH = 50;
private static final int INFO_BOX_SIZE = 11;
private final ItemStack trigger;
private final GuiChannelsList list;
private final GuiAutoCompleteList autoCompleteList;
private final Map<String, List<String>> tooltipSplitCache = new HashMap<>();
private final TIntObjectMap<Map<String, String>> trimCache = new TIntObjectHashMap<>();
private GuiTextField key, value;
protected int guiTop, guiLeft;
private List<String> info;
public GuiScreenConfigureChannels(Container container, ItemStack trigger) {
super(container);
public GuiScreenConfigureChannels(ItemStack trigger) {
this.trigger = trigger;
list = new GuiChannelsList(152, 100, 12, 12, 14);
list = new GuiChannelsList(152, 91, 12, 21, 14);
list.addSelectionListener((list, selectedIndex) -> {
Entry<String, Integer> e = list.getElementAt(selectedIndex);
key.setText(e.getKey());
value.setText(e.getValue().toString());
updateButtons();
});
autoCompleteList = new GuiAutoCompleteList(151 + 12 - 45 - 2, 50, 45, 119 + 12, 14);
}
@Override
@@ -125,10 +162,11 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
};
list.onGuiInit(this);
autoCompleteList.onGuiInit(this);
addButton(
new GuiButton(
0,
ADD_BTN,
guiLeft + 12,
guiTop + 157,
47,
@@ -136,7 +174,7 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
I18n.format("item.structurelib.constructableTrigger.gui.add")));
addButton(
new GuiButton(
1,
UNSET_BTN,
guiLeft + 65,
guiTop + 157,
47,
@@ -144,7 +182,7 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
I18n.format("item.structurelib.constructableTrigger.gui.unset")));
addButton(
new GuiButton(
2,
WIPE_BTN,
guiLeft + 118,
guiTop + 157,
47,
@@ -152,6 +190,15 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
I18n.format("item.structurelib.constructableTrigger.gui.wipe")));
updateButtons();
tooltipSplitCache.clear();
info = StreamSupport
.stream(
Splitter.on("\\n").split(
StatCollector.translateToLocal("item.structurelib.constructableTrigger.gui.info"))
.spliterator(),
false)
.flatMap(line -> fontRendererObj.listFormattedStringToWidth(line, width * 3 / 5).stream())
.collect(Collectors.toList());
}
@Override
@@ -199,22 +246,42 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
return buttonList;
}
private boolean isMouseOverValue() {
int mx = Mouse.getEventX() * this.width / this.mc.displayWidth;
int my = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1;
return mx >= value.xPosition && mx < value.xPosition + value.width
&& my >= value.yPosition
&& my < value.yPosition + value.height;
}
@Override
public void handleMouseInput() {
int delta = Mouse.getEventDWheel();
if (delta != 0) list.handleDWheel(delta);
if (delta != 0) {
if (isMouseOverValue()) {
if (delta > 0) {
value.setText(String.valueOf(getValue() + 1));
} else {
value.setText(String.valueOf(Math.max(getValue() - 1, 1)));
}
} else {
list.handleDWheel(delta);
}
}
super.handleMouseInput();
}
@Override
protected void mouseClicked(int mX, int mY, int button) {
super.mouseClicked(mX, mY, button);
key.mouseClicked(mX, mY, button);
value.mouseClicked(mX, mY, button);
super.mouseClicked(mX, mY, button);
}
@Override
protected void keyTyped(char aChar, int aKey) {
GuiScrollableList<?> l = key.isFocused() ? autoCompleteList : list;
switch (aKey) {
case Keyboard.KEY_TAB:
if (key.isFocused()) {
@@ -227,15 +294,33 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
return;
case Keyboard.KEY_RETURN:
case Keyboard.KEY_NUMPADENTER:
GuiButton add = getButtonList().get(0);
if (key.isFocused() && autoCompleteList.getSelectedElement() != null) {
key.setText(autoCompleteList.getSelectedElement());
key.setFocused(false);
value.setFocused(true);
value.setText("1");
value.setSelectionPos(0);
return;
}
GuiButton add = getButtonList().get(ADD_BTN);
if (add.enabled) doActionPerformed(add);
return;
case Keyboard.KEY_UP:
if (list.selectedIndex > 0) list.setSelection(list.selectedIndex - 1);
if (l.selectedIndex > 0) l.setSelection(l.selectedIndex - 1);
return;
case Keyboard.KEY_DOWN:
if (list.selectedIndex < list.getNumElements() - 1) list.setSelection(list.selectedIndex + 1);
if (l.selectedIndex < l.getNumElements() - 1) l.setSelection(l.selectedIndex + 1);
return;
case Keyboard.KEY_ESCAPE:
if (key.isFocused()) {
if (autoCompleteList.getSelectedElement() != null) {
autoCompleteList.reset();
} else {
key.setFocused(false);
}
return;
}
break;
}
if (key.textboxKeyTyped(aChar, aKey)) {
updateButtons();
@@ -250,10 +335,13 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
// STACKOVERFLOW!
String keyText = key.getText();
boolean existing = !StringUtils.isEmpty(keyText) && ChannelDataAccessor.hasSubChannel(trigger, keyText);
getButtonList().get(0).displayString = existing ? I18n.format("item.structurelib.constructableTrigger.gui.set")
: I18n.format("item.structurelib.constructableTrigger.gui.add");
getButtonList().get(0).enabled = !StringUtils.isBlank(value.getText());
getButtonList().get(1).enabled = existing && !StringUtils.isBlank(value.getText());
getButtonList().get(ADD_BTN).displayString = existing ? I18n.format(I18N_PREFIX + "set")
: I18n.format(I18N_PREFIX + "add");
getButtonList().get(ADD_BTN).enabled = !StringUtils.isBlank(value.getText())
&& Integer.parseInt(value.getText()) > 0;
getButtonList().get(UNSET_BTN).enabled = existing && !StringUtils.isBlank(value.getText());
autoCompleteList.reset();
}
private int getValue() {
@@ -268,18 +356,23 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
protected void actionPerformed(GuiButton btn) {
if (btn == null) return;
switch (btn.id) {
case 0:
case ADD_BTN:
int value = getValue();
if (value <= 0) return;
ChannelDataAccessor.setChannelData(trigger, key.getText(), value);
break;
case 1:
case UNSET_BTN:
ChannelDataAccessor.unsetChannelData(trigger, key.getText());
break;
case 2:
case WIPE_BTN:
ChannelDataAccessor.wipeChannelData(trigger);
key.setText("");
this.value.setText("");
break;
}
updateButtons();
super.actionPerformed(btn);
}
@@ -298,18 +391,17 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
@Override
public void drawScreen(int mX, int mY, float partialTick) {
public void drawGuiContainerBackgroundLayer(float partialTick, int mX, int mY) {
mc.renderEngine.bindTexture(new ResourceLocation("structurelib", "textures/gui/channels.png"));
int topLeftX = (this.width - this.getXSize()) / 2;
int topLeftY = (this.height - this.getYSize()) / 2;
drawTexturedModalRect(topLeftX, topLeftY, 0, 0, getXSize(), getYSize());
super.drawScreen(mX, mY, partialTick);
list.drawScreen(mX, mY, partialTick);
fontRendererObj.drawString(
I18n.format("item.structurelib.constructableTrigger.gui.title"),
guiLeft + 12,
guiTop + 9,
0);
fontRendererObj.drawString(
I18n.format("item.structurelib.constructableTrigger.gui.key"),
guiLeft + 12,
@@ -324,6 +416,221 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
value.drawTextBox();
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
if (key.isFocused() && autoCompleteList.getNumElements() > 0) {
autoCompleteList.drawScreen(mouseX, mouseY, 0);
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
String highlight = null;
if (key.isFocused() && autoCompleteList.getNumElements() > 0) {
highlight = autoCompleteList.getSelectedElement();
}
if (highlight == null && ChannelDescription.has(key.getText())) {
highlight = key.getText();
}
if (highlight != null) {
drawChannelDescriptionTooltip(highlight);
}
if (mouseX > xSize + guiLeft - INFO_BOX_SIZE - 12 && mouseX < xSize + guiLeft - 12
&& mouseY > guiTop + 7
&& mouseY < guiTop + INFO_BOX_SIZE + 7) {
drawHoveringText(info, mouseX, mouseY, fontRendererObj);
}
}
private void drawChannelDescriptionTooltip(String candidate) {
List<String> tooltip = tooltipSplitCache.computeIfAbsent(candidate, this::getChannelDescriptionTooltip);
drawHoveringText(tooltip, guiLeft + 151 + 12, guiTop + 122, fontRendererObj);
}
private List<String> getChannelDescriptionTooltip(String candidate) {
List<String> tooltip = new ArrayList<>();
int maxLine = width - (guiLeft + 151 + 12) - 12;
for (Entry<String, String> e : ChannelDescription.get(candidate).getDescriptions().entrySet()) {
tooltip.addAll(
fontRendererObj.listFormattedStringToWidth(
StatCollector.translateToLocalFormatted(
"item.structurelib.constructableTrigger.gui.channels.from",
Loader.instance().getIndexedModList().get(e.getKey()).getName()),
maxLine));
tooltip.addAll(
fontRendererObj.listFormattedStringToWidth(StatCollector.translateToLocal(e.getValue()), maxLine));
}
return tooltip;
}
public String trim(String str, int keyMaxWidth) {
Map<String, String> cache = trimCache.get(keyMaxWidth);
if (cache == null) {
trimCache.put(keyMaxWidth, cache = new HashMap<>());
}
return cache.computeIfAbsent(str, e -> {
String s = fontRendererObj.trimStringToWidth(e, keyMaxWidth);
if (s.length() != e.length()) {
StringBuilder buffer = new StringBuilder(s).deleteCharAt(s.length() - 1).append("...");
while ((s = fontRendererObj.trimStringToWidth(buffer.toString(), keyMaxWidth)).length()
!= buffer.length())
// drop last original char
buffer.deleteCharAt(s.length() - 4);
do {
buffer.append('.');
} while (fontRendererObj.getStringWidth(buffer.toString()) <= keyMaxWidth);
s = buffer.deleteCharAt(s.length() - 1).insert(s.length() - 3, EnumChatFormatting.GRAY).toString();
}
return s;
});
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) {
return null;
}
@Override
public Iterable<Integer> getItemSpawnSlots(GuiContainer gui, ItemStack item) {
return Collections.emptyList();
}
@Override
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer gui) {
return Collections.emptyList();
}
@Override
public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) {
if (button != 0 || mousex <= guiLeft
|| mousey <= guiTop
|| mousex >= guiLeft + getXSize()
|| mousey >= guiTop + getYSize()) {
return false;
}
Collection<Entry<String, Integer>> channels = ChannelDescription.iterate(draggedStack);
switch (channels.size()) {
case 0:
return false;
case 1:
default: // TODO implement a GUI to select which pair to use, instead of blindly using the first
Entry<String, Integer> e = channels.iterator().next();
ChannelDataAccessor.setChannelData(trigger, e.getKey(), e.getValue());
key.setText(e.getKey());
value.setText(e.getValue().toString());
draggedStack.stackSize = 0;
return true;
}
}
@Override
public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) {
return false;
}
private class GuiAutoCompleteList extends GuiScrollableList<String> {
private List<Entry<String, String>> cache; // <key, display string>
public GuiAutoCompleteList(int width, int height, int originX, int originY, int slotHeight) {
super(width, height, originX, originY, slotHeight);
margin = 2;
}
private List<Entry<String, String>> getOptions() {
if (cache == null) {
cache = search();
}
return cache;
}
private List<Entry<String, String>> search() {
List<Entry<String, String>> cache = new ArrayList<>();
Set<String> added = new HashSet<>();
String term = key.getText();
String[] subjects = ChannelDescription.getAll().keySet().toArray(new String[0]);
Arrays.sort(subjects);
if (StringUtils.isBlank(term)) {
// nothing. just gives out everything
for (String subject : subjects) {
cache.add(new AbstractMap.SimpleImmutableEntry<>(subject, EnumChatFormatting.GRAY + subject));
}
return cache;
}
// prefix match
for (String s : subjects) {
if (s.startsWith(term)) {
cache.add(
new AbstractMap.SimpleImmutableEntry<>(
s,
term + EnumChatFormatting.GRAY + s.substring(term.length())));
added.add(s);
}
}
// subsequence match
for (String subject : subjects) {
if (!added.contains(subject) && subject.length() > term.length()) {
int i = 0, j = 0;
StringBuilder sb = new StringBuilder();
boolean mode = true;
sb.append(EnumChatFormatting.WHITE);
while (i < term.length() && j < subject.length()) {
if (term.codePointAt(i) == subject.codePointAt(j)) {
if (!mode) {
sb.append(EnumChatFormatting.WHITE);
mode = true;
}
sb.appendCodePoint(term.codePointAt(i));
i++;
j++;
} else {
if (mode) {
sb.append(EnumChatFormatting.GRAY);
mode = false;
}
sb.appendCodePoint(subject.codePointAt(j));
j++;
}
}
if (i == term.length()) {
if (j < subject.length()) {
sb.append(EnumChatFormatting.GRAY);
sb.append(subject, j, subject.length());
}
cache.add(new AbstractMap.SimpleImmutableEntry<>(subject, sb.toString()));
added.add(subject);
}
}
}
return cache;
}
public void reset() {
cache = search();
selectedIndex = cache.isEmpty() ? -1 : 0;
resetScroll();
}
@Override
public String getElementAt(int index) {
return index >= 0 && index < cache.size() ? getOptions().get(index).getKey() : null;
}
@Override
public int getNumElements() {
return getOptions().size();
}
@Override
protected void drawElement(int elementIndex, int x, int y, int height, Tessellator tessellator,
boolean isHovering) {
int color = elementIndex == selectedIndex ? 0xffffff : 0xcccccc;
fontRendererObj.drawString(getOptions().get(elementIndex).getValue(), x + margin, y + margin / 2, color);
}
}
private class GuiChannelsList extends GuiScrollableList<Entry<String, Integer>> {
private List<Entry<String, Integer>> cache;
@@ -350,6 +657,7 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
Entry<String, Integer> e = getElementAt(elementIndex);
if (e != null) {
ChannelDataAccessor.unsetChannelData(trigger, e.getKey());
updateButtons();
return false;
}
}
@@ -390,22 +698,5 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
// args x1, y1, y2, color
drawVerticalLine(minX + margin + margin / 2 + KEY_MAX_WIDTH * 2, minY + 1, maxY - 1, 0xffaaaaaa);
}
public String trim(String e, int keyMaxWidth) {
// TODO optimize this to not create a billion string, or maybe cache this
String s = fontRendererObj.trimStringToWidth(e, keyMaxWidth);
if (s.length() != e.length()) {
StringBuilder buffer = new StringBuilder(s).deleteCharAt(s.length() - 1).append("...");
while ((s = fontRendererObj.trimStringToWidth(buffer.toString(), keyMaxWidth)).length()
!= buffer.length())
// drop last original char
buffer.deleteCharAt(s.length() - 4);
do {
buffer.append('.');
} while (fontRendererObj.getStringWidth(buffer.toString()) <= keyMaxWidth);
s = buffer.deleteCharAt(s.length() - 1).insert(s.length() - 3, EnumChatFormatting.GRAY).toString();
}
return s;
}
}
}
@@ -16,7 +16,7 @@ import org.lwjgl.opengl.GL11;
* <p>
* As the code has been released into public domain, it is now LGPL as part of this library as a whole. You can go to
* EnderCore's repository to obtain a public domain copy though
*
* <p>
* Major edits
* <ul>
* <li>Separate dwheel handling to handleDWheel. The next event calls often cause the mouse click event to not fire on
@@ -167,10 +167,17 @@ public abstract class GuiScrollableList<T> {
}
}
protected void resetScroll() {
amountScrolled = 0;
}
/**
* draws the slot to the screen, pass in mouse's current x and y and partial ticks
*/
public void drawScreen(int mX, int mY, float partialTick) {
GL11.glPushMatrix();
GL11.glLoadIdentity();
GL11.glTranslatef(0.0F, 0.0F, -2000.0F);
this.mouseX = mX;
this.mouseY = mY;
@@ -199,13 +206,26 @@ public abstract class GuiScrollableList<T> {
int contentYOffset = this.minY + margin - amountScrolled;
boolean hoveringPrecondition = mX >= minX && mX <= maxX && mY >= minY && mY <= maxY;
int slotHeight = this.slotHeight - margin;
if (selectedIndex != -1) {
int elementY = contentYOffset + selectedIndex * this.slotHeight;
if (elementY + slotHeight > maxY) {
this.amountScrolled = (selectedIndex + 1) * this.slotHeight - this.height + margin;
amountScrolled = (int) this.amountScrolled;
contentYOffset = this.minY + margin - amountScrolled;
} else if (elementY < minY) {
this.amountScrolled = selectedIndex * this.slotHeight;
amountScrolled = (int) this.amountScrolled;
contentYOffset = this.minY + margin - amountScrolled;
}
}
prepareDrawElements();
for (int i = 0; i < getNumElements(); ++i) {
int elementY = contentYOffset + i * this.slotHeight;
int slotHeight = this.slotHeight - margin;
if (elementY <= maxY && elementY + slotHeight >= minY) {
@@ -264,6 +284,7 @@ public abstract class GuiScrollableList<T> {
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
protected void prepareDrawElements() {}
@@ -412,7 +433,7 @@ public abstract class GuiScrollableList<T> {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
tess.startDrawingQuads();
tess.setColorOpaque_I(2105376);
tess.setColorOpaque_I(0x202020);
tess.addVertex(minX, maxY, 0.0D);
tess.addVertex(maxX, maxY, 0.0D);
tess.addVertex(maxX, minY, 0.0D);
@@ -7,9 +7,14 @@ import static net.minecraft.util.StatCollector.translateToLocalFormatted;
import java.util.List;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.util.IIcon;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import org.lwjgl.input.Keyboard;
@@ -20,15 +25,82 @@ import com.gtnewhorizon.structurelib.alignment.constructable.ConstructableUtilit
public class ItemConstructableTrigger extends Item {
private static final String TAG_MODE = "mode";
private static final IIcon[] textures = new IIcon[3];
public enum TriggerMode {
BUILDING,
UPDATING,
REMOVING
}
public ItemConstructableTrigger() {
setUnlocalizedName("structurelib.constructableTrigger");
setTextureName(MOD_ID + ":itemConstructableTrigger");
setCreativeTab(StructureLib.creativeTab);
}
public static void cycleMode(ItemStack held) {
if (held.getTagCompound() == null) held.setTagCompound(new NBTTagCompound());
if (!held.getTagCompound().hasKey(TAG_MODE)) held.getTagCompound().setTag(TAG_MODE, new NBTTagInt(0));
held.getTagCompound().setInteger(TAG_MODE, (held.getTagCompound().getInteger(TAG_MODE) + 1) % 3);
}
@Override
public void registerIcons(IIconRegister register) {
textures[0] = register.registerIcon(MOD_ID + ":constructableTrigger/BUILDING");
textures[1] = register.registerIcon(MOD_ID + ":constructableTrigger/UPDATING");
textures[2] = register.registerIcon(MOD_ID + ":constructableTrigger/REMOVING");
}
@Override
public IIcon getIcon(ItemStack stack, int renderPass, EntityPlayer player, ItemStack usingItem, int useRemaining) {
return getIcon(stack, renderPass);
}
@Override
public IIcon getIcon(ItemStack stack, int pass) {
if (!stack.hasTagCompound() || !stack.getTagCompound().hasKey(TAG_MODE)) {
return textures[0];
}
return textures[stack.getTagCompound().getInteger(TAG_MODE)];
}
@Override
public String getItemStackDisplayName(ItemStack stack) {
if (!stack.hasTagCompound() || !stack.getTagCompound().hasKey(TAG_MODE)) {
return getDisplayName(0);
}
return getDisplayName(stack.getTagCompound().getInteger(TAG_MODE));
}
@Override
public IIcon getIconIndex(ItemStack stack) {
return getIcon(stack, 0);
}
@Override
public IIcon getIconFromDamage(int damage) {
return textures[damage];
}
private String getDisplayName(int mode) {
return StatCollector.translateToLocal("item.structurelib.constructableTrigger.name") + " - "
+ StatCollector.translateToLocal("item.structurelib.constructableTrigger.modes." + mode);
}
public static TriggerMode getMode(ItemStack held) {
if (held == null || !held.hasTagCompound() || !held.getTagCompound().hasKey(TAG_MODE)) {
// default behavior
return TriggerMode.BUILDING;
}
// get user-defined mode
return TriggerMode.values()[held.getTagCompound().getInteger(TAG_MODE)];
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (world.isRemote && getMovingObjectPositionFromPlayer(world, player, true) == null) {
if (!world.isRemote && getMovingObjectPositionFromPlayer(world, player, true) == null) {
if (player.isSneaking()) {
StructureLib.instance().proxy().displayConfigGUI("registries");
} else {
@@ -12,6 +12,7 @@ import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
@@ -50,7 +51,7 @@ import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
* itself.</li>
* <li>The "C" position would be the number of blocks between you and controller, not counting controller itself.</li>
* </ul>
*
*
* @param <T> Type of the context object. Usually this will be the multiblock controller.
*/
public interface IStructureDefinition<T> {
@@ -72,7 +73,7 @@ public interface IStructureDefinition<T> {
/**
* Run a structure check.
*
*
* @param object context object. usually multiblock controller.
* @param piece the structure piece's string identifier.
* @param world the world object this check takes place in.
@@ -107,7 +108,7 @@ public interface IStructureDefinition<T> {
/**
* Spawn hint particles. Should not be called on server side.
*
*
* @param object context object. usually multiblock controller.
* @param piece the structure piece's string identifier.
* @param world the world object this check takes place in.
@@ -320,7 +321,7 @@ public interface IStructureDefinition<T> {
/**
* Low level utility.
*
*
* @param object context object. usually multiblock controller.
* @param trigger The trigger item that contains channel data.
* @param elements the structure piece
@@ -347,80 +348,54 @@ public interface IStructureDefinition<T> {
}
if (checkBlocksIfNotNullForceCheckAllIfTrue != null) {
boolean success;
if (checkBlocksIfNotNullForceCheckAllIfTrue) {
success = StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
(e, w, x, y, z, a, b, c) -> e.check(object, w, x, y, z),
"check");
} else {
success = StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
skipBlockUnloaded((e, w, x, y, z, a, b, c) -> e.check(object, w, x, y, z)),
"check force");
}
boolean success = StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
checkBlocksIfNotNullForceCheckAllIfTrue ? (e, w, x, y, z, a, b, c) -> e.check(object, w, x, y, z)
: skipBlockUnloaded((e, w, x, y, z, a, b, c) -> e.check(object, w, x, y, z)),
checkBlocksIfNotNullForceCheckAllIfTrue ? "check" : "check force");
if (StructureLibAPI.isDebugEnabled() && success) {
StructureLib.LOGGER
.info("Multi [" + basePositionX + ", " + basePositionY + ", " + basePositionZ + "] pass");
}
return success;
} else {
if (hintsOnly) {
StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
ignoreBlockUnloaded((e, w, x, y, z, a, b, c) -> {
e.spawnHint(object, world, x, y, z, trigger);
return true;
}),
"spawnHint");
} else {
StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
ignoreBlockUnloaded((e, w, x, y, z, a, b, c) -> {
e.placeBlock(object, world, x, y, z, trigger);
return true;
}),
"placeBlock");
}
StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
hintsOnly ? ignoreBlockUnloaded((e, w, x, y, z, a, b, c) -> {
e.spawnHint(object, world, x, y, z, trigger);
if (ChannelDataAccessor.hasSubChannel(trigger, StructureLibAPI.CHANNEL_SHOW_ERROR)
&& !e.couldBeValid(object, world, x, y, z, trigger)) {
StructureLibAPI.markHintParticleError(StructureLib.getCurrentPlayer(), world, x, y, z);
}
return true;
}) : ignoreBlockUnloaded((e, w, x, y, z, a, b, c) -> {
e.placeBlock(object, world, x, y, z, trigger);
return true;
}),
hintsOnly ? "spawnHint" : "placeBlock");
}
return true;
}
/**
* Create a new instance of builder.
*
*
* @param <T> type of context object
*/
static <T> StructureDefinition.Builder<T> builder() {
@@ -2,6 +2,8 @@ package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.StructureLib.LOGGER;
import static com.gtnewhorizon.structurelib.StructureLib.PANIC_MODE;
import static com.gtnewhorizon.structurelib.item.ItemConstructableTrigger.TriggerMode.REMOVING;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.checkForRemoving;
import java.util.Arrays;
import java.util.Collections;
@@ -21,6 +23,7 @@ import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
@@ -32,6 +35,16 @@ public interface IStructureElement<T> {
boolean check(T t, World world, int x, int y, int z);
/**
* Pure (stateless and side effect free) function to test if current block could be valid. Used to give user hints
* about incorrectly placed blocks given a controller and trigger item. If couldBeValid(...) == false for a set of
* channels, with those same tiers, check(...) == false. Not required, defaults to true which is always safe but
* won't give the user error hints.
*/
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
}
boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger);
boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger);
@@ -127,12 +140,14 @@ public interface IStructureElement<T> {
*/
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
BlocksToPlace e = getBlocksToPlace(t, world, x, y, z, trigger, env);
IItemSource source = env.getSource();
EntityPlayer actor = env.getActor();
Consumer<IChatComponent> chatter = env.getChatter();
if (e != null) {
if (check(t, world, x, y, z)) return PlaceResult.SKIP;
PlaceResult skipOrRejectBasedOnCheck = checkForRemoving(mode, check(t, world, x, y, z), world, x, y, z);
if (skipOrRejectBasedOnCheck != PlaceResult.ACCEPT) return skipOrRejectBasedOnCheck;
if (e.getStacks() == null) {
ItemStack taken = source.takeOne(e.getPredicate(), true);
return StructureUtility.survivalPlaceBlock(
@@ -149,7 +164,7 @@ public interface IStructureElement<T> {
chatter);
}
for (ItemStack stack : e.getStacks()) {
if (!source.takeOne(stack, true)) continue;
if (mode != REMOVING && !source.takeOne(stack, true)) continue;
return StructureUtility.survivalPlaceBlock(
stack,
NBTMode.EXACT,
@@ -185,6 +200,11 @@ public interface IStructureElement<T> {
return IStructureElement.this.check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return IStructureElement.this.couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return IStructureElement.this.spawnHint(t, world, x, y, z, trigger);
@@ -31,6 +31,16 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
return false;
}
@Override
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
for (IStructureElement<T> fallback : fallbacks()) {
if (fallback.couldBeValid(t, world, x, y, z, trigger)) {
return true;
}
}
return false;
}
@Override
default boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
for (IStructureElement<T> fallback : fallbacks()) {
@@ -14,6 +14,11 @@ public interface IStructureElementCheckOnly<T> extends IStructureElement<T> {
return false;
}
@Override
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
}
@Override
default boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return false;
@@ -17,6 +17,11 @@ interface IStructureNavigate<T> extends IStructureElement<T> {
return true;
}
@Override
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
}
@Override
default boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
@@ -32,6 +32,11 @@ class LazyStructureElement<T> implements IStructureElementDeferred<T> {
return get(t).check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return get(t).couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return get(t).placeBlock(t, world, x, y, z, trigger);
@@ -1,5 +1,10 @@
package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.StructureLib.LOGGER;
import static com.gtnewhorizon.structurelib.StructureLib.PANIC_MODE;
import static com.gtnewhorizon.structurelib.item.ItemConstructableTrigger.TriggerMode.BUILDING;
import static com.gtnewhorizon.structurelib.item.ItemConstructableTrigger.TriggerMode.REMOVING;
import static com.gtnewhorizon.structurelib.item.ItemConstructableTrigger.TriggerMode.UPDATING;
import static java.lang.Integer.MIN_VALUE;
import java.util.Arrays;
@@ -26,6 +31,7 @@ import java.util.function.Supplier;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
@@ -49,13 +55,16 @@ import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger;
import com.gtnewhorizon.structurelib.structure.IStructureElement.PlaceResult;
import com.gtnewhorizon.structurelib.structure.adders.IBlockAdder;
import com.gtnewhorizon.structurelib.structure.adders.ITileAdder;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
import com.gtnewhorizon.structurelib.xmod.ServerUtilitiesCompat;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
/**
@@ -144,6 +153,8 @@ public class StructureUtility {
private static final String NICE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz=|!@#$%&()[]{};:<>/?_,.*^'`";
private static final boolean isSULoaded = Loader.isModLoaded("serverutilities");
@SuppressWarnings("rawtypes")
private static final Map<Vec3Impl, IStructureNavigate> STEP = new HashMap<>();
@@ -155,6 +166,11 @@ public class StructureUtility {
return world.isAirBlock(x, y, z);
}
@Override
public boolean couldBeValid(Object t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(Object o, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, StructureLibAPI.getBlockHint(), 13);
@@ -186,6 +202,11 @@ public class StructureUtility {
return !world.isAirBlock(x, y, z);
}
@Override
public boolean couldBeValid(Object t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(Object o, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, StructureLibAPI.getBlockHint(), 14);
@@ -194,7 +215,11 @@ public class StructureUtility {
@Override
public boolean placeBlock(Object o, World world, int x, int y, int z, ItemStack trigger) {
world.setBlock(x, y, z, StructureLibAPI.getBlockHint(), 14, 2);
placeRemoveOrUpdate(
trigger,
() -> world.setBlock(x, y, z, StructureLibAPI.getBlockHint(), 14, 2),
() -> world.setBlock(x, y, z, StructureLibAPI.getBlockHint(), 14, 2),
() -> world.setBlock(x, y, z, Blocks.air, 0, 2));
return true;
}
@@ -207,11 +232,16 @@ public class StructureUtility {
@Override
public PlaceResult survivalPlaceBlock(Object o, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
if (check(o, world, x, y, z)) return PlaceResult.SKIP;
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
if (mode != REMOVING && check(o, world, x, y, z)) return PlaceResult.SKIP;
// user should place anything here.
// maybe make this configurable, but for now we try to take some cobble from user
if (env.getSource().takeOne(new ItemStack(Blocks.cobblestone), false)) {
world.setBlock(x, y, z, Blocks.cobblestone, 0, 2);
placeRemoveOrUpdate(
trigger,
() -> world.setBlock(x, y, z, Blocks.cobblestone, 0, 2),
() -> world.setBlock(x, y, z, Blocks.cobblestone, 0, 2),
() -> world.setBlock(x, y, z, Blocks.air, 0, 2));
}
return PlaceResult.REJECT;
}
@@ -225,6 +255,11 @@ public class StructureUtility {
return false;
}
@Override
public boolean couldBeValid(Object t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(Object o, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, StructureLibAPI.getBlockHint(), 15);
@@ -313,23 +348,84 @@ public class StructureUtility {
public static PlaceResult survivalPlaceBlock(Block block, int meta, World world, int x, int y, int z, IItemSource s,
EntityPlayer actor, Consumer<IChatComponent> chatter) {
if (block == null) throw new NullPointerException();
if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT;
ItemConstructableTrigger.TriggerMode mode = BUILDING;
if (actor.getHeldItem() != null && actor.getHeldItem().getItem() instanceof ItemConstructableTrigger) {
// best effort lookup if the item in the player's hand is a trigger, and if it is, get the mode from the
// ...trigger instead of assuming default behavior
mode = ItemConstructableTrigger.getMode(actor.getHeldItem());
}
if (mode == BUILDING && !StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor))
return PlaceResult.REJECT;
if (mode == UPDATING) {
if (!world.isAirBlock(x, y, z)) {
if (world.getTileEntity(x, y, z) instanceof TileEntity) {
// We're in updating mode and the block we're looking at might be important, so let's just leave it
// alone
// since it's probably not something we want to replace with something else
return PlaceResult.SKIP;
}
Block blockInWorld = world.getBlock(x, y, z);
if (blockInWorld.isAssociatedBlock(block) && blockInWorld.getDamageValue(world, x, y, z) == meta) {
// This is the block we are looking for, move along
return PlaceResult.SKIP;
}
}
}
Item itemBlock = Item.getItemFromBlock(block);
int itemMeta = itemBlock instanceof ISpecialItemBlock
? ((ISpecialItemBlock) itemBlock).getItemMetaFromBlockMeta(block, meta)
: meta;
if (!s.takeOne(new ItemStack(itemBlock, 1, itemMeta), false)) {
if (chatter != null) chatter.accept(
new ChatComponentTranslation(
"structurelib.autoplace.error.no_simple_block",
new ItemStack(itemBlock, 1, itemMeta).func_151000_E()));
return PlaceResult.REJECT;
ItemStack stack = new ItemStack(itemBlock, 1, itemMeta);
if (mode != REMOVING) {
if (!s.takeOne(stack, true)) {
if (chatter != null) chatter.accept(
new ChatComponentTranslation(
"structurelib.autoplace.error.no_simple_block",
stack.func_151000_E()));
return PlaceResult.REJECT;
}
if (block instanceof ICustomBlockSetting) {
ICustomBlockSetting blockCustom = (ICustomBlockSetting) block;
blockCustom.setBlock(world, x, y, z, meta);
} else {
if (mode == UPDATING && !world.isAirBlock(x, y, z) && checkPermission(world, actor, x, y, z)) {
// We're in updating mode and there's a block in our way (grr), so let's remove whatever is there
// ...and drop it to the player
ItemStack toGive = new ItemStack(world.getBlock(x, y, z));
toGive.setItemDamage(world.getBlock(x, y, z).getDamageValue(world, x, y, z));
if (!world.setBlock(x, y, z, Blocks.air, 0, 4) || !tryGiveOrDropItem(world, actor, toGive)) {
// We either weren't able to give the player the block that was there, or we weren't able to
// remove
// the block, either way, we need to reject the update. Also, since we hid the block update from
// the client in an effort to make the exchange as seamless as possible, we need to now notify
// the client if we did successfully remove the block.
if (world.isAirBlock(x, y, z)) world.notifyBlockChange(x, y, z, Blocks.air);
return PlaceResult.REJECT;
}
}
if (!stack.copy()
.tryPlaceItemIntoWorld(actor, world, x, y, z, ForgeDirection.UP.ordinal(), 0.5f, 0.5f, 0.5f)) {
return PlaceResult.REJECT;
}
}
}
if (block instanceof ICustomBlockSetting) {
ICustomBlockSetting block2 = (ICustomBlockSetting) block;
block2.setBlock(world, x, y, z, meta);
} else {
world.setBlock(x, y, z, block, meta, 2);
if (mode == REMOVING || !s.takeOne(stack, false)) {
// If we're in removing mode, or if the user didn't have the block in their inventory, and we're in some
// other mode, let's check some stuff
if (world.isAirBlock(x, y, z)) {
return PlaceResult.SKIP;
}
ItemStack toGive = new ItemStack(world.getBlock(x, y, z));
toGive.setItemDamage(world.getBlock(x, y, z).getDamageValue(world, x, y, z));
if (mode == REMOVING && !checkPermission(world, actor, x, y, z)) {
return PlaceResult.REJECT;
}
world.setBlockToAir(x, y, z);
if (mode == REMOVING && !tryGiveOrDropItem(world, actor, toGive)) {
// We're in removing mode and something went wrong while trying to give the player the block we removed,
// let's just fail for now
return PlaceResult.REJECT;
}
}
return PlaceResult.ACCEPT;
}
@@ -421,24 +517,82 @@ public class StructureUtility {
if (stack == null) throw new NullPointerException();
if (stack.stackSize != 1) throw new IllegalArgumentException();
if (!(stack.getItem() instanceof ItemBlock)) throw new IllegalArgumentException();
if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT;
if (!assumeStackPresent && !s.takeOne(stack, true)) {
if (chatter != null) chatter.accept(
new ChatComponentTranslation("structurelib.autoplace.error.no_item_stack", stack.func_151000_E()));
return PlaceResult.REJECT;
ItemConstructableTrigger.TriggerMode mode = BUILDING;
if (actor.getHeldItem() != null && actor.getHeldItem().getItem() instanceof ItemConstructableTrigger) {
// best effort lookup if the item in the player's hand is a trigger, and if it is, get the mode from the
// ...trigger instead of assuming default behavior
mode = ItemConstructableTrigger.getMode(actor.getHeldItem());
}
if (!stack.copy().tryPlaceItemIntoWorld(actor, world, x, y, z, ForgeDirection.UP.ordinal(), 0.5f, 0.5f, 0.5f))
return PlaceResult.REJECT;
if (!s.takeOne(stack, false))
// this is bad! probably an exploit somehow. Let's nullify the block we just placed instead
if (mode != REMOVING) {
if (mode == BUILDING) {
if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) {
return PlaceResult.SKIP;
}
}
if (mode == UPDATING) {
if (!world.isAirBlock(x, y, z)) {
if (world.getTileEntity(x, y, z) instanceof TileEntity) {
return PlaceResult.SKIP;
}
Block blockInWorld = world.getBlock(x, y, z);
ItemStack blockInWorldItem = new ItemStack(blockInWorld);
blockInWorldItem.setItemDamage(blockInWorld.getDamageValue(world, x, y, z));
if (blockInWorldItem.isItemEqual(stack)) {
// This is the block we are looking for, move along
return PlaceResult.SKIP;
}
}
}
if (!assumeStackPresent && !s.takeOne(stack, true)) {
if (chatter != null) chatter.accept(
new ChatComponentTranslation(
"structurelib.autoplace.error.no_item_stack",
stack.func_151000_E()));
return PlaceResult.REJECT;
}
if (mode == UPDATING && !world.isAirBlock(x, y, z) && checkPermission(world, actor, x, y, z)) {
// We're in updating mode and there's a block in our way (grr), so let's remove whatever is there
// ...and drop it to the player
ItemStack toGive = new ItemStack(world.getBlock(x, y, z));
toGive.setItemDamage(world.getBlock(x, y, z).getDamageValue(world, x, y, z));
if (!world.setBlock(x, y, z, Blocks.air, 0, 4) || !tryGiveOrDropItem(world, actor, toGive)) {
// We either weren't able to give the player the block that was there, or we weren't able to remove
// the block, either way, we need to reject the update. Also, since we hid the block update from
// the client in an effort to make the exchange as seamless as possible, we need to now notify
// the client if we did successfully remove the block.
if (world.isAirBlock(x, y, z)) world.notifyBlockChange(x, y, z, Blocks.air);
return PlaceResult.REJECT;
}
}
if (!stack.copy()
.tryPlaceItemIntoWorld(actor, world, x, y, z, ForgeDirection.UP.ordinal(), 0.5f, 0.5f, 0.5f)) {
return PlaceResult.REJECT;
}
}
if (mode == REMOVING || !s.takeOne(stack, false)) {
if (world.isAirBlock(x, y, z)) {
return PlaceResult.SKIP;
}
// If the user didn't have the item in their inventory, or we're in removing mode, we set it to air
ItemStack toGive = new ItemStack(world.getBlock(x, y, z));
toGive.setItemDamage(world.getBlock(x, y, z).getDamageValue(world, x, y, z));
if (mode == REMOVING && !checkPermission(world, actor, x, y, z)) {
return PlaceResult.REJECT;
}
world.setBlockToAir(x, y, z);
if (mode == REMOVING && !tryGiveOrDropItem(world, actor, toGive)) {
// We were in removing mode and something went wrong while trying to give the player the block we
// ...removed, let's just fail for now
return PlaceResult.REJECT;
}
}
return PlaceResult.ACCEPT;
}
/**
* Return a structure element that only allow air (or air equivalents, like Railcraft hidden blocks). You usually
* don't need to call this yourselves. Use {@code -} in shape to automatically use this. Provided nontheless in case
* you want this as a fallback to something else.
* don't need to call this yourselves. Use {@code -} in shape to automatically use this. Provided nonetheless in
* case you want this as a fallback to something else.
*/
@SuppressWarnings("unchecked")
public static <T> IStructureElement<T> isAir() {
@@ -447,8 +601,8 @@ public class StructureUtility {
/**
* Return a structure element that allow anything but air (or air equivalents, like Railcraft hidden blocks). You
* usually don't need to call this yourselves. Use {@code +} in shape to automatically use this. Provided nontheless
* in case you want this as a fallback to something else.
* usually don't need to call this yourselves. Use {@code +} in shape to automatically use this. Provided
* nonetheless in case you want this as a fallback to something else.
*/
@SuppressWarnings("unchecked")
public static <T> IStructureElement<T> notAir() {
@@ -479,6 +633,11 @@ public class StructureUtility {
return true;
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, StructureLibAPI.getBlockHint(), meta);
@@ -499,6 +658,11 @@ public class StructureUtility {
return true;
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, icons.get());
@@ -519,6 +683,11 @@ public class StructureUtility {
return true;
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticleTinted(world, x, y, z, icons.get(), RGBa);
@@ -556,7 +725,7 @@ public class StructureUtility {
TIER current = getter.apply(t);
if (Objects.equals(notSet, current)) {
if (Objects.equals(notSet, tier)) {
if (StructureLib.PANIC_MODE) {
if (PANIC_MODE) {
throw new AssertionError("tierExtractor should never return notSet: " + notSet);
} else {
StructureLib.LOGGER.error("#########################################");
@@ -576,46 +745,33 @@ public class StructureUtility {
/**
* Element representing a component with different tiers. Your multi will accept any of them (as long as player does
* not mix them (*)), but would like to know which is used. Player can use more blueprint to get hints denoting more
* not mix tier (*)), but would like to know which is used. Player can use more blueprint to get hints denoting more
* advanced components.
* <p>
* (*): Implementation wise, this structure element will only accept a block if its tier is the same as existing
* tier or if existing tier is unset (i.e. value of third argument)
* <p>
* Above all else, you need to decide what tier you are going to use. For simpler cases, Integer is a good choice.
* You can also use an existing Enum. Tier can never be null though. It can also be a String or a
* Above all else, you need to decide what type of tier you are going to use. For simpler cases, Integer is a good
* choice. You can also use an existing Enum. It can also be a String or a
* {@link net.minecraft.util.ResourceLocation}, or basically anything. It doesn't even have to implement
* {@link Comparable}.
* <p>
* This assumes you will reset the backing storage, and on the first occurrence getter would return notSet. You can
* also make getter to return other value to forcefully select a certain tier, but you're probably better off using
* block adders or {@link #ofBlock(Block, int, Block, int)} and its overloads
* If your tier extractor function returns null on any (Block, meta) pair, then it means this block is rejected.
* This also implies null can never be a valid tier.
* <p>
* Implementation wise, this allows a block only when we don't yet have a tier, or the block at that location has
* the same tier as we already have.
* <p>
* Notice that if your tier extractor function returns null on any (Block, meta) pair, then it means this block is
* rejected, since null can never be a valid tier.
* This structure element require you will reset the backing storage of getter in your own code, such that in every
* round of structure checking, the first call to getter would always return notSet. You can also make getter to
* return other value on that occasion to forcefully select a certain tier, but then you'd probably be better off
* using block adders or {@link #ofBlock(Block, int, Block, int)} and its overloads
* <p>
* There is yet no TileEntity counterpart of this utility. Feel free to submit a PR to add it.
* <p>
* For most typical use cases, you will NOT want to return notSet from your tierExtractor. If you do so, we will
* have this kind of chain of events:
* <ul>
* <li>at check start, tier is reset to notSet
* <li>at first occurrence, ofBlocksTiered finds your current tier is notSet, and the block's tier is notSet, so
* it's accepted
* <li>at 2nd, 3rd..., same thing in 2 happens
* <li>at last occurrence, player placed a valid block with a tier not notSet. ofBlocksTiered now sets your current
* tier to this tier, and accept the block
* <li>check got notified structure is sound, and tier is not notSet. it marks the structure as complete and start
* doing its business
* <li>Player enjoy a (probably) hilariously shaped multi and (probably) reduced build cost.
* </ul>
* (*): Implementation wise, this structure element will only accept a block if its tier is the same as existing
* tier or if existing tier is unset (i.e. value of third argument). If there are multiple (block, tier) tuple for a
* given tier, then player will be allowed to use multiple kinds of blocks, but their tier is guaranteed to be the
* same.
* <p>
* <b>Example:</b>
* <b>Example Implementation:</b>
* <p>
* Assume you have 16 tier, each map to one block's 16 different meta. You will usually want something like this
* Assume you have 16 tier, each map to one particular block's 16 different meta. You will usually want something
* like this
*
* <pre>
* public class Tile extends TileEntity {
@@ -639,6 +795,29 @@ public class StructureUtility {
* }
* </pre>
*
* Important bits:
* <ul>
* <li>The supplied ITierConverter returns null for an invalid block</li>
* <li>Possible tier returned by ITierConverter is Integer object 0 to 15.</li>
* <li>notSet is set to -1. tier got reset to this value by caller before calling into
* {@link IStructureDefinition#check(Object, String, World, ExtendedFacing, int, int, int, int, int, int, boolean)}</li>
* <li>notSet is never a tier returned by ITierConverter.</li>
* </ul>
* <p>
* <p>
* <b>You SHOULD NOT return notSet from your tierExtractor.</b> If you do so, we will have this chain of events:
* <ul>
* <li>at check start, tier is reset to notSet
* <li>the tier extractor returns notSet for first block, so since ofBlocksTiered finds your current tier is notSet,
* and the new block's tier is the same as that, so it's accepted
* <li>at 2nd, 3rd..., same thing in 2 happens
* <li>at last occurrence, player placed a valid block with a tier not notSet. ofBlocksTiered now sets your current
* tier to this tier, and accept the block
* <li>check got notified structure is sound, and tier is not notSet. it marks the structure as complete and start
* doing its business
* <li>Player enjoy a (probably) hilariously shaped multi and (probably) reduced build cost.
* </ul>
*
* @param tierExtractor a function to extract tier info from a block. This function can return null and will never
* be passed a null block or an invalid block meta. If this function returns null, then the
* block would be considered invalid.
@@ -648,8 +827,8 @@ public class StructureUtility {
* construction time, use {@link #lazy(Supplier)} or its overloads to delay a bit. This list is
* only for hint particle spawning and survival build. The hint/autoplace code will choose 1st
* pair to spawn/place if trigger item has master channel data of 1, 2nd pair if 2, and so on.
* @param notSet The value returned from {@code getter} when there were no tier info found in T yet. Can be
* null.
* @param notSet The value returned from {@code getter} when there were no tier info found in T yet. Cannot
* be null.
* @param getter a function to retrieve the current tier from context object
* @param setter a function to set the current tier into context object
*/
@@ -659,7 +838,7 @@ public class StructureUtility {
List<Pair<Block, Integer>> hints = allKnownTiers == null ? Collections.emptyList() : allKnownTiers;
if (hints.stream().anyMatch(Objects::isNull)) throw new IllegalArgumentException();
IStructureElementCheckOnly<T> check = ofBlocksTiered(tierExtractor, notSet, setter, getter);
return new StructureElement_Bridge<T>() {
return new StructureElement_Bridge<>() {
@Override
public boolean check(T t, World world, int x, int y, int z) {
@@ -667,9 +846,28 @@ public class StructureUtility {
}
private Pair<Block, Integer> getHint(ItemStack trigger) {
if (hints.isEmpty()) return null;
return hints.get(Math.min(Math.max(trigger.stackSize, 1), hints.size()) - 1);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
Pair<Block, Integer> hint = getHint(trigger);
if (hint == null) return true;
TIER hintTier = tierExtractor.convert(hint.getKey(), hint.getValue());
Block block = world.getBlock(x, y, z);
int meta = world.getBlockMetadata(x, y, z);
TIER worldTier = tierExtractor.convert(block, meta);
// if the block is in the same tier as the hint block, this could be valid
return Objects.equals(hintTier, worldTier);
}
private boolean isInAllKnownTiers(Block b) {
return allKnownTiers != null
&& allKnownTiers.stream().anyMatch(pair -> pair.getLeft().isAssociatedBlock(b));
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
Pair<Block, Integer> hint = getHint(trigger);
@@ -702,13 +900,17 @@ public class StructureUtility {
@Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
Pair<Block, Integer> hint = getHint(trigger);
if (hint == null) return PlaceResult.REJECT; // TODO or SKIP?
Block block = world.getBlock(x, y, z);
int meta = world.getBlockMetadata(x, y, z);
TIER tier = tierExtractor.convert(block, meta);
if (Objects.equals(tier, tierExtractor.convert(hint.getKey(), hint.getValue())))
if (mode != REMOVING && (Objects.equals(tier, tierExtractor.convert(hint.getKey(), hint.getValue()))))
return PlaceResult.SKIP;
if (mode == REMOVING && (!isInAllKnownTiers(block) && !world.isAirBlock(x, y, z))) {
return PlaceResult.REJECT;
}
return StructureUtility.survivalPlaceBlock(
hint.getKey(),
hint.getValue(),
@@ -767,6 +969,11 @@ public class StructureUtility {
return world.getBlock(x, y, z) == getBlock() && (wildcard || world.getBlockMetadata(x, y, z) == meta);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
if (getBlock() == null) return error().spawnHint(t, world, x, y, z, trigger);
@@ -792,7 +999,9 @@ public class StructureUtility {
@Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
if (check(t, world, x, y, z)) return PlaceResult.SKIP;
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
PlaceResult skipOrRejectBasedOnCheck = checkForRemoving(mode, check(t, world, x, y, z), world, x, y, z);
if (skipOrRejectBasedOnCheck != PlaceResult.ACCEPT) return skipOrRejectBasedOnCheck;
if (getBlock() == null) return PlaceResult.REJECT;
return StructureUtility.survivalPlaceBlock(
getBlock(),
@@ -841,10 +1050,16 @@ public class StructureUtility {
@Override
public boolean check(T t, World world, int x, int y, int z) {
if (init()) return world.getBlock(x, y, z) != block && world.getBlockMetadata(x, y, z) == meta;
if (init()) return world.getBlock(x, y, z) == block && world.getBlockMetadata(x, y, z) == meta;
else return fallback.check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
if (init()) return world.getBlock(x, y, z) == block && world.getBlockMetadata(x, y, z) == meta;
else return fallback.couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
if (init()) {
@@ -873,7 +1088,9 @@ public class StructureUtility {
@Deprecated
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
IItemSource s, EntityPlayerMP actor, Consumer<IChatComponent> chatter) {
if (check(t, world, x, y, z)) return PlaceResult.SKIP;
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
PlaceResult skipOrRejectBasedOnCheck = checkForRemoving(mode, check(t, world, x, y, z), world, x, y, z);
if (skipOrRejectBasedOnCheck != PlaceResult.ACCEPT) return skipOrRejectBasedOnCheck;
if (init()) return StructureUtility.survivalPlaceBlock(block, meta, world, x, y, z, s, actor, chatter);
return fallback.survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, chatter);
}
@@ -881,7 +1098,9 @@ public class StructureUtility {
@Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
if (check(t, world, x, y, z)) return PlaceResult.SKIP;
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
PlaceResult skipOrRejectBasedOnCheck = checkForRemoving(mode, check(t, world, x, y, z), world, x, y, z);
if (skipOrRejectBasedOnCheck != PlaceResult.ACCEPT) return skipOrRejectBasedOnCheck;
if (init()) return StructureUtility.survivalPlaceBlock(
block,
meta,
@@ -921,6 +1140,11 @@ public class StructureUtility {
return blocsMap.getOrDefault(worldBlock, MIN_VALUE) == worldBlock.getDamageValue(world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, hintBlock, hintMeta);
@@ -958,6 +1182,11 @@ public class StructureUtility {
.contains(worldBlock.getDamageValue(world, x, y, z));
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, hintBlock, hintMeta);
@@ -982,6 +1211,11 @@ public class StructureUtility {
return block == worldBlock && meta == worldBlock.getDamageValue(world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, hintBlock, hintMeta);
@@ -1016,6 +1250,13 @@ public class StructureUtility {
return iBlockAdder.apply(t, worldBlock, worldBlock.getDamageValue(world, x, y, z));
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
// calling iBlockAdder can potentially modify external state
// therefore we assume this can always be valid.
return true;
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, hintBlock, hintMeta);
@@ -1049,6 +1290,11 @@ public class StructureUtility {
return blocsMap.getOrDefault(worldBlock, MIN_VALUE) == worldBlock.getDamageValue(world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
((ICustomBlockSetting) defaultBlock).setBlock(world, x, y, z, defaultMeta);
@@ -1093,6 +1339,11 @@ public class StructureUtility {
return blocsMap.getOrDefault(worldBlock, MIN_VALUE) == worldBlock.getDamageValue(world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
world.setBlock(x, y, z, defaultBlock, defaultMeta, 2);
@@ -1158,6 +1409,11 @@ public class StructureUtility {
.contains(worldBlock.getDamageValue(world, x, y, z));
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
((ICustomBlockSetting) defaultBlock).setBlock(world, x, y, z, defaultMeta);
@@ -1203,6 +1459,11 @@ public class StructureUtility {
.contains(worldBlock.getDamageValue(world, x, y, z));
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
world.setBlock(x, y, z, defaultBlock, defaultMeta, 2);
@@ -1251,6 +1512,14 @@ public class StructureUtility {
if (block == null || defaultBlock == null) {
throw new IllegalArgumentException();
}
if (block == Blocks.air) {
if (PANIC_MODE) {
throw new IllegalArgumentException("ofBlock() does not accept air. use isAir() instead");
} else {
LOGGER.warn("ofBlock() does not accept air. use isAir() instead");
return isAir();
}
}
if (block instanceof ICustomBlockSetting) {
return new IStructureElement<T>() {
@@ -1260,6 +1529,11 @@ public class StructureUtility {
return block == worldBlock && meta == worldBlock.getDamageValue(world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
((ICustomBlockSetting) defaultBlock).setBlock(world, x, y, z, defaultMeta);
@@ -1287,6 +1561,11 @@ public class StructureUtility {
return block == worldBlock && meta == worldBlock.getDamageValue(world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
world.setBlock(x, y, z, defaultBlock, defaultMeta, 2);
@@ -1323,6 +1602,11 @@ public class StructureUtility {
return block == world.getBlock(x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
((ICustomBlockSetting) defaultBlock).setBlock(world, x, y, z, defaultMeta);
@@ -1350,6 +1634,11 @@ public class StructureUtility {
return block == world.getBlock(x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return check(t, world, x, y, z);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
world.setBlock(x, y, z, defaultBlock, defaultMeta, 2);
@@ -1416,6 +1705,13 @@ public class StructureUtility {
return iBlockAdder.apply(t, worldBlock, worldBlock.getDamageValue(world, x, y, z));
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
// calling iBlockAdder can potentially modify external state
// therefore we assume this can always be valid.
return true;
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
((ICustomBlockSetting) defaultBlock).setBlock(world, x, y, z, defaultMeta);
@@ -1432,8 +1728,15 @@ public class StructureUtility {
@Deprecated
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
if (world.getBlock(x, y, z) == defaultBlock && world.getBlockMetadata(x, y, z) == defaultMeta)
return PlaceResult.SKIP;
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
PlaceResult skipOrRejectBasedOnCheck = checkForRemoving(
mode,
world.getBlock(x, y, z) == defaultBlock && world.getBlockMetadata(x, y, z) == defaultMeta,
world,
x,
y,
z);
if (skipOrRejectBasedOnCheck != PlaceResult.ACCEPT) return skipOrRejectBasedOnCheck;
return StructureUtility.survivalPlaceBlock(
defaultBlock,
defaultMeta,
@@ -1455,6 +1758,13 @@ public class StructureUtility {
return iBlockAdder.apply(t, worldBlock, worldBlock.getDamageValue(world, x, y, z));
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
// calling iBlockAdder can potentially modify external state
// therefore we assume this can always be valid.
return true;
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
world.setBlock(x, y, z, defaultBlock, defaultMeta, 2);
@@ -1471,8 +1781,15 @@ public class StructureUtility {
@Deprecated
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
if (world.getBlock(x, y, z) == defaultBlock && world.getBlockMetadata(x, y, z) == defaultMeta)
return PlaceResult.SKIP;
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
PlaceResult skipOrRejectBasedOnCheck = checkForRemoving(
mode,
world.getBlock(x, y, z) == defaultBlock && world.getBlockMetadata(x, y, z) == defaultMeta,
world,
x,
y,
z);
if (skipOrRejectBasedOnCheck != PlaceResult.ACCEPT) return skipOrRejectBasedOnCheck;
return StructureUtility.survivalPlaceBlock(
defaultBlock,
defaultMeta,
@@ -1510,6 +1827,13 @@ public class StructureUtility {
return iTileAdder.apply(t, tileEntity);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
// calling iTileAdder can potentially modify external state
// therefore we assume this can always be valid.
return true;
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, hintBlock, hintMeta);
@@ -1536,6 +1860,13 @@ public class StructureUtility {
return tileClass.isInstance(tileEntity) && iTileAdder.test(t, tileClass.cast(tileEntity));
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
// calling iTileAdder can potentially modify external state
// therefore we assume this can always be valid.
return true;
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
StructureLibAPI.hintParticle(world, x, y, z, hintBlock, hintMeta);
@@ -1569,6 +1900,11 @@ public class StructureUtility {
return check;
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return element.couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return element.placeBlock(t, world, x, y, z, trigger);
@@ -1620,6 +1956,11 @@ public class StructureUtility {
return check;
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return element.couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return element.placeBlock(t, world, x, y, z, trigger);
@@ -1678,6 +2019,13 @@ public class StructureUtility {
return predicate.test(t) && downstream.check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
// this COULD potentially impact external state
// but predicate really should not have side effects
return predicate.test(t) && downstream.couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return predicate.test(t) && downstream.spawnHint(t, world, x, y, z, trigger);
@@ -1700,6 +2048,7 @@ public class StructureUtility {
@Deprecated
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
IItemSource s, EntityPlayerMP actor, Consumer<IChatComponent> chatter) {
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
if (predicate.test(t))
return downstream.survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, chatter);
return placeResultWhenDisabled;
@@ -1708,6 +2057,7 @@ public class StructureUtility {
@Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
if (predicate.test(t)) return downstream.survivalPlaceBlock(t, world, x, y, z, trigger, env);
return placeResultWhenDisabled;
}
@@ -1774,6 +2124,11 @@ public class StructureUtility {
return elem.check(t.getCurrentContext(), world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return elem.couldBeValid(t.getCurrentContext(), world, x, y, z, trigger);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return elem.spawnHint(t.getCurrentContext(), world, x, y, z, trigger);
@@ -1861,6 +2216,11 @@ public class StructureUtility {
return to.get().check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.get().couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.get().placeBlock(t, world, x, y, z, trigger);
@@ -1914,6 +2274,11 @@ public class StructureUtility {
return to.apply(t).check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.apply(t).couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.apply(t).placeBlock(t, world, x, y, z, trigger);
@@ -2126,6 +2491,11 @@ public class StructureUtility {
return to.apply(t, null).check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.apply(t, trigger).couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.apply(t, trigger).placeBlock(t, world, x, y, z, trigger);
@@ -2318,6 +2688,11 @@ public class StructureUtility {
return toCheck.apply(t).check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.apply(t, trigger).couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return to.apply(t, trigger).placeBlock(t, world, x, y, z, trigger);
@@ -2562,6 +2937,11 @@ public class StructureUtility {
return backing.check(t, world, x, y, z);
}
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
ItemStack newTrigger = ChannelDataAccessor.withChannel(trigger, channel);
return backing.couldBeValid(t, world, x, y, z, newTrigger);
}
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
ItemStack newTrigger = ChannelDataAccessor.withChannel(trigger, channel);
// We know spawnHint will only be called on client side, so the lack of player isn't quite an issue
@@ -3045,4 +3425,57 @@ public class StructureUtility {
}
return shape;
}
/**
* Performs a creation, removal, or update operation at the given position
*
* @param trigger ItemStack for the trigger item
* @param onCreate Operation to be performed when the mode of the trigger is set to building mode
* @param onUpdate Operation to be performed when the mode of the trigger is set to updating mode
* @param onRemove Operation to be performed when the mode of the trigger is set to removing mode
*/
public static void placeRemoveOrUpdate(ItemStack trigger, Runnable onCreate, Runnable onUpdate, Runnable onRemove) {
ItemConstructableTrigger.TriggerMode mode = ItemConstructableTrigger.getMode(trigger);
switch (mode) {
case BUILDING:
onCreate.run();
break;
case UPDATING:
onUpdate.run();
break;
case REMOVING:
onRemove.run();
break;
}
}
public static boolean tryGiveOrDropItem(World world, EntityPlayer actor, ItemStack stack) {
if (actor.inventory.addItemStackToInventory(stack)) {
actor.inventoryContainer.detectAndSendChanges();
return true;
}
EntityItem toSpawn = new EntityItem(world, actor.posX, actor.posY, actor.posZ, stack);
// For some reason these things sometimes spawn with the velocity of an F1 car, so let's prevent that
toSpawn.motionX = 0;
toSpawn.motionY = 0;
toSpawn.motionZ = 0;
return world.spawnEntityInWorld(toSpawn);
}
public static boolean checkPermission(World world, EntityPlayer actor, int x, int y, int z) {
boolean res = true;
if (isSULoaded) {
res = ServerUtilitiesCompat.checkPermission(world, actor, x, z);
}
res = res && !world.getBlock(x, y, z).isAssociatedBlock(Blocks.bedrock);
// maybe check mining level who knows :shrug:
return res;
}
public static PlaceResult checkForRemoving(ItemConstructableTrigger.TriggerMode mode, boolean checkResult,
World world, int x, int y, int z) {
if (mode != REMOVING && checkResult) return PlaceResult.SKIP;
else if (mode != BUILDING && !checkResult && !world.isAirBlock(x, y, z)) return PlaceResult.REJECT;
return PlaceResult.ACCEPT;
}
}
@@ -0,0 +1,29 @@
package com.gtnewhorizon.structurelib.xmod;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import cpw.mods.fml.common.Optional;
import serverutils.data.ClaimedChunks;
import serverutils.lib.data.ForgePlayer;
import serverutils.lib.data.ForgeTeam;
import serverutils.lib.data.Universe;
import serverutils.lib.math.ChunkDimPos;
public class ServerUtilitiesCompat {
@Optional.Method(modid = "serverutilities")
public static boolean checkPermission(World world, EntityPlayer actor, int x, int z) {
final ForgeTeam owningTeam = ClaimedChunks.instance
.getChunkTeam(new ChunkDimPos(x >> 4, z >> 4, world.provider.dimensionId));
if (owningTeam == null) {
return true;
}
final ForgePlayer currentPlayer = new ForgePlayer(
Universe.get(),
actor.getUniqueID(),
actor.getCommandSenderName());
return owningTeam.isAlly(currentPlayer) || owningTeam.isMember(currentPlayer);
}
}
+74
View File
@@ -178,6 +178,80 @@ StructureLib API documentation.
Just give me a better name and I'd do the renaming.
<h3>Channel Descriptions</h3>
<p>
Each channel can have one description associated with it per mod.
Channel description should briefly describe how a specific channel is used for inside a specific mod.
They will be displayed to player in channel editor GUI that comes with StructureLib.
The registration process can be done either via direct method call to {@link com.gtnewhorizon.structurelib.StructureLibAPI#registerChannelDescription(String, String, String)},
or by sending an IMC message.
After registration, the channel will also show up as autocomplete options when players are editing channels.
</p>
<p>
Here is an example of sending an IMC message to register two channels and their description.
In this example, we assume your modid is <code>my_mod</code> and your mod will ship with localization entries for
localization key <code>channels.my_mod.channel_1</code> and <code>channels.my_mod.channel_2</code>
</p>
<pre>
NBTTagCompound command = new NBTTagCompound();
NBTTagList tags = new NBTTagList();
String[] channels = {"channel_1", "channel_2"};
for (String channel : channels) {
NBTTagCompound tag = new NBTTagCompound();
tag.setString("Channel", channel);
tag.setString("Description", "channels.my_mod." + channel);
tags.appendTag(tag);
}
command.setTag("Channels", tags);
FMLInterModComms.sendMessage("structurelib", "register_channel", command);
</pre>
<p>
There is no strict rules over whether you should do direct API method call or send IMC messages.
You can choose whichever you prefer.
</p>
<h3>Channel Indicator Items</h3>
<p>
You can associate an ItemStack with a given (channel, value) pair.
It is usually (but not required to be) the ItemBlock for the blocks to be placed by this (channel, value) pair.
Player will be able to drag and drop this item to the builtin channel configuration GUI.
The registration process can be done either via direct method call to {@link com.gtnewhorizon.structurelib.StructureLibAPI#registerChannelItem(String, String, int, net.minecraft.item.ItemStack)},
or by sending an IMC message.
After registration, the channel will also show up as autocomplete options when players are editing channels.
</p>
<p>
Here is an example of sending an IMC message to register 3 vanilla sandstone as different indicator for channel "sandstone", with block metadata plus 1 as channel value.
In this example, we assume your modid is <code>my_mod</code>.
</p>
<pre>
NBTTagCompound command = new NBTTagCompound();
NBTTagList items = new NBTTagList();
int[] metas = {0, 1, 2};
for (int meta : metas) {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag("Item", new ItemStack(Blocks.sandstone, 1, meta).writeToNBT(new NBTTagCompound()));
NBTTagList channels = new NBTTagList();
NBTTagCompound channel = new NBTTagCompound();
channel.setString("Channel", "sandstone");
channel.setInteger("Value", meta + 1);
channels.appendTag(channel);
tag.setTag("Channels", channels);
items.appendTag(tag);
}
command.setTag("Items", items);
FMLInterModComms.sendMessage("structurelib", "register_channel_item", command);
</pre>
<p>
There is no strict rules over whether you should do direct API method call or send IMC messages.
You can choose whichever you prefer.
</p>
<h3>Examples</h3>
<h4>For Structure Definition Author</h4>
@@ -1,3 +1,4 @@
tile.structurelib.blockhint.name=Hint
tile.structurelib.blockhint.0.name=Hint 1 dot
tile.structurelib.blockhint.1.name=Hint 2 dots
tile.structurelib.blockhint.2.name=Hint 3 dots
@@ -21,6 +22,9 @@ item.structurelib.frontRotationTool.desc.1=Rotates only the front panel,
item.structurelib.frontRotationTool.desc.2=which allows structure rotation.
item.structurelib.constructableTrigger.name=Multiblock Structure Hologram Projector
item.structurelib.constructableTrigger.modes.0=Building Mode
item.structurelib.constructableTrigger.modes.1=Updating Mode
item.structurelib.constructableTrigger.modes.2=Removing Mode
item.structurelib.constructableTrigger.desc.0=Triggers Constructable Interface
item.structurelib.constructableTrigger.desc.1=Shows multiblock construction schematic,
item.structurelib.constructableTrigger.desc.2=use on the multiblock controller.
@@ -29,12 +33,26 @@ item.structurelib.constructableTrigger.desc.4=Quantity of schematics in item sta
item.structurelib.constructableTrigger.desc.5=Hold §l[LSHIFT]§r to display channel data
item.structurelib.constructableTrigger.desc.lshift.0=Contain %d sub channel.
item.structurelib.constructableTrigger.too_fast=Please wait %d milliseconds before another autoplace...
item.structurelib.constructableTrigger.gui.title=Sub Channels
item.structurelib.constructableTrigger.gui.key=Key:
item.structurelib.constructableTrigger.gui.value=Value:
item.structurelib.constructableTrigger.gui.add=Add
item.structurelib.constructableTrigger.gui.set=Set
item.structurelib.constructableTrigger.gui.unset=Unset
item.structurelib.constructableTrigger.gui.wipe=§4Wipe
item.structurelib.constructableTrigger.gui.error.show=Show Errors
item.structurelib.constructableTrigger.gui.error.hide=Hide Errors
item.structurelib.constructableTrigger.gui.gt_no_hatch.enable=No Hatch
item.structurelib.constructableTrigger.gui.gt_no_hatch.disable=Hatches
item.structurelib.constructableTrigger.keyCategory=Multiblock Structure Hologram Projector Keys
item.structurelib.constructableTrigger.keys.cycleMode=Cycle Projector Mode
item.structurelib.constructableTrigger.gui.channels.from=§rMod: §9§o%s
item.structurelib.constructableTrigger.gui.info=Many multiblocks support some degree of variation in its structure and use sub channels to indicate which variant to use.\n Sub channels are has a sequence of lower case characters as key and a positive integer as value. Most known sub channels should be available as typeahead completions.\nYou can also drag and drop items from NEI to set the corresponding sub channel value. These items all have a tooltip of §oIndicates value X for sub channel Y§r.
channels.structurelib.show_errors=When set, will highlight parts of the multiblock that is definitely wrong
structurelib.tooltip.channelvalue=§7Indicates value §6%d§r§7 for sub channel §6%s
structurelib.tooltip.indicator_dnd=Drop into GUI to select this value for this channel
structurelib.autoplace.built_stat=Built %s blocks
structurelib.autoplace.complete=§aThis multiblock has completed!
@@ -1,3 +1,4 @@
tile.structurelib.blockhint.name=提示方块
tile.structurelib.blockhint.0.name=提示方块:1号
tile.structurelib.blockhint.1.name=提示方块:2号
tile.structurelib.blockhint.2.name=提示方块:3号
@@ -29,12 +30,20 @@ item.structurelib.constructableTrigger.desc.4=此物品堆叠数量会影响显
item.structurelib.constructableTrigger.desc.5=按下 §l[左SHIFT]§r 以显示子信道
item.structurelib.constructableTrigger.desc.lshift.0=包含 %d 个子信道
item.structurelib.constructableTrigger.too_fast=请在下一次自动搭建前等待 %d 毫秒...
item.structurelib.constructableTrigger.gui.title=子信道
item.structurelib.constructableTrigger.gui.key=信道名:
item.structurelib.constructableTrigger.gui.value=值:
item.structurelib.constructableTrigger.gui.add=添加
item.structurelib.constructableTrigger.gui.set=替换
item.structurelib.constructableTrigger.gui.unset=删除
item.structurelib.constructableTrigger.gui.wipe=§4全部清空
item.structurelib.constructableTrigger.gui.channels.from=§r模组: §9§o%s
item.structurelib.constructableTrigger.gui.info=许多多方块的结构都是可变的,在自动放置时,可以使用子信道来向多方块指明该使用哪一个变体。\n子信道由一个字符串标识、并拥有一个正整数作为值。这个GUI中的信道名支持自动补全到绝大多数已知的子信道。\n你也可以将部分物品从NEI中拖拽至GUI内来设置子信道值为该物品表示的值。这些物品的物品说明中都带有§o表示子信道 X 为 Y§r。
channels.structurelib.show_errors=添加后,在投影时会高亮标出必然错误的部分
structurelib.tooltip.channelvalue=§7表示子信道 §6%2$s§r§7 为 §6%d§r
structurelib.tooltip.indicator_dnd=拖入GUI中来选择该值
structurelib.autoplace.built_stat=已放置 %s 个方块
structurelib.autoplace.complete=§a这个多方块结构已经完成自动搭建!
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 386 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 365 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 667 B