From 5aae241da8ccbc9d48d855908c9b62861a885cc6 Mon Sep 17 00:00:00 2001 From: Jay113355 Date: Sun, 9 Jul 2023 16:34:29 -0500 Subject: [PATCH] Port to 1.16.5 --- build.gradle | 111 ++++-- gradle/wrapper/gradle-wrapper.properties | 2 +- .../mcf/davidee/nbtedit/CommandNBTEdit.java | 65 ---- .../java/com/mcf/davidee/nbtedit/NBTEdit.java | 128 ++++--- .../mcf/davidee/nbtedit/NBTEditConfig.java | 31 ++ .../com/mcf/davidee/nbtedit/NBTHelper.java | 18 +- .../mcf/davidee/nbtedit/NBTStringHelper.java | 134 ++++--- .../mcf/davidee/nbtedit/TileEntityHelper.java | 32 -- .../davidee/nbtedit/command/CommandBase.java | 181 +++++++++ .../nbtedit/command/NBTEditCommand.java | 65 ++++ .../davidee/nbtedit/forge/ClientProxy.java | 153 ++------ .../davidee/nbtedit/forge/CommonProxy.java | 29 +- .../davidee/nbtedit/gui/CharacterFilter.java | 5 +- .../nbtedit/gui/GuiCharacterButton.java | 41 +- .../mcf/davidee/nbtedit/gui/GuiEditNBT.java | 238 +++++++----- .../davidee/nbtedit/gui/GuiEditNBTTree.java | 204 +++++----- .../mcf/davidee/nbtedit/gui/GuiNBTButton.java | 40 +- .../mcf/davidee/nbtedit/gui/GuiNBTNode.java | 59 +-- .../mcf/davidee/nbtedit/gui/GuiNBTTree.java | 355 +++++++++++------- .../nbtedit/gui/GuiSaveSlotButton.java | 66 ++-- .../mcf/davidee/nbtedit/gui/GuiTextField.java | 311 +++++++-------- .../davidee/nbtedit/nbt/NBTNodeSorter.java | 20 +- .../com/mcf/davidee/nbtedit/nbt/NBTTree.java | 81 ++-- .../com/mcf/davidee/nbtedit/nbt/NamedNBT.java | 12 +- .../mcf/davidee/nbtedit/nbt/SaveStates.java | 24 +- .../nbtedit/packets/EntityDataPacket.java | 44 +++ .../nbtedit/packets/EntityNBTPacket.java | 104 ----- .../nbtedit/packets/EntityRequestPacket.java | 32 +- .../nbtedit/packets/EntitySavePacket.java | 77 ++++ .../nbtedit/packets/MouseOverPacket.java | 46 +-- .../nbtedit/packets/PacketHandler.java | 98 ++--- .../nbtedit/packets/TileDataPacket.java | 44 +++ .../nbtedit/packets/TileNBTPacket.java | 89 ----- .../nbtedit/packets/TileRequestPacket.java | 39 +- .../nbtedit/packets/TileSavePacket.java | 68 ++++ src/main/resources/META-INF/mods.toml | 30 ++ src/main/resources/pack.mcmeta | 6 + 37 files changed, 1719 insertions(+), 1363 deletions(-) delete mode 100644 src/main/java/com/mcf/davidee/nbtedit/CommandNBTEdit.java create mode 100644 src/main/java/com/mcf/davidee/nbtedit/NBTEditConfig.java delete mode 100644 src/main/java/com/mcf/davidee/nbtedit/TileEntityHelper.java create mode 100644 src/main/java/com/mcf/davidee/nbtedit/command/CommandBase.java create mode 100644 src/main/java/com/mcf/davidee/nbtedit/command/NBTEditCommand.java create mode 100644 src/main/java/com/mcf/davidee/nbtedit/packets/EntityDataPacket.java delete mode 100644 src/main/java/com/mcf/davidee/nbtedit/packets/EntityNBTPacket.java create mode 100644 src/main/java/com/mcf/davidee/nbtedit/packets/EntitySavePacket.java create mode 100644 src/main/java/com/mcf/davidee/nbtedit/packets/TileDataPacket.java delete mode 100644 src/main/java/com/mcf/davidee/nbtedit/packets/TileNBTPacket.java create mode 100644 src/main/java/com/mcf/davidee/nbtedit/packets/TileSavePacket.java create mode 100644 src/main/resources/META-INF/mods.toml create mode 100644 src/main/resources/pack.mcmeta diff --git a/build.gradle b/build.gradle index 7ce3fdf..e1aa17f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,48 +1,99 @@ buildscript { repositories { - jcenter() - maven { url = "http://files.minecraftforge.net/maven" } + // These repositories are only for Gradle plugins, put any other repositories in the repository block further below + maven { url = 'https://maven.minecraftforge.net' } + mavenCentral() } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' + classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true } } -apply plugin: 'net.minecraftforge.gradle.forge' +apply plugin: 'net.minecraftforge.gradle' -version = "1.12-2.0.2" -group = "com.mcf.davidee.nbtedit" -archivesBaseName = "NBTEdit" +group = 'com.mcf.davidee.nbtedit' +version = '1.16.5-2.0.0' -sourceCompatibility = targetCompatibility = 1.7 - -idea { module { inheritOutputDirs = true } } +java { + withSourcesJar() + archivesBaseName = 'NBTEdit' + toolchain.languageVersion = JavaLanguageVersion.of(8) +} minecraft { - version = "1.12-14.21.0.2341" - runDir = "run" - mappings = "snapshot_20170617" - // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. + mappings channel: 'official', version: '1.16.5' + + accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') + + runs { + client { + workingDirectory project.file('run_client') + mods { + nbtedit { + source sourceSets.main + } + } + } + + server { + workingDirectory project.file('run_server') + mods { + nbtedit { + source sourceSets.main + } + } + } + + data { + workingDirectory project.file('run_data') + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + args '--mod', 'nbtedit', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') + + mods { + nbtedit { + source sourceSets.main + } + } + } + } } -task deobfJar(type: Jar) { - from sourceSets.main.output - appendix = 'deobf' +// Include resources generated by data generators. +sourceSets.main.resources { srcDir 'src/generated/resources' } + +repositories { } -tasks.build.dependsOn('sourceJar', 'deobfJar') +dependencies { + minecraft 'net.minecraftforge:forge:1.16.5-36.2.35' +} -processResources { - from (sourceSets.main.resources.srcDirs) { - include '**/*.info' - expand 'version':project.version, 'mcversion':project.minecraft.version +// Example for how to get properties into the manifest for reading at runtime. +jar { + manifest { + attributes([ + 'Specification-Title' : 'nbtedit', + 'Specification-Vendor' : 'Jay113355', + 'Specification-Version' : '1', // We are version 1 of ourselves + 'Implementation-Title' : project.name, + 'Implementation-Version' : project.jar.archiveVersion, + 'Implementation-Vendor' : 'Jay113355', + 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) } - from(sourceSets.main.resources.srcDirs) { exclude '**/*.info' } } -allprojects { - gradle.projectsEvaluated { - tasks.withType(JavaCompile) { - options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" - } - } -} \ No newline at end of file +task deobfJar(type: Jar) { // Generate deobfuscated + from sourceSets.main.output + classifier = 'deobf' +} + +artifacts { + sourcesJar + deobfJar +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation +} + +jar.finalizedBy('reobfJar', 'deobfJar') diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 678d9d8..992eac5 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip diff --git a/src/main/java/com/mcf/davidee/nbtedit/CommandNBTEdit.java b/src/main/java/com/mcf/davidee/nbtedit/CommandNBTEdit.java deleted file mode 100644 index 40223fc..0000000 --- a/src/main/java/com/mcf/davidee/nbtedit/CommandNBTEdit.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.mcf.davidee.nbtedit; - -import com.mcf.davidee.nbtedit.packets.MouseOverPacket; -import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommandSender; -import net.minecraft.command.WrongUsageException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.math.BlockPos; -import org.apache.logging.log4j.Level; - -public class CommandNBTEdit extends CommandBase { - - @Override - public String getName() { - return "nbtedit"; - } - - @Override - public String getUsage(ICommandSender sender) { - return "/nbtedit OR /nbtedit OR /nbtedit "; - } - - @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { - if (sender instanceof EntityPlayerMP) { - EntityPlayerMP player = (EntityPlayerMP) sender; - - if (args.length == 3) { - int x = parseInt(args[0]); - int y = parseInt(args[1]); - int z = parseInt(args[2]); - NBTEdit.log(Level.TRACE, sender.getName() + " issued command \"/nbtedit " + x + " " + y + " " + z + "\""); - NBTEdit.NETWORK.sendTile(player, new BlockPos(x, y, z)); - - } else if (args.length == 1) { - int entityID = (args[0].equalsIgnoreCase("me")) ? player.getEntityId() : parseInt(args[0], 0); - NBTEdit.log(Level.TRACE, sender.getName() + " issued command \"/nbtedit " + entityID + "\""); - NBTEdit.NETWORK.sendEntity(player, entityID); - - } else if (args.length == 0) { - NBTEdit.log(Level.TRACE, sender.getName() + " issued command \"/nbtedit\""); - NBTEdit.NETWORK.INSTANCE.sendTo(new MouseOverPacket(), player); - - } else { - String s = ""; - for (int i = 0; i < args.length; ++i) { - s += args[i]; - if (i != args.length - 1) - s += " "; - } - NBTEdit.log(Level.TRACE, sender.getName() + " issued invalid command \"/nbtedit " + s + "\""); - throw new WrongUsageException("Pass 0, 1, or 3 integers -- ex. /nbtedit"); - } - } - } - - @Override - public boolean checkPermission(MinecraftServer server, ICommandSender sender) { - return sender instanceof EntityPlayer && NBTEdit.proxy.checkPermission((EntityPlayer) sender); - } - -} diff --git a/src/main/java/com/mcf/davidee/nbtedit/NBTEdit.java b/src/main/java/com/mcf/davidee/nbtedit/NBTEdit.java index 2406648..9783ce2 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/NBTEdit.java +++ b/src/main/java/com/mcf/davidee/nbtedit/NBTEdit.java @@ -1,107 +1,115 @@ package com.mcf.davidee.nbtedit; +import com.mcf.davidee.nbtedit.command.NBTEditCommand; +import com.mcf.davidee.nbtedit.forge.ClientProxy; import com.mcf.davidee.nbtedit.forge.CommonProxy; import com.mcf.davidee.nbtedit.nbt.NBTNodeSorter; import com.mcf.davidee.nbtedit.nbt.NBTTree; import com.mcf.davidee.nbtedit.nbt.NamedNBT; import com.mcf.davidee.nbtedit.nbt.SaveStates; import com.mcf.davidee.nbtedit.packets.PacketHandler; -import net.minecraft.command.ServerCommandManager; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.server.MinecraftServer; -import net.minecraftforge.common.config.Configuration; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.minecraft.command.CommandSource; +import net.minecraft.nbt.CompoundNBT; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.common.ForgeConfigSpec; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.RegisterCommandsEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.Mod.EventHandler; -import net.minecraftforge.fml.common.Mod.Instance; -import net.minecraftforge.fml.common.ModMetadata; -import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.event.FMLInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.event.FMLServerStartingEvent; +import net.minecraftforge.fml.config.ModConfig; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLEnvironment; +import net.minecraftforge.server.permission.DefaultPermissionLevel; +import net.minecraftforge.server.permission.PermissionAPI; +import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.appender.FileAppender; import org.apache.logging.log4j.core.layout.PatternLayout; import java.io.File; -@Mod(modid = NBTEdit.MODID, name = NBTEdit.NAME, version = NBTEdit.VERSION, acceptableRemoteVersions = "*") +@Mod(NBTEdit.MODID) public class NBTEdit { public static final String MODID = "nbtedit"; - public static final String NAME = "In-game NBTEdit"; - public static final String VERSION = "1.11.2-2.0.2"; + public static final String NAME = "NBTEdit"; + public static final String VERSION = "1.16.5-2.0.0"; public static final NBTNodeSorter SORTER = new NBTNodeSorter(); public static final PacketHandler NETWORK = new PacketHandler(); - public static Logger logger; + public static Logger logger = LogManager.getLogger(NAME); + public static CommonProxy proxy = new CommonProxy(); public static NamedNBT clipboard = null; public static boolean opOnly = true; public static boolean editOtherPlayers = false; - @Instance(MODID) + static Pair configPair; + private static NBTEdit instance; + private SaveStates saves; - @SidedProxy(clientSide = "com.mcf.davidee.nbtedit.forge.ClientProxy", serverSide = "com.mcf.davidee.nbtedit.forge.CommonProxy") - public static CommonProxy proxy; + public NBTEdit() { + instance = this; + // Register the setup method for modloading + FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); + FMLJavaModLoadingContext.get().getModEventBus().addListener(this::init); + MinecraftForge.EVENT_BUS.register(this); + MinecraftForge.EVENT_BUS.register(NBTEditConfig.class); - private SaveStates saves; + //Load the config + configPair = new ForgeConfigSpec.Builder().configure(NBTEditConfig::new); + ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, configPair.getValue()); - @EventHandler - public void preInit(FMLPreInitializationEvent event) { - Configuration config = new Configuration(event.getSuggestedConfigurationFile()); - config.load(); - opOnly = config.get("General", "opOnly", true, "true if only Ops can NBTEdit; false allows users in creative mode to NBTEdit").getBoolean(true); - editOtherPlayers = config.get("General", "editOtherPlayers", false, "true if editing players other then your self is allowed. false by default. USE AT YOUR OWN RISK").getBoolean(false); - if (config.hasChanged()) { - config.save(); + if (FMLEnvironment.dist == Dist.CLIENT) { + proxy = new ClientProxy(); } + } + + public void setup(FMLCommonSetupEvent event) { + NBTEditConfig config = configPair.getKey(); + opOnly = config.opOnly(); + editOtherPlayers = config.editOtherPlayers(); - logger = event.getModLog(); - org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger) logger; - log.setAdditive(false); //Sets our logger to not show up in console. - log.setLevel(Level.ALL); + org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) logger; + coreLogger.setAdditive(false); //Sets our logger to not show up in console. + coreLogger.setLevel(Level.ALL); // Set up our file logging. PatternLayout layout = PatternLayout.newBuilder().withPattern("[%d{MM-dd HH:mm:ss}] [%level]: %msg%n").build(); - FileAppender.Builder builder = FileAppender.newBuilder(); - builder.withFileName("logs/NBTEdit.log").withName("NBTEdit File Appender").withLayout(layout).withIgnoreExceptions(false); - FileAppender appender = builder.build(); + FileAppender appender = FileAppender.newBuilder() + .withFileName("logs/nbtedit.log") + .setName("NBTEdit File Appender") + .setLayout(layout) + .setIgnoreExceptions(false) + .build(); appender.start(); - log.addAppender(appender); - - ModMetadata m = event.getModMetadata(); - m.autogenerated = false; - m.modId = MODID; - m.version = VERSION; - m.name = NAME; - m.authorList.add("Davidee"); - - m.credits = "Thanks to Mojang, Forge, and all your support."; - m.description = "Allows you to edit NBT Tags in-game.\nPlease visit the URL above for help."; - m.url = "http://www.minecraftforum.net/topic/1558668-151/"; - } + coreLogger.addAppender(appender); - @EventHandler - public void init(FMLInitializationEvent event) { - logger.trace("NBTEdit Initalized"); - saves = new SaveStates(new File(new File(proxy.getMinecraftDirectory(), "saves"), "NBTEdit.dat")); NETWORK.initialize(); } - @EventHandler - public void postInit(FMLPostInitializationEvent event) { + public void init(FMLLoadCompleteEvent event) { + logger.trace("NBTEdit Initialized"); + saves = new SaveStates(new File(new File(proxy.getMinecraftDirectory(), "saves"), "nbtedit.dat")); proxy.registerInformation(); } - @EventHandler - public void serverStarting(FMLServerStartingEvent event) { - MinecraftServer server = event.getServer(); - ServerCommandManager serverCommandManager = (ServerCommandManager) server.getCommandManager(); - serverCommandManager.registerCommand(new CommandNBTEdit()); + @SubscribeEvent + public void onRegisterCommands(RegisterCommandsEvent event) { + CommandDispatcher dispatcher = event.getDispatcher(); + LiteralArgumentBuilder builder = LiteralArgumentBuilder.literal(NBTEditCommand.INSTANCE.commandName()); + NBTEditCommand.INSTANCE.buildCommand(builder); + dispatcher.register(builder); logger.trace("Server Starting -- Added \"/nbtedit\" command"); + PermissionAPI.registerNode("nbtedit.edit", DefaultPermissionLevel.OP, "Allows the user to edit NBT data"); } public static void log(Level l, String s) { @@ -114,7 +122,7 @@ public static void throwing(String cls, String mthd, Throwable thr) { static final String SEP = System.getProperty("line.separator"); - public static void logTag(NBTTagCompound tag) { + public static void logTag(CompoundNBT tag) { NBTTree tree = new NBTTree(tag); String sb = ""; for (String s : tree.toStrings()) { diff --git a/src/main/java/com/mcf/davidee/nbtedit/NBTEditConfig.java b/src/main/java/com/mcf/davidee/nbtedit/NBTEditConfig.java new file mode 100644 index 0000000..7dc5335 --- /dev/null +++ b/src/main/java/com/mcf/davidee/nbtedit/NBTEditConfig.java @@ -0,0 +1,31 @@ +package com.mcf.davidee.nbtedit; + +import net.minecraftforge.common.ForgeConfigSpec; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.config.ModConfig; + +public class NBTEditConfig { + ForgeConfigSpec.BooleanValue opOnly; + ForgeConfigSpec.BooleanValue editOtherPlayers; + + public NBTEditConfig(ForgeConfigSpec.Builder builder) { + this.opOnly = builder.comment("true if only Ops can NBTEdit; false allows users in creative mode to NBTEdit") + .define("op_only", true); + this.editOtherPlayers = builder.comment("true if editing players other then your self is allowed. false by default. USE AT YOUR OWN RISK") + .define("edit_other_players", false); + } + + @SubscribeEvent + public static void onConfigLoad(ModConfig.ModConfigEvent event) { + NBTEdit.opOnly = NBTEdit.configPair.getKey().opOnly(); + NBTEdit.editOtherPlayers = NBTEdit.configPair.getKey().editOtherPlayers(); + } + + public boolean opOnly() { + return opOnly.get(); + } + + public boolean editOtherPlayers() { + return editOtherPlayers.get(); + } +} diff --git a/src/main/java/com/mcf/davidee/nbtedit/NBTHelper.java b/src/main/java/com/mcf/davidee/nbtedit/NBTHelper.java index 2aa0a2b..29cfae5 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/NBTHelper.java +++ b/src/main/java/com/mcf/davidee/nbtedit/NBTHelper.java @@ -5,7 +5,7 @@ import io.netty.buffer.ByteBufOutputStream; import io.netty.handler.codec.EncoderException; import net.minecraft.nbt.*; -import net.minecraftforge.fml.relauncher.ReflectionHelper; +import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import java.io.DataInputStream; import java.io.DataOutput; @@ -15,24 +15,24 @@ public class NBTHelper { - public static NBTTagCompound nbtRead(DataInputStream in) throws IOException { + public static CompoundNBT nbtRead(DataInputStream in) throws IOException { return CompressedStreamTools.read(in); } - public static void nbtWrite(NBTTagCompound compound, DataOutput out) throws IOException { + public static void nbtWrite(CompoundNBT compound, DataOutput out) throws IOException { CompressedStreamTools.write(compound, out); } - public static Map getMap(NBTTagCompound tag) { - return ReflectionHelper.getPrivateValue(NBTTagCompound.class, tag, 2); + public static Map getMap(CompoundNBT tag) { + return ObfuscationReflectionHelper.getPrivateValue(CompoundNBT.class, tag, "field_74784_a"); } - public static NBTBase getTagAt(NBTTagList tag, int index) { - List list = ReflectionHelper.getPrivateValue(NBTTagList.class, tag, 1); + public static INBT getTagAt(ListNBT tag, int index) { + List list = ObfuscationReflectionHelper.getPrivateValue(ListNBT.class, tag, "field_74747_a"); return list.get(index); } - public static void writeToBuffer(NBTTagCompound nbt, ByteBuf buf) { + public static void writeToBuffer(CompoundNBT nbt, ByteBuf buf) { if (nbt == null) { buf.writeByte(0); } else { @@ -44,7 +44,7 @@ public static void writeToBuffer(NBTTagCompound nbt, ByteBuf buf) { } } - public static NBTTagCompound readNbtFromBuffer(ByteBuf buf) { + public static CompoundNBT readNbtFromBuffer(ByteBuf buf) { int index = buf.readerIndex(); byte isNull = buf.readByte(); diff --git a/src/main/java/com/mcf/davidee/nbtedit/NBTStringHelper.java b/src/main/java/com/mcf/davidee/nbtedit/NBTStringHelper.java index 6e37ce1..6c1a2a3 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/NBTStringHelper.java +++ b/src/main/java/com/mcf/davidee/nbtedit/NBTStringHelper.java @@ -1,29 +1,21 @@ package com.mcf.davidee.nbtedit; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagByte; -import net.minecraft.nbt.NBTTagByteArray; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagDouble; -import net.minecraft.nbt.NBTTagEnd; -import net.minecraft.nbt.NBTTagFloat; -import net.minecraft.nbt.NBTTagInt; -import net.minecraft.nbt.NBTTagIntArray; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.nbt.NBTTagLong; -import net.minecraft.nbt.NBTTagShort; -import net.minecraft.nbt.NBTTagString; +import net.minecraft.nbt.*; import com.google.common.base.Strings; import com.mcf.davidee.nbtedit.nbt.NamedNBT; +import net.minecraftforge.common.util.Constants; +/** + * TODO ENUM THE NBT STUFF. -Jay + */ public class NBTStringHelper { public static final char SECTION_SIGN = '\u00A7'; public static String getNBTName(NamedNBT namedNBT) { String name = namedNBT.getName(); - NBTBase obj = namedNBT.getNBT(); + INBT obj = namedNBT.getNBT(); String s = toString(obj); return Strings.isNullOrEmpty(name) ? "" + s : name + ": " + s; @@ -31,66 +23,64 @@ public static String getNBTName(NamedNBT namedNBT) { public static String getNBTNameSpecial(NamedNBT namedNBT) { String name = namedNBT.getName(); - NBTBase obj = namedNBT.getNBT(); + INBT obj = namedNBT.getNBT(); String s = toString(obj); return Strings.isNullOrEmpty(name) ? "" + s : name + ": " + s + SECTION_SIGN + 'r'; } - public static NBTBase newTag(byte type) { + public static INBT newTag(byte type) { switch (type) { - case 0: - return new NBTTagEnd(); - case 1: - return new NBTTagByte((byte) 0); - case 2: - return new NBTTagShort(); - case 3: - return new NBTTagInt(0); - case 4: - return new NBTTagLong(0); - case 5: - return new NBTTagFloat(0); - case 6: - return new NBTTagDouble(0); - case 7: - return new NBTTagByteArray(new byte[0]); - case 8: - return new NBTTagString(""); - case 9: - return new NBTTagList(); - case 10: - return new NBTTagCompound(); - case 11: - return new NBTTagIntArray(new int[0]); + case Constants.NBT.TAG_END: + return EndNBT.INSTANCE; + case Constants.NBT.TAG_BYTE: + return ByteNBT.ZERO; + case Constants.NBT.TAG_SHORT: + return ShortNBT.valueOf((short) 0); + case Constants.NBT.TAG_INT: + return IntNBT.valueOf(0); + case Constants.NBT.TAG_LONG: + return LongNBT.valueOf(0); + case Constants.NBT.TAG_FLOAT: + return FloatNBT.valueOf(0.0f); + case Constants.NBT.TAG_DOUBLE: + return DoubleNBT.valueOf(0.0d); + case Constants.NBT.TAG_BYTE_ARRAY: + return new ByteArrayNBT(new byte[0]); + case Constants.NBT.TAG_STRING: + return StringNBT.valueOf(""); + case Constants.NBT.TAG_LIST: + return new ListNBT(); + case Constants.NBT.TAG_COMPOUND: + return new CompoundNBT(); + case Constants.NBT.TAG_INT_ARRAY: + return new IntArrayNBT(new int[0]); + case Constants.NBT.TAG_LONG_ARRAY: + return new LongArrayNBT(new long[0]); default: return null; } } - public static String toString(NBTBase base) { + public static String toString(INBT base) { switch (base.getId()) { - case 1: - return "" + ((NBTTagByte) base).getByte(); - case 2: - return "" + ((NBTTagShort) base).getShort(); - case 3: - return "" + ((NBTTagInt) base).getInt(); - case 4: - return "" + ((NBTTagLong) base).getLong(); - case 5: - return "" + ((NBTTagFloat) base).getFloat(); - case 6: - return "" + ((NBTTagDouble) base).getDouble(); - case 7: + case Constants.NBT.TAG_BYTE: + case Constants.NBT.TAG_SHORT: + case Constants.NBT.TAG_INT: + case Constants.NBT.TAG_LONG: + case Constants.NBT.TAG_FLOAT: + case Constants.NBT.TAG_DOUBLE: + return ((NumberNBT) base).getAsNumber().toString(); + case Constants.NBT.TAG_BYTE_ARRAY: return base.toString(); - case 8: - return ((NBTTagString) base).getString(); - case 9: + case Constants.NBT.TAG_STRING: + return base.getAsString(); + case Constants.NBT.TAG_LIST: return "(TagList)"; - case 10: + case Constants.NBT.TAG_COMPOUND: return "(TagCompound)"; - case 11: + case Constants.NBT.TAG_INT_ARRAY: + case Constants.NBT.TAG_LONG_ARRAY: return base.toString(); default: return "?"; @@ -99,28 +89,30 @@ public static String toString(NBTBase base) { public static String getButtonName(byte id) { switch (id) { - case 1: + case Constants.NBT.TAG_BYTE: return "Byte"; - case 2: + case Constants.NBT.TAG_SHORT: return "Short"; - case 3: + case Constants.NBT.TAG_INT: return "Int"; - case 4: + case Constants.NBT.TAG_LONG: return "Long"; - case 5: + case Constants.NBT.TAG_FLOAT: return "Float"; - case 6: + case Constants.NBT.TAG_DOUBLE: return "Double"; - case 7: + case Constants.NBT.TAG_BYTE_ARRAY: return "Byte[]"; - case 8: + case Constants.NBT.TAG_STRING: return "String"; - case 9: + case Constants.NBT.TAG_LIST: return "List"; - case 10: + case Constants.NBT.TAG_COMPOUND: return "Compound"; - case 11: - return "Int[]"; + case Constants.NBT.TAG_INT_ARRAY: + return "Int[]";/* + case Constants.NBT.TAG_LONG_ARRAY: + return "Int[]";*/ case 12: return "Edit"; case 13: diff --git a/src/main/java/com/mcf/davidee/nbtedit/TileEntityHelper.java b/src/main/java/com/mcf/davidee/nbtedit/TileEntityHelper.java deleted file mode 100644 index 1ed294a..0000000 --- a/src/main/java/com/mcf/davidee/nbtedit/TileEntityHelper.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.mcf.davidee.nbtedit; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import net.minecraft.tileentity.TileEntity; - -public class TileEntityHelper { - - public static void copyData(T from, T into) throws Exception { - Class clazz = from.getClass(); - Set fields = asSet(clazz.getFields(), clazz.getDeclaredFields()); - Field modifiers = Field.class.getDeclaredField("modifiers"); - modifiers.setAccessible(true); - for (Field field : fields) { - field.setAccessible(true); - modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); - field.set(into, field.get(from)); - } - } - - public static Set asSet(Field[] a, Field[] b) { - HashSet s = new HashSet<>(); - Collections.addAll(s, a); - Collections.addAll(s, b); - return s; - } - -} diff --git a/src/main/java/com/mcf/davidee/nbtedit/command/CommandBase.java b/src/main/java/com/mcf/davidee/nbtedit/command/CommandBase.java new file mode 100644 index 0000000..3feafdc --- /dev/null +++ b/src/main/java/com/mcf/davidee/nbtedit/command/CommandBase.java @@ -0,0 +1,181 @@ +package com.mcf.davidee.nbtedit.command; + +import com.mcf.davidee.nbtedit.NBTEdit; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import net.minecraft.command.CommandException; +import net.minecraft.command.CommandSource; +import net.minecraft.command.Commands; +import net.minecraft.command.ISuggestionProvider; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.util.SharedConstants; +import net.minecraft.util.Util; +import net.minecraft.util.text.*; +import net.minecraft.util.text.event.ClickEvent; +import net.minecraft.util.text.event.HoverEvent; +import net.minecraftforge.fml.server.ServerLifecycleHooks; +import net.minecraftforge.server.permission.PermissionAPI; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Predicate; + +/** + * Created by Jay113355 on 7/12/2022. + */ +public abstract class CommandBase { + private final String commandName; + private final String permissionNode; + + public CommandBase(String commandName) { + this.commandName = commandName; + this.permissionNode = NBTEdit.MODID + ".command." + this.commandName(); + } + + public String commandName() { + return commandName; + } + + public abstract void buildCommand(LiteralArgumentBuilder builder); + + public Collection aliases() { + return Collections.emptySet(); + } + + public boolean hasSubPermission(CommandSource source, String subPermission) { + return hasPermission(source, permissionNode + "." + subPermission, 4); + } + + public boolean hasSubPermission(CommandSource source, String subPermission, int level) { + return hasPermission(source, permissionNode + "." + subPermission, level); + } + + public static boolean hasPermission(CommandSource source, String permission) { + return hasPermission(source, permission, 4); + } + + public static boolean hasPermission(CommandSource source, String permission, int level) { + if (source.getEntity() instanceof ServerPlayerEntity) { + return PermissionAPI.hasPermission((PlayerEntity) source.getEntity(), permission); + } else return source.hasPermission(level); + } + + @Nonnull + public static T requireObj(@Nullable T obj, String endMessage) throws CommandException { + if (obj != null) { + return obj; + } else throw getException(endMessage); + } + + @Nonnull + public static R requireIs(@Nullable O obj, Class is, String endMessage) throws CommandException { + if (is.isInstance(obj)) { + return (R) obj; + } else throw getException(endMessage); + } + + public static void requireTrue(boolean obj, String endMessage) throws CommandException { + if (!obj) { + endCommand(endMessage); + } + } + + @Nonnull + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + public static T requireOpt(Optional opt, String endMessage) throws CommandException { + if (opt.isPresent()) { + return opt.get(); + } else throw getException(endMessage); + } + + @Nonnull + public static ItemStack requireItem(@Nullable ItemStack stack, String message) throws CommandException { + if (stack == null || stack.isEmpty()) { + throw getException(message); + } + return stack; + } + + /** + * @param message The later part of a usage message, e.g. Usage: /commandName %message% + * @return throws CommandException with a usage message. + */ + public int sendUsage(String message) { + throw getException("Usage: /" + this.commandName() + " " + message); + } + + /** + * Terminates the command with a message + * @param message The message to send to the player. + * @throws CommandException 100% of the time. + */ + public static void endCommand(String message) throws CommandException { + throw getException(message); + } + + public static CommandException getException(String message) { + return new CommandException(message(message)) { + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + }; + } + + public static CompletableFuture suggestOnline(CommandContext context, final SuggestionsBuilder builder) { + ISuggestionProvider provider = context.getSource(); + ISuggestionProvider.suggest(provider.getOnlinePlayerNames(), builder); + return builder.buildFuture(); + } + + public static IFormattableTextComponent message(String text) { + return message(text, TextFormatting.RED); + } + + public static IFormattableTextComponent message(String text, TextFormatting color) { + IFormattableTextComponent message = new StringTextComponent(text); + message.withStyle(color); + return message; + } + + /** + * Shortcut for command building + */ + protected static LiteralArgumentBuilder literal(String literal) { + return LiteralArgumentBuilder.literal(literal); + } + + /** + * Shortcut for command building + */ + protected static RequiredArgumentBuilder argument(String argumentName, ArgumentType type) { + return RequiredArgumentBuilder.argument(argumentName, type); + } + + /** + * Shortcut for command building + */ + protected static Predicate permission(String permission) { + return source -> hasPermission(source, permission); + } + + /** + * Shortcut for command building + */ + protected Predicate subPermission(String permission) { + return source -> hasSubPermission(source, permission); + } +} diff --git a/src/main/java/com/mcf/davidee/nbtedit/command/NBTEditCommand.java b/src/main/java/com/mcf/davidee/nbtedit/command/NBTEditCommand.java new file mode 100644 index 0000000..9d16482 --- /dev/null +++ b/src/main/java/com/mcf/davidee/nbtedit/command/NBTEditCommand.java @@ -0,0 +1,65 @@ +package com.mcf.davidee.nbtedit.command; + +import com.mcf.davidee.nbtedit.NBTEdit; +import com.mcf.davidee.nbtedit.packets.MouseOverPacket; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.command.CommandSource; +import net.minecraft.command.arguments.BlockPosArgument; +import net.minecraft.command.arguments.EntityArgument; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fml.network.PacketDistributor; +import org.apache.logging.log4j.Level; + +public class NBTEditCommand extends CommandBase { + public static final NBTEditCommand INSTANCE = new NBTEditCommand(); + + public NBTEditCommand() { + super("nbtedit"); + } + + @Override + public void buildCommand(LiteralArgumentBuilder builder) { + builder + .executes(this::mouse) + .then(argument("entity", EntityArgument.entity()) + .executes(this::entity) + ) + .then(argument("tile", BlockPosArgument.blockPos()) + .executes(this::tile) + ); + } + + public int mouse(CommandContext context) throws CommandSyntaxException { + CommandSource source = context.getSource(); + ServerPlayerEntity player = context.getSource().getPlayerOrException(); + + NBTEdit.log(Level.TRACE, source.getTextName() + " issued command \"/nbtedit\""); + NBTEdit.NETWORK.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new MouseOverPacket()); + return 1; + } + + public int entity(CommandContext context) throws CommandSyntaxException { + CommandSource source = context.getSource(); + ServerPlayerEntity player = context.getSource().getPlayerOrException(); + Entity target = EntityArgument.getEntity(context, "entity"); + + int entityID = target.getId(); + NBTEdit.log(Level.TRACE, source.getTextName() + " issued command \"/nbtedit " + entityID + "\""); + NBTEdit.NETWORK.sendEntity(player, entityID); + return 1; + } + + public int tile(CommandContext context) throws CommandSyntaxException { + CommandSource source = context.getSource(); + ServerPlayerEntity player = context.getSource().getPlayerOrException(); + BlockPos pos = BlockPosArgument.getLoadedBlockPos(context, "tile"); + + NBTEdit.log(Level.TRACE, source.getTextName() + " issued command \"/nbtedit " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + "\""); + NBTEdit.NETWORK.sendTile(player, pos); + return 1; + } +} diff --git a/src/main/java/com/mcf/davidee/nbtedit/forge/ClientProxy.java b/src/main/java/com/mcf/davidee/nbtedit/forge/ClientProxy.java index 67ac380..29e258c 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/forge/ClientProxy.java +++ b/src/main/java/com/mcf/davidee/nbtedit/forge/ClientProxy.java @@ -5,34 +5,19 @@ import com.mcf.davidee.nbtedit.nbt.SaveStates; import com.mcf.davidee.nbtedit.packets.EntityRequestPacket; import com.mcf.davidee.nbtedit.packets.TileRequestPacket; -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.RenderGlobal; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.settings.KeyBinding; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.math.*; +import net.minecraft.util.text.IFormattableTextComponent; +import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; -import net.minecraft.world.World; -import net.minecraftforge.client.event.RenderWorldLastEvent; +import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.client.FMLClientHandler; +import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.client.registry.ClientRegistry; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.InputEvent; -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; +import org.lwjgl.glfw.GLFW; import java.io.File; @@ -46,133 +31,47 @@ public void registerInformation() { SaveStates save = NBTEdit.getSaveStates(); save.load(); save.save(); - NBTEditKey = new KeyBinding("NBTEdit Shortcut", Keyboard.KEY_NONE, "key.categories.misc"); + NBTEditKey = new KeyBinding("NBTEdit Shortcut", GLFW.GLFW_KEY_UNKNOWN, "key.categories.misc"); ClientRegistry.registerKeyBinding(NBTEditKey); } @Override public File getMinecraftDirectory() { - return FMLClientHandler.instance().getClient().mcDataDir; + return Minecraft.getInstance().gameDirectory; } @Override - public void openEditGUI(final int entityID, final NBTTagCompound tag) { - Minecraft.getMinecraft().addScheduledTask(new Runnable() { - @Override - public void run() { - Minecraft.getMinecraft().displayGuiScreen(new GuiEditNBTTree(entityID, tag)); - } - }); + public void openEditGUI(final int entityID, final CompoundNBT tag) { + Minecraft.getInstance().submit(() -> Minecraft.getInstance().setScreen(new GuiEditNBTTree(entityID, tag))); } @Override - public void openEditGUI(final BlockPos pos, final NBTTagCompound tag) { - Minecraft.getMinecraft().addScheduledTask(new Runnable() { - @Override - public void run() { - Minecraft.getMinecraft().displayGuiScreen(new GuiEditNBTTree(pos, tag)); - } - }); + public void openEditGUI(final BlockPos pos, final CompoundNBT tag) { + Minecraft.getInstance().submit(() -> Minecraft.getInstance().setScreen(new GuiEditNBTTree(pos, tag))); } @Override - public void sendMessage(EntityPlayer player, String message, TextFormatting color) { - ITextComponent component = new TextComponentString(message); - component.getStyle().setColor(color); - Minecraft.getMinecraft().player.sendMessage(component); - } - - @SubscribeEvent - public void renderWorldLast(RenderWorldLastEvent event) { - GuiScreen curScreen = Minecraft.getMinecraft().currentScreen; - if (curScreen instanceof GuiEditNBTTree) { - GuiEditNBTTree screen = (GuiEditNBTTree) curScreen; - Entity e = screen.getEntity(); - - if (e != null && e.isEntityAlive()) - drawBoundingBox(event.getContext(), event.getPartialTicks(), e.getEntityBoundingBox()); - else if (screen.isTileEntity()) { - int x = screen.getBlockX(); - int y = screen.y; - int z = screen.z; - World world = Minecraft.getMinecraft().world; - BlockPos pos = new BlockPos(x, y, z); - IBlockState state = world.getBlockState(pos); - Block block = world.getBlockState(pos).getBlock(); - if (block != null) { - //block.setBlockBoundsBasedOnState(world, pos); - drawBoundingBox(event.getContext(), event.getPartialTicks(), block.getSelectedBoundingBox(state, world, pos)); - } - } - } + public void sendMessage(PlayerEntity player, String message, TextFormatting color) { + IFormattableTextComponent component = new StringTextComponent(message); + component.withStyle(color); + Minecraft.getInstance().gui.getChat().addMessage(component); } @SubscribeEvent public void onKey(InputEvent.KeyInputEvent event) { - if (NBTEditKey.isPressed()) { - RayTraceResult pos = Minecraft.getMinecraft().objectMouseOver; + if (NBTEditKey.isDown()) { + RayTraceResult pos = Minecraft.getInstance().hitResult; if (pos != null) { - if (pos.entityHit != null) { - NBTEdit.NETWORK.INSTANCE.sendToServer(new EntityRequestPacket(pos.entityHit.getEntityId())); - } else if (pos.typeOfHit == RayTraceResult.Type.BLOCK) { - NBTEdit.NETWORK.INSTANCE.sendToServer(new TileRequestPacket(pos.getBlockPos())); + if (pos.getType() == RayTraceResult.Type.ENTITY) { + EntityRayTraceResult entityRay = (EntityRayTraceResult) pos; + NBTEdit.NETWORK.INSTANCE.sendToServer(new EntityRequestPacket(entityRay.getEntity().getId())); + } else if (pos.getType() == RayTraceResult.Type.BLOCK) { + BlockRayTraceResult blockRay = (BlockRayTraceResult) pos; + NBTEdit.NETWORK.INSTANCE.sendToServer(new TileRequestPacket(blockRay.getBlockPos())); } else { this.sendMessage(null, "Error - No tile or entity selected", TextFormatting.RED); } } } } - - private void drawBoundingBox(RenderGlobal r, float f, AxisAlignedBB aabb) { - if (aabb == null) - return; - - Entity player = Minecraft.getMinecraft().getRenderViewEntity(); - - double var8 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) f; - double var10 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) f; - double var12 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) f; - - aabb = aabb.grow(-var8, -var10, -var12); - - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GlStateManager.color(1.0F, 0.0F, 0.0F, .5F); - GL11.glLineWidth(3.5F); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder worldRenderer = tessellator.getBuffer(); - - worldRenderer.begin(3, DefaultVertexFormats.POSITION_COLOR); - worldRenderer.pos(aabb.minX, aabb.minY, aabb.minZ); - worldRenderer.pos(aabb.maxX, aabb.minY, aabb.minZ); - worldRenderer.pos(aabb.maxX, aabb.minY, aabb.maxZ); - worldRenderer.pos(aabb.minX, aabb.minY, aabb.maxZ); - worldRenderer.pos(aabb.minX, aabb.minY, aabb.minZ); - tessellator.draw(); - worldRenderer.begin(3, DefaultVertexFormats.POSITION_COLOR); - worldRenderer.pos(aabb.minX, aabb.maxY, aabb.minZ); - worldRenderer.pos(aabb.maxX, aabb.maxY, aabb.minZ); - worldRenderer.pos(aabb.maxX, aabb.maxY, aabb.maxZ); - worldRenderer.pos(aabb.minX, aabb.maxY, aabb.maxZ); - worldRenderer.pos(aabb.minX, aabb.maxY, aabb.minZ); - tessellator.draw(); - worldRenderer.begin(1, DefaultVertexFormats.POSITION_COLOR); - worldRenderer.pos(aabb.minX, aabb.minY, aabb.minZ); - worldRenderer.pos(aabb.minX, aabb.maxY, aabb.minZ); - worldRenderer.pos(aabb.maxX, aabb.minY, aabb.minZ); - worldRenderer.pos(aabb.maxX, aabb.maxY, aabb.minZ); - worldRenderer.pos(aabb.maxX, aabb.minY, aabb.maxZ); - worldRenderer.pos(aabb.maxX, aabb.maxY, aabb.maxZ); - worldRenderer.pos(aabb.minX, aabb.minY, aabb.maxZ); - worldRenderer.pos(aabb.minX, aabb.maxY, aabb.maxZ); - tessellator.draw(); - - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - - } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/forge/CommonProxy.java b/src/main/java/com/mcf/davidee/nbtedit/forge/CommonProxy.java index 7eb03c5..01619f4 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/forge/CommonProxy.java +++ b/src/main/java/com/mcf/davidee/nbtedit/forge/CommonProxy.java @@ -1,12 +1,14 @@ package com.mcf.davidee.nbtedit.forge; import com.mcf.davidee.nbtedit.NBTEdit; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.Util; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.IFormattableTextComponent; +import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.server.permission.PermissionAPI; import java.io.File; @@ -18,24 +20,21 @@ public File getMinecraftDirectory() { return new File("."); } - public void openEditGUI(int entityID, NBTTagCompound tag) { + public void openEditGUI(int entityID, CompoundNBT tag) { } - public void openEditGUI(BlockPos pos, NBTTagCompound tag) { + public void openEditGUI(BlockPos pos, CompoundNBT tag) { } - public void sendMessage(EntityPlayer player, String message, TextFormatting color) { + public void sendMessage(PlayerEntity player, String message, TextFormatting color) { if (player != null) { - ITextComponent component = new TextComponentString(message); - component.getStyle().setColor(color); - player.sendMessage(component); + IFormattableTextComponent component = new StringTextComponent(message); + component.withStyle(color); + player.sendMessage(component, Util.NIL_UUID); } } - public boolean checkPermission(EntityPlayer player) { - if (NBTEdit.opOnly ? player.canUseCommand(4, NBTEdit.MODID) : player.capabilities.isCreativeMode) { - return true; - } - return false; + public boolean checkPermission(PlayerEntity player) { + return NBTEdit.opOnly ? PermissionAPI.hasPermission(player, "nbtedit.edit") : player.isCreative(); } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/CharacterFilter.java b/src/main/java/com/mcf/davidee/nbtedit/gui/CharacterFilter.java index 567364f..7dd9486 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/CharacterFilter.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/CharacterFilter.java @@ -1,15 +1,14 @@ package com.mcf.davidee.nbtedit.gui; -import net.minecraft.util.ChatAllowedCharacters; - import com.mcf.davidee.nbtedit.NBTStringHelper; +import net.minecraft.util.SharedConstants; public class CharacterFilter { public static String filerAllowedCharacters(String str, boolean section) { StringBuilder sb = new StringBuilder(); char[] arr = str.toCharArray(); for (char c : arr) { - if (ChatAllowedCharacters.isAllowedCharacter(c) || (section && (c == NBTStringHelper.SECTION_SIGN || c == '\n'))) + if (SharedConstants.isAllowedChatCharacter(c) || (section && (c == NBTStringHelper.SECTION_SIGN || c == '\n'))) sb.append(c); } diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiCharacterButton.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiCharacterButton.java index 150d150..e6ce8b2 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiCharacterButton.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiCharacterButton.java @@ -1,34 +1,40 @@ package com.mcf.davidee.nbtedit.gui; +import com.mojang.blaze3d.matrix.MatrixStack; +import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.renderer.GlStateManager; - -public class GuiCharacterButton extends Gui { +import net.minecraft.client.gui.widget.Widget; +import net.minecraft.util.text.StringTextComponent; +import net.minecraftforge.fml.client.gui.GuiUtils; + +/** + * The special color symbol and newline buttons for the text editor. + */ +public class GuiCharacterButton extends Widget { public static final int WIDTH = 14, HEIGHT = 14; - private Minecraft mc = Minecraft.getMinecraft(); + private Minecraft mc = Minecraft.getInstance(); private byte id; - private int x, y; private boolean enabled; public GuiCharacterButton(byte id, int x, int y) { + super(x, y, WIDTH, HEIGHT, StringTextComponent.EMPTY); this.id = id; - this.x = x; - this.y = y; } - public void draw(int mx, int my) { - mc.renderEngine.bindTexture(GuiNBTNode.WIDGET_TEXTURE); - if (inBounds(mx, my)) - Gui.drawRect(x, y, x + WIDTH, y + HEIGHT, 0x80ffffff); + @Override + public void render(MatrixStack matrixStack, int mx, int my, float particleTicks) { + mc.getTextureManager().bind(GuiNBTNode.WIDGET_TEXTURE); + if (inBounds(mx, my)) { + Widget.fill(matrixStack, x, y, x + WIDTH, y + HEIGHT, 0x80ffffff); + } if (enabled) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - } else GlStateManager.color(0.5F, 0.5F, 0.5F, 1.0F); + RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); + } else RenderSystem.color4f(0.5F, 0.5F, 0.5F, 1.0F); - drawTexturedModalRect(x, y, id * WIDTH, 27, WIDTH, HEIGHT); + GuiUtils.drawTexturedModalRect(matrixStack, x, y, id * WIDTH, 27, WIDTH, HEIGHT, 0); } public void setEnabled(boolean aFlag) { @@ -39,8 +45,11 @@ public boolean inBounds(int mx, int my) { return enabled && mx >= x && my >= y && mx < x + WIDTH && my < y + HEIGHT; } + public boolean inBounds(double mx, double my) { + return enabled && mx >= x && my >= y && mx < x + WIDTH && my < y + HEIGHT; + } + public byte getId() { return id; } } - \ No newline at end of file diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBT.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBT.java index 43f8c73..3857535 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBT.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBT.java @@ -1,52 +1,45 @@ package com.mcf.davidee.nbtedit.gui; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagByte; -import net.minecraft.nbt.NBTTagByteArray; -import net.minecraft.nbt.NBTTagDouble; -import net.minecraft.nbt.NBTTagFloat; -import net.minecraft.nbt.NBTTagInt; -import net.minecraft.nbt.NBTTagIntArray; -import net.minecraft.nbt.NBTTagLong; -import net.minecraft.nbt.NBTTagShort; -import net.minecraft.nbt.NBTTagString; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; - +import com.mcf.davidee.nbtedit.NBTEdit; import com.mcf.davidee.nbtedit.NBTStringHelper; import com.mcf.davidee.nbtedit.nbt.NamedNBT; import com.mcf.davidee.nbtedit.nbt.Node; import com.mcf.davidee.nbtedit.nbt.ParseHelper; +import com.mojang.blaze3d.matrix.MatrixStack; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.widget.Widget; +import net.minecraft.client.gui.widget.button.Button; +import net.minecraft.nbt.*; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.text.StringTextComponent; +import net.minecraftforge.fml.client.gui.GuiUtils; +import org.lwjgl.glfw.GLFW; +import org.lwjgl.opengl.GL11; -public class GuiEditNBT extends Gui { +/** + * The node editor popup window. + */ +public class GuiEditNBT extends Widget { - public static final ResourceLocation WINDOW_TEXTURE = new ResourceLocation("nbtedit", "textures/gui/window.png"); + public static final ResourceLocation WINDOW_TEXTURE = new ResourceLocation(NBTEdit.MODID, "textures/gui/window.png"); public static final int WIDTH = 178, HEIGHT = 93; - private Minecraft mc = Minecraft.getMinecraft(); + private final Minecraft minecraft = Minecraft.getInstance(); private Node node; - private NBTBase nbt; + private INBT nbt; private boolean canEditText, canEditValue; private GuiNBTTree parent; - private int x, y; - - private GuiTextField key, value; - private GuiButton save, cancel; + private Button save, cancel; private String kError, vError; private GuiCharacterButton newLine, section; - public GuiEditNBT(GuiNBTTree parent, Node node, boolean editText, boolean editValue) { + super(0, 0, WIDTH, HEIGHT, StringTextComponent.EMPTY); this.parent = parent; this.node = node; this.nbt = node.getObject().getNBT(); @@ -62,82 +55,97 @@ public void initGUI(int x, int y) { newLine = new GuiCharacterButton((byte) 1, x + WIDTH - 1, y + 50); String sKey = (key == null) ? node.getObject().getName() : key.getText(); String sValue = (value == null) ? getValue(nbt) : value.getText(); - this.key = new GuiTextField(mc.fontRenderer, x + 46, y + 18, 116, 15, false); - this.value = new GuiTextField(mc.fontRenderer, x + 46, y + 44, 116, 15, true); + this.key = new GuiTextField(minecraft.font, x + 46, y + 18, 116, 15, false); + this.value = new GuiTextField(minecraft.font, x + 46, y + 44, 116, 15, true); key.setText(sKey); key.setEnableBackgroundDrawing(false); - key.func_82265_c(canEditText); + key.setEditable(canEditText); value.setMaxStringLength(256); value.setText(sValue); value.setEnableBackgroundDrawing(false); - value.func_82265_c(canEditValue); - save = new GuiButton(1, x + 9, y + 62, 75, 20, "Save"); + value.setEditable(canEditValue); + save = new Button(x + 9, y + 62, 75, 20, new StringTextComponent("Save"), button -> saveAndQuit()); if (!key.isFocused() && !value.isFocused()) { - if (canEditText) + if (canEditText) { key.setFocused(true); - else if (canEditValue) + } else if (canEditValue) { value.setFocused(true); + } } section.setEnabled(value.isFocused()); newLine.setEnabled(value.isFocused()); - cancel = new GuiButton(0, x + 93, y + 62, 75, 20, "Cancel"); + cancel = new Button(x + 93, y + 62, 75, 20, new StringTextComponent("Cancel"), button -> parent.closeWindow()); } - public void click(int mx, int my) { + @Override + public boolean mouseClicked(double mx, double my, int button) { if (newLine.inBounds(mx, my) && value.isFocused()) { - value.writeText("\n"); + value.insertText("\n"); checkValidInput(); + return true; } else if (section.inBounds(mx, my) && value.isFocused()) { - value.writeText("" + NBTStringHelper.SECTION_SIGN); + value.insertText("" + NBTStringHelper.SECTION_SIGN); checkValidInput(); + return true; + } else if (save.mouseClicked(mx, my, button)) { + save.onPress(); + return true; + } else if (cancel.mouseClicked(mx, my, button)) { + cancel.onPress(); + return true; } else { - key.mouseClicked(mx, my, 0); - value.mouseClicked(mx, my, 0); - if (save.mousePressed(mc, mx, my)) - saveAndQuit(); - if (cancel.mousePressed(mc, mx, my)) - parent.closeWindow(); + boolean retur = false; + if (key.mouseClicked(mx, my, button)) { + value.setFocused(false); + retur = true; + } + if (value.mouseClicked(mx, my, button)) { + key.setFocused(false); + retur = true; + } section.setEnabled(value.isFocused()); newLine.setEnabled(value.isFocused()); + return retur || super.mouseClicked(mx, my, button); } } private void saveAndQuit() { - if (canEditText) + if (canEditText) { node.getObject().setName(key.getText()); + } setValidValue(node, value.getText()); parent.nodeEdited(node); parent.closeWindow(); } - public void draw(int mx, int my) { - //GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("/nbtedit_textures/nbteditwindow.png")); - mc.renderEngine.bindTexture(WINDOW_TEXTURE); + @Override + public void render(MatrixStack matrixStack, int mx, int my, float particleTicks) { + minecraft.getTextureManager().bind(WINDOW_TEXTURE); GL11.glColor4f(1, 1, 1, 1); - drawTexturedModalRect(x, y, 0, 0, WIDTH, HEIGHT); + GuiUtils.drawTexturedModalRect(matrixStack, x, y, 0, 0, WIDTH, HEIGHT, 0); if (!canEditText) - drawRect(x + 42, y + 15, x + 169, y + 31, 0x80000000); + fill(matrixStack, x + 42, y + 15, x + 169, y + 31, 0x80000000); if (!canEditValue) - drawRect(x + 42, y + 41, x + 169, y + 57, 0x80000000); - key.drawTextBox(); - value.drawTextBox(); + fill(matrixStack, x + 42, y + 41, x + 169, y + 57, 0x80000000); + key.drawTextBox(matrixStack); + value.drawTextBox(matrixStack); - save.drawButton(mc, mx, my, 0); - cancel.drawButton(mc, mx, my, 0); + save.render(matrixStack, mx, my, 0); + cancel.render(matrixStack, mx, my, 0); if (kError != null) - drawCenteredString(mc.fontRenderer, kError, x + WIDTH / 2, y + 4, 0xFF0000); + drawCenteredString(matrixStack, minecraft.font, kError, x + WIDTH / 2, y + 4, 0xFF0000); if (vError != null) - drawCenteredString(mc.fontRenderer, vError, x + WIDTH / 2, y + 32, 0xFF0000); + drawCenteredString(matrixStack, minecraft.font, vError, x + WIDTH / 2, y + 32, 0xFF0000); - newLine.draw(mx, my); - section.draw(mx, my); + newLine.render(matrixStack, mx, my, particleTicks); + section.render(matrixStack, mx, my, particleTicks); } - public void drawCenteredString(FontRenderer par1FontRenderer, String par2Str, int par3, int par4, int par5) { - par1FontRenderer.drawString(par2Str, par3 - par1FontRenderer.getStringWidth(par2Str) / 2, par4, par5); + public static void drawCenteredString(MatrixStack matrixStack, FontRenderer fontRenderer, String text, int par3, int par4, int par5) { + fontRenderer.draw(matrixStack, text, par3 - fontRenderer.width(text) / 2f, par4, par5); } public void update() { @@ -145,28 +153,46 @@ public void update() { key.updateCursorCounter(); } - public void keyTyped(char c, int i) { - if (i == Keyboard.KEY_ESCAPE) { + @Override + public boolean keyPressed(int key, int p_231046_2_, int p_231046_3_) { + if (key == GLFW.GLFW_KEY_ESCAPE) { parent.closeWindow(); - } else if (i == Keyboard.KEY_TAB) { - if (key.isFocused() && canEditValue) { - key.setFocused(false); + return true; + } else if (key == GLFW.GLFW_KEY_TAB) { + if (this.key.isFocused() && canEditValue) { + this.key.setFocused(false); value.setFocused(true); } else if (value.isFocused() && canEditText) { - key.setFocused(true); + this.key.setFocused(true); value.setFocused(false); } section.setEnabled(value.isFocused()); newLine.setEnabled(value.isFocused()); - } else if (i == Keyboard.KEY_RETURN) { + } else if (key == GLFW.GLFW_KEY_ENTER) { checkValidInput(); - if (save.enabled) + if (save.active) { saveAndQuit(); + } } else { - key.textboxKeyTyped(c, i); - value.textboxKeyTyped(c, i); + this.key.keyPressed(key, p_231046_2_, p_231046_3_); + value.keyPressed(key, p_231046_2_, p_231046_3_); checkValidInput(); } + return super.keyPressed(key, p_231046_2_, p_231046_3_); + } + + @Override + public boolean charTyped(char p_231042_1_, int p_231042_2_) { + if (this.key.isFocused()) { + boolean handled = key.charTyped(p_231042_1_, p_231042_2_); + checkValidInput(); + return handled; + } else if (value.isFocused()) { + boolean handled = value.charTyped(p_231042_1_, p_231042_2_); + checkValidInput(); + return handled; + } + return false; } private void checkValidInput() { @@ -184,12 +210,12 @@ private void checkValidInput() { vError = e.getMessage(); valid = false; } - save.enabled = valid; + save.active = valid; } private boolean validName() { for (Node node : this.node.getParent().getChildren()) { - NBTBase base = node.getObject().getNBT(); + INBT base = node.getObject().getNBT(); if (base != nbt && node.getObject().getName().equals(key.getText())) return false; } @@ -198,26 +224,26 @@ private boolean validName() { private static void setValidValue(Node node, String value) { NamedNBT named = node.getObject(); - NBTBase base = named.getNBT(); - - if (base instanceof NBTTagByte) - named.setNBT(new NBTTagByte(ParseHelper.parseByte(value))); - if (base instanceof NBTTagShort) - named.setNBT(new NBTTagShort(ParseHelper.parseShort(value))); - if (base instanceof NBTTagInt) - named.setNBT(new NBTTagInt(ParseHelper.parseInt(value))); - if (base instanceof NBTTagLong) - named.setNBT(new NBTTagLong(ParseHelper.parseLong(value))); - if (base instanceof NBTTagFloat) - named.setNBT(new NBTTagFloat(ParseHelper.parseFloat(value))); - if (base instanceof NBTTagDouble) - named.setNBT(new NBTTagDouble(ParseHelper.parseDouble(value))); - if (base instanceof NBTTagByteArray) - named.setNBT(new NBTTagByteArray(ParseHelper.parseByteArray(value))); - if (base instanceof NBTTagIntArray) - named.setNBT(new NBTTagIntArray(ParseHelper.parseIntArray(value))); - if (base instanceof NBTTagString) - named.setNBT(new NBTTagString(value)); + INBT base = named.getNBT(); + + if (base instanceof ByteNBT) + named.setNBT(ByteNBT.valueOf(ParseHelper.parseByte(value))); + if (base instanceof ShortNBT) + named.setNBT(ShortNBT.valueOf(ParseHelper.parseShort(value))); + if (base instanceof IntNBT) + named.setNBT(IntNBT.valueOf(ParseHelper.parseInt(value))); + if (base instanceof LongNBT) + named.setNBT(LongNBT.valueOf(ParseHelper.parseLong(value))); + if (base instanceof FloatNBT) + named.setNBT(FloatNBT.valueOf(ParseHelper.parseFloat(value))); + if (base instanceof DoubleNBT) + named.setNBT(DoubleNBT.valueOf(ParseHelper.parseDouble(value))); + if (base instanceof ByteArrayNBT) + named.setNBT(new ByteArrayNBT(ParseHelper.parseByteArray(value))); + if (base instanceof IntArrayNBT) + named.setNBT(new IntArrayNBT(ParseHelper.parseIntArray(value))); + if (base instanceof StringNBT) + named.setNBT(StringNBT.valueOf(value)); } private static void validValue(String value, byte type) throws NumberFormatException { @@ -249,24 +275,30 @@ private static void validValue(String value, byte type) throws NumberFormatExcep } } - private static String getValue(NBTBase base) { + private static String getValue(INBT base) { switch (base.getId()) { case 7: - String s = ""; - for (byte b : ((NBTTagByteArray) base).getByteArray()) { - s += b + " "; + StringBuilder s = new StringBuilder(); + for (byte b : ((ByteArrayNBT) base).getAsByteArray()) { + s.append(b).append(" "); } - return s; + return s.toString().trim(); case 9: return "TagList"; case 10: return "TagCompound"; case 11: - String i = ""; - for (int a : ((NBTTagIntArray) base).getIntArray()) { - i += a + " "; + StringBuilder i = new StringBuilder(); + for (int a : ((IntArrayNBT) base).getAsIntArray()) { + i.append(a).append(" "); + } + return i.toString().trim(); + case 12: + StringBuilder j = new StringBuilder(); + for (long a : ((LongArrayNBT) base).getAsLongArray()) { + j.append(a).append(" "); } - return i; + return j.toString().trim(); default: return NBTStringHelper.toString(base); } diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBTTree.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBTTree.java index 0e0f7f0..ef92e6c 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBTTree.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiEditNBTTree.java @@ -1,29 +1,28 @@ package com.mcf.davidee.nbtedit.gui; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.entity.Entity; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraft.util.math.BlockPos; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; - import com.mcf.davidee.nbtedit.NBTEdit; import com.mcf.davidee.nbtedit.nbt.NBTTree; -import com.mcf.davidee.nbtedit.packets.EntityNBTPacket; -import com.mcf.davidee.nbtedit.packets.TileNBTPacket; - -import java.io.IOException; +import com.mcf.davidee.nbtedit.packets.EntitySavePacket; +import com.mcf.davidee.nbtedit.packets.TileSavePacket; +import com.mojang.blaze3d.matrix.MatrixStack; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.button.Button; +import net.minecraft.entity.Entity; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.StringTextComponent; +import org.lwjgl.glfw.GLFW; -public class GuiEditNBTTree extends GuiScreen { +public class GuiEditNBTTree extends Screen { public final int entityOrX, y, z; private boolean entity; protected String screenTitle; private GuiNBTTree guiTree; - public GuiEditNBTTree(int entity, NBTTagCompound tag) { + public GuiEditNBTTree(int entity, CompoundNBT tag) { + super(StringTextComponent.EMPTY); this.entity = true; entityOrX = entity; y = 0; @@ -32,7 +31,8 @@ public GuiEditNBTTree(int entity, NBTTagCompound tag) { guiTree = new GuiNBTTree(new NBTTree(tag)); } - public GuiEditNBTTree(BlockPos pos, NBTTagCompound tag) { + public GuiEditNBTTree(BlockPos pos, CompoundNBT tag) { + super(StringTextComponent.EMPTY); this.entity = false; entityOrX = pos.getX(); this.y = pos.getY(); @@ -41,111 +41,129 @@ public GuiEditNBTTree(BlockPos pos, NBTTagCompound tag) { guiTree = new GuiNBTTree(new NBTTree(tag)); } - @SuppressWarnings("unchecked") - public void initGui() { - Keyboard.enableRepeatEvents(true); - buttonList.clear(); + @Override + public void init(Minecraft minecraft, int width, int height) { + super.init(minecraft, width, height); + this.minecraft.keyboardHandler.setSendRepeatsToGui(true); + this.buttons.clear(); + this.children.clear(); + addButton(new Button(width / 4 - 100, this.height - 27, 40, 20, new StringTextComponent("Save"), this::quitWithSave)); + addButton(new Button(width * 3 / 4 - 100, this.height - 27, 40, 20, new StringTextComponent("Quit"), this::quitWithoutSaving)); guiTree.initGUI(width, height, height - 35); - this.buttonList.add(new GuiButton(1, width / 4 - 100, this.height - 27, "Save")); - this.buttonList.add(new GuiButton(0, width * 3 / 4 - 100, this.height - 27, "Quit")); - } - - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); + this.setFocused(guiTree); + } + + @Override + public void render(MatrixStack matrixStack, int mx, int my, float particleTicks) { + this.renderBackground(matrixStack); + guiTree.render(matrixStack, mx, my, particleTicks); + drawCenteredString(matrixStack, minecraft.font, this.screenTitle, this.width / 2, 5, 16777215); + if (guiTree.getWindow() == null) { + super.render(matrixStack, mx, my, particleTicks); + } else { + super.render(matrixStack, -1, -1, particleTicks); + } } - protected void keyTyped(char par1, int key) { + @Override + public boolean keyPressed(int key, int p_231046_2_, int p_231046_3_) { GuiEditNBT window = guiTree.getWindow(); - if (window != null) - window.keyTyped(par1, key); - else { - if (key == 1) { - if (guiTree.isEditingSlot()) + if (window != null) { + return window.keyPressed(key, p_231046_2_, p_231046_3_); + } else { + if (key == GLFW.GLFW_MOUSE_BUTTON_2) { + if (guiTree.isEditingSlot()) { guiTree.stopEditingSlot(); - else - quitWithoutSaving(); - } else if (key == Keyboard.KEY_DELETE) - guiTree.deleteSelected(); - else if (key == Keyboard.KEY_RETURN) - guiTree.editSelected(); - else if (key == Keyboard.KEY_UP) - guiTree.arrowKeyPressed(true); - else if (key == Keyboard.KEY_DOWN) - guiTree.arrowKeyPressed(false); - else - guiTree.keyTyped(par1, key); + } else { + quitWithoutSaving(null); + } + } else { + return guiTree.keyPressed(key, p_231046_2_, p_231046_3_); + } } + return super.keyPressed(key, p_231046_2_, p_231046_3_); } - protected void mouseClicked(int x, int y, int t) throws IOException { - if (guiTree.getWindow() == null) - super.mouseClicked(x, y, t); - if (t == 0) - guiTree.mouseClicked(x, y); - if (t == 1) - guiTree.rightClick(x, y); + @Override + public boolean charTyped(char p_231042_1_, int p_231042_2_) { + GuiEditNBT window = guiTree.getWindow(); + if (window != null) { + return window.charTyped(p_231042_1_, p_231042_2_); + } else { + return guiTree.charTyped(p_231042_1_, p_231042_2_); + } } - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - int ofs = Mouse.getEventDWheel(); - - if (ofs != 0) { - guiTree.shift((ofs >= 1) ? 6 : -6); + @Override + public boolean mouseClicked(double mx, double my, int button) { + if (super.mouseClicked(mx, my, button)) { + return true; } - + /*if (guiTree.getWindow() == null) { + return super.mouseClicked(mx, my, button); + }*/ + if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { + return guiTree.mouseClicked(mx, my, button); + } + if (button == GLFW.GLFW_MOUSE_BUTTON_RIGHT) { + guiTree.rightClick(mx, my); + return true; + } + return false; } - protected void actionPerformed(GuiButton b) { - if (b.enabled) { - switch (b.id) { - case 1: - quitWithSave(); - break; - default: - quitWithoutSaving(); - break; - } + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + if (guiTree.scrollBarActive()) { + guiTree.shift((int) scroll * guiTree.Y_GAP); } + return super.mouseScrolled(mouseX, mouseY, scroll); } - public void updateScreen() { - if (!mc.player.isEntityAlive()) - quitWithoutSaving(); - else - guiTree.updateScreen(); + @Override + public boolean mouseDragged(double mouseX, double mouseY, int button, double xDistance, double yDistance) { + if (guiTree.scrollBarActive() && guiTree.scrolling()) { + guiTree.shift((int) -yDistance); + return true; + } + return super.mouseDragged(mouseX, mouseY, button, xDistance, yDistance); } - private void quitWithSave() { - if (entity) - NBTEdit.NETWORK.INSTANCE.sendToServer(new EntityNBTPacket(entityOrX, guiTree.getNBTTree().toNBTTagCompound())); - else - NBTEdit.NETWORK.INSTANCE.sendToServer(new TileNBTPacket(new BlockPos(entityOrX, y, z), guiTree.getNBTTree().toNBTTagCompound())); - mc.displayGuiScreen(null); - mc.setIngameFocus(); + @Override + public void tick() { + if (!minecraft.player.isAlive()) { + quitWithoutSaving(null); + } else { + guiTree.tick(); + } + } + @Override + public void onClose() { + this.minecraft.keyboardHandler.setSendRepeatsToGui(false); + super.onClose(); } - private void quitWithoutSaving() { - mc.displayGuiScreen(null); + @Override + public boolean isPauseScreen() { + return true; } - public void drawScreen(int x, int y, float par3) { - this.drawDefaultBackground(); - guiTree.draw(x, y); - this.drawCenteredString(mc.fontRenderer, this.screenTitle, this.width / 2, 5, 16777215); - if (guiTree.getWindow() == null) - super.drawScreen(x, y, par3); - else - super.drawScreen(-1, -1, par3); + private void quitWithSave(Button p_onPress_1_) { + if (entity) { + NBTEdit.NETWORK.INSTANCE.sendToServer(new EntitySavePacket(entityOrX, guiTree.getNBTTree().toNBTTagCompound())); + } else { + NBTEdit.NETWORK.INSTANCE.sendToServer(new TileSavePacket(new BlockPos(entityOrX, y, z), guiTree.getNBTTree().toNBTTagCompound())); + } + this.onClose(); } - public boolean doesGuiPauseGame() { - return true; + private void quitWithoutSaving(Button p_onPress_1_) { + this.onClose(); } public Entity getEntity() { - return entity ? mc.world.getEntityByID(entityOrX) : null; + return entity ? minecraft.level.getEntity(entityOrX) : null; } public boolean isTileEntity() { diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTButton.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTButton.java index 1da5297..d6852be 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTButton.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTButton.java @@ -1,15 +1,18 @@ package com.mcf.davidee.nbtedit.gui; import com.mcf.davidee.nbtedit.NBTStringHelper; +import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import org.lwjgl.opengl.GL11; +import net.minecraft.client.gui.AbstractGui; +import net.minecraft.client.gui.widget.Widget; +import net.minecraft.util.text.StringTextComponent; +import net.minecraftforge.fml.client.gui.GuiUtils; -public class GuiNBTButton extends Gui { +public class GuiNBTButton extends Widget { public static final int WIDTH = 9, HEIGHT = 9; - private Minecraft mc = Minecraft.getMinecraft(); + private final Minecraft minecraft = Minecraft.getInstance(); private byte id; private int x, y; @@ -18,36 +21,39 @@ public class GuiNBTButton extends Gui { private long hoverTime; public GuiNBTButton(byte id, int x, int y) { + super(x, y, WIDTH, HEIGHT, new StringTextComponent("")); this.id = id; this.x = x; this.y = y; } - public void draw(int mx, int my) { - mc.renderEngine.bindTexture(GuiNBTNode.WIDGET_TEXTURE); + public void render(MatrixStack matrixStack, int mx, int my, float p_230430_4_) { if (inBounds(mx, my)) {//checks if the mouse is over the button - Gui.drawRect(x, y, x + WIDTH, y + HEIGHT, 0x80ffffff);//draw a grayish background + AbstractGui.fill(matrixStack, x, y, x + WIDTH, y + HEIGHT, 0x80ffffff); //draw a grayish background + //Gui.draw(matrixStack, x, y, x + WIDTH, y + HEIGHT, 0x80ffffff); //draw a grayish background if (hoverTime == -1) hoverTime = System.currentTimeMillis(); } else hoverTime = -1; - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - if (enabled) - drawTexturedModalRect(x, y, (id - 1) * 9, 18, WIDTH, HEIGHT);//Draw the texture + //GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + if (enabled) { + minecraft.getTextureManager().bind(GuiNBTNode.WIDGET_TEXTURE); + GuiUtils.drawTexturedModalRect(matrixStack, x, y, (id - 1) * 9, 18, WIDTH, HEIGHT, 0);//Draw the texture + } if (hoverTime != -1 && System.currentTimeMillis() - hoverTime > 300) { - drawToolTip(mx, my); + drawToolTip(matrixStack, mx, my); } } - private void drawToolTip(int mx, int my) { + private void drawToolTip(MatrixStack matrixStack, int mx, int my) { String s = NBTStringHelper.getButtonName(id); - int width = mc.fontRenderer.getStringWidth(s); - drawRect(mx + 4, my + 7, mx + 5 + width, my + 17, 0xff000000); - mc.fontRenderer.drawString(s, mx + 5, my + 8, 0xffffff); + int width = minecraft.font.width(s); + AbstractGui.fill(matrixStack, mx + 4, my + 7, mx + 5 + width, my + 17, 0xff000000); + minecraft.font.draw(matrixStack, s, mx + 5, my + 8, 0xffffff); } public void setEnabled(boolean aFlag) { @@ -62,6 +68,10 @@ public boolean inBounds(int mx, int my) { return enabled && mx >= x && my >= y && mx < x + WIDTH && my < y + HEIGHT; } + public boolean inBounds(double mx, double my) { + return enabled && mx >= x && my >= y && mx < x + WIDTH && my < y + HEIGHT; + } + public byte getId() { return id; } diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTNode.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTNode.java index 31942f6..62b007e 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTNode.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTNode.java @@ -1,44 +1,44 @@ package com.mcf.davidee.nbtedit.gui; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - +import com.mcf.davidee.nbtedit.NBTEdit; import com.mcf.davidee.nbtedit.NBTStringHelper; import com.mcf.davidee.nbtedit.nbt.NamedNBT; import com.mcf.davidee.nbtedit.nbt.Node; +import com.mojang.blaze3d.matrix.MatrixStack; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.AbstractGui; +import net.minecraft.client.gui.widget.Widget; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.text.StringTextComponent; +import net.minecraftforge.fml.client.gui.GuiUtils; +import org.lwjgl.opengl.GL11; -public class GuiNBTNode extends Gui { - - public static final ResourceLocation WIDGET_TEXTURE = new ResourceLocation("nbtedit", "textures/gui/widgets.png"); - - private Minecraft mc = Minecraft.getMinecraft(); +/** + * Individual node displayed in the tree. + * Renders the Icon and the Text name of the nbt node. + */ +public class GuiNBTNode extends Widget { + public static final ResourceLocation WIDGET_TEXTURE = new ResourceLocation(NBTEdit.MODID, "textures/gui/widgets.png"); + private final Minecraft minecraft = Minecraft.getInstance(); private Node node; private GuiNBTTree tree; - protected int width, height; - protected int x, y; - private String displayString; - public GuiNBTNode(GuiNBTTree tree, Node node, int x, int y) { + super(x, y, 200, 0, StringTextComponent.EMPTY); this.tree = tree; this.node = node; - this.x = x; - this.y = y; - height = mc.fontRenderer.FONT_HEIGHT; + this.height = minecraft.font.lineHeight; updateDisplay(); } - private boolean inBounds(int mx, int my) { + private boolean inBounds(double mx, double my) { return mx >= x && my >= y && mx < width + x && my < height + y; } - private boolean inHideShowBounds(int mx, int my) { + private boolean inHideShowBounds(double mx, double my) { return mx >= x - 9 && my >= y && mx < x && my < y + height; } @@ -46,11 +46,11 @@ public boolean shouldDrawChildren() { return node.shouldDrawChildren(); } - public boolean clicked(int mx, int my) { + public boolean clicked(double mx, double my) { return inBounds(mx, my); } - public boolean hideShowClicked(int mx, int my) { + public boolean hideShowClicked(double mx, double my) { if (node.hasChildren() && inHideShowBounds(mx, my)) { node.setDrawChildren(!node.shouldDrawChildren()); return true; @@ -68,29 +68,30 @@ public void shift(int dy) { public void updateDisplay() { displayString = NBTStringHelper.getNBTNameSpecial(node.getObject()); - width = mc.fontRenderer.getStringWidth(displayString) + 12; + width = minecraft.font.width(displayString) + 12; } - public void draw(int mx, int my) { + public void render(MatrixStack matrixStack, int mx, int my, float partialTicks) { boolean selected = tree.getFocused() == node; boolean hover = inBounds(mx, my); boolean chHover = inHideShowBounds(mx, my); int color = selected ? 0xff : hover ? 16777120 : (node.hasParent()) ? 14737632 : -6250336; - mc.renderEngine.bindTexture(WIDGET_TEXTURE); + minecraft.getTextureManager().bind(WIDGET_TEXTURE); if (selected) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Gui.drawRect(x + 11, y, x + width, y + height, Integer.MIN_VALUE); + AbstractGui.fill(matrixStack, x + 11, y, x + width, y + height, Integer.MIN_VALUE); } if (node.hasChildren()) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - this.drawTexturedModalRect(x - 9, y, (node.shouldDrawChildren()) ? 9 : 0, (chHover) ? height : 0, 9, height); + GuiUtils.drawTexturedModalRect(matrixStack, x - 9, y, (node.shouldDrawChildren()) ? 9 : 0, (chHover) ? height : 0, 9, height, 0); } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - drawTexturedModalRect(x + 1, y, (node.getObject().getNBT().getId() - 1) * 9, 18, 9, 9); - drawString(mc.fontRenderer, displayString, x + 11, y + (this.height - 8) / 2, color); + + GuiUtils.drawTexturedModalRect(matrixStack, x + 1, y, (node.getObject().getNBT().getId() - 1) * 9, 18, 9, 9, 0); + drawString(matrixStack, minecraft.font, displayString, x + 11, y + (this.height - 8) / 2, color); } public boolean shouldDraw(int top, int bottom) { diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTTree.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTTree.java index cb93953..a4ef3fd 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTTree.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiNBTTree.java @@ -7,20 +7,22 @@ import com.mcf.davidee.nbtedit.nbt.NamedNBT; import com.mcf.davidee.nbtedit.nbt.Node; import com.mcf.davidee.nbtedit.nbt.SaveStates; +import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.Minecraft; -import net.minecraft.client.audio.PositionedSoundRecord; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiControls; +import net.minecraft.client.audio.SimpleSound; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.Widget; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.init.SoundEvents; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.nbt.INBT; +import net.minecraft.nbt.ListNBT; +import net.minecraft.util.SoundEvents; +import net.minecraft.util.text.StringTextComponent; +import net.minecraftforge.fml.client.gui.GuiUtils; import org.apache.logging.log4j.Level; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; +import org.lwjgl.glfw.GLFW; import org.lwjgl.opengl.GL11; import java.awt.*; @@ -31,27 +33,28 @@ /* * The main Gui class for NBTEdit. This implementation is messy, naive, and unoptimized, but it works. - * This is from long before GuiLib (and is actually my motivation for GuiLib), but sadly I do not + * This is from long before GuiLib (and is actually my motivation for GuiLib), but sadly I do not * have time to rewrite it. - * + * * Issues: * - Not extensible - a separate tree GUI class for GuiLib would be nice. * - Naive/unoptimized - layout changes force an entire reload of the tree - * - Messy, good luck. Some of the button IDs are hardcoded. + * - Messy, good luck. Some buttons IDs are hardcoded. */ -public class GuiNBTTree extends Gui { +public class GuiNBTTree extends Widget { - private Minecraft mc = Minecraft.getMinecraft(); + private final Minecraft minecraft = Minecraft.getInstance(); private NBTTree tree; - private List nodes; - private GuiSaveSlotButton[] saves; - private GuiNBTButton[] buttons; + private final List nodes; + private final GuiSaveSlotButton[] saves; + private final GuiNBTButton[] buttons; private final int X_GAP = 10, START_X = 10, START_Y = 30; - private final int Y_GAP = Minecraft.getMinecraft().fontRenderer.FONT_HEIGHT + 2; + public final int Y_GAP = Minecraft.getInstance().font.lineHeight + 2; private int y, yClick, bottom, width, height, heightDiff, offset; + private boolean scrolling = false; private Node focused; private int focusedSlotIndex; @@ -63,7 +66,7 @@ public Node getFocused() { } public GuiSaveSlotButton getFocusedSaveSlot() { - return (focusedSlotIndex != -1) ? saves[focusedSlotIndex] : null; + return ( focusedSlotIndex != -1 ) ? saves[focusedSlotIndex] : null; } public NBTTree getNBTTree() { @@ -71,6 +74,7 @@ public NBTTree getNBTTree() { } public GuiNBTTree(NBTTree tree) { + super(0, 0, 0, 0, StringTextComponent.EMPTY); this.tree = tree; yClick = -1; focusedSlotIndex = -1; @@ -80,7 +84,7 @@ public GuiNBTTree(NBTTree tree) { } private int getHeightDifference() { - return getContentHeight() - (bottom - START_Y + 2); + return getContentHeight() - ( bottom - START_Y + 2 ); } private int getContentHeight() { @@ -97,11 +101,12 @@ public void initGUI(int width, int height, int bottom) { this.bottom = bottom; yClick = -1; initGUI(false); - if (window != null) - window.initGUI((width - GuiEditNBT.WIDTH) / 2, (height - GuiEditNBT.HEIGHT) / 2); + if (window != null) { + window.initGUI(( width - GuiEditNBT.WIDTH ) / 2, ( height - GuiEditNBT.HEIGHT ) / 2); + } } - public void updateScreen() { + public void tick() { if (window != null) window.update(); if (focusedSlotIndex != -1) @@ -112,29 +117,29 @@ private void setFocused(Node toFocus) { if (toFocus == null) { for (GuiNBTButton b : buttons) b.setEnabled(false); - } else if (toFocus.getObject().getNBT() instanceof NBTTagCompound) { + } else if (toFocus.getObject().getNBT() instanceof CompoundNBT) { for (GuiNBTButton b : buttons) b.setEnabled(true); buttons[12].setEnabled(toFocus != tree.getRoot()); - buttons[11].setEnabled(toFocus.hasParent() && !(toFocus.getParent().getObject().getNBT() instanceof NBTTagList)); + buttons[11].setEnabled(toFocus.hasParent() && !( toFocus.getParent().getObject().getNBT() instanceof ListNBT )); buttons[13].setEnabled(true); buttons[14].setEnabled(toFocus != tree.getRoot()); buttons[15].setEnabled(NBTEdit.clipboard != null); - } else if (toFocus.getObject().getNBT() instanceof NBTTagList) { + } else if (toFocus.getObject().getNBT() instanceof ListNBT) { if (toFocus.hasChildren()) { byte type = toFocus.getChildren().get(0).getObject().getNBT().getId(); for (GuiNBTButton b : buttons) b.setEnabled(false); buttons[type - 1].setEnabled(true); buttons[12].setEnabled(true); - buttons[11].setEnabled(!(toFocus.getParent().getObject().getNBT() instanceof NBTTagList)); + buttons[11].setEnabled(!( toFocus.getParent().getObject().getNBT() instanceof ListNBT )); buttons[13].setEnabled(true); buttons[14].setEnabled(true); buttons[15].setEnabled(NBTEdit.clipboard != null && NBTEdit.clipboard.getNBT().getId() == type); } else for (GuiNBTButton b : buttons) b.setEnabled(true); - buttons[11].setEnabled(!(toFocus.getParent().getObject().getNBT() instanceof NBTTagList)); + buttons[11].setEnabled(!( toFocus.getParent().getObject().getNBT() instanceof ListNBT )); buttons[13].setEnabled(true); buttons[14].setEnabled(true); buttons[15].setEnabled(NBTEdit.clipboard != null); @@ -237,7 +242,8 @@ private void addNodes(Node node, int x) { addNodes(child, x); } - public void draw(int mx, int my) { + @Override + public void render(MatrixStack matrixStack, int mx, int my, float particleTicks) { int cmx = mx, cmy = my; if (window != null) { cmx = -1; @@ -245,22 +251,22 @@ public void draw(int mx, int my) { } for (GuiNBTNode node : nodes) { if (node.shouldDraw(START_Y - 1, bottom)) - node.draw(cmx, cmy); + node.render(matrixStack, cmx, cmy, particleTicks); } overlayBackground(0, START_Y - 1, 255, 255); overlayBackground(bottom, height, 255, 255); for (GuiNBTButton but : buttons) - but.draw(cmx, cmy); + but.render(matrixStack, cmx, cmy, particleTicks); for (GuiSaveSlotButton but : saves) - but.draw(cmx, cmy); - drawScrollBar(cmx, cmy); + but.render(matrixStack, cmx, cmy, particleTicks); + drawScrollBar(matrixStack, cmx, cmy); if (window != null) - window.draw(mx, my); + window.render(matrixStack, mx, my, particleTicks); } - private void drawScrollBar(int mx, int my) { - if (heightDiff > 0) { - if (Mouse.isButtonDown(0)) { + private void drawScrollBar(MatrixStack matrixStack, int mx, int my) { + if (this.scrollBarActive()) { + /*if (Minecraft.getInstance().mouseHandler.isLeftPressed()) { if (yClick == -1) { if (mx >= width - 20 && mx < width && my >= START_Y - 1 && my < bottom) { yClick = my; @@ -272,31 +278,31 @@ private void drawScrollBar(int mx, int my) { if (height < 1) { height = 1; } - int length = (bottom - (START_Y - 1)) * (bottom - (START_Y - 1)) / getContentHeight(); + int length = ( bottom - ( START_Y - 1 ) ) * ( bottom - ( START_Y - 1 ) ) / getContentHeight(); if (length < 32) length = 32; - if (length > bottom - (START_Y - 1) - 8) - length = bottom - (START_Y - 1) - 8; + if (length > bottom - ( START_Y - 1 ) - 8) + length = bottom - ( START_Y - 1 ) - 8; - scrollMultiplier /= (float) (this.bottom - (START_Y - 1) - length) / (float) height; + scrollMultiplier /= (float) ( this.bottom - ( START_Y - 1 ) - length ) / (float) height; - shift((int) ((yClick - my) * scrollMultiplier)); + shift((int) ( ( yClick - my ) * scrollMultiplier )); yClick = my; } } else - yClick = -1; + yClick = -1;*/ - drawRect(width - 20, START_Y - 1, width, bottom, Integer.MIN_VALUE); + fill(matrixStack, width - 20, START_Y - 1, width, bottom, Integer.MIN_VALUE); - int length = (bottom - (START_Y - 1)) * (bottom - (START_Y - 1)) / getContentHeight(); + int length = ( bottom - ( START_Y - 1 ) ) * ( bottom - ( START_Y - 1 ) ) / getContentHeight(); if (length < 32) length = 32; - if (length > bottom - (START_Y - 1) - 8) - length = bottom - (START_Y - 1) - 8; - int y = -offset * (this.bottom - (START_Y - 1) - length) / heightDiff + (START_Y - 1); + if (length > bottom - ( START_Y - 1 ) - 8) + length = bottom - ( START_Y - 1 ) - 8; + int y = -offset * ( this.bottom - ( START_Y - 1 ) - length ) / heightDiff + ( START_Y - 1 ); if (y < START_Y - 1) y = START_Y - 1; @@ -304,28 +310,40 @@ private void drawScrollBar(int mx, int my) { // this.drawGradientRect(width-20,y,width,y+length,8421504, 12632256); //drawRect(width-20,y,width,y+length,0x80ffffff); - drawGradientRect(width - 20, y, width, y + length, 0x80ffffff, 0x80333333); + GuiUtils.drawGradientRect(matrixStack.last().pose(), 0, width - 20, y, width, y + length, 0x80ffffff, 0x80333333); } } protected void overlayBackground(int par1, int par2, int par3, int par4) { Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder worldRenderer = tessellator.getBuffer(); - mc.renderEngine.bindTexture(OPTIONS_BACKGROUND); + BufferBuilder worldRenderer = tessellator.getBuilder(); + minecraft.getTextureManager().bind(BACKGROUND_LOCATION); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); float var6 = 32.0F; - worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); + worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR_TEX); Color color = new Color(4210752); - worldRenderer.color(color.getRed(), color.getGreen(), color.getBlue(), par4); - worldRenderer.pos(0.0D, (double) par2, 0.0D).tex(0.0D, (double) ((float) par2 / var6)); - worldRenderer.pos((double) this.width, (double) par2, 0.0D).tex((double) ((float) this.width / var6), (double) ((float) par2 / var6)); - worldRenderer.color(color.getRed(), color.getGreen(), color.getBlue(), par3); - worldRenderer.pos((double) this.width, (double) par1, 0.0D).tex((double) ((float) this.width / var6), (double) ((float) par1 / var6)); - worldRenderer.pos(0.0D, (double) par1, 0.0D).tex(0.0D, (double) ((float) par1 / var6)); - tessellator.draw(); - } - - public void mouseClicked(int mx, int my) { + worldRenderer.vertex(0.0D, par2, 0.0D) + .color(color.getRed(), color.getGreen(), color.getBlue(), par4) + .uv(0.0F, ( (float) par2 / var6 )) + .endVertex(); + worldRenderer.vertex(this.width, par2, 0.0D) + .color(color.getRed(), color.getGreen(), color.getBlue(), par4) + .uv(( (float) this.width / var6 ), ( (float) par2 / var6 )) + .endVertex(); + worldRenderer.vertex(this.width, par1, 0.0D) + .color(color.getRed(), color.getGreen(), color.getBlue(), par3) + .uv(( (float) this.width / var6 ), ( (float) par1 / var6 )) + .endVertex(); + worldRenderer.vertex(0.0D, par1, 0.0D) + .color(color.getRed(), color.getGreen(), color.getBlue(), par3) + .uv(0.0F, ( (float) par1 / var6 )) + .endVertex(); + tessellator.end(); + } + + @Override + public boolean mouseClicked(double mx, double my, int button) { + this.scrolling(false); if (window == null) { boolean reInit = false; @@ -333,27 +351,27 @@ public void mouseClicked(int mx, int my) { if (node.hideShowClicked(mx, my)) { // Check hide/show children buttons reInit = true; if (node.shouldDrawChildren()) - offset = (START_Y + 1) - (node.y) + offset; + offset = ( START_Y + 1 ) - ( node.y ) + offset; break; } } if (!reInit) { - for (GuiNBTButton button : buttons) { //Check top buttons - if (button.inBounds(mx, my)) { - buttonClicked(button); - return; + for (GuiNBTButton guiNBTButton : buttons) { //Check top buttons + if (guiNBTButton.inBounds(mx, my)) { + buttonClicked(guiNBTButton); + return true; } } - for (GuiSaveSlotButton button : saves) { - if (button.inBoundsOfX(mx, my)) { - button.reset(); + for (GuiSaveSlotButton saveSlotButton : saves) { + if (saveSlotButton.inBoundsOfX(mx, my)) { + saveSlotButton.reset(); NBTEdit.getSaveStates().save(); - mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F)); - return; + minecraft.getSoundManager().play(SimpleSound.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + return true; } - if (button.inBounds(mx, my)) { - saveButtonClicked(button); - return; + if (saveSlotButton.inBounds(mx, my)) { + saveButtonClicked(saveSlotButton); + return true; } } if (my >= START_Y && mx <= width - 175) { //Check actual nodes, remove focus if nothing clicked @@ -364,52 +382,81 @@ public void mouseClicked(int mx, int my) { break; } } - if (focusedSlotIndex != -1) + if (focusedSlotIndex != -1) { stopEditingSlot(); + } setFocused(newFocus); } - } else + if (scrollBarActive() && mx >= width - 20 && mx < width && my >= START_Y - 1 && my < bottom) { + this.scrolling(true); + /*if (yClick == -1) { + yClick = (int) my; + } else { + float scrollMultiplier = 1.0F; + int height = getHeightDifference(); + + if (height < 1) { + height = 1; + } + int length = ( bottom - ( START_Y - 1 ) ) * ( bottom - ( START_Y - 1 ) ) / getContentHeight(); + if (length < 32) + length = 32; + if (length > bottom - ( START_Y - 1 ) - 8) + length = bottom - ( START_Y - 1 ) - 8; + + scrollMultiplier /= (float) ( this.bottom - ( START_Y - 1 ) - length ) / (float) height; + + + shift((int) ( ( yClick - my ) * scrollMultiplier )); + yClick = (int) my; + }*/ + } + + } else { initGUI(); - } else - window.click(mx, my); + } + } else { + window.mouseClicked(mx, my, button); + } + return true; } private void saveButtonClicked(GuiSaveSlotButton button) { - if (button.save.tag.hasNoTags()) { //Copy into save slot - Node obj = (focused == null) ? tree.getRoot() : focused; - NBTBase base = obj.getObject().getNBT(); + if (button.save.tag.isEmpty()) { //Copy into save slot + Node obj = ( focused == null ) ? tree.getRoot() : focused; + INBT base = obj.getObject().getNBT(); String name = obj.getObject().getName(); - if (base instanceof NBTTagList) { - NBTTagList list = new NBTTagList(); + if (base instanceof ListNBT) { + ListNBT list = new ListNBT(); tree.addChildrenToList(obj, list); - button.save.tag.setTag(name, list); - } else if (base instanceof NBTTagCompound) { - NBTTagCompound compound = new NBTTagCompound(); + button.save.tag.put(name, list); + } else if (base instanceof CompoundNBT) { + CompoundNBT compound = new CompoundNBT(); tree.addChildrenToTag(obj, compound); - button.save.tag.setTag(name, compound); + button.save.tag.put(name, compound); } else - button.save.tag.setTag(name, base.copy()); + button.save.tag.put(name, base.copy()); button.saved(); NBTEdit.getSaveStates().save(); - mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + minecraft.getSoundManager().play(SimpleSound.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); } else { //Paste into - Map nbtMap = NBTHelper.getMap(button.save.tag); + Map nbtMap = NBTHelper.getMap(button.save.tag); if (nbtMap.isEmpty()) { NBTEdit.log(Level.WARN, "Unable to copy from save \"" + button.save.name + "\"."); - NBTEdit.log(Level.WARN, "The save is invalid - a valid save must only contain 1 core NBTBase"); + NBTEdit.log(Level.WARN, "The save is invalid - a valid save must only contain 1 core INBT"); } else { if (focused == null) setFocused(tree.getRoot()); - Entry firstEntry = nbtMap.entrySet().iterator().next(); + Entry firstEntry = nbtMap.entrySet().iterator().next(); assert firstEntry != null; String name = firstEntry.getKey(); - NBTBase nbt = firstEntry.getValue().copy(); - if (focused == tree.getRoot() && nbt instanceof NBTTagCompound && name.equals("ROOT")) { + INBT nbt = firstEntry.getValue().copy(); + if (focused == tree.getRoot() && nbt instanceof CompoundNBT && name.equals("ROOT")) { setFocused(null); - tree = new NBTTree((NBTTagCompound) nbt); + tree = new NBTTree((CompoundNBT) nbt); initGUI(); - mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + minecraft.getSoundManager().play(SimpleSound.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); } else if (canAddToParent(focused.getObject().getNBT(), nbt)) { focused.setDrawChildren(true); for (Iterator> it = focused.getChildren().iterator(); it.hasNext(); ) { //Replace object with same name @@ -423,7 +470,7 @@ private void saveButtonClicked(GuiSaveSlotButton button) { tree.sort(node); setFocused(node); initGUI(true); - mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + minecraft.getSoundManager().play(SimpleSound.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); } } } @@ -445,8 +492,8 @@ else if (focused != null) { List> children = focused.getChildren(); String type = NBTStringHelper.getButtonName(button.getId()); - if (focused.getObject().getNBT() instanceof NBTTagList) { - NBTBase nbt = NBTStringHelper.newTag(button.getId()); + if (focused.getObject().getNBT() instanceof ListNBT) { + INBT nbt = NBTStringHelper.newTag(button.getId()); if (nbt != null) { Node newNode = new Node<>(focused, new NamedNBT("", nbt)); children.add(newNode); @@ -496,7 +543,7 @@ private Node insert(NamedNBT nbt) { } private Node insert(String name, byte type) { - NBTBase nbt = NBTStringHelper.newTag(type); + INBT nbt = NBTStringHelper.newTag(type); if (nbt != null) return insert(new NamedNBT(name, nbt)); return null; @@ -517,13 +564,13 @@ public void deleteSelected() { public void editSelected() { if (focused != null) { - NBTBase base = focused.getObject().getNBT(); - if (focused.hasChildren() && (base instanceof NBTTagCompound || base instanceof NBTTagList)) { + INBT base = focused.getObject().getNBT(); + if (focused.hasChildren() && ( base instanceof CompoundNBT || base instanceof ListNBT )) { focused.setDrawChildren(!focused.shouldDrawChildren()); int index; - if (focused.shouldDrawChildren() && (index = indexOf(focused)) != -1) - offset = (START_Y + 1) - nodes.get(index).y + offset; + if (focused.shouldDrawChildren() && ( index = indexOf(focused) ) != -1) + offset = ( START_Y + 1 ) - nodes.get(index).y + offset; initGUI(); } else if (buttons[11].isEnabled()) { @@ -534,12 +581,12 @@ public void editSelected() { } } - private boolean canAddToParent(NBTBase parent, NBTBase child) { - if (parent instanceof NBTTagCompound) + private boolean canAddToParent(INBT parent, INBT child) { + if (parent instanceof CompoundNBT) return true; - if (parent instanceof NBTTagList) { - NBTTagList list = (NBTTagList) parent; - return list.tagCount() == 0 || list.getTagType() == child.getId(); + if (parent instanceof ListNBT) { + ListNBT list = (ListNBT) parent; + return list.size() == 0 || list.getId() == child.getId(); } return false; } @@ -553,7 +600,7 @@ private void paste() { focused.setDrawChildren(true); NamedNBT namedNBT = NBTEdit.clipboard.copy(); - if (focused.getObject().getNBT() instanceof NBTTagList) { + if (focused.getObject().getNBT() instanceof ListNBT) { namedNBT.setName(""); Node node = new Node<>(focused, namedNBT); focused.addChild(node); @@ -585,12 +632,12 @@ private void paste() { private void copy() { if (focused != null) { NamedNBT namedNBT = focused.getObject(); - if (namedNBT.getNBT() instanceof NBTTagList) { - NBTTagList list = new NBTTagList(); + if (namedNBT.getNBT() instanceof ListNBT) { + ListNBT list = new ListNBT(); tree.addChildrenToList(focused, list); NBTEdit.clipboard = new NamedNBT(namedNBT.getName(), list); - } else if (namedNBT.getNBT() instanceof NBTTagCompound) { - NBTTagCompound compound = new NBTTagCompound(); + } else if (namedNBT.getNBT() instanceof CompoundNBT) { + CompoundNBT compound = new CompoundNBT(); tree.addChildrenToTag(focused, compound); NBTEdit.clipboard = new NamedNBT(namedNBT.getName(), compound); } else @@ -605,10 +652,10 @@ private void cut() { } private void edit() { - NBTBase base = focused.getObject().getNBT(); - NBTBase parent = focused.getParent().getObject().getNBT(); - window = new GuiEditNBT(this, focused, !(parent instanceof NBTTagList), !(base instanceof NBTTagCompound || base instanceof NBTTagList)); - window.initGUI((width - GuiEditNBT.WIDTH) / 2, (height - GuiEditNBT.HEIGHT) / 2); + INBT base = focused.getObject().getNBT(); + INBT parent = focused.getParent().getObject().getNBT(); + window = new GuiEditNBT(this, focused, !( parent instanceof ListNBT ), !( base instanceof CompoundNBT || base instanceof ListNBT )); + window.initGUI(( width - GuiEditNBT.WIDTH ) / 2, ( height - GuiEditNBT.HEIGHT ) / 2); } public void nodeEdited(Node node) { @@ -619,10 +666,13 @@ public void nodeEdited(Node node) { public void arrowKeyPressed(boolean up) { if (focused == null) - shift((up) ? Y_GAP : -Y_GAP); + shift(( up ) ? Y_GAP : -Y_GAP); else shiftFocus(up); } + public void backspacePressed() { + + } private int indexOf(Node node) { for (int i = 0; i < nodes.size(); ++i) { @@ -636,10 +686,10 @@ private int indexOf(Node node) { private void shiftFocus(boolean up) { int index = indexOf(focused); if (index != -1) { - index += (up) ? -1 : 1; + index += ( up ) ? -1 : 1; if (index >= 0 && index < nodes.size()) { setFocused(nodes.get(index).getNode()); - shift((up) ? Y_GAP : -Y_GAP); + shift(( up ) ? Y_GAP : -Y_GAP); } } } @@ -648,7 +698,7 @@ private void shiftTo(Node node) { int index = indexOf(node); if (index != -1) { GuiNBTNode gui = nodes.get(index); - shift((bottom + START_Y + 1) / 2 - (gui.y + gui.height)); + shift(( bottom + START_Y + 1 ) / 2 - ( gui.y + gui.getHeight() )); } } @@ -665,6 +715,18 @@ public void shift(int i) { offset = dif; } + public boolean scrollBarActive() { + return heightDiff > 0; + } + + public boolean scrolling() { + return scrolling; + } + + public void scrolling(boolean bool) { + this.scrolling = bool; + } + public void closeWindow() { window = null; } @@ -679,20 +741,47 @@ public void stopEditingSlot() { focusedSlotIndex = -1; } - public void keyTyped(char ch, int key) { + @Override + public boolean keyPressed(int key, int p_231046_2_, int p_231046_3_) { + if (focusedSlotIndex != -1 && key == GLFW.GLFW_KEY_BACKSPACE) { + saves[focusedSlotIndex].backSpace(); + return true; + } + if (key == GLFW.GLFW_KEY_DELETE) { + this.deleteSelected(); + } else if (key == GLFW.GLFW_KEY_ENTER) { + this.editSelected(); + } else if (key == GLFW.GLFW_KEY_UP) { + this.arrowKeyPressed(true); + } else if (key == GLFW.GLFW_KEY_DOWN) { + this.arrowKeyPressed(false); + } + return super.keyPressed(key, p_231046_2_, p_231046_3_); + } + + @Override + public boolean charTyped(char ch, int key) { if (focusedSlotIndex != -1) { saves[focusedSlotIndex].keyTyped(ch, key); + return true; } else { - if (key == Keyboard.KEY_C && GuiControls.isCtrlKeyDown()) + if (key == 67 && Screen.hasControlDown()) { copy(); - if (key == Keyboard.KEY_V && GuiControls.isCtrlKeyDown() && canPaste()) + return true; + } + if (key == 86 && Screen.hasControlDown() && canPaste()) { paste(); - if (key == Keyboard.KEY_X && GuiControls.isCtrlKeyDown()) + return true; + } + if (key == 88 && Screen.hasControlDown()) { cut(); + return true; + } } + return false; } - public void rightClick(int mx, int my) { + public void rightClick(double mx, double my) { for (int i = 0; i < 7; ++i) { if (saves[i].inBounds(mx, my)) { setFocused(null); @@ -709,14 +798,4 @@ public void rightClick(int mx, int my) { } } } - - private void putColor(BufferBuilder renderer, int argb, int p_178988_2_) { - int i = renderer.getColorIndex(p_178988_2_); - int j = argb >> 16 & 255; - int k = argb >> 8 & 255; - int l = argb & 255; - int i1 = argb >> 24 & 255; - renderer.putColorRGBA(i, j, k, l, i1); - } - } diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiSaveSlotButton.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiSaveSlotButton.java index 430d8be..b8abf4c 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiSaveSlotButton.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiSaveSlotButton.java @@ -1,21 +1,25 @@ package com.mcf.davidee.nbtedit.gui; +import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.client.gui.widget.Widget; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.util.SharedConstants; import net.minecraft.util.math.MathHelper; import net.minecraft.util.ResourceLocation; -import org.lwjgl.input.Keyboard; +import net.minecraft.util.text.StringTextComponent; +import net.minecraftforge.fml.client.gui.GuiUtils; +import org.lwjgl.glfw.GLFW; import org.lwjgl.opengl.GL11; import com.mcf.davidee.nbtedit.nbt.SaveStates; -public class GuiSaveSlotButton extends Gui { +public class GuiSaveSlotButton extends Widget { public static final ResourceLocation TEXTURE = new ResourceLocation("textures/gui/widgets.png"); private static final int X_SIZE = 14, HEIGHT = 20, MAX_WIDTH = 150, MIN_WIDTH = 82, GAP = 3; - private final Minecraft mc; + private final Minecraft minecraft; public final SaveStates.SaveState save; private final int rightX; @@ -27,45 +31,46 @@ public class GuiSaveSlotButton extends Gui { private int tickCount; public GuiSaveSlotButton(SaveStates.SaveState save, int rightX, int y) { + super(rightX, y, MIN_WIDTH, HEIGHT, StringTextComponent.EMPTY); this.save = save; this.rightX = rightX; this.y = y; - mc = Minecraft.getMinecraft(); - xVisible = !save.tag.hasNoTags(); - text = (save.tag.hasNoTags() ? "Save " : "Load ") + save.name; + minecraft = Minecraft.getInstance(); + xVisible = !save.tag.isEmpty(); + text = (save.tag.isEmpty() ? "Save " : "Load ") + save.name; tickCount = -1; updatePosition(); } - public void draw(int mx, int my) { - + @Override + public void render(MatrixStack matrixStack, int mx, int my, float particleTicks) { int textColor = ((inBounds(mx, my))) ? 16777120 : 0xffffff; - renderVanillaButton(x, y, 0, 66, width, HEIGHT); - drawCenteredString(mc.fontRenderer, text, x + width / 2, y + 6, textColor); + renderVanillaButton(matrixStack, x, y, 0, 66, width, HEIGHT); + drawCenteredString(matrixStack, minecraft.font, text, x + width / 2, y + 6, textColor); if (tickCount != -1 && tickCount / 6 % 2 == 0) { - mc.fontRenderer.drawStringWithShadow("_", x + (width + mc.fontRenderer.getStringWidth(text)) / 2 + 1, y + 6, 0xffffff); + minecraft.font.drawShadow(matrixStack, "_", x + (width + minecraft.font.width(text)) / 2 + 1, y + 6, 0xffffff); } if (xVisible) { textColor = ((inBoundsOfX(mx, my))) ? 16777120 : 0xffffff; - renderVanillaButton(leftBoundOfX(), topBoundOfX(), 0, 66, X_SIZE, X_SIZE); - drawCenteredString(mc.fontRenderer, "x", x - GAP - X_SIZE / 2, y + 6, textColor); + renderVanillaButton(matrixStack, leftBoundOfX(), topBoundOfX(), 0, 66, X_SIZE, X_SIZE); + drawCenteredString(matrixStack, minecraft.font, "x", x - GAP - X_SIZE / 2, y + 6, textColor); } } - private void renderVanillaButton(int x, int y, int u, int v, int width, int height) { + private void renderVanillaButton(MatrixStack matrixStack, int x, int y, int u, int v, int width, int height) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - mc.renderEngine.bindTexture(TEXTURE); + minecraft.getTextureManager().bind(TEXTURE); //Top Left - this.drawTexturedModalRect(x, y, u, v, width / 2, height / 2); + GuiUtils.drawTexturedModalRect(matrixStack, x, y, u, v, width / 2, height / 2, 0); //Top Right - this.drawTexturedModalRect(x + width / 2, y, u + 200 - width / 2, v, width / 2, height / 2); + GuiUtils.drawTexturedModalRect(matrixStack, x + width / 2, y, u + 200 - width / 2, v, width / 2, height / 2, 0); //Bottom Left - this.drawTexturedModalRect(x, y + height / 2, u, v + 20 - height / 2, width / 2, height / 2); + GuiUtils.drawTexturedModalRect(matrixStack, x, y + height / 2, u, v + 20 - height / 2, width / 2, height / 2, 0); //Bottom Right - this.drawTexturedModalRect(x + width / 2, y + height / 2, u + 200 - width / 2, v + 20 - height / 2, width / 2, height / 2); + GuiUtils.drawTexturedModalRect(matrixStack, x + width / 2, y + height / 2, u + 200 - width / 2, v + 20 - height / 2, width / 2, height / 2, 0); } private int leftBoundOfX() { @@ -76,7 +81,7 @@ private int topBoundOfX() { return y + (HEIGHT - X_SIZE) / 2; } - public boolean inBoundsOfX(int mx, int my) { + public boolean inBoundsOfX(double mx, double my) { int buttonX = leftBoundOfX(); int buttonY = topBoundOfX(); return xVisible && mx >= buttonX && my >= buttonY && mx < buttonX + X_SIZE && my < buttonY + X_SIZE; @@ -86,8 +91,12 @@ public boolean inBounds(int mx, int my) { return mx >= x && my >= y && mx < x + width && my < y + HEIGHT; } + public boolean inBounds(double mx, double my) { + return mx >= x && my >= y && mx < x + width && my < y + HEIGHT; + } + private void updatePosition() { - width = mc.fontRenderer.getStringWidth(text) + 24; + width = minecraft.font.width(text) + 24; if (width % 2 == 1) ++width; width = MathHelper.clamp(width, MIN_WIDTH, MAX_WIDTH); @@ -96,7 +105,7 @@ private void updatePosition() { public void reset() { xVisible = false; - save.tag = new NBTTagCompound(); + save.tag = new CompoundNBT(); text = "Save " + save.name; updatePosition(); } @@ -108,14 +117,13 @@ public void saved() { updatePosition(); } - public void keyTyped(char c, int key) { - if (key == Keyboard.KEY_BACK) { + if (key == GLFW.GLFW_KEY_BACKSPACE) { backSpace(); } - if (Character.isDigit(c) || Character.isLetter(c)) { + if (SharedConstants.isAllowedChatCharacter(c)) { save.name += c; - text = (save.tag.hasNoTags() ? "Save " : "Load ") + save.name; + text = (save.tag.isEmpty() ? "Save " : "Load ") + save.name; updatePosition(); } } @@ -124,7 +132,7 @@ public void keyTyped(char c, int key) { public void backSpace() { if (save.name.length() > 0) { save.name = save.name.substring(0, save.name.length() - 1); - text = (save.tag.hasNoTags() ? "Save " : "Load ") + save.name; + text = (save.tag.isEmpty() ? "Save " : "Load ") + save.name; updatePosition(); } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiTextField.java b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiTextField.java index 075f180..212f03d 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/gui/GuiTextField.java +++ b/src/main/java/com/mcf/davidee/nbtedit/gui/GuiTextField.java @@ -1,20 +1,22 @@ package com.mcf.davidee.nbtedit.gui; +import com.mcf.davidee.nbtedit.NBTStringHelper; +import com.mojang.blaze3d.matrix.MatrixStack; +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.Widget; import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.util.ChatAllowedCharacters; - +import net.minecraft.util.SharedConstants; +import net.minecraft.util.text.StringTextComponent; +import org.lwjgl.glfw.GLFW; import org.lwjgl.opengl.GL11; -import com.mcf.davidee.nbtedit.NBTStringHelper; - -public class GuiTextField extends Gui { - +public class GuiTextField extends Widget { private final FontRenderer fontRenderer; private final int xPos, yPos; @@ -46,8 +48,9 @@ public class GuiTextField extends Gui { private boolean enableBackgroundDrawing = true; private boolean allowSection; - public GuiTextField(FontRenderer par1FontRenderer, int x, int y, int w, int h, boolean allowSection) { - this.fontRenderer = par1FontRenderer; + public GuiTextField(FontRenderer fontRenderer, int x, int y, int w, int h, boolean allowSection) { + super(x, y, w, h, StringTextComponent.EMPTY); + this.fontRenderer = fontRenderer; this.xPos = x; this.yPos = y; this.width = w; @@ -72,7 +75,7 @@ public void setText(String par1Str) { this.text = par1Str; } - this.setCursorPositionEnd(); + this.moveCursorToEnd(); } /** @@ -85,20 +88,20 @@ public String getText() { /** * @return returns the text between the cursor and selectionEnd */ - public String getSelectedtext() { - int var1 = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; - int var2 = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; + public String getHighlighted() { + int var1 = Math.min(this.cursorPosition, this.selectionEnd); + int var2 = Math.max(this.cursorPosition, this.selectionEnd); return this.text.substring(var1, var2); } /** * replaces selected text, or inserts text at the position on the cursor */ - public void writeText(String par1Str) { + public void insertText(String par1Str) { String var2 = ""; String var3 = CharacterFilter.filerAllowedCharacters(par1Str, allowSection); - int var4 = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; - int var5 = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; + int var4 = Math.min(this.cursorPosition, this.selectionEnd); + int var5 = Math.max(this.cursorPosition, this.selectionEnd); int var6 = this.maxStringLength - this.text.length() - (var4 - this.selectionEnd); if (this.text.length() > 0) { @@ -120,7 +123,16 @@ public void writeText(String par1Str) { } this.text = var2; - this.moveCursorBy(var4 - this.selectionEnd + var8); + this.moveCursor(var4 - this.selectionEnd + var8); + } + + private void deleteText(int p_212950_1_) { + if (Screen.hasControlDown()) { + this.deleteWords(p_212950_1_); + } else { + this.deleteChars(p_212950_1_); + } + } /** @@ -130,9 +142,9 @@ public void writeText(String par1Str) { public void deleteWords(int par1) { if (this.text.length() != 0) { if (this.selectionEnd != this.cursorPosition) { - this.writeText(""); + this.insertText(""); } else { - this.deleteFromCursor(this.getNthWordFromCursor(par1) - this.cursorPosition); + this.deleteChars(this.getNthWordFromCursor(par1) - this.cursorPosition); } } } @@ -140,10 +152,10 @@ public void deleteWords(int par1) { /** * delete the selected text, otherwise deletes characters from either side of the cursor. params: delete num */ - public void deleteFromCursor(int par1) { + public void deleteChars(int par1) { if (this.text.length() != 0) { if (this.selectionEnd != this.cursorPosition) { - this.writeText(""); + this.insertText(""); } else { boolean var2 = par1 < 0; int var3 = var2 ? this.cursorPosition + par1 : this.cursorPosition; @@ -161,7 +173,7 @@ public void deleteFromCursor(int par1) { this.text = var5; if (var2) { - this.moveCursorBy(par1); + this.moveCursor(par1); } } } @@ -215,15 +227,15 @@ public int func_73798_a(int par1, int par2, boolean par3) { /** * Moves the text cursor by a specified number of characters and clears the selection */ - public void moveCursorBy(int par1) { - this.setCursorPosition(this.selectionEnd + par1); + public void moveCursor(int amount) { + this.moveCursorTo(this.selectionEnd + amount); } /** * sets the position of the cursor to the provided index */ - public void setCursorPosition(int par1) { - this.cursorPosition = par1; + public void moveCursorTo(int index) { + this.cursorPosition = index; int var2 = this.text.length(); if (this.cursorPosition < 0) { @@ -234,114 +246,111 @@ public void setCursorPosition(int par1) { this.cursorPosition = var2; } - this.setSelectionPos(this.cursorPosition); + this.setHighlightPos(this.cursorPosition); } /** * sets the cursors position to the beginning */ - public void setCursorPositionZero() { - this.setCursorPosition(0); + public void moveCursorToStart() { + this.moveCursorTo(0); } /** * sets the cursors position to after the text */ - public void setCursorPositionEnd() { - this.setCursorPosition(this.text.length()); + public void moveCursorToEnd() { + this.moveCursorTo(this.text.length()); } /** * Call this method from you GuiScreen to process the keys into textbox. */ - public boolean textboxKeyTyped(char par1, int par2) { - if (this.isEnabled && this.isFocused) { - switch (par1) { - case 1: - this.setCursorPositionEnd(); - this.setSelectionPos(0); - return true; - case 3: - GuiScreen.setClipboardString(this.getSelectedtext()); - return true; - case 22: - this.writeText(GuiScreen.getClipboardString()); - return true; - case 24: - GuiScreen.setClipboardString(this.getSelectedtext()); - this.writeText(""); - return true; - default: - switch (par2) { - case 14: - if (GuiScreen.isCtrlKeyDown()) { - this.deleteWords(-1); - } else { - this.deleteFromCursor(-1); - } - - return true; - case 199: - if (GuiScreen.isShiftKeyDown()) { - this.setSelectionPos(0); - } else { - this.setCursorPositionZero(); - } - - return true; - case 203: - if (GuiScreen.isShiftKeyDown()) { - if (GuiScreen.isCtrlKeyDown()) { - this.setSelectionPos(this.getNthWordFromPos(-1, this.getSelectionEnd())); - } else { - this.setSelectionPos(this.getSelectionEnd() - 1); - } - } else if (GuiScreen.isCtrlKeyDown()) { - this.setCursorPosition(this.getNthWordFromCursor(-1)); - } else { - this.moveCursorBy(-1); - } - - return true; - case 205: - if (GuiScreen.isShiftKeyDown()) { - if (GuiScreen.isCtrlKeyDown()) { - this.setSelectionPos(this.getNthWordFromPos(1, this.getSelectionEnd())); - } else { - this.setSelectionPos(this.getSelectionEnd() + 1); - } - } else if (GuiScreen.isCtrlKeyDown()) { - this.setCursorPosition(this.getNthWordFromCursor(1)); - } else { - this.moveCursorBy(1); - } - return true; - case 207: - if (GuiScreen.isShiftKeyDown()) { - this.setSelectionPos(this.text.length()); - } else { - this.setCursorPositionEnd(); - } - - return true; - case 211: - if (GuiScreen.isCtrlKeyDown()) { - this.deleteWords(1); + public boolean keyPressed(int key, int p_231046_2_, int p_231046_3_) { + if (this.isEnabled && this.isFocused) { + if (Screen.isSelectAll(key)) { + this.moveCursorToEnd(); + this.setHighlightPos(0); + return true; + } else if (Screen.isCopy(key)) { + Minecraft.getInstance().keyboardHandler.setClipboard(this.getHighlighted()); + return true; + } else if (Screen.isPaste(key)) { + this.insertText(Minecraft.getInstance().keyboardHandler.getClipboard()); + return true; + } else if (Screen.isCut(key)) { + Minecraft.getInstance().keyboardHandler.setClipboard(this.getHighlighted()); + this.insertText(""); + return true; + } else { + switch(key) { + case GLFW.GLFW_KEY_BACKSPACE: + this.deleteText(-1); + return true; + case GLFW.GLFW_KEY_INSERT: + case GLFW.GLFW_KEY_DOWN: + case GLFW.GLFW_KEY_UP: + case GLFW.GLFW_KEY_PAGE_UP: + case GLFW.GLFW_KEY_PAGE_DOWN: + return false; + case GLFW.GLFW_KEY_DELETE: + this.deleteText(1); + return true; + case GLFW.GLFW_KEY_RIGHT: + if (Screen.hasShiftDown()) { + if (Screen.hasControlDown()) { + this.setHighlightPos(this.getNthWordFromPos(1, this.getSelectionEnd())); } else { - this.deleteFromCursor(1); + this.setHighlightPos(this.getSelectionEnd() + 1); } - - return true; - default: - if (ChatAllowedCharacters.isAllowedCharacter(par1)) { - this.writeText(Character.toString(par1)); - return true; + } else if (Screen.hasControlDown()) { + this.moveCursorTo(this.getNthWordFromCursor(1)); + } else { + this.moveCursor(1); + } + return true; + case GLFW.GLFW_KEY_LEFT: + if (Screen.hasShiftDown()) { + if (Screen.hasControlDown()) { + this.setHighlightPos(this.getNthWordFromPos(-1, this.getSelectionEnd())); } else { - return false; + this.setHighlightPos(this.getSelectionEnd() - 1); } - } + } else if (Screen.hasControlDown()) { + this.moveCursorTo(this.getNthWordFromCursor(-1)); + } else { + this.moveCursor(-1); + } + + return true; + case GLFW.GLFW_KEY_HOME: + if (Screen.hasShiftDown()) { + this.setHighlightPos(0); + } else { + this.moveCursorToStart(); + } + return true; + case GLFW.GLFW_KEY_END: + if (Screen.hasShiftDown()) { + this.setHighlightPos(this.text.length()); + } else { + this.moveCursorToEnd(); + } + return true; + default: + return false; + } } + } + return false; + } + + @Override + public boolean charTyped(char p_231042_1_, int p_231042_2_) { + if (SharedConstants.isAllowedChatCharacter(p_231042_1_)) { + this.insertText(Character.toString(p_231042_1_)); + return true; } else { return false; } @@ -350,39 +359,42 @@ public boolean textboxKeyTyped(char par1, int par2) { /** * Args: x, y, buttonClicked */ - public void mouseClicked(int par1, int par2, int par3) { + @Override + public boolean mouseClicked(double mx, double my, int button) { String displayString = text.replace(NBTStringHelper.SECTION_SIGN, '?'); - boolean var4 = par1 >= this.xPos && par1 < this.xPos + this.width && par2 >= this.yPos && par2 < this.yPos + this.height; + boolean inBounds = mx >= this.xPos && mx < this.xPos + this.width && my >= this.yPos && my < this.yPos + this.height; - this.setFocused(this.isEnabled && var4); + this.setFocused(this.isEnabled && inBounds); - if (this.isFocused && par3 == 0) { - int var5 = par1 - this.xPos; + if (this.isFocused && button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { + int var5 = (int) mx - this.xPos; if (this.enableBackgroundDrawing) { var5 -= 4; } - String var6 = this.fontRenderer.trimStringToWidth(displayString.substring(this.field_73816_n), this.getWidth()); - this.setCursorPosition(this.fontRenderer.trimStringToWidth(var6, var5).length() + this.field_73816_n); + String var6 = this.fontRenderer.plainSubstrByWidth(displayString.substring(this.field_73816_n), this.getWidth()); + this.moveCursorTo(this.fontRenderer.plainSubstrByWidth(var6, var5).length() + this.field_73816_n); + return true; } + return inBounds; } /** * Draws the textbox */ - public void drawTextBox() { + public void drawTextBox(MatrixStack matrixStack) { String textToDisplay = text.replace(NBTStringHelper.SECTION_SIGN, '?'); if (this.getVisible()) { if (this.getEnableBackgroundDrawing()) { - drawRect(this.xPos - 1, this.yPos - 1, this.xPos + this.width + 1, this.yPos + this.height + 1, -6250336); - drawRect(this.xPos, this.yPos, this.xPos + this.width, this.yPos + this.height, -16777216); + fill(matrixStack, this.xPos - 1, this.yPos - 1, this.xPos + this.width + 1, this.yPos + this.height + 1, -6250336); + fill(matrixStack, this.xPos, this.yPos, this.xPos + this.width, this.yPos + this.height, -16777216); } int var1 = this.isEnabled ? this.enabledColor : this.disabledColor; int var2 = this.cursorPosition - this.field_73816_n; int var3 = this.selectionEnd - this.field_73816_n; - String var4 = this.fontRenderer.trimStringToWidth(textToDisplay.substring(this.field_73816_n), this.getWidth()); + String var4 = this.fontRenderer.plainSubstrByWidth(textToDisplay.substring(this.field_73816_n), this.getWidth()); boolean var5 = var2 >= 0 && var2 <= var4.length(); boolean var6 = this.isFocused && this.cursorCounter / 6 % 2 == 0 && var5; int var7 = this.enableBackgroundDrawing ? this.xPos + 4 : this.xPos; @@ -395,7 +407,7 @@ public void drawTextBox() { if (var4.length() > 0) { String var10 = var5 ? var4.substring(0, var2) : var4; - var9 = this.fontRenderer.drawStringWithShadow(var10, var7, var8, var1); + var9 = this.fontRenderer.drawShadow(matrixStack, var10, var7, var8, var1); } boolean var13 = this.cursorPosition < this.text.length() || this.text.length() >= this.getMaxStringLength(); @@ -409,20 +421,20 @@ public void drawTextBox() { } if (var4.length() > 0 && var5 && var2 < var4.length()) { - this.fontRenderer.drawStringWithShadow(var4.substring(var2), var9, var8, var1); + this.fontRenderer.drawShadow(matrixStack, var4.substring(var2), var9, var8, var1); } if (var6) { if (var13) { - Gui.drawRect(var11, var8 - 1, var11 + 1, var8 + 1 + this.fontRenderer.FONT_HEIGHT, -3092272); + fill(matrixStack, var11, var8 - 1, var11 + 1, var8 + 1 + this.fontRenderer.lineHeight, -3092272); } else { - this.fontRenderer.drawStringWithShadow("_", var11, var8, var1); + this.fontRenderer.drawShadow(matrixStack, "_", var11, var8, var1); } } if (var3 != var2) { - int var12 = var7 + this.fontRenderer.getStringWidth(var4.substring(0, var3)); - this.drawCursorVertical(var11, var8 - 1, var12 - 1, var8 + 1 + this.fontRenderer.FONT_HEIGHT); + int var12 = var7 + this.fontRenderer.width(var4.substring(0, var3)); + this.drawCursorVertical(matrixStack, var11, var8 - 1, var12 - 1, var8 + 1 + this.fontRenderer.lineHeight); } } } @@ -430,7 +442,7 @@ public void drawTextBox() { /** * draws the vertical line cursor in the textbox */ - private void drawCursorVertical(int par1, int par2, int par3, int par4) { + private void drawCursorVertical(MatrixStack matrixStack, int par1, int par2, int par3, int par4) { int var5; if (par1 < par3) { @@ -444,22 +456,21 @@ private void drawCursorVertical(int par1, int par2, int par3, int par4) { par2 = par4; par4 = var5; } - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder worldRenderer = tessellator.getBuffer(); + BufferBuilder tex = tessellator.getBuilder(); GL11.glColor4f(0.0F, 0.0F, 255.0F, 255.0F); - GlStateManager.disableTexture2D(); - GlStateManager.enableColorLogic(); - GlStateManager.colorLogicOp(GL11.GL_OR_REVERSE); + RenderSystem.disableTexture(); + RenderSystem.enableColorLogicOp(); + RenderSystem.logicOp(GlStateManager.LogicOp.OR_REVERSE); - worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); - worldRenderer.pos((double) par1, (double) par4, 0.0D); - worldRenderer.pos((double) par3, (double) par4, 0.0D); - worldRenderer.pos((double) par3, (double) par2, 0.0D); - worldRenderer.pos((double) par1, (double) par2, 0.0D); - tessellator.draw(); - GlStateManager.disableColorLogic(); - GlStateManager.enableTexture2D(); + tex.begin(7, DefaultVertexFormats.POSITION); + tex.vertex(par1, par4, 0.0D).endVertex(); + tex.vertex(par3, par4, 0.0D).endVertex(); + tex.vertex(par3, par2, 0.0D).endVertex(); + tex.vertex(par1, par2, 0.0D).endVertex(); + tessellator.end(); + RenderSystem.disableColorLogicOp(); + RenderSystem.enableTexture(); } public void setMaxStringLength(int par1) { @@ -527,7 +538,7 @@ public boolean isFocused() { return this.isFocused; } - public void func_82265_c(boolean par1) { + public void setEditable(boolean par1) { this.isEnabled = par1; } @@ -548,7 +559,7 @@ public int getWidth() { /** * Sets the position of the selection anchor (i.e. position the selection was started at) */ - public void setSelectionPos(int par1) { + public void setHighlightPos(int par1) { String displayString = text.replace(NBTStringHelper.SECTION_SIGN, '?'); int var2 = displayString.length(); @@ -568,11 +579,11 @@ public void setSelectionPos(int par1) { } int var3 = this.getWidth(); - String var4 = this.fontRenderer.trimStringToWidth(displayString.substring(this.field_73816_n), var3); + String var4 = this.fontRenderer.plainSubstrByWidth(displayString.substring(this.field_73816_n), var3); int var5 = var4.length() + this.field_73816_n; if (par1 == this.field_73816_n) { - this.field_73816_n -= this.fontRenderer.trimStringToWidth(displayString, var3, true).length(); + this.field_73816_n -= this.fontRenderer.plainSubstrByWidth(displayString, var3, true).length(); } if (par1 > var5) { diff --git a/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTNodeSorter.java b/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTNodeSorter.java index da6ce2b..168fd5e 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTNodeSorter.java +++ b/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTNodeSorter.java @@ -1,28 +1,28 @@ package com.mcf.davidee.nbtedit.nbt; -import java.util.Comparator; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.nbt.INBT; +import net.minecraft.nbt.ListNBT; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; +import java.util.Comparator; public class NBTNodeSorter implements Comparator> { @Override public int compare(Node a, Node b) { - NBTBase n1 = a.getObject().getNBT(), n2 = b.getObject().getNBT(); + INBT n1 = a.getObject().getNBT(), n2 = b.getObject().getNBT(); String s1 = a.getObject().getName(), s2 = b.getObject().getName(); - if (n1 instanceof NBTTagCompound || n1 instanceof NBTTagList) { - if (n2 instanceof NBTTagCompound || n2 instanceof NBTTagList) { + if (n1 instanceof CompoundNBT || n1 instanceof ListNBT) { + if (n2 instanceof CompoundNBT || n2 instanceof ListNBT) { int dif = n1.getId() - n2.getId(); - return (dif == 0) ? s1.compareTo(s2) : dif; + return ( dif == 0 ) ? s1.compareTo(s2) : dif; } return 1; } - if (n2 instanceof NBTTagCompound || n2 instanceof NBTTagList) + if (n2 instanceof CompoundNBT || n2 instanceof ListNBT) return -1; int dif = n1.getId() - n2.getId(); - return (dif == 0) ? s1.compareTo(s2) : dif; + return ( dif == 0 ) ? s1.compareTo(s2) : dif; } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTTree.java b/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTTree.java index aecffc1..1d00b22 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTTree.java +++ b/src/main/java/com/mcf/davidee/nbtedit/nbt/NBTTree.java @@ -1,27 +1,22 @@ package com.mcf.davidee.nbtedit.nbt; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - import com.mcf.davidee.nbtedit.NBTEdit; import com.mcf.davidee.nbtedit.NBTHelper; import com.mcf.davidee.nbtedit.NBTStringHelper; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.nbt.INBT; +import net.minecraft.nbt.ListNBT; + +import java.util.*; +import java.util.Map.Entry; public class NBTTree { - private NBTTagCompound baseTag; + private CompoundNBT baseTag; private Node root; - public NBTTree(NBTTagCompound tag) { + public NBTTree(CompoundNBT tag) { baseTag = tag; construct(); } @@ -35,7 +30,7 @@ public boolean canDelete(Node node) { } public boolean delete(Node node) { - return !(node == null || node == root) && deleteNode(node, root); + return !( node == null || node == root ) && deleteNode(node, root); } private boolean deleteNode(Node toDelete, Node cur) { @@ -67,20 +62,20 @@ public void sort(Node node) { } public void addChildrenToTree(Node parent) { - NBTBase tag = parent.getObject().getNBT(); - if (tag instanceof NBTTagCompound) { - Map map = NBTHelper.getMap((NBTTagCompound) tag); - for (Entry entry : map.entrySet()) { - NBTBase base = entry.getValue(); + INBT tag = parent.getObject().getNBT(); + if (tag instanceof CompoundNBT) { + Map map = NBTHelper.getMap((CompoundNBT) tag); + for (Entry entry : map.entrySet()) { + INBT base = entry.getValue(); Node child = new Node<>(parent, new NamedNBT(entry.getKey(), base)); parent.addChild(child); addChildrenToTree(child); } - } else if (tag instanceof NBTTagList) { - NBTTagList list = (NBTTagList) tag; - for (int i = 0; i < list.tagCount(); ++i) { - NBTBase base = NBTHelper.getTagAt(list, i); + } else if (tag instanceof ListNBT) { + ListNBT list = (ListNBT) tag; + for (int i = 0; i < list.size(); ++i) { + INBT base = NBTHelper.getTagAt(list, i); Node child = new Node<>(parent, new NamedNBT(base)); parent.addChild(child); addChildrenToTree(child); @@ -88,42 +83,42 @@ public void addChildrenToTree(Node parent) { } } - public NBTTagCompound toNBTTagCompound() { - NBTTagCompound tag = new NBTTagCompound(); + public CompoundNBT toNBTTagCompound() { + CompoundNBT tag = new CompoundNBT(); addChildrenToTag(root, tag); return tag; } - public void addChildrenToTag(Node parent, NBTTagCompound tag) { + public void addChildrenToTag(Node parent, CompoundNBT tag) { for (Node child : parent.getChildren()) { - NBTBase base = child.getObject().getNBT(); + INBT base = child.getObject().getNBT(); String name = child.getObject().getName(); - if (base instanceof NBTTagCompound) { - NBTTagCompound newTag = new NBTTagCompound(); + if (base instanceof CompoundNBT) { + CompoundNBT newTag = new CompoundNBT(); addChildrenToTag(child, newTag); - tag.setTag(name, newTag); - } else if (base instanceof NBTTagList) { - NBTTagList list = new NBTTagList(); + tag.put(name, newTag); + } else if (base instanceof ListNBT) { + ListNBT list = new ListNBT(); addChildrenToList(child, list); - tag.setTag(name, list); + tag.put(name, list); } else - tag.setTag(name, base.copy()); + tag.put(name, base.copy()); } } - public void addChildrenToList(Node parent, NBTTagList list) { + public void addChildrenToList(Node parent, ListNBT list) { for (Node child : parent.getChildren()) { - NBTBase base = child.getObject().getNBT(); - if (base instanceof NBTTagCompound) { - NBTTagCompound newTag = new NBTTagCompound(); + INBT base = child.getObject().getNBT(); + if (base instanceof CompoundNBT) { + CompoundNBT newTag = new CompoundNBT(); addChildrenToTag(child, newTag); - list.appendTag(newTag); - } else if (base instanceof NBTTagList) { - NBTTagList newList = new NBTTagList(); + list.add(newTag); + } else if (base instanceof ListNBT) { + ListNBT newList = new ListNBT(); addChildrenToList(child, newList); - list.appendTag(newList); + list.add(newList); } else - list.appendTag(base.copy()); + list.add(base.copy()); } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/nbt/NamedNBT.java b/src/main/java/com/mcf/davidee/nbtedit/nbt/NamedNBT.java index 1364031..62667a0 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/nbt/NamedNBT.java +++ b/src/main/java/com/mcf/davidee/nbtedit/nbt/NamedNBT.java @@ -1,17 +1,17 @@ package com.mcf.davidee.nbtedit.nbt; -import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.INBT; public class NamedNBT { protected String name; - protected NBTBase nbt; + protected INBT nbt; - public NamedNBT(NBTBase nbt) { + public NamedNBT(INBT nbt) { this("", nbt); } - public NamedNBT(String name, NBTBase nbt) { + public NamedNBT(String name, INBT nbt) { this.name = name; this.nbt = nbt; } @@ -24,11 +24,11 @@ public void setName(String name) { this.name = name; } - public NBTBase getNBT() { + public INBT getNBT() { return nbt; } - public void setNBT(NBTBase nbt) { + public void setNBT(INBT nbt) { this.nbt = nbt; } diff --git a/src/main/java/com/mcf/davidee/nbtedit/nbt/SaveStates.java b/src/main/java/com/mcf/davidee/nbtedit/nbt/SaveStates.java index 03d73ad..d0c3d00 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/nbt/SaveStates.java +++ b/src/main/java/com/mcf/davidee/nbtedit/nbt/SaveStates.java @@ -1,8 +1,8 @@ package com.mcf.davidee.nbtedit.nbt; import com.mcf.davidee.nbtedit.NBTEdit; +import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; import org.apache.logging.log4j.Level; import java.io.File; @@ -19,27 +19,27 @@ public SaveStates(File file) { this.file = file; tags = new SaveState[7]; for (int i = 0; i < 7; ++i) - tags[i] = new SaveState("Slot " + (i + 1)); + tags[i] = new SaveState("Slot " + ( i + 1 )); } public void read() throws IOException { if (file.exists() && file.canRead()) { - NBTTagCompound root = CompressedStreamTools.read(file); + CompoundNBT root = CompressedStreamTools.read(file); for (int i = 0; i < 7; ++i) { - String name = "slot" + (i + 1); - if (root.hasKey(name)) - tags[i].tag = root.getCompoundTag(name); - if (root.hasKey(name + "Name")) + String name = "slot" + ( i + 1 ); + if (root.contains(name)) + tags[i].tag = root.getCompound(name); + if (root.contains(name + "Name")) tags[i].name = root.getString(name + "Name"); } } } public void write() throws IOException { - NBTTagCompound root = new NBTTagCompound(); + CompoundNBT root = new CompoundNBT(); for (int i = 0; i < 7; ++i) { - root.setTag("slot" + (i + 1), tags[i].tag); - root.setString("slot" + (i + 1) + "Name", tags[i].name); + root.put("slot" + ( i + 1 ), tags[i].tag); + root.putString("slot" + ( i + 1 ) + "Name", tags[i].name); } CompressedStreamTools.write(root, file); } @@ -70,11 +70,11 @@ public SaveState getSaveState(int index) { public static final class SaveState { public String name; - public NBTTagCompound tag; + public CompoundNBT tag; public SaveState(String name) { this.name = name; - this.tag = new NBTTagCompound(); + this.tag = new CompoundNBT(); } } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/EntityDataPacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/EntityDataPacket.java new file mode 100644 index 0000000..c7b3376 --- /dev/null +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/EntityDataPacket.java @@ -0,0 +1,44 @@ +package com.mcf.davidee.nbtedit.packets; + +import com.mcf.davidee.nbtedit.NBTEdit; +import com.mcf.davidee.nbtedit.NBTHelper; +import io.netty.buffer.ByteBuf; +import net.minecraft.nbt.CompoundNBT; +import net.minecraftforge.fml.network.NetworkEvent; + +import java.util.function.Supplier; + +public class EntityDataPacket extends EntityRequestPacket { + /** + * The nbt data of the entity. + */ + protected CompoundNBT tag; + + /** + * Required default constructor. + */ + public EntityDataPacket() { + } + + public EntityDataPacket(int entityID, CompoundNBT tag) { + super(entityID); + this.tag = tag; + } + + public static EntityDataPacket fromBytes(ByteBuf buf) { + int entityID = buf.readInt(); + CompoundNBT tag = NBTHelper.readNbtFromBuffer(buf); + return new EntityDataPacket(entityID, tag); + } + + @Override + public void toBytes(ByteBuf buf) { + super.toBytes(buf); + NBTHelper.writeToBuffer(this.tag, buf); + } + + public void handle(Supplier ctx) { + ctx.get().setPacketHandled(true); + NBTEdit.proxy.openEditGUI(this.entityID, this.tag); + } +} diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/EntityNBTPacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/EntityNBTPacket.java deleted file mode 100644 index 21ac354..0000000 --- a/src/main/java/com/mcf/davidee/nbtedit/packets/EntityNBTPacket.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.mcf.davidee.nbtedit.packets; - -import com.mcf.davidee.nbtedit.NBTEdit; -import com.mcf.davidee.nbtedit.NBTHelper; -import io.netty.buffer.ByteBuf; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.play.server.SPacketSetExperience; -import net.minecraft.network.play.server.SPacketUpdateHealth; -import net.minecraft.util.text.TextFormatting; -import net.minecraft.world.GameType; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; -import net.minecraftforge.fml.relauncher.Side; -import org.apache.logging.log4j.Level; - -public class EntityNBTPacket implements IMessage { - /** - * The id of the entity being edited. - */ - protected int entityID; - /** - * The nbt data of the entity. - */ - protected NBTTagCompound tag; - - /** - * Required default constructor. - */ - public EntityNBTPacket() { - } - - public EntityNBTPacket(int entityID, NBTTagCompound tag) { - this.entityID = entityID; - this.tag = tag; - } - - @Override - public void fromBytes(ByteBuf buf) { - this.entityID = buf.readInt(); - this.tag = NBTHelper.readNbtFromBuffer(buf); - } - - @Override - public void toBytes(ByteBuf buf) { - buf.writeInt(this.entityID); - NBTHelper.writeToBuffer(this.tag, buf); - } - - public static class Handler implements IMessageHandler { - - @Override - public IMessage onMessage(final EntityNBTPacket packet, MessageContext ctx) { - if (ctx.side == Side.SERVER) { - final EntityPlayerMP player = ctx.getServerHandler().player; - player.getServerWorld().addScheduledTask(new Runnable() { - @Override - public void run() { - Entity entity = player.getServerWorld().getEntityByID(packet.entityID); - if (entity != null && NBTEdit.proxy.checkPermission(player)) { - try { - GameType preGameType = null; - if (entity instanceof EntityPlayerMP) - preGameType = ((EntityPlayerMP) entity).interactionManager.getGameType(); - entity.readFromNBT(packet.tag); - NBTEdit.log(Level.TRACE, player.getName() + " edited a tag -- Entity ID #" + packet.entityID); - NBTEdit.logTag(packet.tag); - if (entity instanceof EntityPlayerMP) {//Update player info - // This is fairly hacky. Consider swapping to an event driven system, where classes can register to - // receive entity edit events and provide feedback/send packets as necessary. - EntityPlayerMP targetPlayer = (EntityPlayerMP) entity; - targetPlayer.sendContainerToPlayer(targetPlayer.inventoryContainer); - GameType type = targetPlayer.interactionManager.getGameType(); - if (preGameType != type) { - targetPlayer.setGameType(type); - } - targetPlayer.connection.sendPacket(new SPacketUpdateHealth(targetPlayer.getHealth(), - targetPlayer.getFoodStats().getFoodLevel(), targetPlayer.getFoodStats().getSaturationLevel())); - targetPlayer.connection.sendPacket(new SPacketSetExperience(targetPlayer.experience, - targetPlayer.experienceTotal, targetPlayer.experienceLevel)); - targetPlayer.sendPlayerAbilities(); - targetPlayer.setPositionAndUpdate(targetPlayer.posX, targetPlayer.posY, targetPlayer.posZ); - } - NBTEdit.proxy.sendMessage(player, "Your changes have been saved", TextFormatting.WHITE); - } catch (Throwable t) { - NBTEdit.proxy.sendMessage(player, "Save Failed - Invalid NBT format for Entity", TextFormatting.RED); - NBTEdit.log(Level.WARN, player.getName() + " edited a tag and caused an exception"); - NBTEdit.logTag(packet.tag); - NBTEdit.throwing("EntityNBTPacket", "Handler.onMessage", t); - } - } else { - NBTEdit.proxy.sendMessage(player, "Save Failed - Entity does not exist", TextFormatting.RED); - } - } - }); - } else { - NBTEdit.proxy.openEditGUI(packet.entityID, packet.tag); - } - return null; - } - } -} diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/EntityRequestPacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/EntityRequestPacket.java index 5cb5aa5..ca1e0c0 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/packets/EntityRequestPacket.java +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/EntityRequestPacket.java @@ -2,17 +2,17 @@ import com.mcf.davidee.nbtedit.NBTEdit; import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraftforge.fml.network.NetworkEvent; import org.apache.logging.log4j.Level; -public class EntityRequestPacket implements IMessage { +import java.util.function.Supplier; + +public class EntityRequestPacket { /** * The id of the entity being requested. */ - private int entityID; + protected int entityID; /** * Required default constructor. @@ -24,24 +24,18 @@ public EntityRequestPacket(int entityID) { this.entityID = entityID; } - @Override - public void fromBytes(ByteBuf buf) { - this.entityID = buf.readInt(); + public static EntityRequestPacket fromBytes(ByteBuf buf) { + return new EntityRequestPacket(buf.readInt()); } - @Override public void toBytes(ByteBuf buf) { buf.writeInt(this.entityID); } - public static class Handler implements IMessageHandler { - - @Override - public IMessage onMessage(EntityRequestPacket packet, MessageContext ctx) { - EntityPlayerMP player = ctx.getServerHandler().player; - NBTEdit.log(Level.TRACE, player.getName() + " requested entity with Id #" + packet.entityID); - NBTEdit.NETWORK.sendEntity(player, packet.entityID); - return null; - } + public void handle(Supplier ctx) { + ctx.get().setPacketHandled(true); + ServerPlayerEntity player = ctx.get().getSender(); + NBTEdit.log(Level.TRACE, player.getGameProfile().getName() + " requested entity with Id #" + this.entityID); + ctx.get().enqueueWork(() -> NBTEdit.NETWORK.sendEntity(player, this.entityID)); } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/EntitySavePacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/EntitySavePacket.java new file mode 100644 index 0000000..c83a9fc --- /dev/null +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/EntitySavePacket.java @@ -0,0 +1,77 @@ +package com.mcf.davidee.nbtedit.packets; + +import com.mcf.davidee.nbtedit.NBTEdit; +import com.mcf.davidee.nbtedit.NBTHelper; +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.network.play.server.SSetExperiencePacket; +import net.minecraft.network.play.server.SUpdateHealthPacket; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.world.GameType; +import net.minecraftforge.fml.network.NetworkEvent; +import org.apache.logging.log4j.Level; + +import java.util.function.Supplier; + +public class EntitySavePacket extends EntityDataPacket { + + /** + * Required default constructor. + */ + public EntitySavePacket() { + } + + public EntitySavePacket(int entityID, CompoundNBT tag) { + super(entityID, tag); + } + + public static EntitySavePacket fromBytes(ByteBuf buf) { + int entityID = buf.readInt(); + CompoundNBT tag = NBTHelper.readNbtFromBuffer(buf); + return new EntitySavePacket(entityID, tag); + } + + public void handle(Supplier ctx) { + ctx.get().setPacketHandled(true); + final ServerPlayerEntity player = ctx.get().getSender(); + ctx.get().enqueueWork(() -> { + Entity entity = player.getLevel().getEntity(this.entityID); + if (entity != null && NBTEdit.proxy.checkPermission(player)) { + try { + GameType preGameType = null; + if (entity instanceof ServerPlayerEntity) + preGameType = ( (ServerPlayerEntity) entity ).gameMode.getGameModeForPlayer(); + entity.load(this.tag); + NBTEdit.log(Level.TRACE, player.getGameProfile().getName() + " edited a tag -- Entity ID #" + this.entityID); + NBTEdit.logTag(this.tag); + if (entity instanceof ServerPlayerEntity) {//Update player info + // This is fairly hacky. Consider swapping to an event driven system, where classes can register to + // receive entity edit events and provide feedback/send packets as necessary. + ServerPlayerEntity targetPlayer = (ServerPlayerEntity) entity; + targetPlayer.refreshContainer(targetPlayer.inventoryMenu); + GameType type = targetPlayer.gameMode.getGameModeForPlayer(); + if (preGameType != type) { + targetPlayer.setGameMode(type); + } + targetPlayer.connection.send(new SUpdateHealthPacket(targetPlayer.getHealth(), + targetPlayer.getFoodData().getFoodLevel(), targetPlayer.getFoodData().getSaturationLevel())); + targetPlayer.connection.send(new SSetExperiencePacket(targetPlayer.experienceProgress, + targetPlayer.totalExperience, targetPlayer.experienceLevel)); + targetPlayer.onUpdateAbilities(); + targetPlayer.setPos(targetPlayer.xo, targetPlayer.yo, targetPlayer.zo); + } + NBTEdit.proxy.sendMessage(player, "Your changes have been saved", TextFormatting.WHITE); + } catch (Throwable t) { + NBTEdit.proxy.sendMessage(player, "Save Failed - Invalid NBT format for Entity", TextFormatting.RED); + NBTEdit.log(Level.WARN, player.getGameProfile().getName() + " edited a tag and caused an exception"); + NBTEdit.logTag(this.tag); + NBTEdit.throwing("EntityNBTPacket", "Handler.onMessage", t); + } + } else { + NBTEdit.proxy.sendMessage(player, "Save Failed - Entity does not exist", TextFormatting.RED); + } + }); + } +} diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/MouseOverPacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/MouseOverPacket.java index 1219cda..2308cb9 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/packets/MouseOverPacket.java +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/MouseOverPacket.java @@ -1,15 +1,17 @@ package com.mcf.davidee.nbtedit.packets; import com.mcf.davidee.nbtedit.NBTEdit; -import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.math.BlockRayTraceResult; +import net.minecraft.util.math.EntityRayTraceResult; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.text.TextFormatting; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; -public class MouseOverPacket implements IMessage { +import java.util.function.Supplier; + +public class MouseOverPacket { /** * Required default constructor. @@ -17,29 +19,27 @@ public class MouseOverPacket implements IMessage { public MouseOverPacket() { } - @Override - public void fromBytes(ByteBuf buf) { + public static MouseOverPacket fromBytes(PacketBuffer buf) { + return new MouseOverPacket(); } - @Override - public void toBytes(ByteBuf buf) { + public void toBytes(PacketBuffer buf) { + //Nothing to write. } - public static class Handler implements IMessageHandler { - - @Override - public IMessage onMessage(MouseOverPacket message, MessageContext ctx) { - RayTraceResult pos = Minecraft.getMinecraft().objectMouseOver; - if (pos != null) { - if (pos.entityHit != null) { - return new EntityRequestPacket(pos.entityHit.getEntityId()); - } else if (pos.typeOfHit == RayTraceResult.Type.BLOCK) { - return new TileRequestPacket(pos.getBlockPos()); - } else { - NBTEdit.proxy.sendMessage(null, "Error - No tile or entity selected", TextFormatting.RED); - } + public void handle(Supplier ctx) { + ctx.get().setPacketHandled(true); + RayTraceResult ray = Minecraft.getInstance().hitResult; + if (ray != null) { + if (ray.getType() == RayTraceResult.Type.ENTITY) { + EntityRayTraceResult entityRay = (EntityRayTraceResult) ray; + NBTEdit.NETWORK.INSTANCE.reply(new EntityRequestPacket(entityRay.getEntity().getId()), ctx.get()); + } else if (ray.getType() == RayTraceResult.Type.BLOCK) { + BlockRayTraceResult blockRay = (BlockRayTraceResult) ray; + NBTEdit.NETWORK.INSTANCE.reply(new TileRequestPacket(blockRay.getBlockPos()), ctx.get()); + } else { + NBTEdit.proxy.sendMessage(null, "Error - No tile or entity selected", TextFormatting.RED); } - return null; } } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/PacketHandler.java b/src/main/java/com/mcf/davidee/nbtedit/packets/PacketHandler.java index 462c04d..f1e441b 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/packets/PacketHandler.java +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/PacketHandler.java @@ -2,38 +2,48 @@ import com.mcf.davidee.nbtedit.NBTEdit; import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextFormatting; -import net.minecraftforge.fml.common.network.NetworkRegistry; -import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.network.NetworkDirection; +import net.minecraftforge.fml.network.NetworkRegistry; +import net.minecraftforge.fml.network.PacketDistributor; +import net.minecraftforge.fml.network.simple.SimpleChannel; import org.apache.logging.log4j.Level; +import java.util.Optional; + /** * Created by Jay113355 on 6/28/2016. * */ public class PacketHandler { - public SimpleNetworkWrapper INSTANCE; + public static final ResourceLocation MAIN = new ResourceLocation(NBTEdit.MODID, "main"); + public SimpleChannel INSTANCE; private static int ID = 0; public void initialize() { - INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(NBTEdit.MODID); + INSTANCE = NetworkRegistry.newSimpleChannel(MAIN, () -> "1.0", s -> true, s -> true); registerPackets(); } public void registerPackets() { - INSTANCE.registerMessage(TileRequestPacket.Handler.class, TileRequestPacket.class, ID++, Side.SERVER); - INSTANCE.registerMessage(TileNBTPacket.Handler.class, TileNBTPacket.class, ID++, Side.CLIENT); - INSTANCE.registerMessage(TileNBTPacket.Handler.class, TileNBTPacket.class, ID++, Side.SERVER); - INSTANCE.registerMessage(EntityRequestPacket.Handler.class, EntityRequestPacket.class, ID++, Side.SERVER); - INSTANCE.registerMessage(EntityNBTPacket.Handler.class, EntityNBTPacket.class, ID++, Side.CLIENT); - INSTANCE.registerMessage(EntityNBTPacket.Handler.class, EntityNBTPacket.class, ID++, Side.SERVER); - INSTANCE.registerMessage(MouseOverPacket.Handler.class, MouseOverPacket.class, ID++, Side.CLIENT); + if (ID != 0) { + throw new IllegalStateException("Packets already registered!"); + } + INSTANCE.registerMessage(ID++, MouseOverPacket.class, MouseOverPacket::toBytes, MouseOverPacket::fromBytes, MouseOverPacket::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); + + INSTANCE.registerMessage(ID++, TileRequestPacket.class, TileRequestPacket::toBytes, TileRequestPacket::fromBytes, TileRequestPacket::handle, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + INSTANCE.registerMessage(ID++, TileDataPacket.class, TileDataPacket::toBytes, TileDataPacket::fromBytes, TileDataPacket::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); + INSTANCE.registerMessage(ID++, TileSavePacket.class, TileSavePacket::toBytes, TileSavePacket::fromBytes, TileSavePacket::handle, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + + INSTANCE.registerMessage(ID++, EntityRequestPacket.class, EntityRequestPacket::toBytes, EntityRequestPacket::fromBytes, EntityRequestPacket::handle, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + INSTANCE.registerMessage(ID++, EntityDataPacket.class, EntityDataPacket::toBytes, EntityDataPacket::fromBytes, EntityDataPacket::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); + INSTANCE.registerMessage(ID++, EntitySavePacket.class, EntitySavePacket::toBytes, EntitySavePacket::fromBytes, EntitySavePacket::handle, Optional.of(NetworkDirection.PLAY_TO_SERVER)); } /** @@ -42,22 +52,17 @@ public void registerPackets() { * @param player The player to send the TileEntity to. * @param pos The block containing the TileEntity. */ - public void sendTile(final EntityPlayerMP player, final BlockPos pos) { + public void sendTile(final ServerPlayerEntity player, final BlockPos pos) { if (NBTEdit.proxy.checkPermission(player)) { - player.getServerWorld().addScheduledTask(new Runnable() { - @Override - public void run() { - TileEntity te = player.getServerWorld().getTileEntity(pos); - if (te != null) { - NBTTagCompound tag = new NBTTagCompound(); - te.writeToNBT(tag); - INSTANCE.sendTo(new TileNBTPacket(pos, tag), player); - } else { - NBTEdit.proxy.sendMessage(player, "Error - There is no TileEntity at " - + pos.getX() + ", " + pos.getY() + ", " + pos.getZ(), TextFormatting.RED); - } - } - }); + TileEntity te = player.getLevel().getBlockEntity(pos); + if (te != null) { + CompoundNBT tag = new CompoundNBT(); + te.save(tag); + INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new TileDataPacket(pos, tag)); + } else { + NBTEdit.proxy.sendMessage(player, "Error - There is no TileEntity at " + + pos.getX() + ", " + pos.getY() + ", " + pos.getZ(), TextFormatting.RED); + } } } @@ -67,26 +72,21 @@ public void run() { * @param player The player to send the Entity data to. * @param entityId The id of the Entity. */ - public void sendEntity(final EntityPlayerMP player, final int entityId) { + public void sendEntity(final ServerPlayerEntity player, final int entityId) { if (NBTEdit.proxy.checkPermission(player)) { - player.getServerWorld().addScheduledTask(new Runnable() { - @Override - public void run() { - Entity entity = player.getServerWorld().getEntityByID(entityId); - if (entity instanceof EntityPlayer && entity != player && !NBTEdit.editOtherPlayers) { - NBTEdit.proxy.sendMessage(player, "Error - You may not use NBTEdit on other Players", TextFormatting.RED); - NBTEdit.log(Level.WARN, player.getName() + " tried to use NBTEdit on another player, " + entity.getName()); - return; - } - if (entity != null) { - NBTTagCompound tag = new NBTTagCompound(); - entity.writeToNBT(tag); - INSTANCE.sendTo(new EntityNBTPacket(entityId, tag), player); - } else { - NBTEdit.proxy.sendMessage(player, "\"Error - Unknown EntityID #" + entityId, TextFormatting.RED); - } - } - }); + Entity entity = player.getLevel().getEntity(entityId); + if (entity instanceof PlayerEntity && entity != player && !NBTEdit.editOtherPlayers) { + NBTEdit.proxy.sendMessage(player, "Error - You may not use NBTEdit on other Players", TextFormatting.RED); + NBTEdit.log(Level.WARN, player.getGameProfile().getName() + " tried to use NBTEdit on another player, " + entity.getName()); + return; + } + if (entity != null) { + CompoundNBT tag = new CompoundNBT(); + entity.saveWithoutId(tag); + INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new EntityDataPacket(entityId, tag)); + } else { + NBTEdit.proxy.sendMessage(player, "\"Error - Unknown EntityID #" + entityId, TextFormatting.RED); + } } } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/TileDataPacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/TileDataPacket.java new file mode 100644 index 0000000..c9262e7 --- /dev/null +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/TileDataPacket.java @@ -0,0 +1,44 @@ +package com.mcf.davidee.nbtedit.packets; + +import com.mcf.davidee.nbtedit.NBTEdit; +import com.mcf.davidee.nbtedit.NBTHelper; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fml.network.NetworkEvent; + +import java.util.function.Supplier; + +public class TileDataPacket extends TileRequestPacket { + /** + * The nbt data of the tileEntity. + */ + protected CompoundNBT tag; + + /** + * Required default constructor. + */ + public TileDataPacket() { + } + + public TileDataPacket(BlockPos pos, CompoundNBT tag) { + super(pos); + this.tag = tag; + } + + public static TileDataPacket fromBytes(PacketBuffer buf) { + BlockPos pos = BlockPos.of(buf.readLong()); + CompoundNBT tag = NBTHelper.readNbtFromBuffer(buf); + return new TileDataPacket(pos, tag); + } + + public void toBytes(PacketBuffer buf) { + super.toBytes(buf); + NBTHelper.writeToBuffer(this.tag, buf); + } + + public void handle(Supplier ctx) { + ctx.get().setPacketHandled(true); + NBTEdit.proxy.openEditGUI(this.pos, this.tag); + } +} diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/TileNBTPacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/TileNBTPacket.java deleted file mode 100644 index 52959f6..0000000 --- a/src/main/java/com/mcf/davidee/nbtedit/packets/TileNBTPacket.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.mcf.davidee.nbtedit.packets; - -import com.mcf.davidee.nbtedit.NBTEdit; -import com.mcf.davidee.nbtedit.NBTHelper; -import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.TextFormatting; -import net.minecraft.world.WorldServer; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; -import net.minecraftforge.fml.relauncher.Side; -import org.apache.logging.log4j.Level; - -public class TileNBTPacket implements IMessage { - /** - * The block of the tileEntity. - */ - protected BlockPos pos; - /** - * The nbt data of the tileEntity. - */ - protected NBTTagCompound tag; - - /** - * Required default constructor. - */ - public TileNBTPacket() { - } - - public TileNBTPacket(BlockPos pos, NBTTagCompound tag) { - this.pos = pos; - this.tag = tag; - } - - @Override - public void fromBytes(ByteBuf buf) { - this.pos = BlockPos.fromLong(buf.readLong()); - this.tag = NBTHelper.readNbtFromBuffer(buf); - } - - @Override - public void toBytes(ByteBuf buf) { - buf.writeLong(this.pos.toLong()); - NBTHelper.writeToBuffer(this.tag, buf); - } - - public static class Handler implements IMessageHandler { - - @Override - public IMessage onMessage(final TileNBTPacket packet, MessageContext ctx) { - if (ctx.side == Side.SERVER) { - final EntityPlayerMP player = ctx.getServerHandler().player; - player.getServerWorld().addScheduledTask(new Runnable() { - @Override - public void run() { - TileEntity te = player.getServerWorld().getTileEntity(packet.pos); - if (te != null && NBTEdit.proxy.checkPermission(player)) { - try { - te.readFromNBT(packet.tag); - te.markDirty();// Ensures changes gets saved to disk later on. - if (te.hasWorld() && te.getWorld() instanceof WorldServer) { - ((WorldServer) te.getWorld()).getPlayerChunkMap().markBlockForUpdate(packet.pos);// Broadcast changes. - } - NBTEdit.log(Level.TRACE, player.getName() + " edited a tag -- Tile Entity at " + packet.pos.getX() + ", " + packet.pos.getY() + ", " + packet.pos.getZ()); - NBTEdit.logTag(packet.tag); - NBTEdit.proxy.sendMessage(player, "Your changes have been saved", TextFormatting.WHITE); - } catch (Throwable t) { - NBTEdit.proxy.sendMessage(player, "Save Failed - Invalid NBT format for Tile Entity", TextFormatting.RED); - NBTEdit.log(Level.WARN, player.getName() + " edited a tag and caused an exception"); - NBTEdit.logTag(packet.tag); - NBTEdit.throwing("TileNBTPacket", "Handler.onMessage", t); - } - } else { - NBTEdit.log(Level.WARN, player.getName() + " tried to edit a non-existent TileEntity at " + packet.pos.getX() + ", " + packet.pos.getY() + ", " + packet.pos.getZ()); - NBTEdit.proxy.sendMessage(player, "cSave Failed - There is no TileEntity at " + packet.pos.getX() + ", " + packet.pos.getY() + ", " + packet.pos.getZ(), TextFormatting.RED); - } - } - }); - } else { - NBTEdit.proxy.openEditGUI(packet.pos, packet.tag); - } - return null; - } - } -} diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/TileRequestPacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/TileRequestPacket.java index 9c93926..e34dc1d 100644 --- a/src/main/java/com/mcf/davidee/nbtedit/packets/TileRequestPacket.java +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/TileRequestPacket.java @@ -1,19 +1,19 @@ package com.mcf.davidee.nbtedit.packets; import com.mcf.davidee.nbtedit.NBTEdit; -import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.network.PacketBuffer; import net.minecraft.util.math.BlockPos; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; import org.apache.logging.log4j.Level; -public class TileRequestPacket implements IMessage { +import java.util.function.Supplier; + +public class TileRequestPacket { /** * The position of the tileEntity requested. */ - private BlockPos pos; + protected BlockPos pos; /** * Required default constructor. @@ -25,26 +25,21 @@ public TileRequestPacket(BlockPos pos) { this.pos = pos; } - @Override - public void fromBytes(ByteBuf buf) { - this.pos = BlockPos.fromLong(buf.readLong()); + public static TileRequestPacket fromBytes(PacketBuffer buf) { + return new TileRequestPacket(BlockPos.of(buf.readLong())); } - @Override - public void toBytes(ByteBuf buf) { - buf.writeLong(this.pos.toLong()); + public void toBytes(PacketBuffer buf) { + buf.writeLong(this.pos.asLong()); } - public static class Handler implements IMessageHandler { + public void handle(Supplier ctx) { + ctx.get().setPacketHandled(true); + ServerPlayerEntity player = ctx.get().getSender(); + + ctx.get().enqueueWork(() -> NBTEdit.NETWORK.sendTile(player, pos)); + NBTEdit.log(Level.TRACE, player.getGameProfile().getName() + " requested tileEntity at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()); - @Override - public IMessage onMessage(TileRequestPacket packet, MessageContext ctx) { - EntityPlayerMP player = ctx.getServerHandler().player; - NBTEdit.log(Level.TRACE, player.getName() + " requested tileEntity at " - + packet.pos.getX() + ", " + packet.pos.getY() + ", " + packet.pos.getZ()); - NBTEdit.NETWORK.sendTile(player, packet.pos); - return null; - } } } diff --git a/src/main/java/com/mcf/davidee/nbtedit/packets/TileSavePacket.java b/src/main/java/com/mcf/davidee/nbtedit/packets/TileSavePacket.java new file mode 100644 index 0000000..c1cb832 --- /dev/null +++ b/src/main/java/com/mcf/davidee/nbtedit/packets/TileSavePacket.java @@ -0,0 +1,68 @@ +package com.mcf.davidee.nbtedit.packets; + +import com.mcf.davidee.nbtedit.NBTEdit; +import com.mcf.davidee.nbtedit.NBTHelper; +import io.netty.buffer.ByteBuf; +import net.minecraft.block.BlockState; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.network.PacketBuffer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.world.server.ServerWorld; +import net.minecraftforge.fml.network.NetworkEvent; +import org.apache.logging.log4j.Level; + +import java.util.function.Supplier; + +public class TileSavePacket extends TileDataPacket { + + /** + * Required default constructor. + */ + public TileSavePacket() { + } + + public TileSavePacket(BlockPos pos, CompoundNBT tag) { + this.pos = pos; + this.tag = tag; + } + + public static TileSavePacket fromBytes(PacketBuffer buf) { + BlockPos pos = BlockPos.of(buf.readLong()); + CompoundNBT tag = NBTHelper.readNbtFromBuffer(buf); + return new TileSavePacket(pos, tag); + } + + public void handle(Supplier ctx) { + ctx.get().setPacketHandled(true); + final ServerPlayerEntity player = ctx.get().getSender(); + ctx.get().enqueueWork(() -> { + ServerWorld level = player.getLevel(); + BlockState state = level.getBlockState(this.pos); + TileEntity te = level.getBlockEntity(this.pos); + if (te != null && NBTEdit.proxy.checkPermission(player)) { + try { + te.load(state, this.tag); + te.setChanged();// Ensures changes gets saved to disk later on. + if (te.hasLevel() && te.getLevel() instanceof ServerWorld) { + //TODO Figure out what this changed to in 1.16. if needed. -Jay + //((ServerWorld) te.getLevel()).getPlayerChunkMap().markBlockForUpdate(packet.pos);// Broadcast changes. + } + NBTEdit.log(Level.TRACE, player.getGameProfile().getName() + " edited a tag -- Tile Entity at " + this.pos.getX() + ", " + this.pos.getY() + ", " + this.pos.getZ()); + NBTEdit.logTag(this.tag); + NBTEdit.proxy.sendMessage(player, "Your changes have been saved", TextFormatting.WHITE); + } catch (Throwable t) { + NBTEdit.proxy.sendMessage(player, "Save Failed - Invalid NBT format for Tile Entity", TextFormatting.RED); + NBTEdit.log(Level.WARN, player.getGameProfile().getName() + " edited a tag and caused an exception"); + NBTEdit.logTag(this.tag); + NBTEdit.throwing("TileNBTPacket", "Handler.onMessage", t); + } + } else { + NBTEdit.log(Level.WARN, player.getGameProfile().getName() + " tried to edit a non-existent TileEntity at " + this.pos.getX() + ", " + this.pos.getY() + ", " + this.pos.getZ()); + NBTEdit.proxy.sendMessage(player, "cSave Failed - There is no TileEntity at " + this.pos.getX() + ", " + this.pos.getY() + ", " + this.pos.getZ(), TextFormatting.RED); + } + }); + } +} diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..dfcf0f5 --- /dev/null +++ b/src/main/resources/META-INF/mods.toml @@ -0,0 +1,30 @@ +modLoader = "javafml" #mandatory +loaderVersion = "[36,)" #mandatory +license = "GPLv3" +[[mods]] #mandatory +modId = "nbtedit" #mandatory +version = "${file.version}" #mandatory +displayName = "NBTEdit" #mandatory +#updateJSONURL="http://myurl.me/" #optional +#displayURL="http://example.com/" #optional +#logoFile="nbtedit.png" #optional +credits="DavidGoldman(Davidee) for making the orignal mod." #optional +authors = "Davidee, Jay113355" #optional +# The description text for the mod (multi line!) (#mandatory) +description = ''' +Allows you to edit NBT tags of entities and tiles while in-game. +''' + +[[dependencies.nbtedit]] +modId = "forge" #mandatory +mandatory = true #mandatory +versionRange = "[36,)" #mandatory +ordering = "NONE" +side = "BOTH" + +[[dependencies.nbtedit]] +modId = "minecraft" +mandatory = true +versionRange = "[1.16.5,1.17)" +ordering = "NONE" +side = "BOTH" diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..9dcf8e8 --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "NBTEdit", + "pack_format": 6 + } +}