diff --git a/src/main/java/DummyCore/ASM/DCASMManager.java b/src/main/java/DummyCore/ASM/DCASMManager.java index 133f6b9..36d8fad 100644 --- a/src/main/java/DummyCore/ASM/DCASMManager.java +++ b/src/main/java/DummyCore/ASM/DCASMManager.java @@ -1,10 +1,10 @@ package DummyCore.ASM; +import DummyCore.Utils.CustomTXTConfig; +import DummyCore.Utils.Notifier; import java.util.Arrays; import java.util.List; - import net.minecraft.launchwrapper.IClassTransformer; - import org.apache.logging.log4j.LogManager; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; @@ -24,241 +24,296 @@ import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; -import DummyCore.Utils.CustomTXTConfig; -import DummyCore.Utils.Notifier; +public class DCASMManager implements IClassTransformer { -public class DCASMManager implements IClassTransformer{ - - public static final String FMLClientHandlerName = "cpw.mods.fml.client.FMLClientHandler"; - public static final String logMissingTextureErrorsName = "logMissingTextureErrors"; - public static final String logMissingTextureErrorsDesc = "()V"; - public static final String NetHandlerPlayClientName = "NetHandlerPlayClient"; - public static final String NotchNetHandlerPlayClientName = "fv"; - public static final String ObfNetHandlerPlayClientName = "NetHandlerPlayClient"; - public static final String NetHandlerPlayClient_MethodHandleSpawnMobName = "handleSpawnMob"; - public static final String ObfNetHandlerPlayClient_MethodHandleSpawnMobName = "func_147281_a"; - public static final String NotchNetHandlerPlayClient_MethodHandleSpawnMobName = "a"; - public static final String NetHandlerPlayClient_MethodHandleSpawnMobDesc = "(Lnet/minecraft/network/play/server/S0FPacketSpawnMob;)V"; - public static final String ObfNetHandlerPlayClient_MethodHandleSpawnMobDesc = "(Lnet/minecraft/network/play/server/S0FPacketSpawnMob;)V"; - public static final String NotchNetHandlerPlayClient_MethodHandleSpawnMobDesc = "(Lfz;)V"; - + public static final String FMLClientHandlerName = "cpw.mods.fml.client.FMLClientHandler"; + public static final String logMissingTextureErrorsName = "logMissingTextureErrors"; + public static final String logMissingTextureErrorsDesc = "()V"; + public static final String NetHandlerPlayClientName = "NetHandlerPlayClient"; + public static final String NotchNetHandlerPlayClientName = "fv"; + public static final String ObfNetHandlerPlayClientName = "NetHandlerPlayClient"; + public static final String NetHandlerPlayClient_MethodHandleSpawnMobName = "handleSpawnMob"; + public static final String ObfNetHandlerPlayClient_MethodHandleSpawnMobName = "func_147281_a"; + public static final String NotchNetHandlerPlayClient_MethodHandleSpawnMobName = "a"; + public static final String NetHandlerPlayClient_MethodHandleSpawnMobDesc = + "(Lnet/minecraft/network/play/server/S0FPacketSpawnMob;)V"; + public static final String ObfNetHandlerPlayClient_MethodHandleSpawnMobDesc = + "(Lnet/minecraft/network/play/server/S0FPacketSpawnMob;)V"; + public static final String NotchNetHandlerPlayClient_MethodHandleSpawnMobDesc = "(Lfz;)V"; - @Override - public byte[] transform(String name, String transformedName,byte[] basicClass) - { - - if(basicClass != null) //If the class we are loading exists - { - if(name.equals(FMLClientHandlerName)) - return handleForgeClientHandlerClass(name,transformedName,basicClass); - else - { - if(name.endsWith(NetHandlerPlayClientName) || name.endsWith(NotchNetHandlerPlayClientName) || name.endsWith(ObfNetHandlerPlayClientName)) - { - handleNetHandlerPlayClientClass(name,transformedName,basicClass); - } - else - { - ClassNode classNode = new ClassNode(); //Creating a most basic bytecode->runtime command helper. - ClassReader classReader = new ClassReader(basicClass); //Parsing the bytecode to runtime commands - classReader.accept(classNode, 0); //Giving our helper a parsed list of commands without any code modifications. - if(classNode.invisibleAnnotations != null && classNode.invisibleAnnotations.size() > 0) //If we have some invisible annotations on our class. - { - boolean checkClass = false; - for(int i = 0; i < classNode.invisibleAnnotations.size(); ++i) //Looking through all annotations presented on the class - { - AnnotationNode node = classNode.invisibleAnnotations.get(i); - if(node.desc.equalsIgnoreCase("LDummyCore/Utils/DCASMCheck;")) //If the given annotation is a DummyCore annotation, that sygnals, that the class needs to be checked. - { - checkClass = true; - break; //We have to send our class outside the loop to make sure there is no ConcurrentModificationException. - } - - } - if(checkClass) - return handleClass(name,transformedName,basicClass,classNode,classReader); //If class requires inspection we are sending it into our method - } - } - } - } - - return basicClass; - } - - public byte[] handleNetHandlerPlayClientClass(String name, String transformedName,byte[] basicClass) - { - int obfuscationType = name.endsWith(NetHandlerPlayClientName) ? 0 : name.endsWith(ObfNetHandlerPlayClientName) ? 1 : 2; - String S0FPacketSpawnMob = obfuscationType == 0 || obfuscationType == 1 ? "net/minecraft/network/play/server/S0FPacketSpawnMob" : "fz"; - String EntityLivingBase = obfuscationType == 0 ? "net/minecraft/entity/EntityLivingBase" : obfuscationType == 1 ? "net/minecraft/entity/EntityLivingBase" : "sv"; - if(!CustomTXTConfig.init) - CustomTXTConfig.createCFG(); - if(CustomTXTConfig.mappings.containsKey("fixS0FSpawnMobPacketCrash") && CustomTXTConfig.mappings.get("fixS0FSpawnMobPacketCrash").contains("true")) - { - byte[] defaultBytes = basicClass.clone(); - - try - { - ClassNode cn = new ClassNode(); //<---- Actually creates the EMPTY class - ClassReader cr = new ClassReader(basicClass); //<---- Bytecode -> Instructions - cr.accept(cn, ClassReader.EXPAND_FRAMES); //<---- giving cn the instruction list. 0 is for flags, we want none. - - List methods = cn.methods; - for(int i = 0; i < methods.size(); ++i) - { - MethodNode method = methods.get(i); - if(method.name.equals(NetHandlerPlayClient_MethodHandleSpawnMobName) || method.name.equals(ObfNetHandlerPlayClient_MethodHandleSpawnMobName) || method.name.equals(NotchNetHandlerPlayClient_MethodHandleSpawnMobName)) - { - if(method.desc.equals(NetHandlerPlayClient_MethodHandleSpawnMobDesc) || method.desc.equals(ObfNetHandlerPlayClient_MethodHandleSpawnMobDesc) || method.desc.equals(NotchNetHandlerPlayClient_MethodHandleSpawnMobDesc)) - { - AbstractInsnNode insertAfter = null; - for(int j = 0; j < method.instructions.size(); ++j) - { - AbstractInsnNode ain = method.instructions.get(j); - if(ain instanceof TypeInsnNode && ain.getOpcode() == Opcodes.CHECKCAST) - { - if(method.instructions.size() > j+1) - { - AbstractInsnNode ain1 = method.instructions.get(j+1); - if(ain1 instanceof VarInsnNode && ain1.getOpcode() == Opcodes.ASTORE && ain.getType() == Type.OBJECT) - { - insertAfter = ain1; - break; - } - } - } - } - if(insertAfter != null) - { - InsnList inst = new InsnList(); - inst.add(new LabelNode()); - inst.add(new VarInsnNode(Opcodes.ALOAD,Type.OBJECT)); - LabelNode ifStart = new LabelNode(); - inst.add(new JumpInsnNode(Opcodes.IFNONNULL,ifStart)); - inst.add(new LabelNode()); - inst.add(new LdcInsnNode("Vanilla->DummyCore")); - inst.add(new LdcInsnNode("Handled an attempt to spawn a null mob on client, aborting! This might break everything completely though.")); - inst.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "DummyCore/Utils/Notifier", "notifyErrorCustomMod", "(Ljava/lang/String;Ljava/lang/String;)V", false)); - inst.add(new LabelNode()); - inst.add(new InsnNode(Opcodes.RETURN)); - inst.add(ifStart); - inst.add(new FrameNode(Opcodes.F_FULL, 8, new Object[] {name.replace('.', '/'), S0FPacketSpawnMob, Opcodes.DOUBLE, Opcodes.DOUBLE, Opcodes.DOUBLE, Opcodes.FLOAT, Opcodes.FLOAT, EntityLivingBase}, 0, new Object[] {})); - - method.instructions.insert(insertAfter, inst); - } - } - } - } - - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); //<---- Creating the way we are writing Instructions into bytecode. COMPUTE_MAXS will automatically calculate STACK size and LOCAL count for each method. - cn.accept(cw); //<---- Writing all modifications - - byte[] bytes = cw.toByteArray(); - defaultBytes = null; - return bytes; - } - catch(Exception e) - { - LogManager.getLogger().error("[DummyCore][ASM]Failed to modify "+NetHandlerPlayClientName,e); - return defaultBytes; - } - } - - return basicClass; - } - - public byte[] handleForgeClientHandlerClass(String name, String transformedName,byte[] basicClass) - { - if(!CustomTXTConfig.init) - CustomTXTConfig.createCFG(); - if(!CustomTXTConfig.mappings.containsKey("insertDCCallInTextureLoader") || !CustomTXTConfig.mappings.get("insertDCCallInTextureLoader").equals("true")) - return basicClass; - - byte[] defaultBytes = basicClass.clone(); - try - { - ClassNode cn = new ClassNode(); //<---- Actually creates the EMPTY class - ClassReader cr = new ClassReader(basicClass); //<---- Bytecode -> Instructions - cr.accept(cn, ClassReader.EXPAND_FRAMES); //<---- giving cn the instruction list. 0 is for flags, we want none. - - List methods = cn.methods; - for(int i = 0; i < methods.size(); ++i) - { - MethodNode method = methods.get(i); - if(method.name.equals(logMissingTextureErrorsName) && method.desc.equals(logMissingTextureErrorsDesc)) - { - method.instructions.insert(new LabelNode()); - method.instructions.insert(new MethodInsnNode(Opcodes.INVOKESTATIC, "DummyCore/Core/CoreInitialiser", "fmlLogMissingTextures", "()V", false)); - } - } - - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); //<---- Creating the way we are writing Instructions into bytecode. COMPUTE_MAXS will automatically calculate STACK size and LOCAL count for each method. - cn.accept(cw); //<---- Writing all modifications - - byte[] bytes = cw.toByteArray(); - defaultBytes = null; - return bytes; - } - catch(Exception e) - { - LogManager.getLogger().error("[DummyCore][ASM]Failed to modify "+FMLClientHandlerName,e); - return defaultBytes; - } - } - - public byte[] handleClass(String name, String transformedName,byte[] basicClass,ClassNode cn, ClassReader cr) - { - Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has requested a DummyCore ASM check via DummyCore/Utils/DCASMCheck annotation. Examining..."); - String[] checkedClss = new String[0]; //Initializing the interfaces variable - for(int i = 0; i < cn.invisibleAnnotations.size(); ++i) //Checking through all annotations. - { - AnnotationNode node = cn.invisibleAnnotations.get(i); - if(node.desc.equalsIgnoreCase("LDummyCore/Utils/ExistanceCheck;") && node.values != null && node.values.size() > 0) //Checking if the annotation found is the one, that makes us go through - { - Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has requested a DummyCore ASM check on it's implementations via DummyCore/Utils/ExistanceCheck annotation. Examining..."); - List classes = List.class.cast(node.values.get(1)); //Getting a full list of classes that we need to check for existance - checkedClss = new String[classes.size()]; - checkedClss = String[].class.cast(classes.toArray(checkedClss)); - break; - } - } - Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has given the next interfaces to check: "+Arrays.asList(checkedClss)); - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); //Creating the ability to modify bytecode using modified instructions - if(checkedClss.length > 0) //If we have interfaces to check - { - for(int i = 0; i < checkedClss.length; ++i) - { - if(!classExists(checkedClss[i])) //If the class was NOT found - { - J:for(int j = 0; j < cn.interfaces.size(); ++j) //Looping through all interfaces presented in the class - { - if(cn.interfaces.get(j).equalsIgnoreCase(checkedClss[i].replace('.', '/'))) //If thi is the one we are looking for - { - Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has a "+cn.interfaces.get(j)+" implementation, but the referenced class was not found. Removing the given interface."); - cn.interfaces.remove(j); //Removing it. - break J; - } - } - }else - { - Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has a "+checkedClss[i]+" implementation, and the referenced class was found. Skipping to the next interface..."); - } - } - } - cn.accept(cw); //Writing changed Instructions into bytecode helper - Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has been checked."); - return cw.toByteArray(); //Returning modified bytecode. - } + @Override + public byte[] transform(String name, String transformedName, byte[] basicClass) { - boolean classExists(String s) - { - try - { - Class c = Class.forName(s); - return c != null; - } - catch(ClassNotFoundException e) - { - return false; - } - } + if (basicClass != null) // If the class we are loading exists + { + if (name.equals(FMLClientHandlerName)) + return handleForgeClientHandlerClass(name, transformedName, basicClass); + else { + if (name.endsWith(NetHandlerPlayClientName) + || name.endsWith(NotchNetHandlerPlayClientName) + || name.endsWith(ObfNetHandlerPlayClientName)) { + handleNetHandlerPlayClientClass(name, transformedName, basicClass); + } else { + ClassNode classNode = new ClassNode(); // Creating a most basic bytecode->runtime command helper. + ClassReader classReader = new ClassReader(basicClass); // Parsing the bytecode to runtime commands + classReader.accept( + classNode, + 0); // Giving our helper a parsed list of commands without any code modifications. + if (classNode.invisibleAnnotations != null + && classNode.invisibleAnnotations.size() + > 0) // If we have some invisible annotations on our class. + { + boolean checkClass = false; + for (int i = 0; + i < classNode.invisibleAnnotations.size(); + ++i) // Looking through all annotations presented on the class + { + AnnotationNode node = classNode.invisibleAnnotations.get(i); + if (node.desc.equalsIgnoreCase( + "LDummyCore/Utils/DCASMCheck;")) // If the given annotation is a DummyCore + // annotation, that sygnals, that the class needs + // to be checked. + { + checkClass = true; + break; // We have to send our class outside the loop to make sure there is no + // ConcurrentModificationException. + } + } + if (checkClass) + return handleClass( + name, + transformedName, + basicClass, + classNode, + classReader); // If class requires inspection we are sending it into our method + } + } + } + } + + return basicClass; + } + + public byte[] handleNetHandlerPlayClientClass(String name, String transformedName, byte[] basicClass) { + int obfuscationType = + name.endsWith(NetHandlerPlayClientName) ? 0 : name.endsWith(ObfNetHandlerPlayClientName) ? 1 : 2; + String S0FPacketSpawnMob = obfuscationType == 0 || obfuscationType == 1 + ? "net/minecraft/network/play/server/S0FPacketSpawnMob" + : "fz"; + String EntityLivingBase = obfuscationType == 0 + ? "net/minecraft/entity/EntityLivingBase" + : obfuscationType == 1 ? "net/minecraft/entity/EntityLivingBase" : "sv"; + if (!CustomTXTConfig.init) CustomTXTConfig.createCFG(); + if (CustomTXTConfig.mappings.containsKey("fixS0FSpawnMobPacketCrash") + && CustomTXTConfig.mappings.get("fixS0FSpawnMobPacketCrash").contains("true")) { + byte[] defaultBytes = basicClass.clone(); + + try { + ClassNode cn = new ClassNode(); // <---- Actually creates the EMPTY class + ClassReader cr = new ClassReader(basicClass); // <---- Bytecode -> Instructions + cr.accept( + cn, + ClassReader + .EXPAND_FRAMES); // <---- giving cn the instruction list. 0 is for flags, we want none. + + List methods = cn.methods; + for (int i = 0; i < methods.size(); ++i) { + MethodNode method = methods.get(i); + if (method.name.equals(NetHandlerPlayClient_MethodHandleSpawnMobName) + || method.name.equals(ObfNetHandlerPlayClient_MethodHandleSpawnMobName) + || method.name.equals(NotchNetHandlerPlayClient_MethodHandleSpawnMobName)) { + if (method.desc.equals(NetHandlerPlayClient_MethodHandleSpawnMobDesc) + || method.desc.equals(ObfNetHandlerPlayClient_MethodHandleSpawnMobDesc) + || method.desc.equals(NotchNetHandlerPlayClient_MethodHandleSpawnMobDesc)) { + AbstractInsnNode insertAfter = null; + for (int j = 0; j < method.instructions.size(); ++j) { + AbstractInsnNode ain = method.instructions.get(j); + if (ain instanceof TypeInsnNode && ain.getOpcode() == Opcodes.CHECKCAST) { + if (method.instructions.size() > j + 1) { + AbstractInsnNode ain1 = method.instructions.get(j + 1); + if (ain1 instanceof VarInsnNode + && ain1.getOpcode() == Opcodes.ASTORE + && ain.getType() == Type.OBJECT) { + insertAfter = ain1; + break; + } + } + } + } + if (insertAfter != null) { + InsnList inst = new InsnList(); + inst.add(new LabelNode()); + inst.add(new VarInsnNode(Opcodes.ALOAD, Type.OBJECT)); + LabelNode ifStart = new LabelNode(); + inst.add(new JumpInsnNode(Opcodes.IFNONNULL, ifStart)); + inst.add(new LabelNode()); + inst.add(new LdcInsnNode("Vanilla->DummyCore")); + inst.add( + new LdcInsnNode( + "Handled an attempt to spawn a null mob on client, aborting! This might break everything completely though.")); + inst.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + "DummyCore/Utils/Notifier", + "notifyErrorCustomMod", + "(Ljava/lang/String;Ljava/lang/String;)V", + false)); + inst.add(new LabelNode()); + inst.add(new InsnNode(Opcodes.RETURN)); + inst.add(ifStart); + inst.add(new FrameNode( + Opcodes.F_FULL, + 8, + new Object[] { + name.replace('.', '/'), + S0FPacketSpawnMob, + Opcodes.DOUBLE, + Opcodes.DOUBLE, + Opcodes.DOUBLE, + Opcodes.FLOAT, + Opcodes.FLOAT, + EntityLivingBase + }, + 0, + new Object[] {})); + + method.instructions.insert(insertAfter, inst); + } + } + } + } + + ClassWriter cw = new ClassWriter( + ClassWriter.COMPUTE_MAXS); // <---- Creating the way we are writing Instructions into bytecode. + // COMPUTE_MAXS will automatically calculate STACK size and LOCAL count + // for each method. + cn.accept(cw); // <---- Writing all modifications + + byte[] bytes = cw.toByteArray(); + defaultBytes = null; + return bytes; + } catch (Exception e) { + LogManager.getLogger().error("[DummyCore][ASM]Failed to modify " + NetHandlerPlayClientName, e); + return defaultBytes; + } + } + + return basicClass; + } + + public byte[] handleForgeClientHandlerClass(String name, String transformedName, byte[] basicClass) { + if (!CustomTXTConfig.init) CustomTXTConfig.createCFG(); + if (!CustomTXTConfig.mappings.containsKey("insertDCCallInTextureLoader") + || !CustomTXTConfig.mappings.get("insertDCCallInTextureLoader").equals("true")) return basicClass; + + byte[] defaultBytes = basicClass.clone(); + try { + ClassNode cn = new ClassNode(); // <---- Actually creates the EMPTY class + ClassReader cr = new ClassReader(basicClass); // <---- Bytecode -> Instructions + cr.accept( + cn, + ClassReader.EXPAND_FRAMES); // <---- giving cn the instruction list. 0 is for flags, we want none. + + List methods = cn.methods; + for (int i = 0; i < methods.size(); ++i) { + MethodNode method = methods.get(i); + if (method.name.equals(logMissingTextureErrorsName) + && method.desc.equals(logMissingTextureErrorsDesc)) { + method.instructions.insert(new LabelNode()); + method.instructions.insert(new MethodInsnNode( + Opcodes.INVOKESTATIC, + "DummyCore/Core/CoreInitialiser", + "fmlLogMissingTextures", + "()V", + false)); + } + } + + ClassWriter cw = new ClassWriter( + ClassWriter.COMPUTE_MAXS); // <---- Creating the way we are writing Instructions into bytecode. + // COMPUTE_MAXS will automatically calculate STACK size and LOCAL count for + // each method. + cn.accept(cw); // <---- Writing all modifications + + byte[] bytes = cw.toByteArray(); + defaultBytes = null; + return bytes; + } catch (Exception e) { + LogManager.getLogger().error("[DummyCore][ASM]Failed to modify " + FMLClientHandlerName, e); + return defaultBytes; + } + } + + public byte[] handleClass(String name, String transformedName, byte[] basicClass, ClassNode cn, ClassReader cr) { + Notifier.notifyCustomMod( + "DummyCoreASM", + "Class " + name + + " has requested a DummyCore ASM check via DummyCore/Utils/DCASMCheck annotation. Examining..."); + String[] checkedClss = new String[0]; // Initializing the interfaces variable + for (int i = 0; i < cn.invisibleAnnotations.size(); ++i) // Checking through all annotations. + { + AnnotationNode node = cn.invisibleAnnotations.get(i); + if (node.desc.equalsIgnoreCase("LDummyCore/Utils/ExistanceCheck;") + && node.values != null + && node.values.size() > 0) // Checking if the annotation found is the one, that makes us go through + { + Notifier.notifyCustomMod( + "DummyCoreASM", + "Class " + name + + " has requested a DummyCore ASM check on it's implementations via DummyCore/Utils/ExistanceCheck annotation. Examining..."); + List classes = List.class.cast( + node.values.get(1)); // Getting a full list of classes that we need to check for existance + checkedClss = new String[classes.size()]; + checkedClss = String[].class.cast(classes.toArray(checkedClss)); + break; + } + } + Notifier.notifyCustomMod( + "DummyCoreASM", + "Class " + name + " has given the next interfaces to check: " + Arrays.asList(checkedClss)); + ClassWriter cw = new ClassWriter( + ClassWriter.COMPUTE_MAXS); // Creating the ability to modify bytecode using modified instructions + if (checkedClss.length > 0) // If we have interfaces to check + { + for (int i = 0; i < checkedClss.length; ++i) { + if (!classExists(checkedClss[i])) // If the class was NOT found + { + J: + for (int j = 0; + j < cn.interfaces.size(); + ++j) // Looping through all interfaces presented in the class + { + if (cn.interfaces + .get(j) + .equalsIgnoreCase( + checkedClss[i].replace('.', '/'))) // If thi is the one we are looking for + { + Notifier.notifyCustomMod( + "DummyCoreASM", + "Class " + name + " has a " + cn.interfaces.get(j) + + " implementation, but the referenced class was not found. Removing the given interface."); + cn.interfaces.remove(j); // Removing it. + break J; + } + } + } else { + Notifier.notifyCustomMod( + "DummyCoreASM", + "Class " + name + " has a " + checkedClss[i] + + " implementation, and the referenced class was found. Skipping to the next interface..."); + } + } + } + cn.accept(cw); // Writing changed Instructions into bytecode helper + Notifier.notifyCustomMod("DummyCoreASM", "Class " + name + " has been checked."); + return cw.toByteArray(); // Returning modified bytecode. + } + + boolean classExists(String s) { + try { + Class c = Class.forName(s); + return c != null; + } catch (ClassNotFoundException e) { + return false; + } + } } diff --git a/src/main/java/DummyCore/ASM/DCLoadingPlugin.java b/src/main/java/DummyCore/ASM/DCLoadingPlugin.java index e6725a0..b8cc3ad 100644 --- a/src/main/java/DummyCore/ASM/DCLoadingPlugin.java +++ b/src/main/java/DummyCore/ASM/DCLoadingPlugin.java @@ -1,45 +1,41 @@ package DummyCore.ASM; -import java.io.File; -import java.util.Map; +import static DummyCore.Core.CoreInitialiser.mcVersion; import DummyCore.Core.Core; import cpw.mods.fml.relauncher.FMLInjectionData; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; -import static DummyCore.Core.CoreInitialiser.mcVersion; +import java.io.File; +import java.util.Map; -@MCVersion(value=mcVersion) -public class DCLoadingPlugin implements IFMLLoadingPlugin{ +@MCVersion(value = mcVersion) +public class DCLoadingPlugin implements IFMLLoadingPlugin { - public DCLoadingPlugin() - { - Core.mcDir = (File) FMLInjectionData.data()[6]; - } - - @Override - public String[] getASMTransformerClass() { - return new String[]{DCASMManager.class.getName()}; - } + public DCLoadingPlugin() { + Core.mcDir = (File) FMLInjectionData.data()[6]; + } - @Override - public String getModContainerClass() { - return null; - } + @Override + public String[] getASMTransformerClass() { + return new String[] {DCASMManager.class.getName()}; + } - @Override - public String getSetupClass() { - return null; - } + @Override + public String getModContainerClass() { + return null; + } - @Override - public void injectData(Map data) { - - } + @Override + public String getSetupClass() { + return null; + } - @Override - public String getAccessTransformerClass() { - return null; - } + @Override + public void injectData(Map data) {} + @Override + public String getAccessTransformerClass() { + return null; + } } diff --git a/src/main/java/DummyCore/Blocks/BlocksRegistry.java b/src/main/java/DummyCore/Blocks/BlocksRegistry.java index eed7df6..f2f1993 100644 --- a/src/main/java/DummyCore/Blocks/BlocksRegistry.java +++ b/src/main/java/DummyCore/Blocks/BlocksRegistry.java @@ -1,51 +1,45 @@ package DummyCore.Blocks; -import java.util.Hashtable; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemBlock; import DummyCore.Core.Core; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; +import java.util.Hashtable; +import net.minecraft.block.Block; +import net.minecraft.item.ItemBlock; /** - * + * * @author Modbder * @version From DummyCore 1.0 * @Description Use this class to register new blocks in your game. * This will automatically add your blocks to the corresponding creative tab */ public class BlocksRegistry { - - /** - * Used to check the creative tab block belongs to - */ - public static Hashtable blocksList = new Hashtable(); - - /** - * Use this to register new simple blocks. - * @version From DummyCore 1.0 - * @param b - the block to be registered. - * @param name - in-game name of the block. Will be written to the corresponding .lang file - * @param modClass - class file of your mod. If registered from the mod itself, use getClass(), else just put in this field something like YourModClassName.class - * @param blockClass - used, if you want to register a block, that has an ItemBlock. Can be null. - */ - public static void registerBlock(Block b, String name, Class modClass, Class blockClass) - { - if(blockClass == null) - { - GameRegistry.registerBlock(b, name); - }else - { - GameRegistry.registerBlock(b, blockClass, name); - } - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - b.setCreativeTab(Core.getBlockTabForMod(modClass)); - blocksList.put(b, Core.getBlockTabForMod(modClass).getTabLabel()); - } - } + /** + * Used to check the creative tab block belongs to + */ + public static Hashtable blocksList = new Hashtable(); + + /** + * Use this to register new simple blocks. + * @version From DummyCore 1.0 + * @param b - the block to be registered. + * @param name - in-game name of the block. Will be written to the corresponding .lang file + * @param modClass - class file of your mod. If registered from the mod itself, use getClass(), else just put in this field something like YourModClassName.class + * @param blockClass - used, if you want to register a block, that has an ItemBlock. Can be null. + */ + public static void registerBlock(Block b, String name, Class modClass, Class blockClass) { + if (blockClass == null) { + GameRegistry.registerBlock(b, name); + } else { + GameRegistry.registerBlock(b, blockClass, name); + } + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + b.setCreativeTab(Core.getBlockTabForMod(modClass)); + blocksList.put(b, Core.getBlockTabForMod(modClass).getTabLabel()); + } + } } diff --git a/src/main/java/DummyCore/Client/GuiButton_ChangeGUI.java b/src/main/java/DummyCore/Client/GuiButton_ChangeGUI.java index b106daa..1fc4a46 100644 --- a/src/main/java/DummyCore/Client/GuiButton_ChangeGUI.java +++ b/src/main/java/DummyCore/Client/GuiButton_ChangeGUI.java @@ -6,17 +6,16 @@ import net.minecraft.client.audio.SoundHandler; import net.minecraft.client.gui.GuiButton; import net.minecraft.util.ResourceLocation; -public class GuiButton_ChangeGUI extends GuiButton{ +public class GuiButton_ChangeGUI extends GuiButton { - public GuiButton_ChangeGUI(int p_i1021_1_, int p_i1021_2_, int p_i1021_3_,int p_i1021_4_, int p_i1021_5_, String p_i1021_6_) { - super(p_i1021_1_, p_i1021_2_, p_i1021_3_, p_i1021_4_, p_i1021_5_, p_i1021_6_); - } - - @Override - public void func_146113_a(SoundHandler p_146113_1_) - { - p_146113_1_.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); - Minecraft.getMinecraft().displayGuiScreen(new GuiMenuList(Minecraft.getMinecraft().currentScreen)); + public GuiButton_ChangeGUI( + int p_i1021_1_, int p_i1021_2_, int p_i1021_3_, int p_i1021_4_, int p_i1021_5_, String p_i1021_6_) { + super(p_i1021_1_, p_i1021_2_, p_i1021_3_, p_i1021_4_, p_i1021_5_, p_i1021_6_); } + @Override + public void func_146113_a(SoundHandler p_146113_1_) { + p_146113_1_.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); + Minecraft.getMinecraft().displayGuiScreen(new GuiMenuList(Minecraft.getMinecraft().currentScreen)); + } } diff --git a/src/main/java/DummyCore/Client/GuiCommon.java b/src/main/java/DummyCore/Client/GuiCommon.java index d2fcba3..b35f5fb 100644 --- a/src/main/java/DummyCore/Client/GuiCommon.java +++ b/src/main/java/DummyCore/Client/GuiCommon.java @@ -2,66 +2,58 @@ package DummyCore.Client; import java.util.ArrayList; import java.util.List; - -import org.lwjgl.opengl.GL11; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; -public class GuiCommon extends GuiContainer{ - - public List elementList = new ArrayList(); - public TileEntity genericTile; - public ResourceLocation guiGenLocation = new ResourceLocation("textures/gui/container/dispenser.png"); - public ResourceLocation slotLocation = new ResourceLocation("textures/gui/container/dispenser.png"); +public class GuiCommon extends GuiContainer { - public GuiCommon(Container c) { - super(c); - } - - public GuiCommon(Container c, TileEntity tile) { - this(c); - genericTile = tile; - } + public List elementList = new ArrayList(); + public TileEntity genericTile; + public ResourceLocation guiGenLocation = new ResourceLocation("textures/gui/container/dispenser.png"); + public ResourceLocation slotLocation = new ResourceLocation("textures/gui/container/dispenser.png"); - @Override - protected void drawGuiContainerBackgroundLayer(float f1,int i1, int i2) { - GL11.glColor3f(1, 1, 1); + public GuiCommon(Container c) { + super(c); + } + + public GuiCommon(Container c, TileEntity tile) { + this(c); + genericTile = tile; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f1, int i1, int i2) { + GL11.glColor3f(1, 1, 1); int k = (this.width - this.xSize) / 2; int l = (this.height - this.ySize) / 2; this.mc.renderEngine.bindTexture(guiGenLocation); this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize); - this.drawTexturedModalRect(k+60, l+16, 6, 6, 28, 54); - this.drawTexturedModalRect(k+88, l+16, 6, 6, 28, 54); - for(int i = 0; i < this.inventorySlots.inventorySlots.size(); ++i) - { - Slot slt = (Slot) this.inventorySlots.inventorySlots.get(i); - renderSlot(slt); - GL11.glColor3f(1, 1, 1); - } - for(int i = 0; i < this.elementList.size(); ++i) - { - GuiElement element = elementList.get(i); - Minecraft.getMinecraft().renderEngine.bindTexture(element.getElementTexture()); - element.draw(k+element.getX(),l+element.getY()); - GL11.glColor3f(1, 1, 1); - } - GL11.glColor3f(1, 1, 1); - } - - public void renderSlot(Slot slt) - { - GL11.glColor3f(1, 1, 1); + this.drawTexturedModalRect(k + 60, l + 16, 6, 6, 28, 54); + this.drawTexturedModalRect(k + 88, l + 16, 6, 6, 28, 54); + for (int i = 0; i < this.inventorySlots.inventorySlots.size(); ++i) { + Slot slt = (Slot) this.inventorySlots.inventorySlots.get(i); + renderSlot(slt); + GL11.glColor3f(1, 1, 1); + } + for (int i = 0; i < this.elementList.size(); ++i) { + GuiElement element = elementList.get(i); + Minecraft.getMinecraft().renderEngine.bindTexture(element.getElementTexture()); + element.draw(k + element.getX(), l + element.getY()); + GL11.glColor3f(1, 1, 1); + } + GL11.glColor3f(1, 1, 1); + } + + public void renderSlot(Slot slt) { + GL11.glColor3f(1, 1, 1); int k = (this.width - this.xSize) / 2; int l = (this.height - this.ySize) / 2; this.mc.renderEngine.bindTexture(slotLocation); - this.drawTexturedModalRect(k+slt.xDisplayPosition-1, l+slt.yDisplayPosition-1, 7, 83, 18, 18); - } - - - + this.drawTexturedModalRect(k + slt.xDisplayPosition - 1, l + slt.yDisplayPosition - 1, 7, 83, 18, 18); + } } diff --git a/src/main/java/DummyCore/Client/GuiElement.java b/src/main/java/DummyCore/Client/GuiElement.java index 9d0d69d..d602c7e 100644 --- a/src/main/java/DummyCore/Client/GuiElement.java +++ b/src/main/java/DummyCore/Client/GuiElement.java @@ -5,64 +5,147 @@ import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; public abstract class GuiElement { - int zLevel = 0; - - public abstract ResourceLocation getElementTexture(); + int zLevel = 0; - public abstract void draw(int posX, int posY); - - public abstract int getX(); - - public abstract int getY(); - - public void drawTexturedModalRect(int p_73729_1_, int p_73729_2_, int p_73729_3_, int p_73729_4_, int p_73729_5_, int p_73729_6_) - { + public abstract ResourceLocation getElementTexture(); + + public abstract void draw(int posX, int posY); + + public abstract int getX(); + + public abstract int getY(); + + public void drawTexturedModalRect( + int p_73729_1_, int p_73729_2_, int p_73729_3_, int p_73729_4_, int p_73729_5_, int p_73729_6_) { float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)(p_73729_1_ + 0), (double)(p_73729_2_ + p_73729_6_), (double)this.zLevel, (double)((float)(p_73729_3_ + 0) * f), (double)((float)(p_73729_4_ + p_73729_6_) * f1)); - tessellator.addVertexWithUV((double)(p_73729_1_ + p_73729_5_), (double)(p_73729_2_ + p_73729_6_), (double)this.zLevel, (double)((float)(p_73729_3_ + p_73729_5_) * f), (double)((float)(p_73729_4_ + p_73729_6_) * f1)); - tessellator.addVertexWithUV((double)(p_73729_1_ + p_73729_5_), (double)(p_73729_2_ + 0), (double)this.zLevel, (double)((float)(p_73729_3_ + p_73729_5_) * f), (double)((float)(p_73729_4_ + 0) * f1)); - tessellator.addVertexWithUV((double)(p_73729_1_ + 0), (double)(p_73729_2_ + 0), (double)this.zLevel, (double)((float)(p_73729_3_ + 0) * f), (double)((float)(p_73729_4_ + 0) * f1)); + tessellator.addVertexWithUV( + (double) (p_73729_1_ + 0), + (double) (p_73729_2_ + p_73729_6_), + (double) this.zLevel, + (double) ((float) (p_73729_3_ + 0) * f), + (double) ((float) (p_73729_4_ + p_73729_6_) * f1)); + tessellator.addVertexWithUV( + (double) (p_73729_1_ + p_73729_5_), + (double) (p_73729_2_ + p_73729_6_), + (double) this.zLevel, + (double) ((float) (p_73729_3_ + p_73729_5_) * f), + (double) ((float) (p_73729_4_ + p_73729_6_) * f1)); + tessellator.addVertexWithUV( + (double) (p_73729_1_ + p_73729_5_), + (double) (p_73729_2_ + 0), + (double) this.zLevel, + (double) ((float) (p_73729_3_ + p_73729_5_) * f), + (double) ((float) (p_73729_4_ + 0) * f1)); + tessellator.addVertexWithUV( + (double) (p_73729_1_ + 0), + (double) (p_73729_2_ + 0), + (double) this.zLevel, + (double) ((float) (p_73729_3_ + 0) * f), + (double) ((float) (p_73729_4_ + 0) * f1)); tessellator.draw(); } - public void drawTexturedModelRectFromIcon(int p_94065_1_, int p_94065_2_, IIcon p_94065_3_, int p_94065_4_, int p_94065_5_) - { + public void drawTexturedModelRectFromIcon( + int p_94065_1_, int p_94065_2_, IIcon p_94065_3_, int p_94065_4_, int p_94065_5_) { Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)(p_94065_1_ + 0), (double)(p_94065_2_ + p_94065_5_), (double)this.zLevel, (double)p_94065_3_.getMinU(), (double)p_94065_3_.getMaxV()); - tessellator.addVertexWithUV((double)(p_94065_1_ + p_94065_4_), (double)(p_94065_2_ + p_94065_5_), (double)this.zLevel, (double)p_94065_3_.getMaxU(), (double)p_94065_3_.getMaxV()); - tessellator.addVertexWithUV((double)(p_94065_1_ + p_94065_4_), (double)(p_94065_2_ + 0), (double)this.zLevel, (double)p_94065_3_.getMaxU(), (double)p_94065_3_.getMinV()); - tessellator.addVertexWithUV((double)(p_94065_1_ + 0), (double)(p_94065_2_ + 0), (double)this.zLevel, (double)p_94065_3_.getMinU(), (double)p_94065_3_.getMinV()); + tessellator.addVertexWithUV( + (double) (p_94065_1_ + 0), + (double) (p_94065_2_ + p_94065_5_), + (double) this.zLevel, + (double) p_94065_3_.getMinU(), + (double) p_94065_3_.getMaxV()); + tessellator.addVertexWithUV( + (double) (p_94065_1_ + p_94065_4_), + (double) (p_94065_2_ + p_94065_5_), + (double) this.zLevel, + (double) p_94065_3_.getMaxU(), + (double) p_94065_3_.getMaxV()); + tessellator.addVertexWithUV( + (double) (p_94065_1_ + p_94065_4_), + (double) (p_94065_2_ + 0), + (double) this.zLevel, + (double) p_94065_3_.getMaxU(), + (double) p_94065_3_.getMinV()); + tessellator.addVertexWithUV( + (double) (p_94065_1_ + 0), + (double) (p_94065_2_ + 0), + (double) this.zLevel, + (double) p_94065_3_.getMinU(), + (double) p_94065_3_.getMinV()); tessellator.draw(); } - public static void func_146110_a(int p_146110_0_, int p_146110_1_, float p_146110_2_, float p_146110_3_, int p_146110_4_, int p_146110_5_, float p_146110_6_, float p_146110_7_) - { + public static void func_146110_a( + int p_146110_0_, + int p_146110_1_, + float p_146110_2_, + float p_146110_3_, + int p_146110_4_, + int p_146110_5_, + float p_146110_6_, + float p_146110_7_) { float f4 = 1.0F / p_146110_6_; float f5 = 1.0F / p_146110_7_; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)p_146110_0_, (double)(p_146110_1_ + p_146110_5_), 0.0D, (double)(p_146110_2_ * f4), (double)((p_146110_3_ + (float)p_146110_5_) * f5)); - tessellator.addVertexWithUV((double)(p_146110_0_ + p_146110_4_), (double)(p_146110_1_ + p_146110_5_), 0.0D, (double)((p_146110_2_ + (float)p_146110_4_) * f4), (double)((p_146110_3_ + (float)p_146110_5_) * f5)); - tessellator.addVertexWithUV((double)(p_146110_0_ + p_146110_4_), (double)p_146110_1_, 0.0D, (double)((p_146110_2_ + (float)p_146110_4_) * f4), (double)(p_146110_3_ * f5)); - tessellator.addVertexWithUV((double)p_146110_0_, (double)p_146110_1_, 0.0D, (double)(p_146110_2_ * f4), (double)(p_146110_3_ * f5)); + tessellator.addVertexWithUV( + (double) p_146110_0_, (double) (p_146110_1_ + p_146110_5_), 0.0D, (double) (p_146110_2_ * f4), (double) + ((p_146110_3_ + (float) p_146110_5_) * f5)); + tessellator.addVertexWithUV( + (double) (p_146110_0_ + p_146110_4_), + (double) (p_146110_1_ + p_146110_5_), + 0.0D, + (double) ((p_146110_2_ + (float) p_146110_4_) * f4), + (double) ((p_146110_3_ + (float) p_146110_5_) * f5)); + tessellator.addVertexWithUV( + (double) (p_146110_0_ + p_146110_4_), + (double) p_146110_1_, + 0.0D, + (double) ((p_146110_2_ + (float) p_146110_4_) * f4), + (double) (p_146110_3_ * f5)); + tessellator.addVertexWithUV( + (double) p_146110_0_, (double) p_146110_1_, 0.0D, (double) (p_146110_2_ * f4), (double) + (p_146110_3_ * f5)); tessellator.draw(); } - public static void func_152125_a(int p_152125_0_, int p_152125_1_, float p_152125_2_, float p_152125_3_, int p_152125_4_, int p_152125_5_, int p_152125_6_, int p_152125_7_, float p_152125_8_, float p_152125_9_) - { + public static void func_152125_a( + int p_152125_0_, + int p_152125_1_, + float p_152125_2_, + float p_152125_3_, + int p_152125_4_, + int p_152125_5_, + int p_152125_6_, + int p_152125_7_, + float p_152125_8_, + float p_152125_9_) { float f4 = 1.0F / p_152125_8_; float f5 = 1.0F / p_152125_9_; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)p_152125_0_, (double)(p_152125_1_ + p_152125_7_), 0.0D, (double)(p_152125_2_ * f4), (double)((p_152125_3_ + (float)p_152125_5_) * f5)); - tessellator.addVertexWithUV((double)(p_152125_0_ + p_152125_6_), (double)(p_152125_1_ + p_152125_7_), 0.0D, (double)((p_152125_2_ + (float)p_152125_4_) * f4), (double)((p_152125_3_ + (float)p_152125_5_) * f5)); - tessellator.addVertexWithUV((double)(p_152125_0_ + p_152125_6_), (double)p_152125_1_, 0.0D, (double)((p_152125_2_ + (float)p_152125_4_) * f4), (double)(p_152125_3_ * f5)); - tessellator.addVertexWithUV((double)p_152125_0_, (double)p_152125_1_, 0.0D, (double)(p_152125_2_ * f4), (double)(p_152125_3_ * f5)); + tessellator.addVertexWithUV( + (double) p_152125_0_, (double) (p_152125_1_ + p_152125_7_), 0.0D, (double) (p_152125_2_ * f4), (double) + ((p_152125_3_ + (float) p_152125_5_) * f5)); + tessellator.addVertexWithUV( + (double) (p_152125_0_ + p_152125_6_), + (double) (p_152125_1_ + p_152125_7_), + 0.0D, + (double) ((p_152125_2_ + (float) p_152125_4_) * f4), + (double) ((p_152125_3_ + (float) p_152125_5_) * f5)); + tessellator.addVertexWithUV( + (double) (p_152125_0_ + p_152125_6_), + (double) p_152125_1_, + 0.0D, + (double) ((p_152125_2_ + (float) p_152125_4_) * f4), + (double) (p_152125_3_ * f5)); + tessellator.addVertexWithUV( + (double) p_152125_0_, (double) p_152125_1_, 0.0D, (double) (p_152125_2_ * f4), (double) + (p_152125_3_ * f5)); tessellator.draw(); } - } diff --git a/src/main/java/DummyCore/Client/GuiMainMenuNBT.java b/src/main/java/DummyCore/Client/GuiMainMenuNBT.java index 0189053..5278756 100644 --- a/src/main/java/DummyCore/Client/GuiMainMenuNBT.java +++ b/src/main/java/DummyCore/Client/GuiMainMenuNBT.java @@ -1,6 +1,15 @@ package DummyCore.Client; - +import DummyCore.Utils.Coord2D; +import DummyCore.Utils.DummyConfig; +import DummyCore.Utils.GIFImage; +import DummyCore.Utils.IMainMenu; +import DummyCore.Utils.Notifier; +import DummyCore.Utils.Pair; +import com.google.common.base.Strings; +import com.google.common.collect.Lists; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.Loader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -10,7 +19,6 @@ import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Random; - import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.audio.SoundHandler; @@ -30,311 +38,268 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.common.MinecraftForge; - import org.lwjgl.opengl.GL11; import org.lwjgl.util.glu.Project; -import DummyCore.Utils.Coord2D; -import DummyCore.Utils.DummyConfig; -import DummyCore.Utils.GIFImage; -import DummyCore.Utils.IMainMenu; -import DummyCore.Utils.Notifier; -import DummyCore.Utils.Pair; +public class GuiMainMenuNBT extends GuiMainMenu implements IMainMenu { -import com.google.common.base.Strings; -import com.google.common.collect.Lists; + public static final Hashtable idToTagMapping = new Hashtable(); + public static final Random rand = new Random(); + public ArrayList> menuTextures = new ArrayList>(); + public ArrayList overlayTimeList = new ArrayList(); + public ArrayList music = new ArrayList(); + // -1 - invalid + // 0 - default texture scaled to the size + // 1 - 6 images(panorama) + // 2 - 1 texture rendered across the screen + // 3 - n textures with frame times + // 4 - 2 swapping textures + // 5 - gif image(unfinished) + public int menuType; + public ResourceLocation menuTexture = null; + public ResourceLocation customCursorTexture = null; + public boolean gif; + public ArrayList objects = new ArrayList(); + public int tickTime; + public float overlayTickTime; + public int panoramaTimer = 0; + public DynamicTexture viewportTexture; + public ScaledResolution mcRes; + public boolean hasGradient = false; + public int gradientColorStart, gradientColorEnd; + public int textureRepeat = 10; + public int textureIndex = 0; + public int currentGifFrame; + public int gifTick; + public GIFImage gifImage; + public URI clickedURI; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; + public List textLeft = new ArrayList(); + public List textRight = new ArrayList(); -public class GuiMainMenuNBT extends GuiMainMenu implements IMainMenu{ - - public static final Hashtable idToTagMapping = new Hashtable(); - public static final Random rand = new Random(); - public ArrayList> menuTextures = new ArrayList>(); - public ArrayList overlayTimeList = new ArrayList(); - public ArrayList music = new ArrayList(); - //-1 - invalid - //0 - default texture scaled to the size - //1 - 6 images(panorama) - //2 - 1 texture rendered across the screen - //3 - n textures with frame times - //4 - 2 swapping textures - //5 - gif image(unfinished) - public int menuType; - public ResourceLocation menuTexture = null; - public ResourceLocation customCursorTexture = null; - public boolean gif; - public ArrayList objects = new ArrayList(); - public int tickTime; - public float overlayTickTime; - public int panoramaTimer = 0; - public DynamicTexture viewportTexture; - public ScaledResolution mcRes; - public boolean hasGradient = false; - public int gradientColorStart,gradientColorEnd; - public int textureRepeat = 10; - public int textureIndex = 0; - public int currentGifFrame; - public int gifTick; - public GIFImage gifImage; - public URI clickedURI; - - public List textLeft = new ArrayList(); - public List textRight = new ArrayList(); - - protected void actionPerformed(GuiButton button) - { - super.actionPerformed(button); - try - { - if(button instanceof CustomButton) - { - CustomButton cb = CustomButton.class.cast(button); - if(cb.url != null) - { - if (this.mc.gameSettings.chatLinksPrompt) - { - this.clickedURI = new URI(cb.url.toString()); - this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, clickedURI.toString(), button.id, false)); - } - else - { - this.openURI(new URI(cb.url.toString())); - } - } - } - }catch(Exception e) - { - e.printStackTrace(); - } + protected void actionPerformed(GuiButton button) { + super.actionPerformed(button); + try { + if (button instanceof CustomButton) { + CustomButton cb = CustomButton.class.cast(button); + if (cb.url != null) { + if (this.mc.gameSettings.chatLinksPrompt) { + this.clickedURI = new URI(cb.url.toString()); + this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, clickedURI.toString(), button.id, false)); + } else { + this.openURI(new URI(cb.url.toString())); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } } - - public void openURI(URI uri) - { - try - { + + public void openURI(URI uri) { + try { Class oclass = Class.forName("java.awt.Desktop"); - Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]); + Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]); oclass.getMethod("browse", new Class[] {URI.class}).invoke(object, new Object[] {uri}); clickedURI = null; - } - catch (Throwable throwable) - { + } catch (Throwable throwable) { Notifier.notifyError("Couldn\'t open link"); } } - + @SuppressWarnings("unchecked") - public void confirmClicked(boolean yes, int id) - { - super.confirmClicked(yes, id); - for(GuiButton btn : (List)this.buttonList) - if(btn.id == id && btn instanceof CustomButton && CustomButton.class.cast(btn).url != null) - { - if(yes) - this.openURI(clickedURI); - - this.mc.displayGuiScreen(this); - break; - } + public void confirmClicked(boolean yes, int id) { + super.confirmClicked(yes, id); + for (GuiButton btn : (List) this.buttonList) + if (btn.id == id && btn instanceof CustomButton && CustomButton.class.cast(btn).url != null) { + if (yes) this.openURI(clickedURI); + + this.mc.displayGuiScreen(this); + break; + } } - - public void updateScreen() - { - for(int i = 0; i < objects.size(); ++i) - objects.get(i).guiTick(); - + + public void updateScreen() { + for (int i = 0; i < objects.size(); ++i) objects.get(i).guiTick(); + ++this.panoramaTimer; - if(menuType == 5) - { - ++gifTick; - if(gifTick >= overlayTimeList.get(currentGifFrame)) - { - if(currentGifFrame+1 >= overlayTimeList.size()) - { - gifTick = 0; - currentGifFrame = 0; - }else - { - ++currentGifFrame; - gifTick = 0; - } - } + if (menuType == 5) { + ++gifTick; + if (gifTick >= overlayTimeList.get(currentGifFrame)) { + if (currentGifFrame + 1 >= overlayTimeList.size()) { + gifTick = 0; + currentGifFrame = 0; + } else { + ++currentGifFrame; + gifTick = 0; + } + } } - if(menuType == 3 || menuType == 4) - { - ++tickTime; - if(!menuTextures.isEmpty()) - { - int maxTicks = menuTextures.get(textureIndex).getFirst() + (menuType == 3 ? 0 : overlayTimeList.get(textureIndex)); - if(tickTime >= maxTicks) - { - if(textureIndex+1 >= menuTextures.size()) - { - textureIndex = 0; - tickTime = 0; - overlayTickTime = 0; - }else - { - ++textureIndex; - tickTime = 0; - overlayTickTime = 0; - } - } - if(tickTime >= maxTicks-overlayTimeList.get(textureIndex)) - { - ++overlayTickTime; - } - } + if (menuType == 3 || menuType == 4) { + ++tickTime; + if (!menuTextures.isEmpty()) { + int maxTicks = menuTextures.get(textureIndex).getFirst() + + (menuType == 3 ? 0 : overlayTimeList.get(textureIndex)); + if (tickTime >= maxTicks) { + if (textureIndex + 1 >= menuTextures.size()) { + textureIndex = 0; + tickTime = 0; + overlayTickTime = 0; + } else { + ++textureIndex; + tickTime = 0; + overlayTickTime = 0; + } + } + if (tickTime >= maxTicks - overlayTimeList.get(textureIndex)) { + ++overlayTickTime; + } + } } } - + @SuppressWarnings("unchecked") - public void drawScreen(int mouseX, int mouseY, float partialTicks) - { - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_ALPHA_TEST); - if(menuType == 0) - { - mc.renderEngine.bindTexture(menuTexture); - Tessellator tec = Tessellator.instance; - tec.startDrawingQuads(); - tec.addVertexWithUV(0, 0, zLevel, 0, 0); - tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); - tec.draw(); - } - if(menuType == 1) - { - GL11.glPushMatrix(); + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_ALPHA_TEST); + if (menuType == 0) { + mc.renderEngine.bindTexture(menuTexture); + Tessellator tec = Tessellator.instance; + tec.startDrawingQuads(); + tec.addVertexWithUV(0, 0, zLevel, 0, 0); + tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); + tec.draw(); + } + if (menuType == 1) { + GL11.glPushMatrix(); GL11.glDisable(GL11.GL_ALPHA_TEST); this.renderSkybox(mouseX, mouseY, partialTicks); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glColor4d(1, 1, 1, 1); GL11.glPopMatrix(); - } - if(menuType == 2) - this.drawBackground(textureRepeat); - if(menuType == 3) - { - mc.renderEngine.bindTexture(menuTextures.get(textureIndex).getSecond()); - Tessellator tec = Tessellator.instance; - tec.startDrawingQuads(); - tec.addVertexWithUV(0, 0, zLevel, 0, 0); - tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); - tec.draw(); - } - if(menuType == 4) - { - int maxTicks = menuTextures.get(textureIndex).getFirst(); - mc.renderEngine.bindTexture(menuTextures.get(textureIndex).getSecond()); - Tessellator tec = Tessellator.instance; - tec.startDrawingQuads(); - tec.addVertexWithUV(0, 0, zLevel, 0, 0); - tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); - tec.draw(); - if(tickTime >= maxTicks) - { - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glEnable(GL11.GL_BLEND); - OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); - - mc.renderEngine.bindTexture(menuTextures.get(textureIndex +1 >= menuTextures.size() ? 0 : textureIndex+1).getSecond()); - float maxFadeIndex = overlayTimeList.get(textureIndex); - float currentFadeIndex = (overlayTickTime + partialTicks) / maxFadeIndex; - zLevel += 10; - tec.startDrawingQuads(); - tec.setColorRGBA_F(1, 1, 1, currentFadeIndex); - tec.addVertexWithUV(0, 0, zLevel, 0, 0); - tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); - tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); - tec.draw(); - tec.setColorRGBA_F(1, 1, 1, 1); - GL11.glColor4d(1, 1, 1, 1); - zLevel -= 10; - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_ALPHA_TEST); - } - } - if(menuType == 5) - { - GL11.glPushMatrix(); + } + if (menuType == 2) this.drawBackground(textureRepeat); + if (menuType == 3) { + mc.renderEngine.bindTexture(menuTextures.get(textureIndex).getSecond()); + Tessellator tec = Tessellator.instance; + tec.startDrawingQuads(); + tec.addVertexWithUV(0, 0, zLevel, 0, 0); + tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); + tec.draw(); + } + if (menuType == 4) { + int maxTicks = menuTextures.get(textureIndex).getFirst(); + mc.renderEngine.bindTexture(menuTextures.get(textureIndex).getSecond()); + Tessellator tec = Tessellator.instance; + tec.startDrawingQuads(); + tec.addVertexWithUV(0, 0, zLevel, 0, 0); + tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); + tec.draw(); + if (tickTime >= maxTicks) { + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); + OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); + + mc.renderEngine.bindTexture(menuTextures + .get(textureIndex + 1 >= menuTextures.size() ? 0 : textureIndex + 1) + .getSecond()); + float maxFadeIndex = overlayTimeList.get(textureIndex); + float currentFadeIndex = (overlayTickTime + partialTicks) / maxFadeIndex; + zLevel += 10; + tec.startDrawingQuads(); + tec.setColorRGBA_F(1, 1, 1, currentFadeIndex); + tec.addVertexWithUV(0, 0, zLevel, 0, 0); + tec.addVertexWithUV(0, mcRes.getScaledHeight_double(), zLevel, 0, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), mcRes.getScaledHeight_double(), zLevel, 1, 1); + tec.addVertexWithUV(mcRes.getScaledWidth_double(), 0, zLevel, 1, 0); + tec.draw(); + tec.setColorRGBA_F(1, 1, 1, 1); + GL11.glColor4d(1, 1, 1, 1); + zLevel -= 10; + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_ALPHA_TEST); + } + } + if (menuType == 5) { + GL11.glPushMatrix(); + + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + gifImage.drawOnScreen(currentGifFrame, 0, 0, 1, 1, mcRes.getScaledWidth(), mcRes.getScaledHeight()); - GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - - gifImage.drawOnScreen(currentGifFrame, 0, 0, 1, 1, mcRes.getScaledWidth(), mcRes.getScaledHeight()); - GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glPopMatrix(); - } - - if(this.hasGradient) - { - this.zLevel += 10; - this.drawGradientRect(0, 0, this.width, this.height, this.gradientColorStart, this.gradientColorEnd); - this.drawGradientRect(0, 0, this.width, this.height, 0, Integer.MIN_VALUE); - this.zLevel -= 10; - } + GL11.glPopMatrix(); + } + + if (this.hasGradient) { + this.zLevel += 10; + this.drawGradientRect(0, 0, this.width, this.height, this.gradientColorStart, this.gradientColorEnd); + this.drawGradientRect(0, 0, this.width, this.height, 0, Integer.MIN_VALUE); + this.zLevel -= 10; + } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - - for (int i = 0; i < this.textLeft.size(); i++) - { + + for (int i = 0; i < this.textLeft.size(); i++) { String brd = textLeft.get(i); if (!Strings.isNullOrEmpty(brd)) - this.drawString(this.fontRendererObj, brd, 2, this.height - ( 10 + i * (this.fontRendererObj.FONT_HEIGHT + 1)), 16777215); + this.drawString( + this.fontRendererObj, + brd, + 2, + this.height - (10 + i * (this.fontRendererObj.FONT_HEIGHT + 1)), + 16777215); } - + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - - for (int i = 0; i < this.textRight.size(); i++) - { + + for (int i = 0; i < this.textRight.size(); i++) { String brd = textRight.get(i); if (!Strings.isNullOrEmpty(brd)) - this.drawString(this.fontRendererObj, brd, this.width - this.fontRendererObj.getStringWidth(brd) - 2, this.height - ( 10 + i * (this.fontRendererObj.FONT_HEIGHT + 1)), 16777215); + this.drawString( + this.fontRendererObj, + brd, + this.width - this.fontRendererObj.getStringWidth(brd) - 2, + this.height - (10 + i * (this.fontRendererObj.FONT_HEIGHT + 1)), + 16777215); } - + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - + ForgeHooksClient.renderMainMenu(this, fontRendererObj, width, height); - + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - - for(AbstractGUIObject obj : objects) - obj.drawOnScreen(mouseX, mouseY, partialTicks,zLevel+10); - - for(GuiButton button : (ArrayList)this.buttonList) - if(!objects.contains(button)) - { - GL11.glTranslated(0, 0, 20); - button.drawButton(mc, mouseX, mouseY); - GL11.glTranslated(0, 0, -20); - } - - for(GuiLabel label : (ArrayList)this.labelList) - if(!objects.contains(label)) - { - GL11.glTranslated(0, 0, 20); - label.func_146159_a(mc, mouseX, mouseY); - GL11.glTranslated(0, 0, -20); - } - GL11.glPopMatrix(); + + for (AbstractGUIObject obj : objects) obj.drawOnScreen(mouseX, mouseY, partialTicks, zLevel + 10); + + for (GuiButton button : (ArrayList) this.buttonList) + if (!objects.contains(button)) { + GL11.glTranslated(0, 0, 20); + button.drawButton(mc, mouseX, mouseY); + GL11.glTranslated(0, 0, -20); + } + + for (GuiLabel label : (ArrayList) this.labelList) + if (!objects.contains(label)) { + GL11.glTranslated(0, 0, 20); + label.func_146159_a(mc, mouseX, mouseY); + GL11.glTranslated(0, 0, -20); + } + GL11.glPopMatrix(); } - - public void drawBackground(int repeat) - { - boolean lighting = GL11.glIsEnabled(GL11.GL_LIGHTING); - boolean fog = GL11.glIsEnabled(GL11.GL_FOG); + + public void drawBackground(int repeat) { + boolean lighting = GL11.glIsEnabled(GL11.GL_LIGHTING); + boolean fog = GL11.glIsEnabled(GL11.GL_FOG); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_FOG); Tessellator tessellator = Tessellator.instance; @@ -343,19 +308,20 @@ public class GuiMainMenuNBT extends GuiMainMenu implements IMainMenu{ float f = 32.0F; tessellator.startDrawingQuads(); tessellator.setColorOpaque_I(4210752); - tessellator.addVertexWithUV(0.0D, (double)this.height, 0.0D, 0.0D, (double)((float)this.height / f + (float)repeat)); - tessellator.addVertexWithUV((double)this.width, (double)this.height, 0.0D, (double)((float)this.width / f), (double)((float)this.height / f + (float)repeat)); - tessellator.addVertexWithUV((double)this.width, 0.0D, 0.0D, (double)((float)this.width / f), (double)repeat); - tessellator.addVertexWithUV(0.0D, 0.0D, 0.0D, 0.0D, (double)repeat); + tessellator.addVertexWithUV( + 0.0D, (double) this.height, 0.0D, 0.0D, (double) ((float) this.height / f + (float) repeat)); + tessellator.addVertexWithUV( + (double) this.width, (double) this.height, 0.0D, (double) ((float) this.width / f), (double) + ((float) this.height / f + (float) repeat)); + tessellator.addVertexWithUV( + (double) this.width, 0.0D, 0.0D, (double) ((float) this.width / f), (double) repeat); + tessellator.addVertexWithUV(0.0D, 0.0D, 0.0D, 0.0D, (double) repeat); tessellator.draw(); - if(lighting) - GL11.glEnable(GL11.GL_LIGHTING); - if(fog) - GL11.glEnable(GL11.GL_FOG); + if (lighting) GL11.glEnable(GL11.GL_LIGHTING); + if (fog) GL11.glEnable(GL11.GL_FOG); } - - public void drawPanorama(int mouseX, int mouseY, float partialTicks) - { + + public void drawPanorama(int mouseX, int mouseY, float partialTicks) { Tessellator tessellator = Tessellator.instance; GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); @@ -374,43 +340,40 @@ public class GuiMainMenuNBT extends GuiMainMenu implements IMainMenu{ OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); byte b0 = 8; - for (int k = 0; k < b0 * b0; ++k) - { + for (int k = 0; k < b0 * b0; ++k) { GL11.glPushMatrix(); - float f1 = ((float)(k % b0) / (float)b0 - 0.5F) / 64.0F; - float f2 = ((float)(k / b0) / (float)b0 - 0.5F) / 64.0F; + float f1 = ((float) (k % b0) / (float) b0 - 0.5F) / 64.0F; + float f2 = ((float) (k / b0) / (float) b0 - 0.5F) / 64.0F; float f3 = 0.0F; GL11.glTranslatef(f1, f2, f3); - GL11.glRotatef(MathHelper.sin(((float)this.panoramaTimer + partialTicks) / 400.0F) * 25.0F + 20.0F, 1.0F, 0.0F, 0.0F); - GL11.glRotatef(-((float)this.panoramaTimer + partialTicks) * 0.1F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef( + MathHelper.sin(((float) this.panoramaTimer + partialTicks) / 400.0F) * 25.0F + 20.0F, + 1.0F, + 0.0F, + 0.0F); + GL11.glRotatef(-((float) this.panoramaTimer + partialTicks) * 0.1F, 0.0F, 1.0F, 0.0F); - for (int l = 0; l < 6; ++l) - { + for (int l = 0; l < 6; ++l) { GL11.glPushMatrix(); - if (l == 1) - GL11.glRotated(90, 0, 1, 0); + if (l == 1) GL11.glRotated(90, 0, 1, 0); - if (l == 2) - GL11.glRotated(180, 0, 1, 0); + if (l == 2) GL11.glRotated(180, 0, 1, 0); - if (l == 3) - GL11.glRotated(-90, 0, 1, 0); + if (l == 3) GL11.glRotated(-90, 0, 1, 0); - if (l == 4) - GL11.glRotated(90, 1, 0, 0); + if (l == 4) GL11.glRotated(90, 1, 0, 0); - if (l == 5) - GL11.glRotated(-90, 1, 0, 0); + if (l == 5) GL11.glRotated(-90, 1, 0, 0); this.mc.getTextureManager().bindTexture(menuTextures.get(l).getSecond()); tessellator.startDrawingQuads(); tessellator.setColorRGBA_I(0xffffff, 255 / (k + 1)); float f4 = 0.0F; - tessellator.addVertexWithUV(-1.0D, -1.0D, 1.0D, (double)(0.0F + f4), (double)(0.0F + f4)); - tessellator.addVertexWithUV(1.0D, -1.0D, 1.0D, (double)(1.0F - f4), (double)(0.0F + f4)); - tessellator.addVertexWithUV(1.0D, 1.0D, 1.0D, (double)(1.0F - f4), (double)(1.0F - f4)); - tessellator.addVertexWithUV(-1.0D, 1.0D, 1.0D, (double)(0.0F + f4), (double)(1.0F - f4)); + tessellator.addVertexWithUV(-1.0D, -1.0D, 1.0D, (double) (0.0F + f4), (double) (0.0F + f4)); + tessellator.addVertexWithUV(1.0D, -1.0D, 1.0D, (double) (1.0F - f4), (double) (0.0F + f4)); + tessellator.addVertexWithUV(1.0D, 1.0D, 1.0D, (double) (1.0F - f4), (double) (1.0F - f4)); + tessellator.addVertexWithUV(-1.0D, 1.0D, 1.0D, (double) (0.0F + f4), (double) (1.0F - f4)); tessellator.draw(); GL11.glPopMatrix(); } @@ -429,9 +392,8 @@ public class GuiMainMenuNBT extends GuiMainMenu implements IMainMenu{ GL11.glEnable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_DEPTH_TEST); } - - public void rotateAndBlurSkybox(float partialTicks) - { + + public void rotateAndBlurSkybox(float partialTicks) { this.mc.getTextureManager().bindTexture(menuTexture); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); @@ -444,25 +406,23 @@ public class GuiMainMenuNBT extends GuiMainMenu implements IMainMenu{ GL11.glDisable(GL11.GL_ALPHA_TEST); byte b0 = 3; - for (int i = 0; i < b0; ++i) - { - tessellator.setColorRGBA_F(1.0F, 1.0F, 1.0F, 1.0F / (float)(i + 1)); + for (int i = 0; i < b0; ++i) { + tessellator.setColorRGBA_F(1.0F, 1.0F, 1.0F, 1.0F / (float) (i + 1)); int j = this.width; int k = this.height; - float f1 = (float)(i - b0 / 2) / 256.0F; - tessellator.addVertexWithUV((double)j, (double)k, (double)this.zLevel, (double)(0.0F + f1), 1.0D); - tessellator.addVertexWithUV((double)j, 0.0D, (double)this.zLevel, (double)(1.0F + f1), 1.0D); - tessellator.addVertexWithUV(0.0D, 0.0D, (double)this.zLevel, (double)(1.0F + f1), 0.0D); - tessellator.addVertexWithUV(0.0D, (double)k, (double)this.zLevel, (double)(0.0F + f1), 0.0D); + float f1 = (float) (i - b0 / 2) / 256.0F; + tessellator.addVertexWithUV((double) j, (double) k, (double) this.zLevel, (double) (0.0F + f1), 1.0D); + tessellator.addVertexWithUV((double) j, 0.0D, (double) this.zLevel, (double) (1.0F + f1), 1.0D); + tessellator.addVertexWithUV(0.0D, 0.0D, (double) this.zLevel, (double) (1.0F + f1), 0.0D); + tessellator.addVertexWithUV(0.0D, (double) k, (double) this.zLevel, (double) (0.0F + f1), 0.0D); } tessellator.draw(); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glColorMask(true, true, true, true); } - - public void renderSkybox(int mouseX, int mouseY, float partialTicks) - { + + public void renderSkybox(int mouseX, int mouseY, float partialTicks) { this.mc.getFramebuffer().unbindFramebuffer(); GL11.glViewport(0, 0, 256, 256); this.drawPanorama(mouseX, mouseY, partialTicks); @@ -477,432 +437,428 @@ public class GuiMainMenuNBT extends GuiMainMenu implements IMainMenu{ GL11.glViewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - float f1 = this.width > this.height ? 120.0F / (float)this.width : 120.0F / (float)this.height; - float f2 = (float)this.height * f1 / 256.0F; - float f3 = (float)this.width * f1 / 256.0F; + float f1 = this.width > this.height ? 120.0F / (float) this.width : 120.0F / (float) this.height; + float f2 = (float) this.height * f1 / 256.0F; + float f3 = (float) this.width * f1 / 256.0F; tessellator.setColorRGBA_F(1.0F, 1.0F, 1.0F, 1.0F); int k = this.width; int l = this.height; - tessellator.addVertexWithUV(0.0D, (double)l, (double)this.zLevel, (double)(0.5F - f2), (double)(0.5F + f3)); - tessellator.addVertexWithUV((double)k, (double)l, (double)this.zLevel, (double)(0.5F - f2), (double)(0.5F - f3)); - tessellator.addVertexWithUV((double)k, 0.0D, (double)this.zLevel, (double)(0.5F + f2), (double)(0.5F - f3)); - tessellator.addVertexWithUV(0.0D, 0.0D, (double)this.zLevel, (double)(0.5F + f2), (double)(0.5F + f3)); + tessellator.addVertexWithUV(0.0D, (double) l, (double) this.zLevel, (double) (0.5F - f2), (double) (0.5F + f3)); + tessellator.addVertexWithUV( + (double) k, (double) l, (double) this.zLevel, (double) (0.5F - f2), (double) (0.5F - f3)); + tessellator.addVertexWithUV((double) k, 0.0D, (double) this.zLevel, (double) (0.5F + f2), (double) (0.5F - f3)); + tessellator.addVertexWithUV(0.0D, 0.0D, (double) this.zLevel, (double) (0.5F + f2), (double) (0.5F + f3)); tessellator.draw(); } - - public GuiMainMenuNBT() - { - this.mc = Minecraft.getMinecraft(); - setupNBTInfo(); - } - - @Override - public void initGui() - { - textureIndex = 0; - currentGifFrame = 0; - initNBTInfo(); - mcRes = new ScaledResolution(mc,mc.displayWidth,mc.displayHeight); - } - - @SuppressWarnings("unchecked") - public void initNBTInfo() - { - objects.clear(); - NBTTagCompound tag = idToTagMapping.get(DummyConfig.getMainMenu()); - if(tag.hasKey("Images", 9)) - { - NBTTagList nbtLst = tag.getTagList("Images", 10); - for(int i = 0; i < nbtLst.tagCount(); ++i) - { - NBTTagCompound tg = nbtLst.getCompoundTagAt(i); - CustomImage image = new CustomImage(); - image.texture = new ResourceLocation(tg.getString("Texture")); - image.gif = tg.getString("Texture").endsWith(".gif"); - if(image.gif) - image.gifImage = new GIFImage(image.texture); - - int defaultX = tg.getInteger("XAlignment") == 0 ? 0 : tg.getInteger("XAlignment") == 1 ? this.width / 2 : tg.getInteger("XAlignment") == 2 ? this.width : this.width/tg.getInteger("XAlignment"); - int defaultY = tg.getInteger("YAlignment") == 0 ? 0 : tg.getInteger("YAlignment") == 1 ? this.height / 2 : tg.getInteger("YAlignment") == 2 ? this.height : this.height/tg.getInteger("YAlignment"); - image.x = defaultX + tg.getInteger("X"); - image.y = defaultY + tg.getInteger("Y"); - image.minU = tg.hasKey("MinU") ? tg.getDouble("MinU") : (double)tg.getInteger("TextureMinX")/256D; - image.maxU = tg.hasKey("MaxU") ? tg.getDouble("MaxU") : (double)tg.getInteger("TextureMaxX")/256D; - image.minV = tg.hasKey("MinV") ? tg.getDouble("MinV") : (double)tg.getInteger("TextureMinY")/256D; - image.maxV = tg.hasKey("MaxV") ? tg.getDouble("MaxV") : (double)tg.getInteger("TextureMaxY")/256D; - image.sizeX = tg.getInteger("XSize"); - image.sizeY = tg.getInteger("YSize"); - if(tg.hasKey("Text", 9)) - { - NBTTagList texts = tg.getTagList("Text", 10); - for(int j = 0; j < texts.tagCount(); ++j) - { - NBTTagCompound t = texts.getCompoundTagAt(j); - image.textAngle = t.getFloat("Angle"); - String s = t.hasKey("Splashes") ? createRandomSplash(new ResourceLocation(t.getString("Splashes"))) : t.getString("Text"); - image.additionalText.add(new Pair(new Coord2D(t.getInteger("X"),t.getInteger("Y")),s)); - } - } - objects.add(image); - } - } - if(tag.hasKey("Buttons", 9)) - { - NBTTagList nbtLst = tag.getTagList("Buttons", 10); - for(int i = 0; i < nbtLst.tagCount(); ++i) - { - NBTTagCompound tg = nbtLst.getCompoundTagAt(i); - int id = tg.getInteger("ButtonID"); - int defaultX = tg.getInteger("XAlignment") == 0 ? 0 : tg.getInteger("XAlignment") == 1 ? this.width / 2 : tg.getInteger("XAlignment") == 2 ? this.width : this.width/tg.getInteger("XAlignment"); - int defaultY = tg.getInteger("YAlignment") == 0 ? 0 : tg.getInteger("YAlignment") == 1 ? this.height / 2 : tg.getInteger("YAlignment") == 2 ? this.height : this.height/tg.getInteger("YAlignment"); - int x = defaultX + tg.getInteger("X"); - int y = defaultY + tg.getInteger("Y"); - int sizeX = tg.getInteger("XSize"); - int sizeY = tg.getInteger("YSize"); - String text = tg.getString("Text"); - CustomButton button = new CustomButton(id,x,y,sizeX,sizeY,StatCollector.canTranslate(text) ? StatCollector.translateToLocal(text) : text); - button.texture = new ResourceLocation(tg.getString("Texture")); - button.sound = new ResourceLocation(tg.getString("Sound")); - button.minU = tg.hasKey("MinU") ? tg.getDouble("MinU") : (double)tg.getInteger("TextureMinX")/256D; - button.maxU = tg.hasKey("MaxU") ? tg.getDouble("MaxU") : (double)tg.getInteger("TextureMaxX")/256D; - button.minV = tg.hasKey("MinV") ? tg.getDouble("MinV") : (double)tg.getInteger("TextureMinY")/256D; - button.maxV = tg.hasKey("MaxV") ? tg.getDouble("MaxV") : (double)tg.getInteger("TextureMaxY")/256D; - button.buttonYOffset = tg.hasKey("ButtonYUVOffset") ? tg.getDouble("ButtonYUVOffset") : (double)tg.getInteger("ButtonYOffset")/256D; - if(tg.hasKey("URL")){ - try{ - button.url = new URL(tg.getString("URL")); - } - catch(Exception e){ - - } - } - objects.add(button); - this.buttonList.add(button); - } - } - } - - public String createRandomSplash(ResourceLocation splashesLoc) - { - String retStr = "missingno"; - - BufferedReader bufferedreader = null; - - try - { - ArrayList arraylist = new ArrayList(); - bufferedreader = new BufferedReader(new InputStreamReader(Minecraft.getMinecraft().getResourceManager().getResource(splashesLoc).getInputStream(), "UTF-8")); - String s; - while ((s = bufferedreader.readLine()) != null) - { - s = s.trim(); - if (!s.isEmpty()) - arraylist.add(s); - } - if (!arraylist.isEmpty()) - retStr = (String)arraylist.get(rand.nextInt(arraylist.size())); - - } - catch (IOException e){ - e.printStackTrace(); - } - finally - { - if (bufferedreader != null) - { - try - { - bufferedreader.close(); - } - catch (IOException ioexception){} - } - } - return "|Splash|"+retStr; - } - - public void setupNBTInfo() - { - menuTextures.clear(); - music.clear(); - overlayTimeList.clear(); - textLeft.clear(); - textRight.clear(); - - NBTTagCompound tag = idToTagMapping.get(DummyConfig.getMainMenu()); - menuType = tag.getInteger("MenuType"); - if(tag.hasKey("GradientStart") && tag.hasKey("GradientEnd")) - { - hasGradient = true; - gradientColorStart = tag.getInteger("GradientStart"); - gradientColorEnd = tag.getInteger("GradientEnd"); - } - if(tag.hasKey("TextureRepeats")) - this.textureRepeat = tag.getInteger("TextureRepeats"); - - if(tag.hasKey("Textures", 9)) - { - NBTTagList nbtLst = tag.getTagList("Textures", 10); - for(int i = 0; i < nbtLst.tagCount(); ++i) - { - NBTTagCompound tg = nbtLst.getCompoundTagAt(i); - menuTextures.add(new Pair(tg.getInteger("FadeTime"),new ResourceLocation(tg.getString("Texture")))); - overlayTimeList.add(tg.getInteger("OverlayTime")); - } - }else - { - if(tag.hasKey("Texture",8)) - { - menuTexture = new ResourceLocation(tag.getString("Texture")); - if(tag.getString("Texture").endsWith(".gif")) - { - gif = true; - gifImage = new GIFImage(new ResourceLocation(tag.getString("Texture"))); - for(int i = 0; i < gifImage.frames; ++i) - overlayTimeList.add(tag.getInteger("FrameDelay")); - - if(tag.hasKey("FramesDelay",10)) - { - NBTTagCompound framesDelay = tag.getCompoundTag("FramesDelay"); - for(int i = 0; i < gifImage.frames; ++i) - if(framesDelay.hasKey(i+"", 3)) - overlayTimeList.set(i, framesDelay.getInteger(i+"")); - } - } - } - else - { - menuTexture = null; - menuType = 1; - } - } - if(tag.hasKey("Music", 9)) - { - NBTTagList nbtLst = tag.getTagList("Music", 10); - for(int i = 0; i < nbtLst.tagCount(); ++i) - music.add(new ResourceLocation(nbtLst.getCompoundTagAt(i).getString("Music"))); - } - if(tag.hasKey("TextLeft",9)) - { - NBTTagList nbtLst = tag.getTagList("TextLeft", 8); - for(int i = 0; i < nbtLst.tagCount(); ++i) - { - String txt = nbtLst.getStringTagAt(i); - txt = parsePossibleLink(txt); - if(txt.equals("|SidedInfo|") && FMLCommonHandler.instance().getSidedDelegate()!=null) - textLeft.addAll(FMLCommonHandler.instance().getSidedDelegate().getAdditionalBrandingInformation()); - else - if(!Strings.isNullOrEmpty(txt)) - textLeft.add(txt); - } - textLeft = Lists.reverse(textLeft); - } - - if(tag.hasKey("TextRight",9)) - { - NBTTagList nbtLst = tag.getTagList("TextRight", 8); - for(int i = 0; i < nbtLst.tagCount(); ++i) - { - String txt = nbtLst.getStringTagAt(i); - txt = parsePossibleLink(txt); - if(txt.equals("|SidedInfo|") && FMLCommonHandler.instance().getSidedDelegate()!=null) - textRight.addAll(FMLCommonHandler.instance().getSidedDelegate().getAdditionalBrandingInformation()); - else - if(!Strings.isNullOrEmpty(txt)) - textRight.add(txt); - } - textRight = Lists.reverse(textRight); - } - if(menuType == 1) - { - viewportTexture = new DynamicTexture(256, 256); - menuTexture = this.mc.getTextureManager().getDynamicTextureLocation("background", this.viewportTexture); - } - } - - public String parsePossibleLink(String s) - { - if(s.equals("|MC|")) - s = Loader.instance().getMCVersionString(); - if(s.equals("|MCP|")) - s = Loader.instance().getMCPVersionString(); - if(s.equals("|FML|")) - s = "FML v"+Loader.instance().getFMLVersionString(); - if(s.equals("|Forge|")) - s = MinecraftForge.getBrandingVersion(); - if(s.equals("|FMLBranding|")) - s = Loader.instance().getFMLBrandingProperties().containsKey("fmlbranding") ? Loader.instance().getFMLBrandingProperties().get("fmlbranding") : ""; - if(s.equals("|Mods|")) - { + + public GuiMainMenuNBT() { + this.mc = Minecraft.getMinecraft(); + setupNBTInfo(); + } + + @Override + public void initGui() { + textureIndex = 0; + currentGifFrame = 0; + initNBTInfo(); + mcRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + } + + @SuppressWarnings("unchecked") + public void initNBTInfo() { + objects.clear(); + NBTTagCompound tag = idToTagMapping.get(DummyConfig.getMainMenu()); + if (tag.hasKey("Images", 9)) { + NBTTagList nbtLst = tag.getTagList("Images", 10); + for (int i = 0; i < nbtLst.tagCount(); ++i) { + NBTTagCompound tg = nbtLst.getCompoundTagAt(i); + CustomImage image = new CustomImage(); + image.texture = new ResourceLocation(tg.getString("Texture")); + image.gif = tg.getString("Texture").endsWith(".gif"); + if (image.gif) image.gifImage = new GIFImage(image.texture); + + int defaultX = tg.getInteger("XAlignment") == 0 + ? 0 + : tg.getInteger("XAlignment") == 1 + ? this.width / 2 + : tg.getInteger("XAlignment") == 2 + ? this.width + : this.width / tg.getInteger("XAlignment"); + int defaultY = tg.getInteger("YAlignment") == 0 + ? 0 + : tg.getInteger("YAlignment") == 1 + ? this.height / 2 + : tg.getInteger("YAlignment") == 2 + ? this.height + : this.height / tg.getInteger("YAlignment"); + image.x = defaultX + tg.getInteger("X"); + image.y = defaultY + tg.getInteger("Y"); + image.minU = tg.hasKey("MinU") ? tg.getDouble("MinU") : (double) tg.getInteger("TextureMinX") / 256D; + image.maxU = tg.hasKey("MaxU") ? tg.getDouble("MaxU") : (double) tg.getInteger("TextureMaxX") / 256D; + image.minV = tg.hasKey("MinV") ? tg.getDouble("MinV") : (double) tg.getInteger("TextureMinY") / 256D; + image.maxV = tg.hasKey("MaxV") ? tg.getDouble("MaxV") : (double) tg.getInteger("TextureMaxY") / 256D; + image.sizeX = tg.getInteger("XSize"); + image.sizeY = tg.getInteger("YSize"); + if (tg.hasKey("Text", 9)) { + NBTTagList texts = tg.getTagList("Text", 10); + for (int j = 0; j < texts.tagCount(); ++j) { + NBTTagCompound t = texts.getCompoundTagAt(j); + image.textAngle = t.getFloat("Angle"); + String s = t.hasKey("Splashes") + ? createRandomSplash(new ResourceLocation(t.getString("Splashes"))) + : t.getString("Text"); + image.additionalText.add( + new Pair(new Coord2D(t.getInteger("X"), t.getInteger("Y")), s)); + } + } + objects.add(image); + } + } + if (tag.hasKey("Buttons", 9)) { + NBTTagList nbtLst = tag.getTagList("Buttons", 10); + for (int i = 0; i < nbtLst.tagCount(); ++i) { + NBTTagCompound tg = nbtLst.getCompoundTagAt(i); + int id = tg.getInteger("ButtonID"); + int defaultX = tg.getInteger("XAlignment") == 0 + ? 0 + : tg.getInteger("XAlignment") == 1 + ? this.width / 2 + : tg.getInteger("XAlignment") == 2 + ? this.width + : this.width / tg.getInteger("XAlignment"); + int defaultY = tg.getInteger("YAlignment") == 0 + ? 0 + : tg.getInteger("YAlignment") == 1 + ? this.height / 2 + : tg.getInteger("YAlignment") == 2 + ? this.height + : this.height / tg.getInteger("YAlignment"); + int x = defaultX + tg.getInteger("X"); + int y = defaultY + tg.getInteger("Y"); + int sizeX = tg.getInteger("XSize"); + int sizeY = tg.getInteger("YSize"); + String text = tg.getString("Text"); + CustomButton button = new CustomButton( + id, + x, + y, + sizeX, + sizeY, + StatCollector.canTranslate(text) ? StatCollector.translateToLocal(text) : text); + button.texture = new ResourceLocation(tg.getString("Texture")); + button.sound = new ResourceLocation(tg.getString("Sound")); + button.minU = tg.hasKey("MinU") ? tg.getDouble("MinU") : (double) tg.getInteger("TextureMinX") / 256D; + button.maxU = tg.hasKey("MaxU") ? tg.getDouble("MaxU") : (double) tg.getInteger("TextureMaxX") / 256D; + button.minV = tg.hasKey("MinV") ? tg.getDouble("MinV") : (double) tg.getInteger("TextureMinY") / 256D; + button.maxV = tg.hasKey("MaxV") ? tg.getDouble("MaxV") : (double) tg.getInteger("TextureMaxY") / 256D; + button.buttonYOffset = tg.hasKey("ButtonYUVOffset") + ? tg.getDouble("ButtonYUVOffset") + : (double) tg.getInteger("ButtonYOffset") / 256D; + if (tg.hasKey("URL")) { + try { + button.url = new URL(tg.getString("URL")); + } catch (Exception e) { + + } + } + objects.add(button); + this.buttonList.add(button); + } + } + } + + public String createRandomSplash(ResourceLocation splashesLoc) { + String retStr = "missingno"; + + BufferedReader bufferedreader = null; + + try { + ArrayList arraylist = new ArrayList(); + bufferedreader = new BufferedReader(new InputStreamReader( + Minecraft.getMinecraft() + .getResourceManager() + .getResource(splashesLoc) + .getInputStream(), + "UTF-8")); + String s; + while ((s = bufferedreader.readLine()) != null) { + s = s.trim(); + if (!s.isEmpty()) arraylist.add(s); + } + if (!arraylist.isEmpty()) retStr = (String) arraylist.get(rand.nextInt(arraylist.size())); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (bufferedreader != null) { + try { + bufferedreader.close(); + } catch (IOException ioexception) { + } + } + } + return "|Splash|" + retStr; + } + + public void setupNBTInfo() { + menuTextures.clear(); + music.clear(); + overlayTimeList.clear(); + textLeft.clear(); + textRight.clear(); + + NBTTagCompound tag = idToTagMapping.get(DummyConfig.getMainMenu()); + menuType = tag.getInteger("MenuType"); + if (tag.hasKey("GradientStart") && tag.hasKey("GradientEnd")) { + hasGradient = true; + gradientColorStart = tag.getInteger("GradientStart"); + gradientColorEnd = tag.getInteger("GradientEnd"); + } + if (tag.hasKey("TextureRepeats")) this.textureRepeat = tag.getInteger("TextureRepeats"); + + if (tag.hasKey("Textures", 9)) { + NBTTagList nbtLst = tag.getTagList("Textures", 10); + for (int i = 0; i < nbtLst.tagCount(); ++i) { + NBTTagCompound tg = nbtLst.getCompoundTagAt(i); + menuTextures.add(new Pair( + tg.getInteger("FadeTime"), new ResourceLocation(tg.getString("Texture")))); + overlayTimeList.add(tg.getInteger("OverlayTime")); + } + } else { + if (tag.hasKey("Texture", 8)) { + menuTexture = new ResourceLocation(tag.getString("Texture")); + if (tag.getString("Texture").endsWith(".gif")) { + gif = true; + gifImage = new GIFImage(new ResourceLocation(tag.getString("Texture"))); + for (int i = 0; i < gifImage.frames; ++i) overlayTimeList.add(tag.getInteger("FrameDelay")); + + if (tag.hasKey("FramesDelay", 10)) { + NBTTagCompound framesDelay = tag.getCompoundTag("FramesDelay"); + for (int i = 0; i < gifImage.frames; ++i) + if (framesDelay.hasKey(i + "", 3)) overlayTimeList.set(i, framesDelay.getInteger(i + "")); + } + } + } else { + menuTexture = null; + menuType = 1; + } + } + if (tag.hasKey("Music", 9)) { + NBTTagList nbtLst = tag.getTagList("Music", 10); + for (int i = 0; i < nbtLst.tagCount(); ++i) + music.add(new ResourceLocation(nbtLst.getCompoundTagAt(i).getString("Music"))); + } + if (tag.hasKey("TextLeft", 9)) { + NBTTagList nbtLst = tag.getTagList("TextLeft", 8); + for (int i = 0; i < nbtLst.tagCount(); ++i) { + String txt = nbtLst.getStringTagAt(i); + txt = parsePossibleLink(txt); + if (txt.equals("|SidedInfo|") && FMLCommonHandler.instance().getSidedDelegate() != null) + textLeft.addAll( + FMLCommonHandler.instance().getSidedDelegate().getAdditionalBrandingInformation()); + else if (!Strings.isNullOrEmpty(txt)) textLeft.add(txt); + } + textLeft = Lists.reverse(textLeft); + } + + if (tag.hasKey("TextRight", 9)) { + NBTTagList nbtLst = tag.getTagList("TextRight", 8); + for (int i = 0; i < nbtLst.tagCount(); ++i) { + String txt = nbtLst.getStringTagAt(i); + txt = parsePossibleLink(txt); + if (txt.equals("|SidedInfo|") && FMLCommonHandler.instance().getSidedDelegate() != null) + textRight.addAll( + FMLCommonHandler.instance().getSidedDelegate().getAdditionalBrandingInformation()); + else if (!Strings.isNullOrEmpty(txt)) textRight.add(txt); + } + textRight = Lists.reverse(textRight); + } + if (menuType == 1) { + viewportTexture = new DynamicTexture(256, 256); + menuTexture = this.mc.getTextureManager().getDynamicTextureLocation("background", this.viewportTexture); + } + } + + public String parsePossibleLink(String s) { + if (s.equals("|MC|")) s = Loader.instance().getMCVersionString(); + if (s.equals("|MCP|")) s = Loader.instance().getMCPVersionString(); + if (s.equals("|FML|")) s = "FML v" + Loader.instance().getFMLVersionString(); + if (s.equals("|Forge|")) s = MinecraftForge.getBrandingVersion(); + if (s.equals("|FMLBranding|")) + s = Loader.instance().getFMLBrandingProperties().containsKey("fmlbranding") + ? Loader.instance().getFMLBrandingProperties().get("fmlbranding") + : ""; + if (s.equals("|Mods|")) { int tModCount = Loader.instance().getModList().size(); int aModCount = Loader.instance().getActiveModList().size(); - s = String.format("%d mod%s loaded, %d mod%s active", tModCount, tModCount!=1 ? "s" :"", aModCount, aModCount!=1 ? "s" :"" ); - } - if(s.equals("|Copyright|")) - s = "Copyright Mojang AB. Do not distribute!"; - return s; - } - - public static interface AbstractGUIObject - { - public void drawOnScreen(int mouseX, int mouseY, float partialTicks, double zLevel); - public void guiTick(); - } - - public static class CustomImage extends GuiScreen implements AbstractGUIObject - { - public ResourceLocation texture = null; - public float textAngle; - public boolean gif; - public ArrayList> additionalText = new ArrayList>(); - public int x,y; - public int sizeX,sizeY; - public double minU,minV,maxU,maxV; - public GIFImage gifImage; - public int frameTime; - - public void drawOnScreen(int mouseX, int mouseY, float partialTicks, double zLevel) - { - if(mc == null) - mc = Minecraft.getMinecraft(); - - if(!gif) - { - mc.renderEngine.bindTexture(texture); - Tessellator tec = Tessellator.instance; - tec.startDrawingQuads(); - - tec.addVertexWithUV(x, y, zLevel, minU, minV); - tec.addVertexWithUV(x, y+sizeY, zLevel, minU, maxV); - tec.addVertexWithUV(x+sizeX, y+sizeY, zLevel, maxU, maxV); - tec.addVertexWithUV(x+sizeX, y, zLevel, maxU, minV); - - tec.draw(); - }else{ - - GL11.glPushMatrix(); - - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glTranslated(x, y, zLevel); - - gifImage.drawOnScreen(MathHelper.floor_double(frameTime+partialTicks) % gifImage.frames, minU, minV, maxU, maxV, sizeX, sizeY); - - GL11.glTranslated(-x, -y, -zLevel); - - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glPopMatrix(); - - } - - if(!additionalText.isEmpty()) - { - for(Pair p : additionalText) - { - String text = p.getSecond(); - boolean splash = text.contains("|Splash|"); - if(splash) - text = text.substring(8); - - double dx = p.getFirst().x; - double dy = p.getFirst().z; - GL11.glPushMatrix(); - - GL11.glTranslated(x+dx, y+dy, zLevel+10); - - GL11.glRotated(textAngle, 0, 0, 1); - - double scale = 1.8D; - if(splash) - { - scale = 1.8D - MathHelper.abs(MathHelper.sin((float)(Minecraft.getSystemTime() % 1000L) / 1000.0F * (float)Math.PI * 2.0F) * 0.1F); - scale = scale * 100.0F / (float)(mc.fontRenderer.getStringWidth(text) + 32); - } - - GL11.glScaled(scale, scale, 1); - - this.drawCenteredString(mc.fontRenderer, text, 0, -8, -256); - - GL11.glScaled(1/scale, 1/scale, 1); - - GL11.glRotated(-textAngle, 0, 0, 1); - - GL11.glTranslated(-(x+dx), -(y+dy), -(zLevel+10)); - - GL11.glColor4d(1, 1, 1, 1); - - GL11.glPopMatrix(); - } - } - } + s = String.format( + "%d mod%s loaded, %d mod%s active", + tModCount, tModCount != 1 ? "s" : "", aModCount, aModCount != 1 ? "s" : ""); + } + if (s.equals("|Copyright|")) s = "Copyright Mojang AB. Do not distribute!"; + return s; + } - @Override - public void guiTick() { - if(gif) - ++frameTime; - } - } - - public static class CustomButton extends GuiButton implements AbstractGUIObject - { - public ResourceLocation texture = null; - public ResourceLocation sound = null; - public double minU,minV,maxU,maxV; - public double buttonYOffset; - public URL url; - - public CustomButton(int id, int x, int y, int sizeX, int sizeY, String text) - { - super(id,x,y,sizeX,sizeY,text); - } - - public void func_146113_a(SoundHandler sh) - { - sh.playSound(PositionedSoundRecord.func_147674_a(sound != null ? sound : new ResourceLocation("gui.button.press"), 1.0F)); - } - - public void drawOnScreen(int mouseX, int mouseY, float partialTicks, double zLevel) - { - Minecraft mc = Minecraft.getMinecraft(); - - mc.renderEngine.bindTexture(texture); - Tessellator tec = Tessellator.instance; - tec.startDrawingQuads(); - - int l = 0xe0e0e0; - double offsetY = buttonYOffset; - if(!this.enabled) - { - offsetY = 0; - l = 0xa0a0a0; - } - - if(mouseX >= xPosition && mouseX <= xPosition+width) - { - if(mouseY >= yPosition && mouseY <= yPosition+height) - { - offsetY = buttonYOffset * 2; - l = 0xffffff; - } - } - - tec.addVertexWithUV(xPosition, yPosition, zLevel, minU, minV+offsetY); - tec.addVertexWithUV(xPosition, yPosition+height, zLevel, minU, maxV+offsetY); - tec.addVertexWithUV(xPosition+width, yPosition+height, zLevel, maxU, maxV+offsetY); - tec.addVertexWithUV(xPosition+width, yPosition, zLevel, maxU, minV+offsetY); - - tec.draw(); - - GL11.glTranslated(0, 0, 100); - this.drawCenteredString(mc.fontRenderer, displayString, this.xPosition + this.width / 2, this.yPosition + (this.height - 8) / 2, l); - GL11.glTranslated(0, 0, -100); - GL11.glColor4d(1, 1, 1, 1); - } + public static interface AbstractGUIObject { + public void drawOnScreen(int mouseX, int mouseY, float partialTicks, double zLevel); - @Override - public void guiTick() { - - } - } + public void guiTick(); + } + + public static class CustomImage extends GuiScreen implements AbstractGUIObject { + public ResourceLocation texture = null; + public float textAngle; + public boolean gif; + public ArrayList> additionalText = new ArrayList>(); + public int x, y; + public int sizeX, sizeY; + public double minU, minV, maxU, maxV; + public GIFImage gifImage; + public int frameTime; + + public void drawOnScreen(int mouseX, int mouseY, float partialTicks, double zLevel) { + if (mc == null) mc = Minecraft.getMinecraft(); + + if (!gif) { + mc.renderEngine.bindTexture(texture); + Tessellator tec = Tessellator.instance; + tec.startDrawingQuads(); + + tec.addVertexWithUV(x, y, zLevel, minU, minV); + tec.addVertexWithUV(x, y + sizeY, zLevel, minU, maxV); + tec.addVertexWithUV(x + sizeX, y + sizeY, zLevel, maxU, maxV); + tec.addVertexWithUV(x + sizeX, y, zLevel, maxU, minV); + + tec.draw(); + } else { + + GL11.glPushMatrix(); + + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glTranslated(x, y, zLevel); + + gifImage.drawOnScreen( + MathHelper.floor_double(frameTime + partialTicks) % gifImage.frames, + minU, + minV, + maxU, + maxV, + sizeX, + sizeY); + + GL11.glTranslated(-x, -y, -zLevel); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glPopMatrix(); + } + + if (!additionalText.isEmpty()) { + for (Pair p : additionalText) { + String text = p.getSecond(); + boolean splash = text.contains("|Splash|"); + if (splash) text = text.substring(8); + + double dx = p.getFirst().x; + double dy = p.getFirst().z; + GL11.glPushMatrix(); + + GL11.glTranslated(x + dx, y + dy, zLevel + 10); + + GL11.glRotated(textAngle, 0, 0, 1); + + double scale = 1.8D; + if (splash) { + scale = 1.8D + - MathHelper.abs(MathHelper.sin((float) (Minecraft.getSystemTime() % 1000L) + / 1000.0F + * (float) Math.PI + * 2.0F) + * 0.1F); + scale = scale * 100.0F / (float) (mc.fontRenderer.getStringWidth(text) + 32); + } + + GL11.glScaled(scale, scale, 1); + + this.drawCenteredString(mc.fontRenderer, text, 0, -8, -256); + + GL11.glScaled(1 / scale, 1 / scale, 1); + + GL11.glRotated(-textAngle, 0, 0, 1); + + GL11.glTranslated(-(x + dx), -(y + dy), -(zLevel + 10)); + + GL11.glColor4d(1, 1, 1, 1); + + GL11.glPopMatrix(); + } + } + } + + @Override + public void guiTick() { + if (gif) ++frameTime; + } + } + + public static class CustomButton extends GuiButton implements AbstractGUIObject { + public ResourceLocation texture = null; + public ResourceLocation sound = null; + public double minU, minV, maxU, maxV; + public double buttonYOffset; + public URL url; + + public CustomButton(int id, int x, int y, int sizeX, int sizeY, String text) { + super(id, x, y, sizeX, sizeY, text); + } + + public void func_146113_a(SoundHandler sh) { + sh.playSound(PositionedSoundRecord.func_147674_a( + sound != null ? sound : new ResourceLocation("gui.button.press"), 1.0F)); + } + + public void drawOnScreen(int mouseX, int mouseY, float partialTicks, double zLevel) { + Minecraft mc = Minecraft.getMinecraft(); + + mc.renderEngine.bindTexture(texture); + Tessellator tec = Tessellator.instance; + tec.startDrawingQuads(); + + int l = 0xe0e0e0; + double offsetY = buttonYOffset; + if (!this.enabled) { + offsetY = 0; + l = 0xa0a0a0; + } + + if (mouseX >= xPosition && mouseX <= xPosition + width) { + if (mouseY >= yPosition && mouseY <= yPosition + height) { + offsetY = buttonYOffset * 2; + l = 0xffffff; + } + } + + tec.addVertexWithUV(xPosition, yPosition, zLevel, minU, minV + offsetY); + tec.addVertexWithUV(xPosition, yPosition + height, zLevel, minU, maxV + offsetY); + tec.addVertexWithUV(xPosition + width, yPosition + height, zLevel, maxU, maxV + offsetY); + tec.addVertexWithUV(xPosition + width, yPosition, zLevel, maxU, minV + offsetY); + + tec.draw(); + + GL11.glTranslated(0, 0, 100); + this.drawCenteredString( + mc.fontRenderer, + displayString, + this.xPosition + this.width / 2, + this.yPosition + (this.height - 8) / 2, + l); + GL11.glTranslated(0, 0, -100); + GL11.glColor4d(1, 1, 1, 1); + } + + @Override + public void guiTick() {} + } } diff --git a/src/main/java/DummyCore/Client/GuiMainMenuOld.java b/src/main/java/DummyCore/Client/GuiMainMenuOld.java index ca4de0b..c8ba29d 100644 --- a/src/main/java/DummyCore/Client/GuiMainMenuOld.java +++ b/src/main/java/DummyCore/Client/GuiMainMenuOld.java @@ -1,19 +1,15 @@ package DummyCore.Client; +import DummyCore.Utils.IMainMenu; +import com.google.common.base.Strings; +import com.google.common.collect.Lists; +import cpw.mods.fml.common.FMLCommonHandler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Random; - -import org.apache.commons.io.Charsets; -import org.lwjgl.opengl.GL11; - -import com.google.common.base.Strings; -import com.google.common.collect.Lists; - -import cpw.mods.fml.common.FMLCommonHandler; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; @@ -24,68 +20,60 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.ForgeHooksClient; -import DummyCore.Utils.IMainMenu; +import org.apache.commons.io.Charsets; +import org.lwjgl.opengl.GL11; -public class GuiMainMenuOld extends GuiMainMenu implements IMainMenu{ +public class GuiMainMenuOld extends GuiMainMenu implements IMainMenu { - private static final ResourceLocation minecraftTitleTextures = new ResourceLocation("textures/gui/title/minecraft.png"); - private String splashText; - protected static final ResourceLocation buttonTextures = new ResourceLocation("textures/gui/widgets.png"); - private static final Random rand = new Random(); private static final ResourceLocation splashTexts = new ResourceLocation("texts/splashes.txt"); - - public void initGui() - { - super.initGui(); - BufferedReader bufferedreader = null; + private static final ResourceLocation minecraftTitleTextures = + new ResourceLocation("textures/gui/title/minecraft.png"); + private String splashText; + protected static final ResourceLocation buttonTextures = new ResourceLocation("textures/gui/widgets.png"); + private static final Random rand = new Random(); + private static final ResourceLocation splashTexts = new ResourceLocation("texts/splashes.txt"); - try - { - ArrayList arraylist = new ArrayList(); - bufferedreader = new BufferedReader(new InputStreamReader(Minecraft.getMinecraft().getResourceManager().getResource(splashTexts).getInputStream(), Charsets.UTF_8)); - String s; + public void initGui() { + super.initGui(); + BufferedReader bufferedreader = null; - while ((s = bufferedreader.readLine()) != null) - { - s = s.trim(); + try { + ArrayList arraylist = new ArrayList(); + bufferedreader = new BufferedReader(new InputStreamReader( + Minecraft.getMinecraft() + .getResourceManager() + .getResource(splashTexts) + .getInputStream(), + Charsets.UTF_8)); + String s; - if (!s.isEmpty()) - { - arraylist.add(s); - } - } + while ((s = bufferedreader.readLine()) != null) { + s = s.trim(); - if (!arraylist.isEmpty()) - { - do - { - this.splashText = (String)arraylist.get(rand.nextInt(arraylist.size())); - } - while (this.splashText.hashCode() == 125780783); - } - } - catch (IOException ioexception1) - { - - } - finally - { - if (bufferedreader != null) - { - try - { - bufferedreader.close(); - } - catch (IOException ioexception) - { - - } - } - } - } - - @Override - public void drawScreen(int p_73863_1_, int p_73863_2_, float p_73863_3_) - { + if (!s.isEmpty()) { + arraylist.add(s); + } + } + + if (!arraylist.isEmpty()) { + do { + this.splashText = (String) arraylist.get(rand.nextInt(arraylist.size())); + } while (this.splashText.hashCode() == 125780783); + } + } catch (IOException ioexception1) { + + } finally { + if (bufferedreader != null) { + try { + bufferedreader.close(); + } catch (IOException ioexception) { + + } + } + } + } + + @Override + public void drawScreen(int p_73863_1_, int p_73863_2_, float p_73863_3_) { Tessellator tessellator = Tessellator.instance; short short1 = 274; int k = this.width / 2 - short1 / 2; @@ -102,76 +90,92 @@ public class GuiMainMenuOld extends GuiMainMenu implements IMainMenu{ tessellator.setColorOpaque_I(-1); GL11.glPushMatrix(); - GL11.glTranslatef((float)(this.width / 2 + 90), 70.0F, 0.0F); + GL11.glTranslatef((float) (this.width / 2 + 90), 70.0F, 0.0F); GL11.glRotatef(-20.0F, 0.0F, 0.0F, 1.0F); - float f1 = 1.8F - MathHelper.abs(MathHelper.sin((float)(Minecraft.getSystemTime() % 1000L) / 1000.0F * (float)Math.PI * 2.0F) * 0.1F); - f1 = f1 * 100.0F / (float)(this.fontRendererObj.getStringWidth(this.splashText) + 32); + float f1 = 1.8F + - MathHelper.abs( + MathHelper.sin((float) (Minecraft.getSystemTime() % 1000L) / 1000.0F * (float) Math.PI * 2.0F) + * 0.1F); + f1 = f1 * 100.0F / (float) (this.fontRendererObj.getStringWidth(this.splashText) + 32); GL11.glScalef(f1, f1, f1); this.drawCenteredString(this.fontRendererObj, this.splashText, 0, -8, -256); GL11.glPopMatrix(); String s = "Minecraft 1.7.10"; - if (this.mc.isDemo()) - { + if (this.mc.isDemo()) { s = s + " Demo"; } List brandings = Lists.reverse(FMLCommonHandler.instance().getBrandings(true)); - for (int i = 0; i < brandings.size(); i++) - { + for (int i = 0; i < brandings.size(); i++) { String brd = brandings.get(i); - if (!Strings.isNullOrEmpty(brd)) - { - this.drawString(this.fontRendererObj, brd, 2, this.height - ( 10 + i * (this.fontRendererObj.FONT_HEIGHT + 1)), 16777215); + if (!Strings.isNullOrEmpty(brd)) { + this.drawString( + this.fontRendererObj, + brd, + 2, + this.height - (10 + i * (this.fontRendererObj.FONT_HEIGHT + 1)), + 16777215); } } ForgeHooksClient.renderMainMenu(this, fontRendererObj, width, height); String s1 = "Copyright Mojang AB. Do not distribute!"; - this.drawString(this.fontRendererObj, s1, this.width - this.fontRendererObj.getStringWidth(s1) - 2, this.height - 10, -1); + this.drawString( + this.fontRendererObj, + s1, + this.width - this.fontRendererObj.getStringWidth(s1) - 2, + this.height - 10, + -1); int k1; - for (k1 = 0; k1 < this.buttonList.size(); ++k1) - { - drawButton(((GuiButton)this.buttonList.get(k1)),this.mc, p_73863_1_, p_73863_2_); + for (k1 = 0; k1 < this.buttonList.size(); ++k1) { + drawButton(((GuiButton) this.buttonList.get(k1)), this.mc, p_73863_1_, p_73863_2_); } - for (k1 = 0; k1 < this.labelList.size(); ++k1) - { - ((GuiLabel)this.labelList.get(k1)).func_146159_a(this.mc, p_73863_1_, p_73863_2_); + for (k1 = 0; k1 < this.labelList.size(); ++k1) { + ((GuiLabel) this.labelList.get(k1)).func_146159_a(this.mc, p_73863_1_, p_73863_2_); } } - - public void drawButton(GuiButton button,Minecraft p_146112_1_, int p_146112_2_, int p_146112_3_) - { - if (button.enabled) - { + + public void drawButton(GuiButton button, Minecraft p_146112_1_, int p_146112_2_, int p_146112_3_) { + if (button.enabled) { FontRenderer fontrenderer = p_146112_1_.fontRenderer; p_146112_1_.getTextureManager().bindTexture(buttonTextures); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - boolean field_146123_n = p_146112_2_ >= button.xPosition && p_146112_3_ >= button.yPosition && p_146112_2_ < button.xPosition + button.width && p_146112_3_ < button.yPosition + button.height; + boolean field_146123_n = p_146112_2_ >= button.xPosition + && p_146112_3_ >= button.yPosition + && p_146112_2_ < button.xPosition + button.width + && p_146112_3_ < button.yPosition + button.height; int k = button.getHoverState(field_146123_n); GL11.glEnable(GL11.GL_BLEND); OpenGlHelper.glBlendFunc(770, 771, 1, 0); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - this.drawTexturedModalRect(button.xPosition, button.yPosition, 0, 46 + k * 20, button.width / 2, button.height); - this.drawTexturedModalRect(button.xPosition + button.width / 2, button.yPosition, 200 - button.width / 2, 46 + k * 20, button.width / 2, button.height); + this.drawTexturedModalRect( + button.xPosition, button.yPosition, 0, 46 + k * 20, button.width / 2, button.height); + this.drawTexturedModalRect( + button.xPosition + button.width / 2, + button.yPosition, + 200 - button.width / 2, + 46 + k * 20, + button.width / 2, + button.height); int l = 14737632; - if (button.packedFGColour != 0) - { + if (button.packedFGColour != 0) { l = button.packedFGColour; - } - else if (!button.enabled) - { + } else if (!button.enabled) { l = 10526880; - } - else if (button.getHoverState(true) == 0) - { + } else if (button.getHoverState(true) == 0) { l = 16777120; } - this.drawCenteredString(fontrenderer, button.displayString, button.xPosition + button.width / 2, button.yPosition + (button.height - 8) / 2, l); + this.drawCenteredString( + fontrenderer, + button.displayString, + button.xPosition + button.width / 2, + button.yPosition + (button.height - 8) / 2, + l); } } } diff --git a/src/main/java/DummyCore/Client/GuiMainMenuVanilla.java b/src/main/java/DummyCore/Client/GuiMainMenuVanilla.java index e7c6367..00c8e3f 100644 --- a/src/main/java/DummyCore/Client/GuiMainMenuVanilla.java +++ b/src/main/java/DummyCore/Client/GuiMainMenuVanilla.java @@ -1,8 +1,6 @@ package DummyCore.Client; -import net.minecraft.client.gui.GuiMainMenu; import DummyCore.Utils.IMainMenu; +import net.minecraft.client.gui.GuiMainMenu; -public class GuiMainMenuVanilla extends GuiMainMenu implements IMainMenu{ - -} +public class GuiMainMenuVanilla extends GuiMainMenu implements IMainMenu {} diff --git a/src/main/java/DummyCore/Client/GuiMenuList.java b/src/main/java/DummyCore/Client/GuiMenuList.java index 314013a..c52a6f0 100644 --- a/src/main/java/DummyCore/Client/GuiMenuList.java +++ b/src/main/java/DummyCore/Client/GuiMenuList.java @@ -1,26 +1,24 @@ package DummyCore.Client; -import org.lwjgl.opengl.GL11; - import DummyCore.Utils.DummyConfig; import DummyCore.Utils.DummyData; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; +import org.lwjgl.opengl.GL11; + +public class GuiMenuList extends GuiScreen { -public class GuiMenuList extends GuiScreen{ - private GuiScreen mainMenu; private GuiSlotMenuList modList; private int selected = -1; private Class selectedMod; private int listWidth; - public GuiMenuList(GuiScreen mainMenu) - { - this.mainMenu=mainMenu; + + public GuiMenuList(GuiScreen mainMenu) { + this.mainMenu = mainMenu; } /** @@ -28,26 +26,22 @@ public class GuiMenuList extends GuiScreen{ */ @SuppressWarnings("unchecked") @Override - public void initGui() - { + public void initGui() { for (DummyData data : MainMenuRegistry.menuInfoLst) { - listWidth=Math.max(listWidth,getFontRenderer().getStringWidth(data.fieldName) + 10); - listWidth=Math.max(listWidth,getFontRenderer().getStringWidth(data.fieldValue) + 10); + listWidth = Math.max(listWidth, getFontRenderer().getStringWidth(data.fieldName) + 10); + listWidth = Math.max(listWidth, getFontRenderer().getStringWidth(data.fieldValue) + 10); } - listWidth=Math.min(listWidth, 150); + listWidth = Math.min(listWidth, 150); this.buttonList.add(new GuiButton(6, this.width / 2 - 75, this.height - 38, I18n.format("gui.done"))); - this.modList=new GuiSlotMenuList(this, listWidth); + this.modList = new GuiSlotMenuList(this, listWidth); this.modList.registerScrollButtons(this.buttonList, 7, 8); } @Override protected void actionPerformed(GuiButton button) { - if (button.enabled) - { - switch (button.id) - { - case 6: - { + if (button.enabled) { + switch (button.id) { + case 6: { this.mc.displayGuiScreen(this.mainMenu); return; } @@ -56,8 +50,7 @@ public class GuiMenuList extends GuiScreen{ super.actionPerformed(button); } - public int drawLine(String line, int offset, int shifty) - { + public int drawLine(String line, int offset, int shifty) { this.fontRendererObj.drawString(line, offset, shifty, 0xd7edea); return shifty + 10; } @@ -66,17 +59,15 @@ public class GuiMenuList extends GuiScreen{ * Draws the screen and all the components in it. */ @Override - public void drawScreen(int p_571_1_, int p_571_2_, float p_571_3_) - { + public void drawScreen(int p_571_1_, int p_571_2_, float p_571_3_) { this.modList.drawScreen(p_571_1_, p_571_2_, p_571_3_); this.drawCenteredString(this.fontRendererObj, "Menu List", this.width / 2, 16, 0xFFFFFF); - int offset = this.listWidth + 20; - if (selectedMod != null) - { - DummyData data = MainMenuRegistry.menuInfoLst.get(selected); + int offset = this.listWidth + 20; + if (selectedMod != null) { + DummyData data = MainMenuRegistry.menuInfoLst.get(selected); GL11.glEnable(GL11.GL_BLEND); - { - offset = ( this.listWidth + this.width ) / 2; + { + offset = (this.listWidth + this.width) / 2; this.drawCenteredString(this.fontRendererObj, data.fieldName, offset, 35, 0xFFFFFF); this.drawCenteredString(this.fontRendererObj, data.fieldValue, offset, 45, 0xFFFFFF); } @@ -98,19 +89,17 @@ public class GuiMenuList extends GuiScreen{ /** * @param var1 */ - public void selectIndex(int var1) - { - this.selected=var1; - if (var1>=0 && var1<=MainMenuRegistry.menuList.size()) { - this.selectedMod=MainMenuRegistry.menuList.get(selected); + public void selectIndex(int var1) { + this.selected = var1; + if (var1 >= 0 && var1 <= MainMenuRegistry.menuList.size()) { + this.selectedMod = MainMenuRegistry.menuList.get(selected); } else { - this.selectedMod=null; + this.selectedMod = null; } DummyConfig.setMainMenu(selected); } - public boolean indexSelected(int var1) - { - return var1==selected; + public boolean indexSelected(int var1) { + return var1 == selected; } } diff --git a/src/main/java/DummyCore/Client/GuiSlotMenuList.java b/src/main/java/DummyCore/Client/GuiSlotMenuList.java index aeacfe5..16eb14e 100644 --- a/src/main/java/DummyCore/Client/GuiSlotMenuList.java +++ b/src/main/java/DummyCore/Client/GuiSlotMenuList.java @@ -1,56 +1,60 @@ package DummyCore.Client; import DummyCore.Utils.DummyData; +import cpw.mods.fml.client.GuiScrollingList; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; -import cpw.mods.fml.client.GuiScrollingList; public class GuiSlotMenuList extends GuiScrollingList { - + private GuiMenuList parent; - public GuiSlotMenuList(GuiMenuList parent, int listWidth) - { + public GuiSlotMenuList(GuiMenuList parent, int listWidth) { super(Minecraft.getMinecraft(), listWidth, parent.height, 32, parent.height - 66 + 4, 10, 35); - this.parent=parent; + this.parent = parent; } @Override - protected int getSize() - { + protected int getSize() { return MainMenuRegistry.menuList.size(); } @Override - protected void elementClicked(int var1, boolean var2) - { + protected void elementClicked(int var1, boolean var2) { this.parent.selectIndex(var1); } @Override - protected boolean isSelected(int var1) - { + protected boolean isSelected(int var1) { return this.parent.indexSelected(var1); } @Override - protected void drawBackground() - { + protected void drawBackground() { this.parent.drawDefaultBackground(); } @Override - protected int getContentHeight() - { + protected int getContentHeight() { return (this.getSize()) * 35 + 1; } @Override - protected void drawSlot(int listIndex, int var2, int var3, int var4, Tessellator var5) - { + protected void drawSlot(int listIndex, int var2, int var3, int var4, Tessellator var5) { DummyData data = MainMenuRegistry.menuInfoLst.get(listIndex); - this.parent.getFontRenderer().drawString(this.parent.getFontRenderer().trimStringToWidth(data.fieldName, listWidth - 10), this.left + 3 , var3 + 2, 0xFFFFFF); - this.parent.getFontRenderer().drawString(this.parent.getFontRenderer().trimStringToWidth(data.fieldValue, listWidth - 10), this.left + 3 , var3 + 12, 0xCCCCCC); + this.parent + .getFontRenderer() + .drawString( + this.parent.getFontRenderer().trimStringToWidth(data.fieldName, listWidth - 10), + this.left + 3, + var3 + 2, + 0xFFFFFF); + this.parent + .getFontRenderer() + .drawString( + this.parent.getFontRenderer().trimStringToWidth(data.fieldValue, listWidth - 10), + this.left + 3, + var3 + 12, + 0xCCCCCC); } - } diff --git a/src/main/java/DummyCore/Client/MainMenuGUIRenderer.java b/src/main/java/DummyCore/Client/MainMenuGUIRenderer.java index d620866..335210f 100644 --- a/src/main/java/DummyCore/Client/MainMenuGUIRenderer.java +++ b/src/main/java/DummyCore/Client/MainMenuGUIRenderer.java @@ -3,16 +3,12 @@ package DummyCore.Client; import DummyCore.Utils.IMainMenu; public class MainMenuGUIRenderer { - - public static IMainMenu currentScreenBeingRendered; - - public static void setCurrentGUI(IMainMenu menu) - { - currentScreenBeingRendered = menu; - } - - public static void initGui() - { - } + public static IMainMenu currentScreenBeingRendered; + + public static void setCurrentGUI(IMainMenu menu) { + currentScreenBeingRendered = menu; + } + + public static void initGui() {} } diff --git a/src/main/java/DummyCore/Client/MainMenuRegistry.java b/src/main/java/DummyCore/Client/MainMenuRegistry.java index c01400c..9ba0971 100644 --- a/src/main/java/DummyCore/Client/MainMenuRegistry.java +++ b/src/main/java/DummyCore/Client/MainMenuRegistry.java @@ -1,5 +1,12 @@ package DummyCore.Client; +import DummyCore.Core.Core; +import DummyCore.Utils.DummyConfig; +import DummyCore.Utils.DummyData; +import DummyCore.Utils.IMainMenu; +import DummyCore.Utils.LoadingUtils; +import DummyCore.Utils.Notifier; +import com.google.common.collect.Iterators; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -8,7 +15,6 @@ import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; - import joptsimple.internal.Strings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; @@ -16,529 +22,519 @@ import net.minecraft.client.gui.GuiScreen; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; import net.minecraft.nbt.NBTTagCompound; - import org.apache.commons.io.IOUtils; -import DummyCore.Core.Core; -import DummyCore.Utils.DummyConfig; -import DummyCore.Utils.DummyData; -import DummyCore.Utils.IMainMenu; -import DummyCore.Utils.LoadingUtils; -import DummyCore.Utils.Notifier; - -import com.google.common.collect.Iterators; - public class MainMenuRegistry { - - public static List> menuList = new ArrayList>(); - public static List tagsToMenu = new ArrayList(); - - public static List menuInfoLst = new ArrayList(); - - public static boolean isGuiDisplayed; - - public static GuiScreen currentScreen; - - public static Class clazz = MainMenuRegistry.class; - - public static void registerNewGui(Class menu) - { - if(IMainMenu.class.isAssignableFrom(menu)) - { - menuList.add(menu); - menuInfoLst.add(new DummyData(menu.getName(),"No description provided by author ;(")); - }else - { - Notifier.notifyCustomMod("DummyCore", "Attempting to register "+menu+" as a main menu, but the registered object does not implements IMainMenu!"); - } - } - - public static void registerNewGui(Class menu, String name, String description) - { - if(IMainMenu.class.isAssignableFrom(menu)) - { - menuList.add(menu); - menuInfoLst.add(new DummyData(name,description)); - }else - { - Notifier.notifyCustomMod("DummyCore", "Attempting to register "+menu+" as a main menu, but the registered object does not implements IMainMenu!"); - } - } - - public static void newMainMenu(int index) - { - try - { - if(menuList.size() < index) - { - index = menuList.size()-1; - } - DummyConfig.setMainMenu(index); - currentScreen = menuList.get(DummyConfig.getMainMenu()).newInstance(); - Minecraft.getMinecraft().displayGuiScreen(currentScreen); - }catch(Exception e) - { - e.printStackTrace(); - return; - } - } - - public static GuiScreen getGuiDisplayed() - { - Minecraft mc = Minecraft.getMinecraft(); - if(mc.currentScreen != null && mc.currentScreen.getClass() != GuiMainMenu.class && mc.currentScreen instanceof IMainMenu) - return mc.currentScreen; - if(currentScreen != null) - return currentScreen; - try - { - return menuList.get(DummyConfig.getMainMenu()).newInstance(); - } - catch (Exception e) - { - e.printStackTrace(); - return null; - } - } - - public static void registerMenuConfigs() - { - Iterator $i = tagsToMenu.iterator(); - while($i.hasNext()) - { - NBTTagCompound tag = $i.next(); - registerNewGui(GuiMainMenuNBT.class,tag.getString("menuName"),tag.getString("menuDesc")); - GuiMainMenuNBT.idToTagMapping.put(menuList.size()-1, tag); - } - tagsToMenu.clear(); - } - - public static void createHelpFile(File dir) throws IOException - { - dir.mkdirs(); - File txtFile = new File(dir,"help.txt"); - if(!txtFile.exists()) - txtFile.createNewFile(); - PrintWriter pw = new PrintWriter(txtFile); - pw.println(Strings.repeat('=', 128)); - pw.println("Welcome to DummyCore's main menu help file"); - pw.println("It got created automatically and exists to teach you how to create Main Menu using files"); - pw.println("You can delete this file if it is not necessary. It will get sad though :("); - pw.println(Strings.repeat('=', 128)); - pw.println("Part 0: Bases"); - pw.println(Strings.repeat('=', 128)); - pw.println("To create your own custom main menu using DummyCore the following conditions must be met:"); - pw.println("a)You need to create a file with any name in this directory"); - pw.println("b)The file needs to have a .dcmenu extension"); - pw.println("c)The file must be a text file with UTF-8 encoding"); - pw.println("d)The file must contain valid JSON syntax within"); - pw.println("e)The file must contain both menuName and menuDesc strings declared"); - pw.println("A small example of a correct file:"); - pw.println(""); - pw.println("{"); - pw.println(" menuName:\"I am a menu name!\","); - pw.println(" menuDesc:\"I am a menu description!\""); - pw.println("}"); - pw.println(""); - pw.println(Strings.repeat('=', 128)); - pw.println("Part 1: Textures"); - pw.println(Strings.repeat('=', 128)); - pw.println("You can control the way your menu renders in the game. For that it needs to have the following declared:"); - pw.println("Your file must either contain an array of NBT(FadeTime:Integer and Texture:String) called Textures, or a String called Texture"); - pw.println("Your file must also contain a MenuType Integer representing the way your texture gets rendered"); - pw.println("Valid render types:"); - pw.println("-1 Will not render your menu"); - pw.println("0 Will render the image given as a Texture String, with scaling it so it takes all the screen"); - pw.println("1 Will render 6 images declared in the Textures NBT Array(Integer FadeTime takes no effect) just as vanilla MC does"); - pw.println("2 Will render 1 small texture given as a Texture String, repeating it all across the screen"); - pw.println("3 Will render N textures given in the Textures NBT Array with Texture String, leaving 1 texture for the time given in the Textures NBT Array with the FadeTime integer"); - pw.println("4 Will render N textures given in the Textures NBT Array with fading one over another with the time given in the Textures NBT Array with the OverlayTime Integer and rendering each image FadeTime Integer ticks"); - pw.println("5 Will render a .gif image declared in Texture String(This one might require 'not 10 years outdated OpenGL', though my videocard(read - crap) works fine)."); - pw.println("[GIF]To specify delay between frames you can use FrameDelay(Integer) to specify the delay for all frames, or FramesDelay(NBT Tag containing Integers) to specify delay for each frame specific. Delay is in ticks!"); - pw.println("[GIF]FramesDelay must contain FrameNumber:FrameTime. Example would be FramesDelay{0:5,1:3,4:12}. This will set the delay for frame 0 to 5 ticks, frame 1 gets 3 ticks and frmae 4 gets 12 ticks. All others get FrameDelay, or 0 if no specified"); - pw.println("[GIF]Please, for your own mental health use Forge's loading screen gif as an example, otherwise you are going to rage struggling to make this thing work. You've been warned!"); - pw.println("You can also add 2 Integer tags: GradientStart and GradientEnd. They are your gradient colors, rendered above your image."); - pw.println("Use HEX(4 digit!(RGBA(Red Green Blue Alpha))) color as your color and any HEX -> Deciminary converter to find out your color number"); - pw.println("If you are using menu type 2(1 image across the GUI) you need to specify the amount of times the image is repeated across the GUI(or the scale of each individual image)"); - pw.println("This is done by adding TextureRepeats(Integer) to the tag. The more the number - the smaller the image will be, but the more repeated it will be. Default MC uses 10. You may not specify this field, the default value will be used then"); - pw.println("Valid example of a simple 4 repeating textures menu:"); - pw.println(""); - pw.println("{"); - pw.println(" menuName:\"I am a menu name!\","); - pw.println(" menuDesc:\"I am a menu description!\","); - pw.println(" MenuType:3,"); - pw.println(" Textures:["); - pw.println(" {"); - pw.println(" Texture:\"examplemodid:textures/menu/MenuImage0.png\","); - pw.println(" FadeTime:100"); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"examplemodid:textures/menu/MenuImage1.png\","); - pw.println(" FadeTime:100"); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"examplemodid:textures/menu/MenuImage2.png\","); - pw.println(" FadeTime:100"); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"examplemodid:textures/menu/MenuImage3.png\","); - pw.println(" FadeTime:100"); - pw.println(" }"); - pw.println(" ]"); - pw.println("}"); - pw.println(""); - pw.println(Strings.repeat('=', 128)); - pw.println("Part 2: Music"); - pw.println(Strings.repeat('=', 128)); - pw.println("You can also include your custom music with DummyCore!"); - pw.println("To include your music you would need to declare it with an NBT Array with Music String(must be registered via sounds.json)"); - pw.println("The array itself must also be named Music and can contain up to infinite music tags"); - pw.println("The music will randomly get chosen in the menu once there is no music playing"); - pw.println("Valid example of a simple 3 music tracks menu:"); - pw.println(""); - pw.println("{"); - pw.println(" menuName:\"I am a menu name!\","); - pw.println(" menuDesc:\"I am a menu description!\","); - pw.println(" Music:["); - pw.println(" {Music:\"examplemodid:music.MenuMusic0\"},"); - pw.println(" {Music:\"examplemodid:music.MenuMusic1\"},"); - pw.println(" {Music:\"examplemodid:music.MenuMusic2\"}"); - pw.println(" ]"); - pw.println("}"); - pw.println(""); - pw.println(Strings.repeat('=', 128)); - pw.println("Part 3: Custom Images"); - pw.println(Strings.repeat('=', 128)); - pw.println("DummyCore allows you to add custom images to your menu(like MC text)"); - pw.println("To add them you need to declare them within NBT Array called Images"); - pw.println("The NBT inside the array can contain the following tags:"); - pw.println("Texture(String) is a link to your image. Must be written as modid:texturepath, and can be either .png or .gif"); - pw.println("XAlignment(Integer) and YAlignment(Integer) is a way to represent the image's default position, before applying x and y translations."); - pw.println("XAlignment(Integer) and YAlignment(Integer) can have the following Integers:"); - pw.println(" 0 - means the default position will be 0(top left)"); - pw.println(" 1 - means the default position will be in the center(middle, duh)"); - pw.println(" 2 - means the default position will be in the bottom right corner"); - pw.println(" anything>2 - means the default position will be guiSize/value"); - pw.println(" Both those entries can have different values"); - pw.println("X(Integer) and Y(Integer) is defaultPosition + X or Y, so they are your offsets"); - pw.println("TextureMinX(Integer) and TextureMinY(Integer) is the start position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); - pw.println("TextureMaxX(Integer) and TextureMaxY(Integer) is the end position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); - pw.println("Alternatively you can use MinU, MinV, MaxU and MaxV doubles - these represent the texturePosition/textureSize. Only use if you know how that works. Allows for more custom HD texture positioning"); - pw.println("XSize(Integer) and YSize(Integer) is the size of your texture in the GUI."); - pw.println("Text(NBT Array) allows you to declare custom text to be displayed somewhere near your image"); - pw.println("Text(NBT Array) can have up to infinite tags. Each tag needs to contain X(Integer), Y(Integer) and Text(String) values. The text is positioned the same way the image is. Text will be rendered as a splash if it has a |Splash| prefix. Can also contain Splashes(Text) link to a splashes.txt file and Angle(Float) to rotate the splashes text"); - pw.println("Valid example of a menu with Minecraft image:"); - pw.println("Notice, that there are 2 images, due to minecraft.png actually having a split texture"); - pw.println(""); - pw.println("{"); - pw.println(" menuName:\"I am a menu name!\","); - pw.println(" menuDesc:\"I am a menu description!\","); - pw.println(" Images:["); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/title/minecraft.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:0,"); - pw.println(" X:-137,"); - pw.println(" Y:30,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:0,"); - pw.println(" TextureMaxX:155,"); - pw.println(" TextureMaxY:44,"); - pw.println(" XSize:155,"); - pw.println(" YSize:44"); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/title/minecraft.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:0,"); - pw.println(" X:18,"); - pw.println(" Y:30,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:45,"); - pw.println(" TextureMaxX:155,"); - pw.println(" TextureMaxY:89,"); - pw.println(" XSize:155,"); - pw.println(" YSize:44,"); - pw.println(" Text:["); - pw.println(" {"); - pw.println(" X:112,"); - pw.println(" Y:48,"); - pw.println(" Splashes:\"minecraft:texts/splashes.txt\","); - pw.println(" Angle:-20.0"); - pw.println(" }"); - pw.println(" ]"); - pw.println(" }"); - pw.println(" ]"); - pw.println("}"); - pw.println(""); - pw.println(Strings.repeat('=', 128)); - pw.println("Part 4: Custom Buttons"); - pw.println(Strings.repeat('=', 128)); - pw.println("DummyCore allows you to add custom buttons to your menu"); - pw.println("To add them you need to declare them within NBT Array called Buttons"); - pw.println("Each NBT in the array can have the following declared within:"); - pw.println(" Texture(String) is a link to the button's image. Must be written as modid:texturepath, and can be .png only"); - pw.println(" XAlignment(Integer) and YAlignment(Integer) is a way to represent the button's default position, before applying x and y translations."); - pw.println(" XAlignment(Integer) and YAlignment(Integer) can have the following Integers:"); - pw.println(" 0 - means the default position will be 0(top left)"); - pw.println(" 1 - means the default position will be in the center(middle, duh)"); - pw.println(" 2 - means the default position will be in the bottom right corner"); - pw.println(" anything>2 - means the default position will be guiSize/value"); - pw.println(" X(Integer) and Y(Integer) is defaultPosition + X or Y, so they are your offsets"); - pw.println(" TextureMinX(Integer) and TextureMinY(Integer) is the start position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); - pw.println(" TextureMaxX(Integer) and TextureMaxY(Integer) is the end position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); - pw.println(" Alternatively you can use MinU, MinV, MaxU and MaxV doubles - these represent the texturePosition/textureSize. Only use if you know how that works. Allows for more custom HD texture positioning"); - pw.println(" XSize(Integer) and YSize(Integer) is the size of your button in the GUI."); - pw.println(" ButtonYOffset(Integer) is the amount of pixels the button texture will be offset on the texture file to get the button's disabled and mouseover textures"); - pw.println(" Alternatively can be ButtonYUVOffset double"); - pw.println(" ButtonID(Integer) is the ID of the button. Valid IDs I know of:"); - pw.println(" 0 - Options Button"); - pw.println(" 1 - Singleplayer Button"); - pw.println(" 2 - Multiplayer Button"); - pw.println(" 3 - Empty"); - pw.println(" 4 - Quit Button"); - pw.println(" 5 - Language Button"); - pw.println(" 6 - Mod List Button"); - pw.println(" 7 - Empty"); - pw.println(" 8 - Empty"); - pw.println(" 9 - Empty"); - pw.println(" 10 - Empty"); - pw.println(" 11 - Demo Singleplayer Button"); - pw.println(" 12 - Demo Reset Button"); - pw.println(" 13 - Empty"); - pw.println(" 65535 - DummyCore's change GUI Button"); - pw.println(" Sound(String) is a link to the button's press sound. Must be a registered(via sounds.json) sound"); - pw.println(" URL(String) is a URL link to any Internet website. Pressing the button will trigger site's page opening in the presser's browser"); - pw.println(" Text(String) is a text or a localization reference for the button"); - pw.println("Valid example of a menu with default Minecraft buttons:"); - pw.println(""); - pw.println("{"); - pw.println(" menuName:\"I am a menu name!\","); - pw.println(" menuDesc:\"I am a menu description!\","); - pw.println(" Buttons:["); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:4,"); - pw.println(" X:-100,"); - pw.println(" Y:132,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:46,"); - pw.println(" TextureMaxX:200,"); - pw.println(" TextureMaxY:66,"); - pw.println(" XSize:98,"); - pw.println(" YSize:20,"); - pw.println(" ButtonYOffset:20,"); - pw.println(" ButtonID:0,"); - pw.println(" Sound:\"gui.button.press\","); - pw.println(" Text:\"menu.options\""); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:4,"); - pw.println(" X:2,"); - pw.println(" Y:132,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:46,"); - pw.println(" TextureMaxX:200,"); - pw.println(" TextureMaxY:66,"); - pw.println(" XSize:98,"); - pw.println(" YSize:20,"); - pw.println(" ButtonYOffset:20,"); - pw.println(" ButtonID:4,"); - pw.println(" Sound:\"gui.button.press\","); - pw.println(" Text:\"menu.quit\""); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:4,"); - pw.println(" X:-124,"); - pw.println(" Y:132,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:86,"); - pw.println(" TextureMaxX:20,"); - pw.println(" TextureMaxY:106,"); - pw.println(" XSize:20,"); - pw.println(" YSize:20,"); - pw.println(" ButtonYOffset:20,"); - pw.println(" ButtonID:5,"); - pw.println(" Sound:\"gui.button.press\","); - pw.println(" Text:\"\""); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:4,"); - pw.println(" X:-100,"); - pw.println(" Y:48,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:46,"); - pw.println(" TextureMaxX:200,"); - pw.println(" TextureMaxY:66,"); - pw.println(" XSize:200,"); - pw.println(" YSize:20,"); - pw.println(" ButtonYOffset:20,"); - pw.println(" ButtonID:1,"); - pw.println(" Sound:\"gui.button.press\","); - pw.println(" Text:\"menu.singleplayer\""); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:4,"); - pw.println(" X:-100,"); - pw.println(" Y:72,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:46,"); - pw.println(" TextureMaxX:200,"); - pw.println(" TextureMaxY:66,"); - pw.println(" XSize:200,"); - pw.println(" YSize:20,"); - pw.println(" ButtonYOffset:20,"); - pw.println(" ButtonID:2,"); - pw.println(" Sound:\"gui.button.press\","); - pw.println(" Text:\"menu.multiplayer\""); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:4,"); - pw.println(" X:-100,"); - pw.println(" Y:96,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:46,"); - pw.println(" TextureMaxX:200,"); - pw.println(" TextureMaxY:66,"); - pw.println(" XSize:98,"); - pw.println(" YSize:20,"); - pw.println(" ButtonYOffset:20,"); - pw.println(" ButtonID:14,"); - pw.println(" Sound:\"gui.button.press\","); - pw.println(" Text:\"menu.online\""); - pw.println(" },"); - pw.println(" {"); - pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); - pw.println(" XAlignment:1,"); - pw.println(" YAlignment:4,"); - pw.println(" X:2,"); - pw.println(" Y:96,"); - pw.println(" TextureMinX:0,"); - pw.println(" TextureMinY:46,"); - pw.println(" TextureMaxX:200,"); - pw.println(" TextureMaxY:66,"); - pw.println(" XSize:98,"); - pw.println(" YSize:20,"); - pw.println(" ButtonYOffset:20,"); - pw.println(" ButtonID:6,"); - pw.println(" Sound:\"gui.button.press\","); - pw.println(" Text:\"Mods\""); - pw.println(" }"); - pw.println(" ]"); - pw.println("}"); - pw.println(""); - pw.println(Strings.repeat('=', 128)); - pw.println("Part 5: Custom Text"); - pw.println(Strings.repeat('=', 128)); - pw.println("DummyCore allows you to add custom text(bottom corners) to your menu"); - pw.println("Your menu tag needs to have 2 NBT Arrays(String) in order for this to work"); - pw.println("1 array is named TextLeft and 2 - TextRight"); - pw.println("You can insert 'symbolic links' in the text array"); - pw.println("For example, having a |FML| will add FML's current version to text"); - pw.println("Valid 'symbolic liknls':"); - pw.println(" |MC| prints Minecraft's current version"); - pw.println(" |MCP| prints MinecraftCoderPack's current version"); - pw.println(" |FML| prints FML's current version"); - pw.println(" |Forge| prints Forge's current version"); - pw.println(" |SidedInfo| prints FML's special sided information"); - pw.println(" |FMLBranding| prints FML's special brandings information"); - pw.println(" |Mods| prints current amount of mods loaded"); - pw.println(" |Copyright| prints Mojang's copyright"); - pw.println("Valid example of default main menu text:"); - pw.println(""); - pw.println("{"); - pw.println(" menuName:\"I am a menu name!\","); - pw.println(" menuDesc:\"I am a menu description!\","); - pw.println(" TextLeft:["); - pw.println(" \"|MC|\","); - pw.println(" \"|MCP|\","); - pw.println(" \"|FML|\","); - pw.println(" \"|Forge|\","); - pw.println(" \"|SidedInfo|\","); - pw.println(" \"|FMLBranding|\","); - pw.println(" \"|Mods|\""); - pw.println(" ],"); - pw.println(" TextRight:["); - pw.println(" \"|Copyright|\""); - pw.println(" ],"); - pw.println("}"); - pw.println(""); - pw.flush(); - pw.close(); - } - - public static void initMenuConfigs() - { - try - { - File dir = new File(Core.mcDir,"config"); - dir.mkdirs(); - dir = new File(dir,"dcMainMenu"); - if(!dir.exists()) - createHelpFile(dir); - File[] files = dir.listFiles(); - Iterator $i = Iterators.forArray(files); - while($i.hasNext()) - { - File detected = $i.next(); - if(detected.getName().endsWith(".dcmenu")) - { - FileInputStream fis = new FileInputStream(detected); - if(fis != null) - { - try - { - String st = IOUtils.toString(fis,"UTF-8"); - NBTTagCompound tag = (NBTTagCompound) JsonToNBT.func_150315_a(st); - if(validateNBT(tag)) - { - tagsToMenu.add(tag); - Notifier.notifySimple("[MainMenuRegistry]"+detected+" Is a valid main menu and has been send to parsing queue."); - }else - { - Notifier.notifyError("[MainMenuRegistry]"+detected+" Is not a valid menu!"); - } - } - catch(IOException ioe) - { - LoadingUtils.makeACrash("[MainMenuRegistry]Couldn't read file "+detected, clazz, ioe, false); - } - catch(UnsupportedCharsetException uce) - { - LoadingUtils.makeACrash("[MainMenuRegistry]UTF-8 is unsupported on your system(???)", clazz, uce, false); - } catch (NBTException nbte) - { - LoadingUtils.makeACrash("[MainMenuRegistry]"+detected+" Is not a valid menu!", clazz, nbte, false); - nbte.printStackTrace(); - } - finally - { - IOUtils.closeQuietly(fis); - } - } - } - } - } - catch(IOException ioe) - { - LoadingUtils.makeACrash("[MainMenuRegistry]Couldn't read files in your config directory", clazz, ioe, false); - } - } - - public static boolean validateNBT(NBTTagCompound tag) - { - return tag.hasKey("menuName") && tag.hasKey("menuDesc"); - } + public static List> menuList = new ArrayList>(); + public static List tagsToMenu = new ArrayList(); + + public static List menuInfoLst = new ArrayList(); + + public static boolean isGuiDisplayed; + + public static GuiScreen currentScreen; + + public static Class clazz = MainMenuRegistry.class; + + public static void registerNewGui(Class menu) { + if (IMainMenu.class.isAssignableFrom(menu)) { + menuList.add(menu); + menuInfoLst.add(new DummyData(menu.getName(), "No description provided by author ;(")); + } else { + Notifier.notifyCustomMod( + "DummyCore", + "Attempting to register " + menu + + " as a main menu, but the registered object does not implements IMainMenu!"); + } + } + + public static void registerNewGui(Class menu, String name, String description) { + if (IMainMenu.class.isAssignableFrom(menu)) { + menuList.add(menu); + menuInfoLst.add(new DummyData(name, description)); + } else { + Notifier.notifyCustomMod( + "DummyCore", + "Attempting to register " + menu + + " as a main menu, but the registered object does not implements IMainMenu!"); + } + } + + public static void newMainMenu(int index) { + try { + if (menuList.size() < index) { + index = menuList.size() - 1; + } + DummyConfig.setMainMenu(index); + currentScreen = menuList.get(DummyConfig.getMainMenu()).newInstance(); + Minecraft.getMinecraft().displayGuiScreen(currentScreen); + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + + public static GuiScreen getGuiDisplayed() { + Minecraft mc = Minecraft.getMinecraft(); + if (mc.currentScreen != null + && mc.currentScreen.getClass() != GuiMainMenu.class + && mc.currentScreen instanceof IMainMenu) return mc.currentScreen; + if (currentScreen != null) return currentScreen; + try { + return menuList.get(DummyConfig.getMainMenu()).newInstance(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static void registerMenuConfigs() { + Iterator $i = tagsToMenu.iterator(); + while ($i.hasNext()) { + NBTTagCompound tag = $i.next(); + registerNewGui(GuiMainMenuNBT.class, tag.getString("menuName"), tag.getString("menuDesc")); + GuiMainMenuNBT.idToTagMapping.put(menuList.size() - 1, tag); + } + tagsToMenu.clear(); + } + + public static void createHelpFile(File dir) throws IOException { + dir.mkdirs(); + File txtFile = new File(dir, "help.txt"); + if (!txtFile.exists()) txtFile.createNewFile(); + PrintWriter pw = new PrintWriter(txtFile); + pw.println(Strings.repeat('=', 128)); + pw.println("Welcome to DummyCore's main menu help file"); + pw.println("It got created automatically and exists to teach you how to create Main Menu using files"); + pw.println("You can delete this file if it is not necessary. It will get sad though :("); + pw.println(Strings.repeat('=', 128)); + pw.println("Part 0: Bases"); + pw.println(Strings.repeat('=', 128)); + pw.println("To create your own custom main menu using DummyCore the following conditions must be met:"); + pw.println("a)You need to create a file with any name in this directory"); + pw.println("b)The file needs to have a .dcmenu extension"); + pw.println("c)The file must be a text file with UTF-8 encoding"); + pw.println("d)The file must contain valid JSON syntax within"); + pw.println("e)The file must contain both menuName and menuDesc strings declared"); + pw.println("A small example of a correct file:"); + pw.println(""); + pw.println("{"); + pw.println(" menuName:\"I am a menu name!\","); + pw.println(" menuDesc:\"I am a menu description!\""); + pw.println("}"); + pw.println(""); + pw.println(Strings.repeat('=', 128)); + pw.println("Part 1: Textures"); + pw.println(Strings.repeat('=', 128)); + pw.println( + "You can control the way your menu renders in the game. For that it needs to have the following declared:"); + pw.println( + "Your file must either contain an array of NBT(FadeTime:Integer and Texture:String) called Textures, or a String called Texture"); + pw.println("Your file must also contain a MenuType Integer representing the way your texture gets rendered"); + pw.println("Valid render types:"); + pw.println("-1 Will not render your menu"); + pw.println("0 Will render the image given as a Texture String, with scaling it so it takes all the screen"); + pw.println( + "1 Will render 6 images declared in the Textures NBT Array(Integer FadeTime takes no effect) just as vanilla MC does"); + pw.println("2 Will render 1 small texture given as a Texture String, repeating it all across the screen"); + pw.println( + "3 Will render N textures given in the Textures NBT Array with Texture String, leaving 1 texture for the time given in the Textures NBT Array with the FadeTime integer"); + pw.println( + "4 Will render N textures given in the Textures NBT Array with fading one over another with the time given in the Textures NBT Array with the OverlayTime Integer and rendering each image FadeTime Integer ticks"); + pw.println( + "5 Will render a .gif image declared in Texture String(This one might require 'not 10 years outdated OpenGL', though my videocard(read - crap) works fine)."); + pw.println( + "[GIF]To specify delay between frames you can use FrameDelay(Integer) to specify the delay for all frames, or FramesDelay(NBT Tag containing Integers) to specify delay for each frame specific. Delay is in ticks!"); + pw.println( + "[GIF]FramesDelay must contain FrameNumber:FrameTime. Example would be FramesDelay{0:5,1:3,4:12}. This will set the delay for frame 0 to 5 ticks, frame 1 gets 3 ticks and frmae 4 gets 12 ticks. All others get FrameDelay, or 0 if no specified"); + pw.println( + "[GIF]Please, for your own mental health use Forge's loading screen gif as an example, otherwise you are going to rage struggling to make this thing work. You've been warned!"); + pw.println( + "You can also add 2 Integer tags: GradientStart and GradientEnd. They are your gradient colors, rendered above your image."); + pw.println( + "Use HEX(4 digit!(RGBA(Red Green Blue Alpha))) color as your color and any HEX -> Deciminary converter to find out your color number"); + pw.println( + "If you are using menu type 2(1 image across the GUI) you need to specify the amount of times the image is repeated across the GUI(or the scale of each individual image)"); + pw.println( + "This is done by adding TextureRepeats(Integer) to the tag. The more the number - the smaller the image will be, but the more repeated it will be. Default MC uses 10. You may not specify this field, the default value will be used then"); + pw.println("Valid example of a simple 4 repeating textures menu:"); + pw.println(""); + pw.println("{"); + pw.println(" menuName:\"I am a menu name!\","); + pw.println(" menuDesc:\"I am a menu description!\","); + pw.println(" MenuType:3,"); + pw.println(" Textures:["); + pw.println(" {"); + pw.println(" Texture:\"examplemodid:textures/menu/MenuImage0.png\","); + pw.println(" FadeTime:100"); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"examplemodid:textures/menu/MenuImage1.png\","); + pw.println(" FadeTime:100"); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"examplemodid:textures/menu/MenuImage2.png\","); + pw.println(" FadeTime:100"); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"examplemodid:textures/menu/MenuImage3.png\","); + pw.println(" FadeTime:100"); + pw.println(" }"); + pw.println(" ]"); + pw.println("}"); + pw.println(""); + pw.println(Strings.repeat('=', 128)); + pw.println("Part 2: Music"); + pw.println(Strings.repeat('=', 128)); + pw.println("You can also include your custom music with DummyCore!"); + pw.println( + "To include your music you would need to declare it with an NBT Array with Music String(must be registered via sounds.json)"); + pw.println("The array itself must also be named Music and can contain up to infinite music tags"); + pw.println("The music will randomly get chosen in the menu once there is no music playing"); + pw.println("Valid example of a simple 3 music tracks menu:"); + pw.println(""); + pw.println("{"); + pw.println(" menuName:\"I am a menu name!\","); + pw.println(" menuDesc:\"I am a menu description!\","); + pw.println(" Music:["); + pw.println(" {Music:\"examplemodid:music.MenuMusic0\"},"); + pw.println(" {Music:\"examplemodid:music.MenuMusic1\"},"); + pw.println(" {Music:\"examplemodid:music.MenuMusic2\"}"); + pw.println(" ]"); + pw.println("}"); + pw.println(""); + pw.println(Strings.repeat('=', 128)); + pw.println("Part 3: Custom Images"); + pw.println(Strings.repeat('=', 128)); + pw.println("DummyCore allows you to add custom images to your menu(like MC text)"); + pw.println("To add them you need to declare them within NBT Array called Images"); + pw.println("The NBT inside the array can contain the following tags:"); + pw.println( + "Texture(String) is a link to your image. Must be written as modid:texturepath, and can be either .png or .gif"); + pw.println( + "XAlignment(Integer) and YAlignment(Integer) is a way to represent the image's default position, before applying x and y translations."); + pw.println("XAlignment(Integer) and YAlignment(Integer) can have the following Integers:"); + pw.println(" 0 - means the default position will be 0(top left)"); + pw.println(" 1 - means the default position will be in the center(middle, duh)"); + pw.println(" 2 - means the default position will be in the bottom right corner"); + pw.println(" anything>2 - means the default position will be guiSize/value"); + pw.println(" Both those entries can have different values"); + pw.println("X(Integer) and Y(Integer) is defaultPosition + X or Y, so they are your offsets"); + pw.println( + "TextureMinX(Integer) and TextureMinY(Integer) is the start position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); + pw.println( + "TextureMaxX(Integer) and TextureMaxY(Integer) is the end position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); + pw.println( + "Alternatively you can use MinU, MinV, MaxU and MaxV doubles - these represent the texturePosition/textureSize. Only use if you know how that works. Allows for more custom HD texture positioning"); + pw.println("XSize(Integer) and YSize(Integer) is the size of your texture in the GUI."); + pw.println("Text(NBT Array) allows you to declare custom text to be displayed somewhere near your image"); + pw.println( + "Text(NBT Array) can have up to infinite tags. Each tag needs to contain X(Integer), Y(Integer) and Text(String) values. The text is positioned the same way the image is. Text will be rendered as a splash if it has a |Splash| prefix. Can also contain Splashes(Text) link to a splashes.txt file and Angle(Float) to rotate the splashes text"); + pw.println("Valid example of a menu with Minecraft image:"); + pw.println("Notice, that there are 2 images, due to minecraft.png actually having a split texture"); + pw.println(""); + pw.println("{"); + pw.println(" menuName:\"I am a menu name!\","); + pw.println(" menuDesc:\"I am a menu description!\","); + pw.println(" Images:["); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/title/minecraft.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:0,"); + pw.println(" X:-137,"); + pw.println(" Y:30,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:0,"); + pw.println(" TextureMaxX:155,"); + pw.println(" TextureMaxY:44,"); + pw.println(" XSize:155,"); + pw.println(" YSize:44"); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/title/minecraft.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:0,"); + pw.println(" X:18,"); + pw.println(" Y:30,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:45,"); + pw.println(" TextureMaxX:155,"); + pw.println(" TextureMaxY:89,"); + pw.println(" XSize:155,"); + pw.println(" YSize:44,"); + pw.println(" Text:["); + pw.println(" {"); + pw.println(" X:112,"); + pw.println(" Y:48,"); + pw.println(" Splashes:\"minecraft:texts/splashes.txt\","); + pw.println(" Angle:-20.0"); + pw.println(" }"); + pw.println(" ]"); + pw.println(" }"); + pw.println(" ]"); + pw.println("}"); + pw.println(""); + pw.println(Strings.repeat('=', 128)); + pw.println("Part 4: Custom Buttons"); + pw.println(Strings.repeat('=', 128)); + pw.println("DummyCore allows you to add custom buttons to your menu"); + pw.println("To add them you need to declare them within NBT Array called Buttons"); + pw.println("Each NBT in the array can have the following declared within:"); + pw.println( + " Texture(String) is a link to the button's image. Must be written as modid:texturepath, and can be .png only"); + pw.println( + " XAlignment(Integer) and YAlignment(Integer) is a way to represent the button's default position, before applying x and y translations."); + pw.println(" XAlignment(Integer) and YAlignment(Integer) can have the following Integers:"); + pw.println(" 0 - means the default position will be 0(top left)"); + pw.println(" 1 - means the default position will be in the center(middle, duh)"); + pw.println(" 2 - means the default position will be in the bottom right corner"); + pw.println(" anything>2 - means the default position will be guiSize/value"); + pw.println(" X(Integer) and Y(Integer) is defaultPosition + X or Y, so they are your offsets"); + pw.println( + " TextureMinX(Integer) and TextureMinY(Integer) is the start position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); + pw.println( + " TextureMaxX(Integer) and TextureMaxY(Integer) is the end position on your texture file(the file is considered to be 256x256, so making a bigger file will require you to perform additional calculations)"); + pw.println( + " Alternatively you can use MinU, MinV, MaxU and MaxV doubles - these represent the texturePosition/textureSize. Only use if you know how that works. Allows for more custom HD texture positioning"); + pw.println(" XSize(Integer) and YSize(Integer) is the size of your button in the GUI."); + pw.println( + " ButtonYOffset(Integer) is the amount of pixels the button texture will be offset on the texture file to get the button's disabled and mouseover textures"); + pw.println(" Alternatively can be ButtonYUVOffset double"); + pw.println(" ButtonID(Integer) is the ID of the button. Valid IDs I know of:"); + pw.println(" 0 - Options Button"); + pw.println(" 1 - Singleplayer Button"); + pw.println(" 2 - Multiplayer Button"); + pw.println(" 3 - Empty"); + pw.println(" 4 - Quit Button"); + pw.println(" 5 - Language Button"); + pw.println(" 6 - Mod List Button"); + pw.println(" 7 - Empty"); + pw.println(" 8 - Empty"); + pw.println(" 9 - Empty"); + pw.println(" 10 - Empty"); + pw.println(" 11 - Demo Singleplayer Button"); + pw.println(" 12 - Demo Reset Button"); + pw.println(" 13 - Empty"); + pw.println(" 65535 - DummyCore's change GUI Button"); + pw.println(" Sound(String) is a link to the button's press sound. Must be a registered(via sounds.json) sound"); + pw.println( + " URL(String) is a URL link to any Internet website. Pressing the button will trigger site's page opening in the presser's browser"); + pw.println(" Text(String) is a text or a localization reference for the button"); + pw.println("Valid example of a menu with default Minecraft buttons:"); + pw.println(""); + pw.println("{"); + pw.println(" menuName:\"I am a menu name!\","); + pw.println(" menuDesc:\"I am a menu description!\","); + pw.println(" Buttons:["); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:4,"); + pw.println(" X:-100,"); + pw.println(" Y:132,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:46,"); + pw.println(" TextureMaxX:200,"); + pw.println(" TextureMaxY:66,"); + pw.println(" XSize:98,"); + pw.println(" YSize:20,"); + pw.println(" ButtonYOffset:20,"); + pw.println(" ButtonID:0,"); + pw.println(" Sound:\"gui.button.press\","); + pw.println(" Text:\"menu.options\""); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:4,"); + pw.println(" X:2,"); + pw.println(" Y:132,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:46,"); + pw.println(" TextureMaxX:200,"); + pw.println(" TextureMaxY:66,"); + pw.println(" XSize:98,"); + pw.println(" YSize:20,"); + pw.println(" ButtonYOffset:20,"); + pw.println(" ButtonID:4,"); + pw.println(" Sound:\"gui.button.press\","); + pw.println(" Text:\"menu.quit\""); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:4,"); + pw.println(" X:-124,"); + pw.println(" Y:132,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:86,"); + pw.println(" TextureMaxX:20,"); + pw.println(" TextureMaxY:106,"); + pw.println(" XSize:20,"); + pw.println(" YSize:20,"); + pw.println(" ButtonYOffset:20,"); + pw.println(" ButtonID:5,"); + pw.println(" Sound:\"gui.button.press\","); + pw.println(" Text:\"\""); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:4,"); + pw.println(" X:-100,"); + pw.println(" Y:48,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:46,"); + pw.println(" TextureMaxX:200,"); + pw.println(" TextureMaxY:66,"); + pw.println(" XSize:200,"); + pw.println(" YSize:20,"); + pw.println(" ButtonYOffset:20,"); + pw.println(" ButtonID:1,"); + pw.println(" Sound:\"gui.button.press\","); + pw.println(" Text:\"menu.singleplayer\""); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:4,"); + pw.println(" X:-100,"); + pw.println(" Y:72,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:46,"); + pw.println(" TextureMaxX:200,"); + pw.println(" TextureMaxY:66,"); + pw.println(" XSize:200,"); + pw.println(" YSize:20,"); + pw.println(" ButtonYOffset:20,"); + pw.println(" ButtonID:2,"); + pw.println(" Sound:\"gui.button.press\","); + pw.println(" Text:\"menu.multiplayer\""); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:4,"); + pw.println(" X:-100,"); + pw.println(" Y:96,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:46,"); + pw.println(" TextureMaxX:200,"); + pw.println(" TextureMaxY:66,"); + pw.println(" XSize:98,"); + pw.println(" YSize:20,"); + pw.println(" ButtonYOffset:20,"); + pw.println(" ButtonID:14,"); + pw.println(" Sound:\"gui.button.press\","); + pw.println(" Text:\"menu.online\""); + pw.println(" },"); + pw.println(" {"); + pw.println(" Texture:\"minecraft:textures/gui/widgets.png\","); + pw.println(" XAlignment:1,"); + pw.println(" YAlignment:4,"); + pw.println(" X:2,"); + pw.println(" Y:96,"); + pw.println(" TextureMinX:0,"); + pw.println(" TextureMinY:46,"); + pw.println(" TextureMaxX:200,"); + pw.println(" TextureMaxY:66,"); + pw.println(" XSize:98,"); + pw.println(" YSize:20,"); + pw.println(" ButtonYOffset:20,"); + pw.println(" ButtonID:6,"); + pw.println(" Sound:\"gui.button.press\","); + pw.println(" Text:\"Mods\""); + pw.println(" }"); + pw.println(" ]"); + pw.println("}"); + pw.println(""); + pw.println(Strings.repeat('=', 128)); + pw.println("Part 5: Custom Text"); + pw.println(Strings.repeat('=', 128)); + pw.println("DummyCore allows you to add custom text(bottom corners) to your menu"); + pw.println("Your menu tag needs to have 2 NBT Arrays(String) in order for this to work"); + pw.println("1 array is named TextLeft and 2 - TextRight"); + pw.println("You can insert 'symbolic links' in the text array"); + pw.println("For example, having a |FML| will add FML's current version to text"); + pw.println("Valid 'symbolic liknls':"); + pw.println(" |MC| prints Minecraft's current version"); + pw.println(" |MCP| prints MinecraftCoderPack's current version"); + pw.println(" |FML| prints FML's current version"); + pw.println(" |Forge| prints Forge's current version"); + pw.println(" |SidedInfo| prints FML's special sided information"); + pw.println(" |FMLBranding| prints FML's special brandings information"); + pw.println(" |Mods| prints current amount of mods loaded"); + pw.println(" |Copyright| prints Mojang's copyright"); + pw.println("Valid example of default main menu text:"); + pw.println(""); + pw.println("{"); + pw.println(" menuName:\"I am a menu name!\","); + pw.println(" menuDesc:\"I am a menu description!\","); + pw.println(" TextLeft:["); + pw.println(" \"|MC|\","); + pw.println(" \"|MCP|\","); + pw.println(" \"|FML|\","); + pw.println(" \"|Forge|\","); + pw.println(" \"|SidedInfo|\","); + pw.println(" \"|FMLBranding|\","); + pw.println(" \"|Mods|\""); + pw.println(" ],"); + pw.println(" TextRight:["); + pw.println(" \"|Copyright|\""); + pw.println(" ],"); + pw.println("}"); + pw.println(""); + pw.flush(); + pw.close(); + } + + public static void initMenuConfigs() { + try { + File dir = new File(Core.mcDir, "config"); + dir.mkdirs(); + dir = new File(dir, "dcMainMenu"); + if (!dir.exists()) createHelpFile(dir); + File[] files = dir.listFiles(); + Iterator $i = Iterators.forArray(files); + while ($i.hasNext()) { + File detected = $i.next(); + if (detected.getName().endsWith(".dcmenu")) { + FileInputStream fis = new FileInputStream(detected); + if (fis != null) { + try { + String st = IOUtils.toString(fis, "UTF-8"); + NBTTagCompound tag = (NBTTagCompound) JsonToNBT.func_150315_a(st); + if (validateNBT(tag)) { + tagsToMenu.add(tag); + Notifier.notifySimple("[MainMenuRegistry]" + detected + + " Is a valid main menu and has been send to parsing queue."); + } else { + Notifier.notifyError("[MainMenuRegistry]" + detected + " Is not a valid menu!"); + } + } catch (IOException ioe) { + LoadingUtils.makeACrash( + "[MainMenuRegistry]Couldn't read file " + detected, clazz, ioe, false); + } catch (UnsupportedCharsetException uce) { + LoadingUtils.makeACrash( + "[MainMenuRegistry]UTF-8 is unsupported on your system(???)", clazz, uce, false); + } catch (NBTException nbte) { + LoadingUtils.makeACrash( + "[MainMenuRegistry]" + detected + " Is not a valid menu!", clazz, nbte, false); + nbte.printStackTrace(); + } finally { + IOUtils.closeQuietly(fis); + } + } + } + } + } catch (IOException ioe) { + LoadingUtils.makeACrash( + "[MainMenuRegistry]Couldn't read files in your config directory", clazz, ioe, false); + } + } + + public static boolean validateNBT(NBTTagCompound tag) { + return tag.hasKey("menuName") && tag.hasKey("menuDesc"); + } } diff --git a/src/main/java/DummyCore/Core/Core.java b/src/main/java/DummyCore/Core/Core.java index 03fb155..b75ae84 100644 --- a/src/main/java/DummyCore/Core/Core.java +++ b/src/main/java/DummyCore/Core/Core.java @@ -1,202 +1,187 @@ package DummyCore.Core; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; - -import net.minecraft.creativetab.CreativeTabs; -import net.minecraftforge.common.config.Configuration; import DummyCore.CreativeTabs.CreativePageBlocks; import DummyCore.CreativeTabs.CreativePageItems; import DummyCore.Utils.IDummyConfig; import DummyCore.Utils.LoadingUtils; import DummyCore.Utils.Notifier; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraftforge.common.config.Configuration; public class Core { - - public static final ArrayList registeredMods = new ArrayList(); - public static File mcDir; - - public static boolean isModRegistered(Class mod) - { - for(DCMod dcm : registeredMods) - if(dcm.modClass.equals(mod)) - return true; - - return false; - } - - public static DCMod getModFromClass(Class c) - { - for(DCMod dcm : registeredMods) - if(dcm.modClass.equals(c)) - return dcm; - - return null; - } - - private static void registerMod(Class c, String name, boolean addCreativeTabs) - { - if(!isModRegistered(c)) - { - DCMod mod = new DCMod(c,name); - if(addCreativeTabs) - { - mod.blocks = new CreativePageBlocks(name); - mod.items = new CreativePageItems(name); - } - registeredMods.add(mod); - }else - { - Notifier.notifyError(name+"[classPath:"+c+"]Already has a DummyCore mod associated with it(is already registered), ignoring"); - } - } - private static void registerConfigurationFileForMod(Class c, String path) - { - try - { - if(!isModRegistered(c)) - { - LoadingUtils.makeACrash("[DummyCore]Catched an attempt to register configuration file for not registered mod, this should not be possible and many things will go wrong as a result!", new IllegalStateException(c+" Is not a valid DCMod!"), false); - }else - { - DCMod mod = getModFromClass(c); - File file = new File(path,mod.ufName+".cfg"); - if(file.isDirectory()) - file.delete(); - - if(!file.exists()) - file.createNewFile(); - - Configuration cfg = new Configuration(file); - cfg.save(); - mod.injectFMLConfig(cfg); - Notifier.notifySimple("Configuration File for mod "+mod+" was successfully created with path "+path+mod.ufName+".cfg"); - } - } - catch(IOException e) - { - DCMod mod = getModFromClass(c); - LoadingUtils.makeACrash("[DummyCore]Could not create a config file for mod "+mod+" - check your file system!", e, true); - } - } - - /** - * Use this in you Pre-Initialization functions. This will register your mod in the DummyCore system and automatically create all config and .lang files. - * From DummyCore v1.1 you no longer need to use IMCEvent to register all blocks and items. - * @param c - class file of your mod. MUST be registered from the mod itself. Use getClass(). - * @param modname - this name will be used to name CreativeTabs, config and .lang files. - * @param configPath - the path to your configuration file. You can use FMLPreInitialisationEvent.getModConfigurationDirectory().getAbsolutePath() to get your path. - * @param config - the initialized! object, that implements IDummyConfig. - * @version From DummyCore 1.0. - * @Warning From DummyCore 1.1 no longer the function registerConfigurationHandler must be called. - * - */ - public static void registerModAbsolute(Class c, String modname, String configPath, IDummyConfig config) - { - registerModAbsolute(c,modname,configPath,config,true); - } - - /** - * Use this in you Pre-Initialization functions. This will register your mod in the DummyCore system and automatically create all config and .lang files. - * From DummyCore v1.1 you no longer need to use IMCEvent to register all blocks and items. - * @param c - class file of your mod. MUST be registered from the mod itself. Use getClass(). - * @param modname - this name will be used to name CreativeTabs, config and .lang files. - * @param configPath - the path to your configuration file. You can use FMLPreInitialisationEvent.getModConfigurationDirectory().getAbsolutePath() to get your path. - * @param config - the initialized! object, that implements IDummyConfig. - * @param addCreativeTabs if the custom creative tabs for your mod should be created. - * @version From DummyCore 2.0. - * - */ - public static void registerModAbsolute(Class c, String modname, String configPath, IDummyConfig config, boolean addCreativeTabs) - { - registerMod(c,modname,addCreativeTabs); - registerConfigurationFileForMod(c,configPath); - registerConfigurationHandler(config,c); - loadConfigForMod(c); - } - - /** - * Used to get the config file of the mod using .class file. - * @param c - the class file of the mod. - * @return The corresponding config file of the mod. - * @version From DummyCore 2.0 - */ - public static Configuration getConfigFileForMod(Class c) - { - if(!isModRegistered(c)) - { - Notifier.notifyError("Catched an attempt to get configuration for a not registered mod, things are about go wery wrong! Offendor: "+c); - return null; - } - return getModFromClass(c).fmlCfg; - } - - /** - * Used to register new Configuration Handlers of the mod. - * @param config - the initialised! object, that implements IDummyConfig. - * @param c - the class file of the mod. Use getClass(). Should only be called in the mod itself. - * @throws RuntimeException - * @version From DummyCore 2.0 - */ - private static void registerConfigurationHandler(IDummyConfig config, Class c) - { - if(!isModRegistered(c)) - { - LoadingUtils.makeACrash("[DummyCore]Catched an attempt to register IDummyConfig for not registered mod, this should not be possible and many things will go wrong as a result!", new IllegalStateException(c+" Is not a valid DCMod!"), false); - }else - { - DCMod mod = getModFromClass(c); - mod.injectConfig(config); - Notifier.notifySimple("IDummyConfing for mod "+mod+" was successfully created"); - } - } - - public static void loadConfigForMod(Class c) - { - if(!isModRegistered(c)) - { - LoadingUtils.makeACrash("[DummyCore]Catched an attempt to load IDummyConfig for not registered mod, this should not be possible and many things will go wrong as a result!", new IllegalStateException(c+" Is not a valid DCMod!"), false); - }else - { - DCMod mod = getModFromClass(c); - mod.fmlCfg.load(); - mod.cfg.load(mod.fmlCfg); - mod.fmlCfg.save(); - } - } - - /** - * Use this to get the creativetab of all mod items. - * @param c - the .class file of the mod. - * @return The corresponding Creative Tab - * @version From DummyCore 2.0 - */ - public static CreativeTabs getItemTabForMod(Class c) - { - if(!isModRegistered(c)) - { - Notifier.notifyError("Catched an attempt to get CreativeTabs for a not registered mod, things are about go wery wrong! Offendor: "+c); - return null; - } - return getModFromClass(c).items; - } - - /** - * Use this to get the creativetab of all mod blocks. - * @param c - the .class file of the mod. - * @return The corresponding Creative Tab - * @version From DummyCore 2.0 - */ - public static CreativeTabs getBlockTabForMod(Class c) - { - if(!isModRegistered(c)) - { - Notifier.notifyError("Catched an attempt to get CreativeTabs for a not registered mod, things are about go wery wrong! Offendor: "+c); - return null; - } - return getModFromClass(c).blocks; - } + public static final ArrayList registeredMods = new ArrayList(); + public static File mcDir; + public static boolean isModRegistered(Class mod) { + for (DCMod dcm : registeredMods) if (dcm.modClass.equals(mod)) return true; + + return false; + } + + public static DCMod getModFromClass(Class c) { + for (DCMod dcm : registeredMods) if (dcm.modClass.equals(c)) return dcm; + + return null; + } + + private static void registerMod(Class c, String name, boolean addCreativeTabs) { + if (!isModRegistered(c)) { + DCMod mod = new DCMod(c, name); + if (addCreativeTabs) { + mod.blocks = new CreativePageBlocks(name); + mod.items = new CreativePageItems(name); + } + registeredMods.add(mod); + } else { + Notifier.notifyError(name + "[classPath:" + c + + "]Already has a DummyCore mod associated with it(is already registered), ignoring"); + } + } + + private static void registerConfigurationFileForMod(Class c, String path) { + try { + if (!isModRegistered(c)) { + LoadingUtils.makeACrash( + "[DummyCore]Catched an attempt to register configuration file for not registered mod, this should not be possible and many things will go wrong as a result!", + new IllegalStateException(c + " Is not a valid DCMod!"), + false); + } else { + DCMod mod = getModFromClass(c); + File file = new File(path, mod.ufName + ".cfg"); + if (file.isDirectory()) file.delete(); + + if (!file.exists()) file.createNewFile(); + + Configuration cfg = new Configuration(file); + cfg.save(); + mod.injectFMLConfig(cfg); + Notifier.notifySimple("Configuration File for mod " + mod + " was successfully created with path " + + path + mod.ufName + ".cfg"); + } + } catch (IOException e) { + DCMod mod = getModFromClass(c); + LoadingUtils.makeACrash( + "[DummyCore]Could not create a config file for mod " + mod + " - check your file system!", e, true); + } + } + + /** + * Use this in you Pre-Initialization functions. This will register your mod in the DummyCore system and automatically create all config and .lang files. + * From DummyCore v1.1 you no longer need to use IMCEvent to register all blocks and items. + * @param c - class file of your mod. MUST be registered from the mod itself. Use getClass(). + * @param modname - this name will be used to name CreativeTabs, config and .lang files. + * @param configPath - the path to your configuration file. You can use FMLPreInitialisationEvent.getModConfigurationDirectory().getAbsolutePath() to get your path. + * @param config - the initialized! object, that implements IDummyConfig. + * @version From DummyCore 1.0. + * @Warning From DummyCore 1.1 no longer the function registerConfigurationHandler must be called. + * + */ + public static void registerModAbsolute(Class c, String modname, String configPath, IDummyConfig config) { + registerModAbsolute(c, modname, configPath, config, true); + } + + /** + * Use this in you Pre-Initialization functions. This will register your mod in the DummyCore system and automatically create all config and .lang files. + * From DummyCore v1.1 you no longer need to use IMCEvent to register all blocks and items. + * @param c - class file of your mod. MUST be registered from the mod itself. Use getClass(). + * @param modname - this name will be used to name CreativeTabs, config and .lang files. + * @param configPath - the path to your configuration file. You can use FMLPreInitialisationEvent.getModConfigurationDirectory().getAbsolutePath() to get your path. + * @param config - the initialized! object, that implements IDummyConfig. + * @param addCreativeTabs if the custom creative tabs for your mod should be created. + * @version From DummyCore 2.0. + * + */ + public static void registerModAbsolute( + Class c, String modname, String configPath, IDummyConfig config, boolean addCreativeTabs) { + registerMod(c, modname, addCreativeTabs); + registerConfigurationFileForMod(c, configPath); + registerConfigurationHandler(config, c); + loadConfigForMod(c); + } + + /** + * Used to get the config file of the mod using .class file. + * @param c - the class file of the mod. + * @return The corresponding config file of the mod. + * @version From DummyCore 2.0 + */ + public static Configuration getConfigFileForMod(Class c) { + if (!isModRegistered(c)) { + Notifier.notifyError( + "Catched an attempt to get configuration for a not registered mod, things are about go wery wrong! Offendor: " + + c); + return null; + } + return getModFromClass(c).fmlCfg; + } + + /** + * Used to register new Configuration Handlers of the mod. + * @param config - the initialised! object, that implements IDummyConfig. + * @param c - the class file of the mod. Use getClass(). Should only be called in the mod itself. + * @throws RuntimeException + * @version From DummyCore 2.0 + */ + private static void registerConfigurationHandler(IDummyConfig config, Class c) { + if (!isModRegistered(c)) { + LoadingUtils.makeACrash( + "[DummyCore]Catched an attempt to register IDummyConfig for not registered mod, this should not be possible and many things will go wrong as a result!", + new IllegalStateException(c + " Is not a valid DCMod!"), + false); + } else { + DCMod mod = getModFromClass(c); + mod.injectConfig(config); + Notifier.notifySimple("IDummyConfing for mod " + mod + " was successfully created"); + } + } + + public static void loadConfigForMod(Class c) { + if (!isModRegistered(c)) { + LoadingUtils.makeACrash( + "[DummyCore]Catched an attempt to load IDummyConfig for not registered mod, this should not be possible and many things will go wrong as a result!", + new IllegalStateException(c + " Is not a valid DCMod!"), + false); + } else { + DCMod mod = getModFromClass(c); + mod.fmlCfg.load(); + mod.cfg.load(mod.fmlCfg); + mod.fmlCfg.save(); + } + } + + /** + * Use this to get the creativetab of all mod items. + * @param c - the .class file of the mod. + * @return The corresponding Creative Tab + * @version From DummyCore 2.0 + */ + public static CreativeTabs getItemTabForMod(Class c) { + if (!isModRegistered(c)) { + Notifier.notifyError( + "Catched an attempt to get CreativeTabs for a not registered mod, things are about go wery wrong! Offendor: " + + c); + return null; + } + return getModFromClass(c).items; + } + + /** + * Use this to get the creativetab of all mod blocks. + * @param c - the .class file of the mod. + * @return The corresponding Creative Tab + * @version From DummyCore 2.0 + */ + public static CreativeTabs getBlockTabForMod(Class c) { + if (!isModRegistered(c)) { + Notifier.notifyError( + "Catched an attempt to get CreativeTabs for a not registered mod, things are about go wery wrong! Offendor: " + + c); + return null; + } + return getModFromClass(c).blocks; + } } diff --git a/src/main/java/DummyCore/Core/CoreInitialiser.java b/src/main/java/DummyCore/Core/CoreInitialiser.java index 0b1508e..a539c16 100644 --- a/src/main/java/DummyCore/Core/CoreInitialiser.java +++ b/src/main/java/DummyCore/Core/CoreInitialiser.java @@ -5,11 +5,6 @@ import static DummyCore.Core.CoreInitialiser.modid; import static DummyCore.Core.CoreInitialiser.modname; import static DummyCore.Core.CoreInitialiser.version; -import java.util.Arrays; - -import net.minecraft.command.CommandHandler; -import net.minecraft.server.MinecraftServer; -import net.minecraftforge.common.MinecraftForge; import DummyCore.Utils.CommandTransfer; import DummyCore.Utils.DummyConfig; import DummyCore.Utils.DummyDataUtils; @@ -35,110 +30,102 @@ import cpw.mods.fml.common.event.FMLServerStoppedEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; +import java.util.Arrays; +import net.minecraft.command.CommandHandler; +import net.minecraft.server.MinecraftServer; +import net.minecraftforge.common.MinecraftForge; /** * @author Modbder * @version From DummyCore 1.0 */ -@Mod(modid = modid, name = modname, version = version, useMetadata = false,acceptedMinecraftVersions=mcVersion) -public class CoreInitialiser{ - - public static final String modid = "DummyCore"; - public static final String modname = "DummyCore"; - public static final String mcVersion = "1.7.10"; - public static final String version = "GRADLETOKEN_VERSION"; - - public static CoreInitialiser instance; - public static DummyConfig cfg = new DummyConfig(); - public static SimpleNetworkWrapper network; - @SidedProxy(clientSide = "DummyCore.Utils.NetProxy_Client",serverSide = "DummyCore.Utils.NetProxy_Server") - public static NetProxy_Server proxy; - public static final DummyPacketHandler packetHandler = new DummyPacketHandler(); - - public static void initMetadata(ModMetadata meta) - { - meta.autogenerated = false; - meta.modId = modid; - meta.name = modname; - meta.version = version; - meta.credits = "Modbder"; - meta.authorList= Arrays.asList(new String[] { - "Dummy Thinking Team", - "Modbder", - "TheDen2099", - "MrDangerDen", - "TheMysticDark" - }); - meta.description="Dummy Core is a required package to launch mods made by Dummy Thinking team."; - } - - @EventHandler - public void preInit(FMLPreInitializationEvent e) - { - - initMetadata(e.getModMetadata()); - Core.registerModAbsolute(getClass(), "DummyCore", e.getModConfigurationDirectory().getAbsolutePath(),cfg,false); - - if(instance == null) instance = this; - network = NetworkRegistry.INSTANCE.newSimpleChannel("DummyCore"); - network.registerMessage(DummyPacketHandler.class, DummyPacketIMSG.class, 0, Side.SERVER); - network.registerMessage(DummyPacketHandler.class, DummyPacketIMSG.class, 0, Side.CLIENT); - network.registerMessage(DummyTilePacketHandler.class, DummyPacketIMSG_Tile.class, 1, Side.SERVER); - network.registerMessage(DummyTilePacketHandler.class, DummyPacketIMSG_Tile.class, 1, Side.CLIENT); - - MinecraftForge.EVENT_BUS.register(new DummyEventHandler()); - MinecraftForge.EVENT_BUS.register(new DummyDataUtils()); - FMLCommonHandler.instance().bus().register(new DummyEventHandler()); - - proxy.registerInfo(); - - if(Loader.isModLoaded(modid)) - LoadingUtils.knownBigASMModifiers.add("DummyCore"); - if(Loader.isModLoaded("DragonAPI")) - LoadingUtils.knownBigASMModifiers.add("DragonAPI"); //<- I have nothing against Reika, I like his mods, I just like to point out that DragonAPI adds quite a lot of ASM hooks - if(Loader.isModLoaded("Optifine") || Loader.isModLoaded("optifine")) - LoadingUtils.knownBigASMModifiers.add("Optifine"); - if(Loader.isModLoaded("CoFHCore")) - LoadingUtils.knownBigASMModifiers.add("CoFHCore"); - if(Loader.isModLoaded("easycoloredlights")) - LoadingUtils.knownBigASMModifiers.add("Easy Colored Lights"); - if(Loader.isModLoaded("thaumicinfusion")) - LoadingUtils.knownBigASMModifiers.add("Thaumic Infusion"); - if(MiscUtils.classExists("api.player.forge.PlayerAPIPlugin")) - LoadingUtils.knownBigASMModifiers.add("Player API"); - if(MiscUtils.classExists("cofh.tweak.CoFHTweaks")) - LoadingUtils.knownBigASMModifiers.add("CoFH Tweaks"); - if(Loader.isModLoaded("CoFHCore")) - LoadingUtils.knownBigASMModifiers.add("CoFHCore"); - if(MiscUtils.classExists("codechicken.core.asm.CodeChickenCoreModContainer")) - LoadingUtils.knownBigASMModifiers.add("CodeChickenCore"); - - FMLCommonHandler.instance().registerCrashCallable(new DCCrashCallable()); - ModVersionChecker.addRequest(getClass(), "https://www.dropbox.com/s/iwdfv0mc4qns00f/DummyCoreVersion.txt?dl=1"); - } - - @EventHandler - public void init(FMLInitializationEvent e) - { - NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy); - proxy.registerInit(); - } - - @EventHandler - public void onServerStop(FMLServerStoppedEvent e) - { - DummyDataUtils.stop(); - } - - @EventHandler - public void serverStart(FMLServerStartingEvent event) - { - MinecraftServer mcserver = event.getServer(); - ((CommandHandler)mcserver.getCommandManager()).registerCommand(new CommandTransfer()); +@Mod(modid = modid, name = modname, version = version, useMetadata = false, acceptedMinecraftVersions = mcVersion) +public class CoreInitialiser { + + public static final String modid = "DummyCore"; + public static final String modname = "DummyCore"; + public static final String mcVersion = "1.7.10"; + public static final String version = "GRADLETOKEN_VERSION"; + + public static CoreInitialiser instance; + public static DummyConfig cfg = new DummyConfig(); + public static SimpleNetworkWrapper network; + + @SidedProxy(clientSide = "DummyCore.Utils.NetProxy_Client", serverSide = "DummyCore.Utils.NetProxy_Server") + public static NetProxy_Server proxy; + + public static final DummyPacketHandler packetHandler = new DummyPacketHandler(); + + public static void initMetadata(ModMetadata meta) { + meta.autogenerated = false; + meta.modId = modid; + meta.name = modname; + meta.version = version; + meta.credits = "Modbder"; + meta.authorList = Arrays.asList( + new String[] {"Dummy Thinking Team", "Modbder", "TheDen2099", "MrDangerDen", "TheMysticDark"}); + meta.description = "Dummy Core is a required package to launch mods made by Dummy Thinking team."; + } + + @EventHandler + public void preInit(FMLPreInitializationEvent e) { + + initMetadata(e.getModMetadata()); + Core.registerModAbsolute( + getClass(), "DummyCore", e.getModConfigurationDirectory().getAbsolutePath(), cfg, false); + + if (instance == null) instance = this; + network = NetworkRegistry.INSTANCE.newSimpleChannel("DummyCore"); + network.registerMessage(DummyPacketHandler.class, DummyPacketIMSG.class, 0, Side.SERVER); + network.registerMessage(DummyPacketHandler.class, DummyPacketIMSG.class, 0, Side.CLIENT); + network.registerMessage(DummyTilePacketHandler.class, DummyPacketIMSG_Tile.class, 1, Side.SERVER); + network.registerMessage(DummyTilePacketHandler.class, DummyPacketIMSG_Tile.class, 1, Side.CLIENT); + + MinecraftForge.EVENT_BUS.register(new DummyEventHandler()); + MinecraftForge.EVENT_BUS.register(new DummyDataUtils()); + FMLCommonHandler.instance().bus().register(new DummyEventHandler()); + + proxy.registerInfo(); + + if (Loader.isModLoaded(modid)) LoadingUtils.knownBigASMModifiers.add("DummyCore"); + if (Loader.isModLoaded("DragonAPI")) + LoadingUtils.knownBigASMModifiers.add( + "DragonAPI"); // <- I have nothing against Reika, I like his mods, I just like to point out that + // DragonAPI adds quite a lot of ASM hooks + if (Loader.isModLoaded("Optifine") || Loader.isModLoaded("optifine")) + LoadingUtils.knownBigASMModifiers.add("Optifine"); + if (Loader.isModLoaded("CoFHCore")) LoadingUtils.knownBigASMModifiers.add("CoFHCore"); + if (Loader.isModLoaded("easycoloredlights")) LoadingUtils.knownBigASMModifiers.add("Easy Colored Lights"); + if (Loader.isModLoaded("thaumicinfusion")) LoadingUtils.knownBigASMModifiers.add("Thaumic Infusion"); + if (MiscUtils.classExists("api.player.forge.PlayerAPIPlugin")) + LoadingUtils.knownBigASMModifiers.add("Player API"); + if (MiscUtils.classExists("cofh.tweak.CoFHTweaks")) LoadingUtils.knownBigASMModifiers.add("CoFH Tweaks"); + if (Loader.isModLoaded("CoFHCore")) LoadingUtils.knownBigASMModifiers.add("CoFHCore"); + if (MiscUtils.classExists("codechicken.core.asm.CodeChickenCoreModContainer")) + LoadingUtils.knownBigASMModifiers.add("CodeChickenCore"); + + FMLCommonHandler.instance().registerCrashCallable(new DCCrashCallable()); + ModVersionChecker.addRequest(getClass(), "https://www.dropbox.com/s/iwdfv0mc4qns00f/DummyCoreVersion.txt?dl=1"); + } + + @EventHandler + public void init(FMLInitializationEvent e) { + NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy); + proxy.registerInit(); + } + + @EventHandler + public void onServerStop(FMLServerStoppedEvent e) { + DummyDataUtils.stop(); + } + + @EventHandler + public void serverStart(FMLServerStartingEvent event) { + MinecraftServer mcserver = event.getServer(); + ((CommandHandler) mcserver.getCommandManager()).registerCommand(new CommandTransfer()); + } + + public static void fmlLogMissingTextures() { + proxy.removeMissingTextureErrors(); } - - public static void fmlLogMissingTextures() - { - proxy.removeMissingTextureErrors(); - } } diff --git a/src/main/java/DummyCore/Core/DCCrashCallable.java b/src/main/java/DummyCore/Core/DCCrashCallable.java index a6d9b7c..8dcd1e8 100644 --- a/src/main/java/DummyCore/Core/DCCrashCallable.java +++ b/src/main/java/DummyCore/Core/DCCrashCallable.java @@ -5,25 +5,22 @@ import cpw.mods.fml.common.ICrashCallable; public class DCCrashCallable implements ICrashCallable { - @Override - public String call() throws Exception { - return "'Special case ASM modification mods: '" + - "'Note, that this mods might not be involved in the crash in ANY WAY!'" + - "'DummyCore just prints some known mods for a lot of ASM modifications'" + - computeASMIfiers(); - } + @Override + public String call() throws Exception { + return "'Special case ASM modification mods: '" + + "'Note, that this mods might not be involved in the crash in ANY WAY!'" + + "'DummyCore just prints some known mods for a lot of ASM modifications'" + + computeASMIfiers(); + } - @Override - public String getLabel() { - return "[DummyCore]"; - } - - public String computeASMIfiers() - { - String retStr=""; - for(String s : LoadingUtils.knownBigASMModifiers) - retStr += "'"+s+"'"; - return retStr; - } + @Override + public String getLabel() { + return "[DummyCore]"; + } + public String computeASMIfiers() { + String retStr = ""; + for (String s : LoadingUtils.knownBigASMModifiers) retStr += "'" + s + "'"; + return retStr; + } } diff --git a/src/main/java/DummyCore/Core/DCMod.java b/src/main/java/DummyCore/Core/DCMod.java index e17abb2..1b191de 100644 --- a/src/main/java/DummyCore/Core/DCMod.java +++ b/src/main/java/DummyCore/Core/DCMod.java @@ -1,6 +1,5 @@ package DummyCore.Core; -import net.minecraftforge.common.config.Configuration; import DummyCore.CreativeTabs.CreativePageBlocks; import DummyCore.CreativeTabs.CreativePageItems; import DummyCore.Utils.IDummyConfig; @@ -8,49 +7,48 @@ import DummyCore.Utils.Notifier; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.LoaderState; import cpw.mods.fml.common.ModContainer; +import net.minecraftforge.common.config.Configuration; -public class DCMod{ +public class DCMod { - public Object modInstance; - public Class modClass; - public ModContainer modContainer; - public String modid; - public String version; - public String ufName; - public IDummyConfig cfg; - public Configuration fmlCfg; - public CreativePageBlocks blocks; - public CreativePageItems items; - - public DCMod(Class mod, String uName) - { - ufName = uName; - modClass = mod; - modContainer = Loader.instance().activeModContainer(); - modInstance = modContainer.getMod(); - modid = modContainer.getModId(); - version = modContainer.getVersion(); - - if(Loader.instance().hasReachedState(LoaderState.INITIALIZATION)){ - Notifier.notifyWarn(String.format("Mod %s is being registered in %s state! This can cause all kinds of unexpected behaviour!",ufName+"[modid:"+modid+",classpath:"+mod+"]",Loader.instance().getLoaderState().toString())); - } - } - - public DCMod injectConfig(IDummyConfig cfg) - { - this.cfg = cfg; - return this; - } - - public DCMod injectFMLConfig(Configuration cfg) - { - this.fmlCfg = cfg; - return this; - } - - public String toString() - { - return ufName+"[modid:"+modid+",classPath:"+modClass+"]"; - } - + public Object modInstance; + public Class modClass; + public ModContainer modContainer; + public String modid; + public String version; + public String ufName; + public IDummyConfig cfg; + public Configuration fmlCfg; + public CreativePageBlocks blocks; + public CreativePageItems items; + + public DCMod(Class mod, String uName) { + ufName = uName; + modClass = mod; + modContainer = Loader.instance().activeModContainer(); + modInstance = modContainer.getMod(); + modid = modContainer.getModId(); + version = modContainer.getVersion(); + + if (Loader.instance().hasReachedState(LoaderState.INITIALIZATION)) { + Notifier.notifyWarn(String.format( + "Mod %s is being registered in %s state! This can cause all kinds of unexpected behaviour!", + ufName + "[modid:" + modid + ",classpath:" + mod + "]", + Loader.instance().getLoaderState().toString())); + } + } + + public DCMod injectConfig(IDummyConfig cfg) { + this.cfg = cfg; + return this; + } + + public DCMod injectFMLConfig(Configuration cfg) { + this.fmlCfg = cfg; + return this; + } + + public String toString() { + return ufName + "[modid:" + modid + ",classPath:" + modClass + "]"; + } } diff --git a/src/main/java/DummyCore/CreativeTabs/CreativePageBlocks.java b/src/main/java/DummyCore/CreativeTabs/CreativePageBlocks.java index 580a6e3..189848f 100644 --- a/src/main/java/DummyCore/CreativeTabs/CreativePageBlocks.java +++ b/src/main/java/DummyCore/CreativeTabs/CreativePageBlocks.java @@ -1,10 +1,10 @@ package DummyCore.CreativeTabs; -import java.util.ArrayList; -import java.util.List; import DummyCore.Core.CoreInitialiser; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; @@ -14,75 +14,63 @@ import net.minecraft.item.ItemStack; /** * @version From DummyCore 1.0 * @author Modbder - * Do not change anything here! Used to work with Blocks. + * Do not change anything here! Used to work with Blocks. */ -public final class CreativePageBlocks extends CreativeTabs{ - public int delayTime = 0; - public ItemStack displayStack = new ItemStack(Blocks.crafting_table,1,0); - private final String tabLabel; - public List blockList = new ArrayList(); - public int tries = 0; - public ItemStack overrideDisplayStack; - - public CreativePageBlocks(String m) { - super(m + " Blocks"); - tabLabel = m + " Blocks"; - } - - public ItemStack getIconItemStack() - { - if(overrideDisplayStack != null) - return overrideDisplayStack; - CoreInitialiser.proxy.choseDisplayStack(this); - return this.displayStack; +public final class CreativePageBlocks extends CreativeTabs { + public int delayTime = 0; + public ItemStack displayStack = new ItemStack(Blocks.crafting_table, 1, 0); + private final String tabLabel; + public List blockList = new ArrayList(); + public int tries = 0; + public ItemStack overrideDisplayStack; + + public CreativePageBlocks(String m) { + super(m + " Blocks"); + tabLabel = m + " Blocks"; } - - public List initialiseBlocksList() - { - ++tries; - if(this.blockList.isEmpty() && tries <= 1) - { - for(int t = 0; t < Block.blockRegistry.getKeys().size(); ++t) - { - Block b = Block.getBlockFromName((String) Block.blockRegistry.getKeys().toArray()[t]); - if(b != null && b.getCreativeTabToDisplayOn() == this) - { - Item itm = Item.getItemFromBlock(b); - if(itm != null) - { - List lst = new ArrayList(); - itm.getSubItems(itm,this,lst); - if(!lst.isEmpty()) - { - for(ItemStack stk : lst) - { - if(stk != null) - { - this.blockList.add(stk); - } - } - - } - } - - } - } - - return blockList; - }else - { - return this.blockList; - } + + public ItemStack getIconItemStack() { + if (overrideDisplayStack != null) return overrideDisplayStack; + CoreInitialiser.proxy.choseDisplayStack(this); + return this.displayStack; } + + public List initialiseBlocksList() { + ++tries; + if (this.blockList.isEmpty() && tries <= 1) { + for (int t = 0; t < Block.blockRegistry.getKeys().size(); ++t) { + Block b = Block.getBlockFromName( + (String) Block.blockRegistry.getKeys().toArray()[t]); + if (b != null && b.getCreativeTabToDisplayOn() == this) { + Item itm = Item.getItemFromBlock(b); + if (itm != null) { + List lst = new ArrayList(); + itm.getSubItems(itm, this, lst); + if (!lst.isEmpty()) { + for (ItemStack stk : lst) { + if (stk != null) { + this.blockList.add(stk); + } + } + } + } + } + } + + return blockList; + } else { + return this.blockList; + } + } + @SideOnly(Side.CLIENT) @Override - public String getTranslatedTabLabel() - { + public String getTranslatedTabLabel() { return this.tabLabel; } - @Override - public Item getTabIconItem() { - return displayStack.getItem(); - } -} \ No newline at end of file + @Override + public Item getTabIconItem() { + return displayStack.getItem(); + } +} diff --git a/src/main/java/DummyCore/CreativeTabs/CreativePageItems.java b/src/main/java/DummyCore/CreativeTabs/CreativePageItems.java index ee1dd01..e1d7124 100644 --- a/src/main/java/DummyCore/CreativeTabs/CreativePageItems.java +++ b/src/main/java/DummyCore/CreativeTabs/CreativePageItems.java @@ -1,10 +1,10 @@ package DummyCore.CreativeTabs; -import java.util.ArrayList; -import java.util.List; import DummyCore.Core.CoreInitialiser; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; @@ -13,71 +13,60 @@ import net.minecraft.item.ItemStack; /** * @version From DummyCore 1.0 * @author Modbder - * Do not change anything here! Used to work with Items. + * Do not change anything here! Used to work with Items. */ -public final class CreativePageItems extends CreativeTabs{ - public int delayTime = 0; - public ItemStack displayStack = new ItemStack((Item) Items.iron_axe,1,0); - private final String tabLabel; - public List itemList = new ArrayList(); - public int tries = 0; - public ItemStack overrideDisplayStack; - - public CreativePageItems(String m) { - super(m + " Items"); - tabLabel = m + " Items"; - } - - @Override - public ItemStack getIconItemStack() - { - if(overrideDisplayStack != null) - return overrideDisplayStack; - CoreInitialiser.proxy.choseDisplayStack(this); - return this.displayStack; +public final class CreativePageItems extends CreativeTabs { + public int delayTime = 0; + public ItemStack displayStack = new ItemStack((Item) Items.iron_axe, 1, 0); + private final String tabLabel; + public List itemList = new ArrayList(); + public int tries = 0; + public ItemStack overrideDisplayStack; + + public CreativePageItems(String m) { + super(m + " Items"); + tabLabel = m + " Items"; } - - public List initialiseItemsList() - { - ++tries; - if(this.itemList.isEmpty() && tries <= 1) - { - for(int t = 0; t < Item.itemRegistry.getKeys().size(); ++t) - { - Item itm = (Item) Item.itemRegistry.getObject(Item.itemRegistry.getKeys().toArray()[t]); - if(itm != null && itm.getCreativeTab() == this) - { - List lst = new ArrayList(); - itm.getSubItems(itm,this,lst); - if(!lst.isEmpty()) - { - for(ItemStack stk : lst) - { - if(stk != null) - { - this.itemList.add(stk); - } - } - } - } - } - return this.itemList; - }else - { - return this.itemList; - } - + + @Override + public ItemStack getIconItemStack() { + if (overrideDisplayStack != null) return overrideDisplayStack; + CoreInitialiser.proxy.choseDisplayStack(this); + return this.displayStack; } - + + public List initialiseItemsList() { + ++tries; + if (this.itemList.isEmpty() && tries <= 1) { + for (int t = 0; t < Item.itemRegistry.getKeys().size(); ++t) { + Item itm = (Item) + Item.itemRegistry.getObject(Item.itemRegistry.getKeys().toArray()[t]); + if (itm != null && itm.getCreativeTab() == this) { + List lst = new ArrayList(); + itm.getSubItems(itm, this, lst); + if (!lst.isEmpty()) { + for (ItemStack stk : lst) { + if (stk != null) { + this.itemList.add(stk); + } + } + } + } + } + return this.itemList; + } else { + return this.itemList; + } + } + @SideOnly(Side.CLIENT) @Override - public String getTranslatedTabLabel() - { + public String getTranslatedTabLabel() { return this.tabLabel; } - @Override - public Item getTabIconItem() { - return Items.iron_axe; - } -} \ No newline at end of file + @Override + public Item getTabIconItem() { + return Items.iron_axe; + } +} diff --git a/src/main/java/DummyCore/Events/DummyEvent_OnClientGUIButtonPress.java b/src/main/java/DummyCore/Events/DummyEvent_OnClientGUIButtonPress.java index 9dcecf1..9ffa489 100644 --- a/src/main/java/DummyCore/Events/DummyEvent_OnClientGUIButtonPress.java +++ b/src/main/java/DummyCore/Events/DummyEvent_OnClientGUIButtonPress.java @@ -4,25 +4,24 @@ import DummyCore.Utils.DummyData; import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayer; -public class DummyEvent_OnClientGUIButtonPress extends Event{ - - public int buttonID; - public String client_ParentClassPath; - public String client_ButtonClassPath; - public EntityPlayer presser; - public int x, y, z; - public DummyData[] additionalData; - - public DummyEvent_OnClientGUIButtonPress(int bID, String s, String s_1, EntityPlayer player,int dx, int dy, int dz, DummyData[] data) - { - buttonID = bID; - client_ParentClassPath = s; - client_ButtonClassPath = s_1; - presser = player; - x = dx; - y = dy; - z = dz; - additionalData = data; - } +public class DummyEvent_OnClientGUIButtonPress extends Event { + public int buttonID; + public String client_ParentClassPath; + public String client_ButtonClassPath; + public EntityPlayer presser; + public int x, y, z; + public DummyData[] additionalData; + + public DummyEvent_OnClientGUIButtonPress( + int bID, String s, String s_1, EntityPlayer player, int dx, int dy, int dz, DummyData[] data) { + buttonID = bID; + client_ParentClassPath = s; + client_ButtonClassPath = s_1; + presser = player; + x = dx; + y = dy; + z = dz; + additionalData = data; + } } diff --git a/src/main/java/DummyCore/Events/DummyEvent_OnKeyboardKeyPressed_Server.java b/src/main/java/DummyCore/Events/DummyEvent_OnKeyboardKeyPressed_Server.java index c7d5b6c..ccab613 100644 --- a/src/main/java/DummyCore/Events/DummyEvent_OnKeyboardKeyPressed_Server.java +++ b/src/main/java/DummyCore/Events/DummyEvent_OnKeyboardKeyPressed_Server.java @@ -1,21 +1,19 @@ package DummyCore.Events; -import net.minecraft.entity.player.EntityPlayer; import cpw.mods.fml.common.eventhandler.Event; +import net.minecraft.entity.player.EntityPlayer; -public class DummyEvent_OnKeyboardKeyPressed_Server extends Event{ - - public int keyID; - public String keyName; - public EntityPlayer presser; - public boolean pressed; - - public DummyEvent_OnKeyboardKeyPressed_Server(int keyId, String keyname, EntityPlayer player, boolean bool) - { - keyID = keyId; - keyName = keyname; - presser = player; - pressed = bool; - } +public class DummyEvent_OnKeyboardKeyPressed_Server extends Event { + public int keyID; + public String keyName; + public EntityPlayer presser; + public boolean pressed; + + public DummyEvent_OnKeyboardKeyPressed_Server(int keyId, String keyname, EntityPlayer player, boolean bool) { + keyID = keyId; + keyName = keyname; + presser = player; + pressed = bool; + } } diff --git a/src/main/java/DummyCore/Events/DummyEvent_OnPacketRecieved.java b/src/main/java/DummyCore/Events/DummyEvent_OnPacketRecieved.java index b797234..deed2a8 100644 --- a/src/main/java/DummyCore/Events/DummyEvent_OnPacketRecieved.java +++ b/src/main/java/DummyCore/Events/DummyEvent_OnPacketRecieved.java @@ -1,27 +1,26 @@ package DummyCore.Events; -import net.minecraft.entity.player.EntityPlayer; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.relauncher.Side; +import net.minecraft.entity.player.EntityPlayer; /** - * + * * @author Modbder * @version From DummyCore 1.7 * @Description Now all packets work on Events. */ -public class DummyEvent_OnPacketRecieved extends Event{ +public class DummyEvent_OnPacketRecieved extends Event { - public final Side effectiveSide; - - public final String recievedData; - - public final EntityPlayer recievedEntity; - - public DummyEvent_OnPacketRecieved(Side s, String str, EntityPlayer pl) - { - effectiveSide = s; - recievedData = str; - recievedEntity = pl; - } + public final Side effectiveSide; + + public final String recievedData; + + public final EntityPlayer recievedEntity; + + public DummyEvent_OnPacketRecieved(Side s, String str, EntityPlayer pl) { + effectiveSide = s; + recievedData = str; + recievedEntity = pl; + } } diff --git a/src/main/java/DummyCore/Items/ItemRegistry.java b/src/main/java/DummyCore/Items/ItemRegistry.java index 765f657..e1893b6 100644 --- a/src/main/java/DummyCore/Items/ItemRegistry.java +++ b/src/main/java/DummyCore/Items/ItemRegistry.java @@ -1,62 +1,56 @@ package DummyCore.Items; -import java.util.Hashtable; - -import net.minecraft.item.Item; import DummyCore.Core.Core; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; +import java.util.Hashtable; +import net.minecraft.item.Item; /** - * + * * @author Modbder * @version From DummyCore 1.0 * @Description Use this class to register new items in your game. * This will automatically add your items to the corresponding creative tab */ public class ItemRegistry { - - /** - * Used to check the creative tab item belongs to - */ - public static Hashtable itemsList = new Hashtable(); - - /** - * Use this to register new simple items. - * @version From DummyCore 1.0 - * @param i - the item to be registered. - * @param name - name of the item in the itemregistry - * @param modClass - class file of your mod. If registered from the mod itself, use getClass(), else just put in this field something like YourModClassName.class - */ - public static void registerItem(Item i, String name, Class modClass) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - i.setCreativeTab(Core.getItemTabForMod(modClass)); - itemsList.put(i, Core.getItemTabForMod(modClass).getTabLabel()); - } - GameRegistry.registerItem(i, name); - } - - /** - * Use this to register new simple items. - * @version From DummyCore 1.0 - * @param i - the item to be registered. - * @param modClass - class file of your mod. If registered from the mod itself, use getClass(), else just put in this field something like YourModClassName.class - */ - @Deprecated - public static void registerItem(Item i, Class modClass) - { - //Notifier.notifyCustomMod("DummyCore", "[Warning] Mod "+Core.getModName(Core.getIdForMod(modClass))+" tries to register items in an outdated way, may cause errors!"); - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - i.setCreativeTab(Core.getItemTabForMod(modClass)); - itemsList.put(i, Core.getItemTabForMod(modClass).getTabLabel()); - } - } - - + + /** + * Used to check the creative tab item belongs to + */ + public static Hashtable itemsList = new Hashtable(); + + /** + * Use this to register new simple items. + * @version From DummyCore 1.0 + * @param i - the item to be registered. + * @param name - name of the item in the itemregistry + * @param modClass - class file of your mod. If registered from the mod itself, use getClass(), else just put in this field something like YourModClassName.class + */ + public static void registerItem(Item i, String name, Class modClass) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + i.setCreativeTab(Core.getItemTabForMod(modClass)); + itemsList.put(i, Core.getItemTabForMod(modClass).getTabLabel()); + } + GameRegistry.registerItem(i, name); + } + + /** + * Use this to register new simple items. + * @version From DummyCore 1.0 + * @param i - the item to be registered. + * @param modClass - class file of your mod. If registered from the mod itself, use getClass(), else just put in this field something like YourModClassName.class + */ + @Deprecated + public static void registerItem(Item i, Class modClass) { + // Notifier.notifyCustomMod("DummyCore", "[Warning] Mod "+Core.getModName(Core.getIdForMod(modClass))+" tries to + // register items in an outdated way, may cause errors!"); + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + i.setCreativeTab(Core.getItemTabForMod(modClass)); + itemsList.put(i, Core.getItemTabForMod(modClass).getTabLabel()); + } + } } diff --git a/src/main/java/DummyCore/Utils/ASMInfoClass.java b/src/main/java/DummyCore/Utils/ASMInfoClass.java index 98c66ac..f341d1e 100644 --- a/src/main/java/DummyCore/Utils/ASMInfoClass.java +++ b/src/main/java/DummyCore/Utils/ASMInfoClass.java @@ -1,152 +1,135 @@ package DummyCore.Utils; -import java.util.Arrays; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.EntityList; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.network.play.server.S0FPacketSpawnMob; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.tree.ClassNode; - /** - * + * * @author modbder * @Description This class is a helper for me. */ @SuppressWarnings("unused") final class ASMInfoClass { - private class ASMClassStructure - { - //header = 0xCAFEBABE + Version - - //constant pool = Constants(field/method names, etc) - - //access rights = Private/protected flags - - //Interfaces LIST - - //Fields LIST - - //Methods LIST - - //Attributes - } - - private class AssemblerCommands - { - //ldc = Const -> Stack - //iadd = i0+i1 -> Stack - //goto = go to line - //if_icmpeq = if - //jsr, ret = subprogram, return from it. - //athrow = Exception - //istore = Local variable -> Stack - //iload = Local variable <- Stack - //iastore = i0 -> i[] - //getfield = Local <- field - //putfield = Local -> field - //getstatic = Local <- static field - //putstatic = Local -> static field - //invokestatic = invoke a static method - //invokevirtual = invoke a method - //invokespecial = invoke a PARENT or a PRIVATE method - //invokeinterface = invoke an INTERFACE(ABSTRACT) method - //new = new object - //newarray = new array - //anewarray(multinewarray) = link array? - //f2i = Float to Integer(i2d,i2f,i2l,etc) - //instanceof = is a instanceof b - //checkcast = is possible to (a)b - } - - private class Signatures - { - //Every method/field/etc has a CONSTANT in class's CONST field(look above). - //Everything is converted into signatures. - //public static void main( String[] argv ) = ([java/lang/String;)V - //Everything in () are PARAMS. [ indicates an ARRAY. java/lang/String = link to PARAM. If PARAM is not an object, it will be I = int, F = float, D = double, etc. - //; indicates APRAM end. V = return type. V = void, I = int, etc. Objects are done via LINK. - } - - private class Attributes - { - //Methods have their stats listed in CODE in the Attributes(look above) - //Methods have next data: - //MAX Stack size(not sure if the same for java 8?) - //Local variable COUNT - //InsNode array. - //If compiled with a DEBUG flag will have additional info: - //Local variable NAME - //POSITION of source-code lines - } - - private class ASMUsageRules - { - //Using of ASM needs to follow simple lines - - //1. PARSER of the .class file MUST be called first. Will analyze the .class - - //Lookup the DCASMManager: - /* - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(basicClass); <---- Here it is - classReader.accept(classNode, 0); <---- CALLING the parser - ... - */ - - //2. Event Producer(for CORE ASM type(we are using a TREE, which is built over CORE)) - - //It is usually combined with the PARSER for the TREE. - //Lookup the DCASMManager: - /* - ... - ClassReader classReader = new ClassReader(basicClass); <---- Here it is - ... - */ - - //3. The CLASS WRITER. MUST be called !!!BEFORE!!! ASM Modifications! - //Lookup the DCASMManager: - /* - ... - Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has given the next interfaces to check: "+Arrays.asList(checkedClss)); - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); <---- Here it is - ... - */ - //The class CAN be analyzed BEFORE calling a WRITER. However, you MUST initialize one BEFORE ASM Modifications! - - //4. Class ADAPTERS(event FILTERS). No such thing for DCASMManager. - - //Using CORE ASM is done with a specific USE ORDER: - //1. Creating a class READER, event READER, analyzer, WRITER, etc. - //2. Injecting BYTECODE and CHANING it using the ADAPTERS. - //3. Retrieving the BYTECODE back to the JVM - } - - private class ASMPackages - { - //org.objectweb.asm && org.objectweb.asm.sinature -> CORE ASM. READERS and WRITERS. - //org.objectweb.asm.util -> Utils for CORE ASM - //org.objectweb.asm.commons -> common HELPING functions for modifying bytecode using CORE ASM. - //org.objectweb.asm.tree -> TREE ASM. - //org.objectweb.asm.tree.analysis -> common ANALYSIS functions for TREE ASM - } - - private class ASMStructure - { - //ASM is based upon modifying SINGLE class feature AT A TIME. - //ClassVisitor is what is used to do that. - //Every method there has something to do with the corresponding CLASS file structure piece(look above) - //Simple object can be accessed without something special. - //More complex need to be VISITED, and that returns a specific VISITOR to modify THAT EXACT feature. - //Modifying an annotation takes ClassVisitor.visitAnnotation, which returns a specific AnnotationVisitor! - - //ASM key modification things are: - //ClassReader = Transforms the bytecode array into EVENTS. - //ClassWriter = Transforms the EVENTS into bytecode array. - //ClassAdapter = Filters EVENTS for the ClassWriter. - } + private class ASMClassStructure { + // header = 0xCAFEBABE + Version + + // constant pool = Constants(field/method names, etc) + + // access rights = Private/protected flags + + // Interfaces LIST + + // Fields LIST + + // Methods LIST + + // Attributes + } + + private class AssemblerCommands { + // ldc = Const -> Stack + // iadd = i0+i1 -> Stack + // goto = go to line + // if_icmpeq = if + // jsr, ret = subprogram, return from it. + // athrow = Exception + // istore = Local variable -> Stack + // iload = Local variable <- Stack + // iastore = i0 -> i[] + // getfield = Local <- field + // putfield = Local -> field + // getstatic = Local <- static field + // putstatic = Local -> static field + // invokestatic = invoke a static method + // invokevirtual = invoke a method + // invokespecial = invoke a PARENT or a PRIVATE method + // invokeinterface = invoke an INTERFACE(ABSTRACT) method + // new = new object + // newarray = new array + // anewarray(multinewarray) = link array? + // f2i = Float to Integer(i2d,i2f,i2l,etc) + // instanceof = is a instanceof b + // checkcast = is possible to (a)b + } + + private class Signatures { + // Every method/field/etc has a CONSTANT in class's CONST field(look above). + // Everything is converted into signatures. + // public static void main( String[] argv ) = ([java/lang/String;)V + // Everything in () are PARAMS. [ indicates an ARRAY. java/lang/String = link to PARAM. If PARAM is not an + // object, it will be I = int, F = float, D = double, etc. + // ; indicates APRAM end. V = return type. V = void, I = int, etc. Objects are done via LINK. + } + + private class Attributes { + // Methods have their stats listed in CODE in the Attributes(look above) + // Methods have next data: + // MAX Stack size(not sure if the same for java 8?) + // Local variable COUNT + // InsNode array. + // If compiled with a DEBUG flag will have additional info: + // Local variable NAME + // POSITION of source-code lines + } + + private class ASMUsageRules { + // Using of ASM needs to follow simple lines + + // 1. PARSER of the .class file MUST be called first. Will analyze the .class + + // Lookup the DCASMManager: + /* + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(basicClass); <---- Here it is + classReader.accept(classNode, 0); <---- CALLING the parser + ... + */ + + // 2. Event Producer(for CORE ASM type(we are using a TREE, which is built over CORE)) + + // It is usually combined with the PARSER for the TREE. + // Lookup the DCASMManager: + /* + ... + ClassReader classReader = new ClassReader(basicClass); <---- Here it is + ... + */ + + // 3. The CLASS WRITER. MUST be called !!!BEFORE!!! ASM Modifications! + // Lookup the DCASMManager: + /* + ... + Notifier.notifyCustomMod("DummyCoreASM", "Class "+name+" has given the next interfaces to check: "+Arrays.asList(checkedClss)); + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); <---- Here it is + ... + */ + // The class CAN be analyzed BEFORE calling a WRITER. However, you MUST initialize one BEFORE ASM Modifications! + + // 4. Class ADAPTERS(event FILTERS). No such thing for DCASMManager. + + // Using CORE ASM is done with a specific USE ORDER: + // 1. Creating a class READER, event READER, analyzer, WRITER, etc. + // 2. Injecting BYTECODE and CHANING it using the ADAPTERS. + // 3. Retrieving the BYTECODE back to the JVM + } + + private class ASMPackages { + // org.objectweb.asm && org.objectweb.asm.sinature -> CORE ASM. READERS and WRITERS. + // org.objectweb.asm.util -> Utils for CORE ASM + // org.objectweb.asm.commons -> common HELPING functions for modifying bytecode using CORE ASM. + // org.objectweb.asm.tree -> TREE ASM. + // org.objectweb.asm.tree.analysis -> common ANALYSIS functions for TREE ASM + } + + private class ASMStructure { + // ASM is based upon modifying SINGLE class feature AT A TIME. + // ClassVisitor is what is used to do that. + // Every method there has something to do with the corresponding CLASS file structure piece(look above) + // Simple object can be accessed without something special. + // More complex need to be VISITED, and that returns a specific VISITOR to modify THAT EXACT feature. + // Modifying an annotation takes ClassVisitor.visitAnnotation, which returns a specific AnnotationVisitor! + + // ASM key modification things are: + // ClassReader = Transforms the bytecode array into EVENTS. + // ClassWriter = Transforms the EVENTS into bytecode array. + // ClassAdapter = Filters EVENTS for the ClassWriter. + } } diff --git a/src/main/java/DummyCore/Utils/BlockPosition.java b/src/main/java/DummyCore/Utils/BlockPosition.java index 8acf5ef..6436d7f 100644 --- a/src/main/java/DummyCore/Utils/BlockPosition.java +++ b/src/main/java/DummyCore/Utils/BlockPosition.java @@ -5,24 +5,22 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class BlockPosition { - - public int x; - public int y; - public int z; - public Block blk; - public int metadata; - public TileEntity blockTile; - public World wrld; - - public BlockPosition(World w, int posX, int posY, int posZ) - { - wrld = w; - x = posX; - y = posY; - z = posZ; - blk = w.getBlock(posX, posY, posZ); - metadata = w.getBlockMetadata(posX, posY, posZ); - blockTile = w.getTileEntity(posX, posY, posZ); - } + public int x; + public int y; + public int z; + public Block blk; + public int metadata; + public TileEntity blockTile; + public World wrld; + + public BlockPosition(World w, int posX, int posY, int posZ) { + wrld = w; + x = posX; + y = posY; + z = posZ; + blk = w.getBlock(posX, posY, posZ); + metadata = w.getBlockMetadata(posX, posY, posZ); + blockTile = w.getTileEntity(posX, posY, posZ); + } } diff --git a/src/main/java/DummyCore/Utils/CommandTransfer.java b/src/main/java/DummyCore/Utils/CommandTransfer.java index 8d69045..701d247 100644 --- a/src/main/java/DummyCore/Utils/CommandTransfer.java +++ b/src/main/java/DummyCore/Utils/CommandTransfer.java @@ -6,21 +6,21 @@ import net.minecraft.entity.player.EntityPlayerMP; public class CommandTransfer extends CommandBase { - @Override - public String getCommandName() { - return "DummyCore.Transfer"; - } + @Override + public String getCommandName() { + return "DummyCore.Transfer"; + } - @Override - public String getCommandUsage(ICommandSender p_71518_1_) { - return "/DummyCore.Transfer "; - } + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/DummyCore.Transfer "; + } - @Override - public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_) { - int var3 = parseIntWithMin(p_71515_1_, p_71515_2_[1], Integer.MIN_VALUE); - EntityPlayerMP player = p_71515_2_.length == 0 ? getCommandSenderAsPlayer(p_71515_1_) : getPlayer(p_71515_1_, p_71515_2_[0]); + @Override + public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_) { + int var3 = parseIntWithMin(p_71515_1_, p_71515_2_[1], Integer.MIN_VALUE); + EntityPlayerMP player = + p_71515_2_.length == 0 ? getCommandSenderAsPlayer(p_71515_1_) : getPlayer(p_71515_1_, p_71515_2_[0]); player.travelToDimension(var3); - } - + } } diff --git a/src/main/java/DummyCore/Utils/ContainerInventory.java b/src/main/java/DummyCore/Utils/ContainerInventory.java index 79e7223..91cfe63 100644 --- a/src/main/java/DummyCore/Utils/ContainerInventory.java +++ b/src/main/java/DummyCore/Utils/ContainerInventory.java @@ -8,164 +8,136 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -public abstract class ContainerInventory extends Container{ +public abstract class ContainerInventory extends Container { - public final IInventory inv; - public final InventoryPlayer pInv; - public final TileEntity tile; - public final EntityPlayer player; - - public int pInvOffsetX; - public int pInvOffsetZ; - - public ContainerInventory(InventoryPlayer playerInv, TileEntity tileInv) - { - super(); - inv = (IInventory) tileInv; - pInv = playerInv; - tile = tileInv; - player = playerInv.player; - - inv.openInventory(); - setupSlots(); - } - - public abstract void setupSlots(); - - public void setupPlayerInventory() - { + public final IInventory inv; + public final InventoryPlayer pInv; + public final TileEntity tile; + public final EntityPlayer player; + + public int pInvOffsetX; + public int pInvOffsetZ; + + public ContainerInventory(InventoryPlayer playerInv, TileEntity tileInv) { + super(); + inv = (IInventory) tileInv; + pInv = playerInv; + tile = tileInv; + player = playerInv.player; + + inv.openInventory(); + setupSlots(); + } + + public abstract void setupSlots(); + + public void setupPlayerInventory() { for (int i = 0; i < 3; ++i) for (int j = 0; j < 9; ++j) - this.addSlotToContainer(new Slot(pInv, j + i * 9 + 9, 8 + j * 18 + pInvOffsetX, 84 + i * 18 + pInvOffsetZ)); + this.addSlotToContainer( + new Slot(pInv, j + i * 9 + 9, 8 + j * 18 + pInvOffsetX, 84 + i * 18 + pInvOffsetZ)); for (int i = 0; i < 9; ++i) this.addSlotToContainer(new Slot(pInv, i, 8 + i * 18 + pInvOffsetX, 142 + pInvOffsetZ)); - } - - @Override - public boolean canInteractWith(EntityPlayer player) { - return inv.isUseableByPlayer(player); - } + } + @Override - public void onContainerClosed(EntityPlayer player) - { + public boolean canInteractWith(EntityPlayer player) { + return inv.isUseableByPlayer(player); + } + + @Override + public void onContainerClosed(EntityPlayer player) { super.onContainerClosed(player); inv.closeInventory(); } - + @Override - public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int slotIndex) - { + public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int slotIndex) { ItemStack newItemStack = null; Slot slot = (Slot) inventorySlots.get(slotIndex); - if (slot != null && slot.getHasStack()) - { + if (slot != null && slot.getHasStack()) { ItemStack itemStack = slot.getStack(); newItemStack = itemStack.copy(); - if (slotIndex < inv.getSizeInventory()) - { - if (!this.mergeItemStack(itemStack, inv.getSizeInventory(), inventorySlots.size(), false)) - return null; - } - else if (!this.mergeItemStack(itemStack, 0, inv.getSizeInventory(), false)) - return null; + if (slotIndex < inv.getSizeInventory()) { + if (!this.mergeItemStack(itemStack, inv.getSizeInventory(), inventorySlots.size(), false)) return null; + } else if (!this.mergeItemStack(itemStack, 0, inv.getSizeInventory(), false)) return null; - if (itemStack.stackSize == 0) - slot.putStack(null); - else - slot.onSlotChanged(); + if (itemStack.stackSize == 0) slot.putStack(null); + else slot.onSlotChanged(); } return newItemStack; - } - - //Credits to Pahimar for his awesome ItemStack merging code! - @Override - public boolean mergeItemStack(ItemStack itemStack, int slotMin, int slotMax, boolean ascending) - { - boolean slotFound = false; - int currentSlotIndex = ascending ? slotMax - 1 : slotMin; + } + + // Credits to Pahimar for his awesome ItemStack merging code! + @Override + public boolean mergeItemStack(ItemStack itemStack, int slotMin, int slotMax, boolean ascending) { + boolean slotFound = false; + int currentSlotIndex = ascending ? slotMax - 1 : slotMin; Slot slot; ItemStack stackInSlot; - if (itemStack.isStackable()) - { - while (itemStack.stackSize > 0 && (!ascending && currentSlotIndex < slotMax || ascending && currentSlotIndex >= slotMin)) - { - slot = (Slot) this.inventorySlots.get(currentSlotIndex); + if (itemStack.isStackable()) { + while (itemStack.stackSize > 0 + && (!ascending && currentSlotIndex < slotMax || ascending && currentSlotIndex >= slotMin)) { + slot = (Slot) this.inventorySlots.get(currentSlotIndex); stackInSlot = slot.getStack(); - if (slot.isItemValid(itemStack) && equalsIgnoreStackSize(itemStack, stackInSlot)) - { + if (slot.isItemValid(itemStack) && equalsIgnoreStackSize(itemStack, stackInSlot)) { int combinedStackSize = stackInSlot.stackSize + itemStack.stackSize; int slotStackSizeLimit = Math.min(stackInSlot.getMaxStackSize(), slot.getSlotStackLimit()); - if (combinedStackSize <= slotStackSizeLimit) - { + if (combinedStackSize <= slotStackSizeLimit) { itemStack.stackSize = 0; stackInSlot.stackSize = combinedStackSize; slot.onSlotChanged(); slotFound = true; - } - else if (stackInSlot.stackSize < slotStackSizeLimit) - { + } else if (stackInSlot.stackSize < slotStackSizeLimit) { itemStack.stackSize -= slotStackSizeLimit - stackInSlot.stackSize; stackInSlot.stackSize = slotStackSizeLimit; slot.onSlotChanged(); slotFound = true; } - } - currentSlotIndex += ascending ? -1 : 1; + } + currentSlotIndex += ascending ? -1 : 1; } } - if (itemStack.stackSize > 0) - { + if (itemStack.stackSize > 0) { currentSlotIndex = ascending ? slotMax - 1 : slotMin; - while (!ascending && currentSlotIndex < slotMax || ascending && currentSlotIndex >= slotMin) - { + while (!ascending && currentSlotIndex < slotMax || ascending && currentSlotIndex >= slotMin) { slot = (Slot) this.inventorySlots.get(currentSlotIndex); stackInSlot = slot.getStack(); - if (slot.isItemValid(itemStack) && stackInSlot == null) - { + if (slot.isItemValid(itemStack) && stackInSlot == null) { slot.putStack(cloneItemStack(itemStack, Math.min(itemStack.stackSize, slot.getSlotStackLimit()))); slot.onSlotChanged(); - if (slot.getStack() != null) - { + if (slot.getStack() != null) { itemStack.stackSize -= slot.getStack().stackSize; slotFound = true; } break; } - currentSlotIndex += ascending ? -1 : 1; + currentSlotIndex += ascending ? -1 : 1; } } - return slotFound; + return slotFound; } - - public static ItemStack cloneItemStack(ItemStack itemStack, int stackSize) - { + + public static ItemStack cloneItemStack(ItemStack itemStack, int stackSize) { ItemStack clonedItemStack = itemStack.copy(); clonedItemStack.stackSize = stackSize; return clonedItemStack; } - - public static boolean equalsIgnoreStackSize(ItemStack itemStack1, ItemStack itemStack2) - { - if (itemStack1 != null && itemStack2 != null) - { - if (itemStack1.getItem() == itemStack2.getItem()) - { - if (itemStack1.getItemDamage() == itemStack2.getItemDamage()) - { - if (itemStack1.hasTagCompound() && itemStack2.hasTagCompound()) - { - if (ItemStack.areItemStackTagsEqual(itemStack1, itemStack2)) - { + + public static boolean equalsIgnoreStackSize(ItemStack itemStack1, ItemStack itemStack2) { + if (itemStack1 != null && itemStack2 != null) { + if (itemStack1.getItem() == itemStack2.getItem()) { + if (itemStack1.getItemDamage() == itemStack2.getItemDamage()) { + if (itemStack1.hasTagCompound() && itemStack2.hasTagCompound()) { + if (ItemStack.areItemStackTagsEqual(itemStack1, itemStack2)) { return true; } - } - else if (!itemStack1.hasTagCompound() && !itemStack2.hasTagCompound()) - { + } else if (!itemStack1.hasTagCompound() && !itemStack2.hasTagCompound()) { return true; } } diff --git a/src/main/java/DummyCore/Utils/Coord2D.java b/src/main/java/DummyCore/Utils/Coord2D.java index d045493..4a57538 100644 --- a/src/main/java/DummyCore/Utils/Coord2D.java +++ b/src/main/java/DummyCore/Utils/Coord2D.java @@ -1,38 +1,33 @@ package DummyCore.Utils; /** - * + * * @author Modbder * @version From DummyCore 1.0 * @Description used to work with 2d coord system. Of course, should be a vec2D, but we are working with minecraft =) */ public class Coord2D { - - public float x; - public float z; - - public Coord2D(float i, float j) - { - this.x = i; - this.z = j; - } - - public Coord2D() - { - this(0,0); - } - - public String toString() - { - return "||x:"+x+"||z:"+z; - } - - public static Coord2D fromString(String data) - { - DummyData[] dt = DataStorage.parseData(data); - float cX = Float.parseFloat(dt[0].fieldValue); - float cZ = Float.parseFloat(dt[1].fieldValue); - return new Coord2D(cX,cZ); - } + public float x; + public float z; + + public Coord2D(float i, float j) { + this.x = i; + this.z = j; + } + + public Coord2D() { + this(0, 0); + } + + public String toString() { + return "||x:" + x + "||z:" + z; + } + + public static Coord2D fromString(String data) { + DummyData[] dt = DataStorage.parseData(data); + float cX = Float.parseFloat(dt[0].fieldValue); + float cZ = Float.parseFloat(dt[1].fieldValue); + return new Coord2D(cX, cZ); + } } diff --git a/src/main/java/DummyCore/Utils/Coord3D.java b/src/main/java/DummyCore/Utils/Coord3D.java index 05250e9..119b863 100644 --- a/src/main/java/DummyCore/Utils/Coord3D.java +++ b/src/main/java/DummyCore/Utils/Coord3D.java @@ -1,48 +1,42 @@ package DummyCore.Utils; /** - * + * * @author Modbder * @version From DummyCore 1.1 * @Description used to work with 3d coord system. Of course, should be a vec3D, but we are working with minecraft =) */ public class Coord3D { - - public float x; - public float y; - public float z; - - public Coord3D(double posX, double posY, double posZ) - { - this.x = (float) posX; - this.y = (float) posY; - this.z = (float) posZ; - } - - public Coord3D(float i, float k, float j) - { - this.x = i; - this.y = k; - this.z = j; - } - - public Coord3D() - { - this(0,0,0); - } - - public String toString() - { - return "||x:"+x+"||y:"+y+"||z:"+z; - } - - public static Coord3D fromString(String data) - { - DummyData[] dt = DataStorage.parseData(data); - float cX = Float.parseFloat(dt[0].fieldValue); - float cY = Float.parseFloat(dt[1].fieldValue); - float cZ = Float.parseFloat(dt[2].fieldValue); - return new Coord3D(cX,cY,cZ); - } + public float x; + public float y; + public float z; + + public Coord3D(double posX, double posY, double posZ) { + this.x = (float) posX; + this.y = (float) posY; + this.z = (float) posZ; + } + + public Coord3D(float i, float k, float j) { + this.x = i; + this.y = k; + this.z = j; + } + + public Coord3D() { + this(0, 0, 0); + } + + public String toString() { + return "||x:" + x + "||y:" + y + "||z:" + z; + } + + public static Coord3D fromString(String data) { + DummyData[] dt = DataStorage.parseData(data); + float cX = Float.parseFloat(dt[0].fieldValue); + float cY = Float.parseFloat(dt[1].fieldValue); + float cZ = Float.parseFloat(dt[2].fieldValue); + return new Coord3D(cX, cY, cZ); + } } diff --git a/src/main/java/DummyCore/Utils/CustomTXTConfig.java b/src/main/java/DummyCore/Utils/CustomTXTConfig.java index a99e18f..1d82cb7 100644 --- a/src/main/java/DummyCore/Utils/CustomTXTConfig.java +++ b/src/main/java/DummyCore/Utils/CustomTXTConfig.java @@ -1,87 +1,71 @@ package DummyCore.Utils; +import DummyCore.Core.Core; +import cpw.mods.fml.common.FMLCommonHandler; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.Hashtable; -import DummyCore.Core.Core; -import cpw.mods.fml.common.FMLCommonHandler; - public class CustomTXTConfig { - - public static final Hashtable mappings = new Hashtable(); - public static boolean init = false; - - public static void createCFG() - { - try - { - File cfgDir = new File(Core.mcDir,"config"); - if(!cfgDir.exists()) - cfgDir.mkdirs(); - - File actualCfg = new File(cfgDir,"DummyCoreASMSettings.cfg"); - if(!actualCfg.exists()) - createDefaultCFG(actualCfg); - - readCfg(actualCfg); - init = true; - } - catch(Exception e) - { - FMLCommonHandler.instance().raiseException(e, "[DummyCore]Something went wrong while trying to create ASM configuration!", true); - } - } - - public static void createDefaultCFG(File cfgFile) - { - try - { - if(!cfgFile.exists()) - cfgFile.createNewFile(); - PrintWriter pw = new PrintWriter(cfgFile,"UTF-8"); - pw.println("#Fix vanilla's mob packet issue?"); - pw.println("#This is not really a fix though..."); - pw.println("#If this breaks your game - turn this option to false"); - pw.println("fixS0FSpawnMobPacketCrash=true"); - pw.println("#Insert a simple call in FML's texture loader?"); - pw.println("#This enables the disabling texture errors feature of DummyCore"); - pw.println("#You can set this to false if ASM crashes you"); - pw.println("insertDCCallInTextureLoader=true"); - pw.flush(); - pw.close(); - } - catch(Exception e) - { - FMLCommonHandler.instance().raiseException(e, "[DummyCore]Something went wrong while trying to create ASM configuration!", true); - } - } - - public static void readCfg(File cfgFile) - { - mappings.clear(); - try - { - FileReader fr = new FileReader(cfgFile); - BufferedReader br = new BufferedReader(fr); - String line; - while((line = br.readLine()) != null) - { - if(line.startsWith("#")) - continue; - if(line.indexOf('=') == -1) - continue; - mappings.put(line.substring(0, line.indexOf('=')), line.substring(line.indexOf('=')+1)); - } - br.close(); - fr.close(); - } - catch(Exception e) - { - LoadingUtils.makeACrash("[DummyCore]Failed to read ASM settings!", CustomTXTConfig.class, e, false); - } - } + public static final Hashtable mappings = new Hashtable(); + public static boolean init = false; + + public static void createCFG() { + try { + File cfgDir = new File(Core.mcDir, "config"); + if (!cfgDir.exists()) cfgDir.mkdirs(); + + File actualCfg = new File(cfgDir, "DummyCoreASMSettings.cfg"); + if (!actualCfg.exists()) createDefaultCFG(actualCfg); + + readCfg(actualCfg); + init = true; + } catch (Exception e) { + FMLCommonHandler.instance() + .raiseException( + e, "[DummyCore]Something went wrong while trying to create ASM configuration!", true); + } + } + + public static void createDefaultCFG(File cfgFile) { + try { + if (!cfgFile.exists()) cfgFile.createNewFile(); + PrintWriter pw = new PrintWriter(cfgFile, "UTF-8"); + pw.println("#Fix vanilla's mob packet issue?"); + pw.println("#This is not really a fix though..."); + pw.println("#If this breaks your game - turn this option to false"); + pw.println("fixS0FSpawnMobPacketCrash=true"); + pw.println("#Insert a simple call in FML's texture loader?"); + pw.println("#This enables the disabling texture errors feature of DummyCore"); + pw.println("#You can set this to false if ASM crashes you"); + pw.println("insertDCCallInTextureLoader=true"); + pw.flush(); + pw.close(); + } catch (Exception e) { + FMLCommonHandler.instance() + .raiseException( + e, "[DummyCore]Something went wrong while trying to create ASM configuration!", true); + } + } + + public static void readCfg(File cfgFile) { + mappings.clear(); + try { + FileReader fr = new FileReader(cfgFile); + BufferedReader br = new BufferedReader(fr); + String line; + while ((line = br.readLine()) != null) { + if (line.startsWith("#")) continue; + if (line.indexOf('=') == -1) continue; + mappings.put(line.substring(0, line.indexOf('=')), line.substring(line.indexOf('=') + 1)); + } + br.close(); + fr.close(); + } catch (Exception e) { + LoadingUtils.makeACrash("[DummyCore]Failed to read ASM settings!", CustomTXTConfig.class, e, false); + } + } } diff --git a/src/main/java/DummyCore/Utils/DCASMCheck.java b/src/main/java/DummyCore/Utils/DCASMCheck.java index a0feab9..10f61d9 100644 --- a/src/main/java/DummyCore/Utils/DCASMCheck.java +++ b/src/main/java/DummyCore/Utils/DCASMCheck.java @@ -1,5 +1,3 @@ package DummyCore.Utils; -public @interface DCASMCheck { - -} +public @interface DCASMCheck {} diff --git a/src/main/java/DummyCore/Utils/DataStorage.java b/src/main/java/DummyCore/Utils/DataStorage.java index 3a6a7f7..59bd0f0 100644 --- a/src/main/java/DummyCore/Utils/DataStorage.java +++ b/src/main/java/DummyCore/Utils/DataStorage.java @@ -4,85 +4,74 @@ import java.util.ArrayList; import java.util.List; /** - * + * * @author Modbder * @version From DummyCore 1.2 * @Description used to store almost any kind of variable in a single String instance. */ public class DataStorage { - private static String dataString = ""; - - /** - * Adds the given DummyData to the data string - * @version From DummyCore 1.2 - * @param data - the data to be added to the string - */ - public static void addDataToString(DummyData data) - { - dataString = dataString.concat(data.toString()); - } - - /** - * Returns the data string, with all data written to it. Also resets the string, so this should be used only once, after you have stored all your data. - * @version From DummyCore 1.2 - * @return Correctly formated DataString - */ - public static String getDataString() - { - String ret = dataString; - dataString = ""; - return ret; - } - - /** - * Used to get your DummyData from the correctly formated string. - * @version From DummyCore 1.2 - * @param s - the string to extract data from - * @return - An array of all data from the given string - */ - public static DummyData[] parseData(String s) - { - String field = ""; - Object value = null; - List data = new ArrayList(); - for(int i = 0; i < s.length(); ++i) - { - if(i+2 < s.length() && s.substring(i, i+2).contains("||")) - { - int size = 0; - ForSize:for(int i1 = i; i1 < s.length();++i1) - { - if(s.charAt(i1) == ':') - break ForSize; - ++size; - } - field = s.substring(i+2, i+size); - } - if(i+1 < s.length() && s.substring(i, i+1).contains(":")) - { - int size = 0; - ForSize:for(int i1 = i; i1 < s.length();++i1) - { - if(s.charAt(i1) == '|') - break ForSize; - ++size; - } - value = s.substring(i+1, i+size); - } - if(field != "" && value != null) - { - DummyData date = new DummyData(field,value); - data.add(date); - field = ""; - value = null; - } - } - DummyData[] ret = new DummyData[data.size()]; - for(int i = 0; i < ret.length; ++i) - { - ret[i] = data.get(i); - } - return ret; - } + private static String dataString = ""; + /** + * Adds the given DummyData to the data string + * @version From DummyCore 1.2 + * @param data - the data to be added to the string + */ + public static void addDataToString(DummyData data) { + dataString = dataString.concat(data.toString()); + } + + /** + * Returns the data string, with all data written to it. Also resets the string, so this should be used only once, after you have stored all your data. + * @version From DummyCore 1.2 + * @return Correctly formated DataString + */ + public static String getDataString() { + String ret = dataString; + dataString = ""; + return ret; + } + + /** + * Used to get your DummyData from the correctly formated string. + * @version From DummyCore 1.2 + * @param s - the string to extract data from + * @return - An array of all data from the given string + */ + public static DummyData[] parseData(String s) { + String field = ""; + Object value = null; + List data = new ArrayList(); + for (int i = 0; i < s.length(); ++i) { + if (i + 2 < s.length() && s.substring(i, i + 2).contains("||")) { + int size = 0; + ForSize: + for (int i1 = i; i1 < s.length(); ++i1) { + if (s.charAt(i1) == ':') break ForSize; + ++size; + } + field = s.substring(i + 2, i + size); + } + if (i + 1 < s.length() && s.substring(i, i + 1).contains(":")) { + int size = 0; + ForSize: + for (int i1 = i; i1 < s.length(); ++i1) { + if (s.charAt(i1) == '|') break ForSize; + ++size; + } + value = s.substring(i + 1, i + size); + } + if (field != "" && value != null) { + DummyData date = new DummyData(field, value); + data.add(date); + field = ""; + value = null; + } + } + DummyData[] ret = new DummyData[data.size()]; + for (int i = 0; i < ret.length; ++i) { + ret[i] = data.get(i); + } + return ret; + } } diff --git a/src/main/java/DummyCore/Utils/DrawUtils.java b/src/main/java/DummyCore/Utils/DrawUtils.java index 594880f..8266f6b 100644 --- a/src/main/java/DummyCore/Utils/DrawUtils.java +++ b/src/main/java/DummyCore/Utils/DrawUtils.java @@ -1,8 +1,9 @@ package DummyCore.Utils; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.util.Hashtable; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemRenderer; @@ -19,171 +20,184 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.ForgeHooksClient; - import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - public class DrawUtils { - - public static Hashtable locTable = new Hashtable(); - - /** - * Used to bind texture from the mod. First string is the mod id, and the second is the texture path. - * @version From DummyCore 2.0 - * @param mod - the in-code modname. always use small letters! - * @param texture - path to your thexture. - */ - @SideOnly(Side.CLIENT) - public static void bindTexture(String mod, String texture) - { - if(locTable.contains(mod+":"+texture)) - Minecraft.getMinecraft().getTextureManager().bindTexture(locTable.get(mod+":"+texture)); - else - { - ResourceLocation loc = new ResourceLocation(mod,texture); - locTable.put(mod+":"+texture, loc); - Minecraft.getMinecraft().getTextureManager().bindTexture(loc); - } - } - - /** - * Used to draw a textured rectangle using the given IIcon - * @version From DummyCore 2.0 - * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution - * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution - * @param icon - the icon itself - * @param width - the width of your Icon - * @param height - the height of your Icon - * @param zLevel - the z rendering level on the GUI(depth) - * @return - */ + + public static Hashtable locTable = new Hashtable(); + + /** + * Used to bind texture from the mod. First string is the mod id, and the second is the texture path. + * @version From DummyCore 2.0 + * @param mod - the in-code modname. always use small letters! + * @param texture - path to your thexture. + */ @SideOnly(Side.CLIENT) - public static boolean drawScaledTexturedRect_Items(int x, int y, IIcon icon, int width, int height, float zLevel) - { - if(icon == null) - return false; - else - { - Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); + public static void bindTexture(String mod, String texture) { + if (locTable.contains(mod + ":" + texture)) + Minecraft.getMinecraft().getTextureManager().bindTexture(locTable.get(mod + ":" + texture)); + else { + ResourceLocation loc = new ResourceLocation(mod, texture); + locTable.put(mod + ":" + texture, loc); + Minecraft.getMinecraft().getTextureManager().bindTexture(loc); + } + } + + /** + * Used to draw a textured rectangle using the given IIcon + * @version From DummyCore 2.0 + * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution + * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution + * @param icon - the icon itself + * @param width - the width of your Icon + * @param height - the height of your Icon + * @param zLevel - the z rendering level on the GUI(depth) + * @return + */ + @SideOnly(Side.CLIENT) + public static boolean drawScaledTexturedRect_Items(int x, int y, IIcon icon, int width, int height, float zLevel) { + if (icon == null) return false; + else { + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); double minU = icon.getMinU(); double maxU = icon.getMaxU(); double minV = icon.getMinV(); double maxV = icon.getMaxV(); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV(x + 0, y + height, zLevel, minU, minV + ((maxV - minV) * (double)height) / 16D); - tessellator.addVertexWithUV(x + width, y + height, zLevel, minU + ((maxU - minU) * (double)width) / 16D, minV + ((maxV - minV) * (double)height) / 16D); - tessellator.addVertexWithUV(x + width, y + 0, zLevel, minU + ((maxU - minU) * (double)width) / 16D, minV); + tessellator.addVertexWithUV( + x + 0, y + height, zLevel, minU, minV + ((maxV - minV) * (double) height) / 16D); + tessellator.addVertexWithUV( + x + width, + y + height, + zLevel, + minU + ((maxU - minU) * (double) width) / 16D, + minV + ((maxV - minV) * (double) height) / 16D); + tessellator.addVertexWithUV(x + width, y + 0, zLevel, minU + ((maxU - minU) * (double) width) / 16D, minV); tessellator.addVertexWithUV(x + 0, y + 0, zLevel, minU, minV); tessellator.draw(); return true; } } - - /** - * Used to draw a textured rectangle using the given IIcon - * @version From DummyCore 2.0 - * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution - * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution - * @param icon - the icon itself - * @param width - the width of your Icon - * @param height - the height of your Icon - * @param zLevel - the z rendering level on the GUI(depth) - * @return - */ + + /** + * Used to draw a textured rectangle using the given IIcon + * @version From DummyCore 2.0 + * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution + * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution + * @param icon - the icon itself + * @param width - the width of your Icon + * @param height - the height of your Icon + * @param zLevel - the z rendering level on the GUI(depth) + * @return + */ @SideOnly(Side.CLIENT) - public static boolean drawScaledTexturedRect(int x, int y, IIcon icon, int width, int height, float zLevel) - { - if(icon == null) - return false; - else - { - Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + public static boolean drawScaledTexturedRect(int x, int y, IIcon icon, int width, int height, float zLevel) { + if (icon == null) return false; + else { + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); double minU = icon.getMinU(); double maxU = icon.getMaxU(); double minV = icon.getMinV(); double maxV = icon.getMaxV(); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV(x + 0, y + height, zLevel, minU, minV + ((maxV - minV) * (double)height) / 16D); - tessellator.addVertexWithUV(x + width, y + height, zLevel, minU + ((maxU - minU) * (double)width) / 16D, minV + ((maxV - minV) * (double)height) / 16D); - tessellator.addVertexWithUV(x + width, y + 0, zLevel, minU + ((maxU - minU) * (double)width) / 16D, minV); + tessellator.addVertexWithUV( + x + 0, y + height, zLevel, minU, minV + ((maxV - minV) * (double) height) / 16D); + tessellator.addVertexWithUV( + x + width, + y + height, + zLevel, + minU + ((maxU - minU) * (double) width) / 16D, + minV + ((maxV - minV) * (double) height) / 16D); + tessellator.addVertexWithUV(x + width, y + 0, zLevel, minU + ((maxU - minU) * (double) width) / 16D, minV); tessellator.addVertexWithUV(x + 0, y + 0, zLevel, minU, minV); tessellator.draw(); return true; } } - - /** - * Used to draw a textured rectangle using the given IIcon - * @version From DummyCore 2.0 - * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution - * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution - * @param icon - the icon itself - * @param width - the width of your rectangle - * @param height - the height of your rectangle - * @param zLevel - the z rendering level on the GUI(depth) - * @return - */ + + /** + * Used to draw a textured rectangle using the given IIcon + * @version From DummyCore 2.0 + * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution + * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution + * @param icon - the icon itself + * @param width - the width of your rectangle + * @param height - the height of your rectangle + * @param zLevel - the z rendering level on the GUI(depth) + * @return + */ @SideOnly(Side.CLIENT) - public static void drawTexture(int x, int y, IIcon icon, int width, int height, float zLevel) - { - for(int i = 0; i < width; i += 16) - for(int j = 0; j < height; j += 16) - drawScaledTexturedRect(x + i, y + j, icon, Math.min(width - i, 16), Math.min(height - j, 16),zLevel); - + public static void drawTexture(int x, int y, IIcon icon, int width, int height, float zLevel) { + for (int i = 0; i < width; i += 16) + for (int j = 0; j < height; j += 16) + drawScaledTexturedRect(x + i, y + j, icon, Math.min(width - i, 16), Math.min(height - j, 16), zLevel); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } - - /** - * Used to draw a textured rectangle using the given IIcon - * @version From DummyCore 2.0 - * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution - * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution - * @param icon - the icon itself - * @param width - the width of your rectangle - * @param height - the height of your rectangle - * @param zLevel - the z rendering level on the GUI(depth) - * @return - */ + + /** + * Used to draw a textured rectangle using the given IIcon + * @version From DummyCore 2.0 + * @param x - the X coordinate on the screen. Should be bound to the ScaledResolution + * @param y - the Y coordinate on the screen. Should be bound to the ScaledResolution + * @param icon - the icon itself + * @param width - the width of your rectangle + * @param height - the height of your rectangle + * @param zLevel - the z rendering level on the GUI(depth) + * @return + */ @SideOnly(Side.CLIENT) - public static void drawTexture_Items(int x, int y, IIcon icon, int width, int height, float zLevel) - { - for(int i = 0; i < width; i += 16) - for(int j = 0; j < height; j += 16) - drawScaledTexturedRect_Items(x + i, y + j, icon, Math.min(width - i, 16), Math.min(height - j, 16),zLevel); - + public static void drawTexture_Items(int x, int y, IIcon icon, int width, int height, float zLevel) { + for (int i = 0; i < width; i += 16) + for (int j = 0; j < height; j += 16) + drawScaledTexturedRect_Items( + x + i, y + j, icon, Math.min(width - i, 16), Math.min(height - j, 16), zLevel); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } - - /** - * Actually draws a textured rectangle - * @version From DummyCore 2.0 - * @param x - first vertex U - * @param y - first vertex V - * @param textureX - second vertex U - * @param textureY - second vertex V - * @param sizeX - third vertex U - * @param sizeY - third vertex V - * @param zLevel - the zlevel on the GUI - */ + + /** + * Actually draws a textured rectangle + * @version From DummyCore 2.0 + * @param x - first vertex U + * @param y - first vertex V + * @param textureX - second vertex U + * @param textureY - second vertex V + * @param sizeX - third vertex U + * @param sizeY - third vertex V + * @param zLevel - the zlevel on the GUI + */ @SideOnly(Side.CLIENT) - public static void drawTexturedModalRect(int x, int y, int textureX, int textureY, int sizeX, int sizeY, int zLevel) - { - float f = 0.00390625F; //1/256 - float f1 = 0.00390625F; //1/256 + public static void drawTexturedModalRect( + int x, int y, int textureX, int textureY, int sizeX, int sizeY, int zLevel) { + float f = 0.00390625F; // 1/256 + float f1 = 0.00390625F; // 1/256 Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)(x + 0), (double)(y + sizeY), (double)zLevel, (double)((float)(textureX + 0) * f), (double)((float)(textureY + sizeY) * f1)); - tessellator.addVertexWithUV((double)(x + sizeX), (double)(y + sizeY), (double)zLevel, (double)((float)(textureX + sizeX) * f), (double)((float)(textureY + sizeY) * f1)); - tessellator.addVertexWithUV((double)(x + sizeX), (double)(y + 0), (double)zLevel, (double)((float)(textureX + sizeX) * f), (double)((float)(textureY + 0) * f1)); - tessellator.addVertexWithUV((double)(x + 0), (double)(y + 0), (double)zLevel, (double)((float)(textureX + 0) * f), (double)((float)(textureY + 0) * f1)); + tessellator.addVertexWithUV( + (double) (x + 0), (double) (y + sizeY), (double) zLevel, (double) ((float) (textureX + 0) * f), (double) + ((float) (textureY + sizeY) * f1)); + tessellator.addVertexWithUV( + (double) (x + sizeX), + (double) (y + sizeY), + (double) zLevel, + (double) ((float) (textureX + sizeX) * f), + (double) ((float) (textureY + sizeY) * f1)); + tessellator.addVertexWithUV( + (double) (x + sizeX), + (double) (y + 0), + (double) zLevel, + (double) ((float) (textureX + sizeX) * f), + (double) ((float) (textureY + 0) * f1)); + tessellator.addVertexWithUV( + (double) (x + 0), (double) (y + 0), (double) zLevel, (double) ((float) (textureX + 0) * f), (double) + ((float) (textureY + 0) * f1)); tessellator.draw(); } - + /** * Renders the given ItemStack in the world. Call ONLY from render methods! * @version From DummyCore 2.0 @@ -205,141 +219,181 @@ public class DrawUtils { * @param force3DRender - should be item rendered in 3d even if the fancy graphics are off? */ @SideOnly(Side.CLIENT) - public static void renderItemStack_Full(ItemStack stk,double posX, double posY, double posZ, double screenPosX, double screenPosY, double screenPosZ, float rotation, float rotationZ, float colorRed, float colorGreen, float colorBlue, float offsetX, float offsetY, float offsetZ, boolean force3DRender) - { - if(stk != null) - { - ItemStack itemstack = stk.copy(); - itemstack.stackSize = 1; //Doing this so no weird glitches occur. - RenderBlocks renderBlocksRi = new RenderBlocks(); - Random random = new Random(); - boolean renderWithColor = true; - if (itemstack != null && itemstack.getItem() != null) - { - Minecraft.getMinecraft().renderEngine.bindTexture(Minecraft.getMinecraft().renderEngine.getResourceLocation(stk.getItemSpriteNumber())); - TextureUtil.func_152777_a(false, false, 1.0F); - random.setSeed(187L); - GL11.glPushMatrix(); - float f2 = rotationZ; - float f3 = rotation; - byte b0 = 1; - - if (stk.stackSize > 1) - { - b0 = 2; - } - - if (stk.stackSize > 5) - { - b0 = 3; - } - - if (stk.stackSize > 20) - { - b0 = 4; - } - - if (stk.stackSize > 40) - { - b0 = 5; - } - - GL11.glTranslated((float)screenPosX+offsetX, (float)screenPosY+offsetY, (float)screenPosZ+offsetZ); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - float f6; - float f7; - int k; - EntityItem fakeItem = new EntityItem(Minecraft.getMinecraft().theWorld, posX, posY, posZ, stk); - GL11.glRotatef(f2, 0, 0, 1); - if (ForgeHooksClient.renderEntityItem(fakeItem, itemstack, f2, f3, random, Minecraft.getMinecraft().renderEngine, renderBlocksRi, b0)) - { - - } - else if (itemstack.getItemSpriteNumber() == 0 && itemstack.getItem() instanceof ItemBlock && RenderBlocks.renderItemIn3d(Block.getBlockFromItem(itemstack.getItem()).getRenderType())) - { - Block block = Block.getBlockFromItem(itemstack.getItem()); - GL11.glRotatef(f3, 0.0F, 1.0F, 0.0F); - float f9 = 0.25F; - k = block.getRenderType(); - - if (k == 1 || k == 19 || k == 12 || k == 2) - { - f9 = 0.5F; - } - - if (block.getRenderBlockPass() > 0) - { - GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); - GL11.glEnable(GL11.GL_BLEND); - OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); - } - - GL11.glScalef(f9, f9, f9); - - for (int l = 0; l < b0; ++l) - { - GL11.glPushMatrix(); - - if (l > 0) - { - f6 = (random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9; - f7 = (random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9; - float f8 = (random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9; - GL11.glTranslatef(f6, f7, f8); - } - - renderBlocksRi.renderBlockAsItem(block, itemstack.getItemDamage(), 1.0F); - GL11.glPopMatrix(); - } - - if (block.getRenderBlockPass() > 0) - { - GL11.glDisable(GL11.GL_BLEND); - } - } - else - { - if (itemstack.getItem().requiresMultipleRenderPasses()) - { - GL11.glScalef(0.5F, 0.5F, 0.5F); - for (int j = 0; j < itemstack.getItem().getRenderPasses(itemstack.getItemDamage()); ++j) - { - random.setSeed(187L); - itemstack.getItem().getIcon(itemstack, j); - renderItemStack(stk, posX, posY, posZ, screenPosX, screenPosY, screenPosZ, rotation, colorRed, colorGreen, colorBlue, j, stk.stackSize,force3DRender); - } - } - else - { - if (itemstack != null && itemstack.getItem() instanceof ItemCloth) - { - GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); - GL11.glEnable(GL11.GL_BLEND); - OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); - } - GL11.glScalef(0.5F, 0.5F, 0.5F); - itemstack.getIconIndex(); - - if (renderWithColor) - { - renderItemStack(stk, posX, posY, posZ, screenPosX, screenPosY, screenPosZ, rotation, colorRed, colorGreen, colorBlue, 0, stk.stackSize,force3DRender); - } - if (itemstack != null && itemstack.getItem() instanceof ItemCloth) - { - GL11.glDisable(GL11.GL_BLEND); - } - } - } - fakeItem = null; - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - GL11.glPopMatrix(); - Minecraft.getMinecraft().renderEngine.bindTexture(Minecraft.getMinecraft().renderEngine.getResourceLocation(stk.getItemSpriteNumber())); - TextureUtil.func_147945_b(); - } - itemstack = null; - } + public static void renderItemStack_Full( + ItemStack stk, + double posX, + double posY, + double posZ, + double screenPosX, + double screenPosY, + double screenPosZ, + float rotation, + float rotationZ, + float colorRed, + float colorGreen, + float colorBlue, + float offsetX, + float offsetY, + float offsetZ, + boolean force3DRender) { + if (stk != null) { + ItemStack itemstack = stk.copy(); + itemstack.stackSize = 1; // Doing this so no weird glitches occur. + RenderBlocks renderBlocksRi = new RenderBlocks(); + Random random = new Random(); + boolean renderWithColor = true; + if (itemstack != null && itemstack.getItem() != null) { + Minecraft.getMinecraft() + .renderEngine + .bindTexture( + Minecraft.getMinecraft().renderEngine.getResourceLocation(stk.getItemSpriteNumber())); + TextureUtil.func_152777_a(false, false, 1.0F); + random.setSeed(187L); + GL11.glPushMatrix(); + float f2 = rotationZ; + float f3 = rotation; + byte b0 = 1; + + if (stk.stackSize > 1) { + b0 = 2; + } + + if (stk.stackSize > 5) { + b0 = 3; + } + + if (stk.stackSize > 20) { + b0 = 4; + } + + if (stk.stackSize > 40) { + b0 = 5; + } + + GL11.glTranslated( + (float) screenPosX + offsetX, (float) screenPosY + offsetY, (float) screenPosZ + offsetZ); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + float f6; + float f7; + int k; + EntityItem fakeItem = new EntityItem(Minecraft.getMinecraft().theWorld, posX, posY, posZ, stk); + GL11.glRotatef(f2, 0, 0, 1); + if (ForgeHooksClient.renderEntityItem( + fakeItem, + itemstack, + f2, + f3, + random, + Minecraft.getMinecraft().renderEngine, + renderBlocksRi, + b0)) { + + } else if (itemstack.getItemSpriteNumber() == 0 + && itemstack.getItem() instanceof ItemBlock + && RenderBlocks.renderItemIn3d( + Block.getBlockFromItem(itemstack.getItem()).getRenderType())) { + Block block = Block.getBlockFromItem(itemstack.getItem()); + GL11.glRotatef(f3, 0.0F, 1.0F, 0.0F); + float f9 = 0.25F; + k = block.getRenderType(); + + if (k == 1 || k == 19 || k == 12 || k == 2) { + f9 = 0.5F; + } + + if (block.getRenderBlockPass() > 0) { + GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); + GL11.glEnable(GL11.GL_BLEND); + OpenGlHelper.glBlendFunc( + GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); + } + + GL11.glScalef(f9, f9, f9); + + for (int l = 0; l < b0; ++l) { + GL11.glPushMatrix(); + + if (l > 0) { + f6 = (random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9; + f7 = (random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9; + float f8 = (random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9; + GL11.glTranslatef(f6, f7, f8); + } + + renderBlocksRi.renderBlockAsItem(block, itemstack.getItemDamage(), 1.0F); + GL11.glPopMatrix(); + } + + if (block.getRenderBlockPass() > 0) { + GL11.glDisable(GL11.GL_BLEND); + } + } else { + if (itemstack.getItem().requiresMultipleRenderPasses()) { + GL11.glScalef(0.5F, 0.5F, 0.5F); + for (int j = 0; j < itemstack.getItem().getRenderPasses(itemstack.getItemDamage()); ++j) { + random.setSeed(187L); + itemstack.getItem().getIcon(itemstack, j); + renderItemStack( + stk, + posX, + posY, + posZ, + screenPosX, + screenPosY, + screenPosZ, + rotation, + colorRed, + colorGreen, + colorBlue, + j, + stk.stackSize, + force3DRender); + } + } else { + if (itemstack != null && itemstack.getItem() instanceof ItemCloth) { + GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); + GL11.glEnable(GL11.GL_BLEND); + OpenGlHelper.glBlendFunc( + GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); + } + GL11.glScalef(0.5F, 0.5F, 0.5F); + itemstack.getIconIndex(); + + if (renderWithColor) { + renderItemStack( + stk, + posX, + posY, + posZ, + screenPosX, + screenPosY, + screenPosZ, + rotation, + colorRed, + colorGreen, + colorBlue, + 0, + stk.stackSize, + force3DRender); + } + if (itemstack != null && itemstack.getItem() instanceof ItemCloth) { + GL11.glDisable(GL11.GL_BLEND); + } + } + } + fakeItem = null; + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glPopMatrix(); + Minecraft.getMinecraft() + .renderEngine + .bindTexture( + Minecraft.getMinecraft().renderEngine.getResourceLocation(stk.getItemSpriteNumber())); + TextureUtil.func_147945_b(); + } + itemstack = null; + } } - + /** * Sub-function to the first one. You shouldn't use this, however it is also possible. * @version From DummyCore 2.0 @@ -359,32 +413,44 @@ public class DrawUtils { * @param force3DRender - should be item rendered in 3d even if the fancy graphics are off? */ @SideOnly(Side.CLIENT) - public static void renderItemStack(ItemStack stk,double posX, double posY, double posZ, double screenPosX, double screenPosY, double screenPosZ, float rotation, float colorRed, float colorGreen, float colorBlue, int renderPass, int itemsAmount, boolean force3DRender) - { + public static void renderItemStack( + ItemStack stk, + double posX, + double posY, + double posZ, + double screenPosX, + double screenPosY, + double screenPosZ, + float rotation, + float colorRed, + float colorGreen, + float colorBlue, + int renderPass, + int itemsAmount, + boolean force3DRender) { final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png"); Random random = new Random(); IIcon iicon = stk.getItem().getIcon(stk, renderPass); - + Tessellator tessellator = Tessellator.instance; - if (iicon == null) - { + if (iicon == null) { TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); - ResourceLocation resourcelocation = texturemanager.getResourceLocation(stk.getItem().getSpriteNumber()); - iicon = ((TextureMap)texturemanager.getTexture(resourcelocation)).getAtlasSprite("missingno"); + ResourceLocation resourcelocation = + texturemanager.getResourceLocation(stk.getItem().getSpriteNumber()); + iicon = ((TextureMap) texturemanager.getTexture(resourcelocation)).getAtlasSprite("missingno"); } - float minU = ((IIcon)iicon).getMinU(); - float maxU = ((IIcon)iicon).getMaxU(); - float minV = ((IIcon)iicon).getMinV(); - float maxV = ((IIcon)iicon).getMaxV(); + float minU = ((IIcon) iicon).getMinU(); + float maxU = ((IIcon) iicon).getMaxU(); + float minV = ((IIcon) iicon).getMinV(); + float maxV = ((IIcon) iicon).getMaxV(); float f6 = 1.0F; float f7 = 0.5F; float f8 = 0.25F; float f10; - if (Minecraft.getMinecraft().gameSettings.fancyGraphics || force3DRender) - { + if (Minecraft.getMinecraft().gameSettings.fancyGraphics || force3DRender) { GL11.glPushMatrix(); GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F); float f9 = 0.0625F; @@ -393,53 +459,46 @@ public class DrawUtils { int j = itemstack.stackSize; byte b0; - if (j < 2) - { + if (j < 2) { b0 = 1; - } - else if (j < 16) - { + } else if (j < 16) { b0 = 2; - } - else if (j < 32) - { + } else if (j < 32) { b0 = 3; - } - else - { + } else { b0 = 4; } - - GL11.glTranslatef(-f7, -f8, -((f9 + f10) * (float)b0 / 2.0F)); - for (int k = 0; k < b0; ++k) - { - if (k > 0) - { + GL11.glTranslatef(-f7, -f8, -((f9 + f10) * (float) b0 / 2.0F)); + + for (int k = 0; k < b0; ++k) { + if (k > 0) { float x = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; float y = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; random.nextFloat(); GL11.glTranslatef(x, y, f9 + f10); - } - else - { + } else { GL11.glTranslatef(0f, 0f, f9 + f10); } - if (itemstack.getItemSpriteNumber() == 0) - { + if (itemstack.getItemSpriteNumber() == 0) { Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); - } - else - { - Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); + } else { + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); } GL11.glColor4f(colorRed, colorGreen, colorBlue, 1.0F); - ItemRenderer.renderItemIn2D(tessellator, maxU, minV, minU, maxV, ((IIcon)iicon).getIconWidth(), ((IIcon)iicon).getIconHeight(), f9); + ItemRenderer.renderItemIn2D( + tessellator, + maxU, + minV, + minU, + maxV, + ((IIcon) iicon).getIconWidth(), + ((IIcon) iicon).getIconHeight(), + f9); - if (itemstack.hasEffect(renderPass)) - { + if (itemstack.hasEffect(renderPass)) { GL11.glDepthFunc(GL11.GL_EQUAL); GL11.glDisable(GL11.GL_LIGHTING); Minecraft.getMinecraft().renderEngine.bindTexture(RES_ITEM_GLINT); @@ -451,14 +510,14 @@ public class DrawUtils { GL11.glPushMatrix(); float f12 = 0.125F; GL11.glScalef(f12, f12, f12); - float f13 = (float)(Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F; + float f13 = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F; GL11.glTranslatef(f13, 0.0F, 0.0F); GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F); ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, f9); GL11.glPopMatrix(); GL11.glPushMatrix(); GL11.glScalef(f12, f12, f12); - f13 = (float)(Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F; + f13 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F; GL11.glTranslatef(-f13, 0.0F, 0.0F); GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F); ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, f9); @@ -471,15 +530,11 @@ public class DrawUtils { } GL11.glPopMatrix(); - } - else - { - for (int l = 0; l < itemsAmount; ++l) - { + } else { + for (int l = 0; l < itemsAmount; ++l) { GL11.glPushMatrix(); - if (l > 0) - { + if (l > 0) { f10 = (random.nextFloat() * 2.0F - 1.0F) * 0.3F; float f16 = (random.nextFloat() * 2.0F - 1.0F) * 0.3F; float f17 = (random.nextFloat() * 2.0F - 1.0F) * 0.3F; @@ -488,10 +543,14 @@ public class DrawUtils { GL11.glColor4f(colorRed, colorGreen, colorBlue, 1.0F); tessellator.startDrawingQuads(); tessellator.setNormal(0.0F, 1.0F, 0.0F); - tessellator.addVertexWithUV((double)(0.0F - f7), (double)(0.0F - f8), 0.0D, (double)minU, (double)maxV); - tessellator.addVertexWithUV((double)(f6 - f7), (double)(0.0F - f8), 0.0D, (double)maxU, (double)maxV); - tessellator.addVertexWithUV((double)(f6 - f7), (double)(1.0F - f8), 0.0D, (double)maxU, (double)minV); - tessellator.addVertexWithUV((double)(0.0F - f7), (double)(1.0F - f8), 0.0D, (double)minU, (double)minV); + tessellator.addVertexWithUV( + (double) (0.0F - f7), (double) (0.0F - f8), 0.0D, (double) minU, (double) maxV); + tessellator.addVertexWithUV( + (double) (f6 - f7), (double) (0.0F - f8), 0.0D, (double) maxU, (double) maxV); + tessellator.addVertexWithUV( + (double) (f6 - f7), (double) (1.0F - f8), 0.0D, (double) maxU, (double) minV); + tessellator.addVertexWithUV( + (double) (0.0F - f7), (double) (1.0F - f8), 0.0D, (double) minU, (double) minV); tessellator.draw(); GL11.glPopMatrix(); } diff --git a/src/main/java/DummyCore/Utils/DummyBounds.java b/src/main/java/DummyCore/Utils/DummyBounds.java index d88e323..28c541d 100644 --- a/src/main/java/DummyCore/Utils/DummyBounds.java +++ b/src/main/java/DummyCore/Utils/DummyBounds.java @@ -1,24 +1,21 @@ package DummyCore.Utils; /** - * + * * @author Modbder * @version From DummyCore 1.2 * @Description Used to check, if the float is inbetween 2 others. */ public class DummyBounds { - private final float min; - private final float max; - - public DummyBounds(float m1, float m2) - { - min = m1; - max = m2; - } - - public boolean isInRange(float f) - { - return f > min && f < max; - } + private final float min; + private final float max; + public DummyBounds(float m1, float m2) { + min = m1; + max = m2; + } + + public boolean isInRange(float f) { + return f > min && f < max; + } } diff --git a/src/main/java/DummyCore/Utils/DummyColor.java b/src/main/java/DummyCore/Utils/DummyColor.java index fc40af8..f0dda29 100644 --- a/src/main/java/DummyCore/Utils/DummyColor.java +++ b/src/main/java/DummyCore/Utils/DummyColor.java @@ -1,47 +1,41 @@ package DummyCore.Utils; /** - * + * * @author Modbder * @version From DummyCore 1.1 * @Description Used to work with colors. Requires RGB colors, lesser than 256 to work. Can also convert them to the corresponding Hex value. */ public class DummyColor { - - private int[] color = new int[3]; - - public DummyColor(int red, int green, int blue) - { - color[0] = red; - color[1] = green; - color[2] = blue; - } - - public int getRed() - { - return color[0]; - } - - public int getGreen() - { - return color[1]; - } - - public int getBlue() - { - return color[2]; - } - - public int getColorInHex() - { - int ret = 0x000000; - int rHex = MathUtils.convertToHex(getRed()); - int gHex = MathUtils.convertToHex(getGreen()); - int bHex = MathUtils.convertToHex(getBlue()); - rHex *= 10000; - gHex *= 100; - ret = rHex+gHex+bHex; - return ret; - } + private int[] color = new int[3]; + + public DummyColor(int red, int green, int blue) { + color[0] = red; + color[1] = green; + color[2] = blue; + } + + public int getRed() { + return color[0]; + } + + public int getGreen() { + return color[1]; + } + + public int getBlue() { + return color[2]; + } + + public int getColorInHex() { + int ret = 0x000000; + int rHex = MathUtils.convertToHex(getRed()); + int gHex = MathUtils.convertToHex(getGreen()); + int bHex = MathUtils.convertToHex(getBlue()); + rHex *= 10000; + gHex *= 100; + ret = rHex + gHex + bHex; + return ret; + } } diff --git a/src/main/java/DummyCore/Utils/DummyConfig.java b/src/main/java/DummyCore/Utils/DummyConfig.java index 3aab955..66f824b 100644 --- a/src/main/java/DummyCore/Utils/DummyConfig.java +++ b/src/main/java/DummyCore/Utils/DummyConfig.java @@ -2,38 +2,42 @@ package DummyCore.Utils; import net.minecraftforge.common.config.Configuration; -public class DummyConfig implements IDummyConfig{ +public class DummyConfig implements IDummyConfig { - public int MultiItemUID; - public int MultiBlockUID; - public static int dummyCoreSyncTimer; - private static int mainMenuID; - public boolean removeMissingTexturesErrors; - public boolean allowCustomMainMenu; - public static boolean enableNotifierLogging; - public static boolean shouldChangeImage; - public static Configuration cfg; - public void load(Configuration config) - { - cfg = config; - removeMissingTexturesErrors = config.getBoolean("removeMissingTexturesErrors", "GLOBAL", true, ""); - enableNotifierLogging = config.getBoolean("enableNotifierLogging", "GLOBAL", true, ""); - shouldChangeImage = config.getBoolean("shouldChangeImageInCreativeTabs", "GLOBAL", true, ""); - allowCustomMainMenu = config.getBoolean("allowCustomMainMenu", "GLOBAL", true, ""); - mainMenuID = config.getInt("mainMenuID", "GLOBAL", 0,0,Integer.MAX_VALUE, ""); - dummyCoreSyncTimer = config.getInt("syncTimer", "GLOBAL", 100, 10, 1000, "Time inbetween syncing of data. The more the number is, the worse the sync is going to be, hwever, the less packets will be sent, and, therefore, the less annoying the server lag will be."); - } - - public static void setMainMenu(int i) - { - cfg.load(); - cfg.get("GLOBAL", "mainMenuID", 0, "").set(i); - mainMenuID = i; - cfg.save(); - } - - public static int getMainMenu() - { - return mainMenuID; - } + public int MultiItemUID; + public int MultiBlockUID; + public static int dummyCoreSyncTimer; + private static int mainMenuID; + public boolean removeMissingTexturesErrors; + public boolean allowCustomMainMenu; + public static boolean enableNotifierLogging; + public static boolean shouldChangeImage; + public static Configuration cfg; + + public void load(Configuration config) { + cfg = config; + removeMissingTexturesErrors = config.getBoolean("removeMissingTexturesErrors", "GLOBAL", true, ""); + enableNotifierLogging = config.getBoolean("enableNotifierLogging", "GLOBAL", true, ""); + shouldChangeImage = config.getBoolean("shouldChangeImageInCreativeTabs", "GLOBAL", true, ""); + allowCustomMainMenu = config.getBoolean("allowCustomMainMenu", "GLOBAL", true, ""); + mainMenuID = config.getInt("mainMenuID", "GLOBAL", 0, 0, Integer.MAX_VALUE, ""); + dummyCoreSyncTimer = config.getInt( + "syncTimer", + "GLOBAL", + 100, + 10, + 1000, + "Time inbetween syncing of data. The more the number is, the worse the sync is going to be, hwever, the less packets will be sent, and, therefore, the less annoying the server lag will be."); + } + + public static void setMainMenu(int i) { + cfg.load(); + cfg.get("GLOBAL", "mainMenuID", 0, "").set(i); + mainMenuID = i; + cfg.save(); + } + + public static int getMainMenu() { + return mainMenuID; + } } diff --git a/src/main/java/DummyCore/Utils/DummyData.java b/src/main/java/DummyCore/Utils/DummyData.java index dc0bcb1..79a4162 100644 --- a/src/main/java/DummyCore/Utils/DummyData.java +++ b/src/main/java/DummyCore/Utils/DummyData.java @@ -1,35 +1,32 @@ package DummyCore.Utils; /** - * + * * @author Modbder * @version From DummyCore 1.2 * @Description used to store almost any kind of variable using a special Data. When working, remember, that you can store any Object to the corresponding name. */ public class DummyData { - public final String fieldName; - public final String fieldValue; - public DummyData(String field, String value) - { - fieldName = field; - fieldValue = value; - } - - public DummyData(String field, Object value) - { - fieldName = field; - fieldValue = value.toString(); - } - - public String toString() - { - String ret = ""; - ret = ret.concat("||").concat(fieldName).concat(":").concat(fieldValue.toString()); - return ret; - } - - public static DummyData makeNull() - { - return new DummyData("null","null"); - } + public final String fieldName; + public final String fieldValue; + + public DummyData(String field, String value) { + fieldName = field; + fieldValue = value; + } + + public DummyData(String field, Object value) { + fieldName = field; + fieldValue = value.toString(); + } + + public String toString() { + String ret = ""; + ret = ret.concat("||").concat(fieldName).concat(":").concat(fieldValue.toString()); + return ret; + } + + public static DummyData makeNull() { + return new DummyData("null", "null"); + } } diff --git a/src/main/java/DummyCore/Utils/DummyDataUtils.java b/src/main/java/DummyCore/Utils/DummyDataUtils.java index 0221ea7..e2ca1b4 100644 --- a/src/main/java/DummyCore/Utils/DummyDataUtils.java +++ b/src/main/java/DummyCore/Utils/DummyDataUtils.java @@ -1,12 +1,15 @@ package DummyCore.Utils; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent; +import cpw.mods.fml.relauncher.Side; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Hashtable; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; @@ -14,530 +17,431 @@ import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerEvent.LoadFromFile; import net.minecraftforge.event.entity.player.PlayerEvent.SaveToFile; import net.minecraftforge.event.world.WorldEvent; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent; -import cpw.mods.fml.relauncher.Side; /** - * + * * @author Modbder * @version From DummyCore 1.4 * @Description used to store any String for players/worlds in the world save folder and get it. */ public class DummyDataUtils { - private static NBTTagCompound globalConfig; - private static Hashtable playerFiles = new Hashtable(); - private static Hashtable playerConfigs = new Hashtable(); - private static String getPath; - private static boolean isWorking; - private static File directory; - private static final Class clazz = DummyDataUtils.class; - - /** - * A new version of world loads, better server compathabilities. - */ - @SubscribeEvent - public void serverWorldLoad(WorldEvent.Load event) - { - try - { - World w = event.world; - if(w != null && !w.isRemote && w.provider != null && w.provider.dimensionId == 0) - { - File f = event.world.getSaveHandler().getWorldDirectory(); - if(f != null) - { - String fPath = f.getAbsolutePath(); - String dDataPath = fPath+"//DummyData//"; - directory = new File(dDataPath); - directory.mkdirs(); - File globalDataDat = new File(directory+"//GlobalData.ddat"); - - File f1 = new File(directory+"//PlayerData//"); - f1.mkdirs(); - getPath = dDataPath; - globalConfig = createOrLoadTag(globalDataDat); - isWorking = true; - } - } - }catch(Exception e) - { - Notifier.notifyCustomMod("DummyCore", "Error loading DummyData!");e.printStackTrace();return; - } - } - - @SubscribeEvent - public void serverWorldSave(WorldEvent.Save event) - { - try - { - World w = event.world; - if(w != null && !w.isRemote && w.provider != null && w.provider.dimensionId == 0) - { - File f = event.world.getSaveHandler().getWorldDirectory(); - if(f != null) - { - String fPath = f.getAbsolutePath(); - String dDataPath = fPath+"//DummyData//"; - directory = new File(dDataPath); - directory.mkdirs(); - File globalDataDat = new File(directory+"//GlobalData.ddat"); - saveGlobalTag(globalDataDat); - } - } - }catch(Exception e) - { - Notifier.notifyCustomMod("DummyCore", "Error loading DummyData!");e.printStackTrace();return; - } - } - - @SubscribeEvent - public void playerLoad(LoadFromFile event) - { - if(!event.entityPlayer.worldObj.isRemote) - { - EntityPlayer player = event.entityPlayer; - boolean exists = true; - File playerFile = getDataFileForPlayer(player.getCommandSenderName()); - if(playerFile.isDirectory()) - { - restoreFileFromDir(playerFile); - exists = false; - } - - if(!playerFile.exists()) - { - exists = false; - createFile(playerFile); - } - - if(exists) - { - NBTTagCompound tag = loadNBTFromFile(playerFile); - playerConfigs.put(player.getCommandSenderName(), tag); - }else - { - playerConfigs.put(player.getCommandSenderName(), new NBTTagCompound()); - } - } - } - - @SubscribeEvent - public void playerSave(SaveToFile event) - { - if(!event.entityPlayer.worldObj.isRemote) - { - EntityPlayer player = event.entityPlayer; - File playerFile = getDataFileForPlayer(player.getCommandSenderName()); - if(playerFile.isDirectory()) - restoreFileFromDir(playerFile); - - if(!playerFile.exists()) - createFile(playerFile); - - writeNBTToFile(globalConfig,playerFile); - } - } - - @SubscribeEvent - public void playerLogOut(PlayerLoggedOutEvent event) - { - if(!event.player.worldObj.isRemote) - { - playerFiles.remove(event.player.getCommandSenderName()); - playerConfigs.remove(event.player.getCommandSenderName()); - } - } - - private static void saveGlobalTag(File file) - { - if(file.isDirectory()) - restoreFileFromDir(file); - - if(!file.exists()) - createFile(file); - writeNBTToFile(globalConfig,file); - } - - - private static void writeNBTToFile(NBTTagCompound tag, File file) - { - try - { - FileOutputStream oStream = new FileOutputStream(file); - try - { - CompressedStreamTools.writeCompressed(tag, oStream); - } - catch(IOException ioe) - { - LoadingUtils.makeACrash(file+" appears to be damaged, either fix it or delete it!", clazz, ioe, false); - } - finally - { - oStream.close(); - } - } - catch(FileNotFoundException fnfe) - { - LoadingUtils.makeACrash(file+" does not exists. This is an impossible error and should be reported as soon as possible", clazz, fnfe, true); - } - catch(SecurityException se) - { - LoadingUtils.makeACrash(file+" Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); - } - catch(IOException ioe) - { - LoadingUtils.makeACrash(file+" Can't be created, check your file system!", clazz, ioe, true); - } - } - - private static void restoreFileFromDir(File file) - { - Notifier.notifyError(file+" Is a directory, and should not be. Trying to resolve the issue..."); - try - { - file.delete(); - file.createNewFile(); - } - catch(IOException ioe) - { - LoadingUtils.makeACrash(file+" Can't be created, check your file system!", clazz, ioe, true); - } - catch(SecurityException se) - { - LoadingUtils.makeACrash(file+" Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); - } - } - - private static void createFile(File file) - { - try - { - file.createNewFile(); - } - catch(IOException ioe) - { - LoadingUtils.makeACrash(file+" Can't be created, check your file system!", clazz, ioe, true); - } - catch(SecurityException se) - { - LoadingUtils.makeACrash(file+" Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); - } - } - - private static NBTTagCompound createOrLoadTag(File file) - { - NBTTagCompound tag = new NBTTagCompound(); - - boolean exists = true; - if(file.isDirectory()) - { - restoreFileFromDir(file); - exists = false; - } - - if(!file.exists()) - { - exists = false; - createFile(file); - } - - if(exists) - { - tag = loadNBTFromFile(file); - } - - return tag; - } - - private static NBTTagCompound loadNBTFromFile(File file) - { - try - { - FileInputStream iStream = new FileInputStream(file); - try - { - NBTTagCompound tag = CompressedStreamTools.readCompressed(iStream); - return tag; - } - catch(IOException ioe) - { - LoadingUtils.makeACrash(file+" appears to be damaged, either fix it or delete it!", clazz, ioe, false); - } - - finally - { - iStream.close(); - } - } - catch(FileNotFoundException fnfe) - { - LoadingUtils.makeACrash(file+" does not exists. This is an impossible error and should be reported as soon as possible", clazz, fnfe, true); - } - catch(SecurityException se) - { - LoadingUtils.makeACrash(file+" Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); - } - catch(IOException ioe) - { - LoadingUtils.makeACrash(file+" Can't be created, check your file system!", clazz, ioe, true); - } - - return new NBTTagCompound(); - } - - public static void stop() - { - globalConfig = null; - playerFiles.clear(); - playerConfigs.clear(); - getPath = "no path"; - isWorking = false; - directory = null; - MiscUtils.registeredClientData.clear(); - MiscUtils.registeredClientWorldData.clear(); - MiscUtils.registeredServerData.clear(); - MiscUtils.registeredServerWorldData.clear(); - } - - private static File getDataFileForPlayer(String playerName) - { - if(!playerFiles.containsKey(playerName)) - { - File ret = new File(getPath+"/PlayerData/"+playerName+".ddat"); - if(!ret.exists()) - try { - ret.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - playerFiles.put(playerName, ret); - return ret; - }else - { - return playerFiles.get(playerName); - } - - } - - private static NBTTagCompound getDataConfigForPlayer(String playerName) - { - if(!canWorkWithData()) - return null; - - if(!playerConfigs.containsKey(playerName)) - { - playerConfigs.put(playerName, createOrLoadTag(playerFiles.get(playerName))); - } - return playerConfigs.get(playerName); - } - - /** - * Writes the given String to the GlobalData.ddat file with the key of dataName - * @version From DummyCore 1.4 - * @param modid - the id of your mod - * @param dataName - key of the data - * @param dataString - data to store - */ - public static void writeCustomDataForMod(String modid, String dataName, String dataString) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - MiscUtils.registeredClientWorldData.put(modid+"|"+dataName, dataString); - }else - { - if(!canWorkWithData())return; - globalConfig.setString(modid+"|"+dataName,dataString); - MiscUtils.registeredServerWorldData.put(modid+"|"+dataName, dataString); - syncGlobalDataToClient(modid, dataName); - } - } - - public static void loadCustomDataForMod(String modid, String dataName) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - return; - }else - { - if(!canWorkWithData()) - return; - - MiscUtils.registeredServerWorldData.put(modid+"|"+dataName, globalConfig.getString(modid+"|"+dataName)); - syncGlobalDataToClient(modid, dataName); - } - } - - public static void loadGlobalDataForMod(String modid) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - return; - }else - { - if(!canWorkWithData()) - return; - - MiscUtils.registeredServerWorldData.put(modid+"|"+modid, globalConfig.getString(modid+"|"+modid)); - syncGlobalDataToClient(modid, modid); - } - } - - /** - * Writes the given String to the GlobalData.ddat file with the key of modid - * @version From DummyCore 1.4 - * @param modid - the id of your mod - * @param dataString - data to store - */ - public static void writeGlobalDataForMod(String modid, String dataString) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - MiscUtils.registeredClientWorldData.put(modid+"|"+modid, dataString); - }else - { - if(!canWorkWithData())return; - globalConfig.setString(modid+"|"+modid, dataString); - MiscUtils.registeredServerWorldData.put(modid+"|"+modid, dataString); - syncGlobalDataToClient(modid); - } - } - - - /** - * Returns the String from the GlobalData.ddat file with the key of modid - * @version From DummyCore 1.4 - * @param modid - the id of your mod - * @return a string with the data, written to the ddat file. Returns "no data" if none was found - */ - public static String getGlobalDataForMod(String modid) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - return MiscUtils.registeredClientWorldData.get(modid+"|"+modid); - }else - { - if(!MiscUtils.registeredServerWorldData.containsKey(modid+"|"+modid)) - loadGlobalDataForMod(modid); - return MiscUtils.registeredServerWorldData.get(modid+"|"+modid); - } - } - - /** - * Returns the String from the GlobalData.ddat file with the custom key - * @version From DummyCore 1.4 - * @param modid - the id of your mod - * @param dataName - key of the data - * @return a string with the data, written to the ddat file. Returns "no data" if none was found - */ - public static String getCustomDataForMod(String modid, String dataName) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - return MiscUtils.registeredClientWorldData.get(modid+"|"+dataName); - }else - { - if(!MiscUtils.registeredServerWorldData.containsKey(modid+"|"+dataName)) - loadCustomDataForMod(modid,dataName); - return MiscUtils.registeredServerWorldData.get(modid+"|"+dataName); - } - } - - /** - * Sets the given data to the ddat file of the player with given name. - * @version From DummyCore 1.4 - * @param playerName - name of the player - * @param modid - id of the mod - * @param dataName - key of the data - * @param dataValue - the data to store - */ - public static void setDataForPlayer(String playerName, String modid, String dataName, String dataValue) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - MiscUtils.registeredClientData.put(playerName+"_"+modid+"|"+dataName, dataValue); - }else - { - if(!canWorkWithData()) - return; - NBTTagCompound tag = getDataConfigForPlayer(playerName); - tag.setString(modid+"|"+dataName, dataValue); - MiscUtils.registeredServerData.put(playerName+"_"+modid+"|"+dataName, dataValue); - syncPlayerDataToClient(playerName, modid, dataName); - } - } - - public static void loadPlayerDataForMod(String playerName, String modid, String dataName) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - return; - }else - { - if(!canWorkWithData())return; - NBTTagCompound tag = getDataConfigForPlayer(playerName); - MiscUtils.registeredServerData.put(playerName+"_"+modid+"|"+dataName, tag.getString(modid+"|"+dataName)); - syncPlayerDataToClient(playerName, modid, dataName); - } - } - - - /** - * Returns the String from the ddat file of the given player with the custom key - * @version From DummyCore 1.4 - * @param playerName - name of the player - * @param modid - id of the mod - * @param dataName - key of the data - * @return a string with the data, written to the ddat file. Returns "no data" if none was found - */ - public static String getDataForPlayer(String playerName, String modid, String dataName) - { - Side s = FMLCommonHandler.instance().getEffectiveSide(); - if(s == Side.CLIENT) - { - return MiscUtils.registeredClientData.get(playerName+"_"+modid+"|"+dataName); - }else - { - if(!MiscUtils.registeredServerData.containsKey(playerName+"_"+modid+"|"+dataName)) - loadPlayerDataForMod(playerName, modid, dataName); - return MiscUtils.registeredServerData.get(playerName+"_"+modid+"|"+dataName); - } - } - - /** - * Used to check, if current world exists(for example, if the player is in the main menu returns false) - * @version From DummyCore 1.4 - * @return True, if there is a running world, false if not. - */ - public static boolean canWorkWithData() - { - return isWorking; - } - - public static void syncGlobalDataToClient(String modid, String dataName) - { - SyncUtils.addRequiresSync(modid, dataName); - } - - public static void syncGlobalDataToClient(String modid) - { - SyncUtils.addRequiresSync(modid, modid); - } - - public static void syncPlayerDataToClient(String playerName, String modid, String dataName) - { - SyncUtils.addRequiresSync(playerName, modid, dataName); - } + private static NBTTagCompound globalConfig; + private static Hashtable playerFiles = new Hashtable(); + private static Hashtable playerConfigs = new Hashtable(); + private static String getPath; + private static boolean isWorking; + private static File directory; + private static final Class clazz = DummyDataUtils.class; + /** + * A new version of world loads, better server compathabilities. + */ + @SubscribeEvent + public void serverWorldLoad(WorldEvent.Load event) { + try { + World w = event.world; + if (w != null && !w.isRemote && w.provider != null && w.provider.dimensionId == 0) { + File f = event.world.getSaveHandler().getWorldDirectory(); + if (f != null) { + String fPath = f.getAbsolutePath(); + String dDataPath = fPath + "//DummyData//"; + directory = new File(dDataPath); + directory.mkdirs(); + File globalDataDat = new File(directory + "//GlobalData.ddat"); + + File f1 = new File(directory + "//PlayerData//"); + f1.mkdirs(); + getPath = dDataPath; + globalConfig = createOrLoadTag(globalDataDat); + isWorking = true; + } + } + } catch (Exception e) { + Notifier.notifyCustomMod("DummyCore", "Error loading DummyData!"); + e.printStackTrace(); + return; + } + } + + @SubscribeEvent + public void serverWorldSave(WorldEvent.Save event) { + try { + World w = event.world; + if (w != null && !w.isRemote && w.provider != null && w.provider.dimensionId == 0) { + File f = event.world.getSaveHandler().getWorldDirectory(); + if (f != null) { + String fPath = f.getAbsolutePath(); + String dDataPath = fPath + "//DummyData//"; + directory = new File(dDataPath); + directory.mkdirs(); + File globalDataDat = new File(directory + "//GlobalData.ddat"); + saveGlobalTag(globalDataDat); + } + } + } catch (Exception e) { + Notifier.notifyCustomMod("DummyCore", "Error loading DummyData!"); + e.printStackTrace(); + return; + } + } + + @SubscribeEvent + public void playerLoad(LoadFromFile event) { + if (!event.entityPlayer.worldObj.isRemote) { + EntityPlayer player = event.entityPlayer; + boolean exists = true; + File playerFile = getDataFileForPlayer(player.getCommandSenderName()); + if (playerFile.isDirectory()) { + restoreFileFromDir(playerFile); + exists = false; + } + + if (!playerFile.exists()) { + exists = false; + createFile(playerFile); + } + + if (exists) { + NBTTagCompound tag = loadNBTFromFile(playerFile); + playerConfigs.put(player.getCommandSenderName(), tag); + } else { + playerConfigs.put(player.getCommandSenderName(), new NBTTagCompound()); + } + } + } + + @SubscribeEvent + public void playerSave(SaveToFile event) { + if (!event.entityPlayer.worldObj.isRemote) { + EntityPlayer player = event.entityPlayer; + File playerFile = getDataFileForPlayer(player.getCommandSenderName()); + if (playerFile.isDirectory()) restoreFileFromDir(playerFile); + + if (!playerFile.exists()) createFile(playerFile); + + writeNBTToFile(globalConfig, playerFile); + } + } + + @SubscribeEvent + public void playerLogOut(PlayerLoggedOutEvent event) { + if (!event.player.worldObj.isRemote) { + playerFiles.remove(event.player.getCommandSenderName()); + playerConfigs.remove(event.player.getCommandSenderName()); + } + } + + private static void saveGlobalTag(File file) { + if (file.isDirectory()) restoreFileFromDir(file); + + if (!file.exists()) createFile(file); + writeNBTToFile(globalConfig, file); + } + + private static void writeNBTToFile(NBTTagCompound tag, File file) { + try { + FileOutputStream oStream = new FileOutputStream(file); + try { + CompressedStreamTools.writeCompressed(tag, oStream); + } catch (IOException ioe) { + LoadingUtils.makeACrash( + file + " appears to be damaged, either fix it or delete it!", clazz, ioe, false); + } finally { + oStream.close(); + } + } catch (FileNotFoundException fnfe) { + LoadingUtils.makeACrash( + file + " does not exists. This is an impossible error and should be reported as soon as possible", + clazz, + fnfe, + true); + } catch (SecurityException se) { + LoadingUtils.makeACrash( + file + " Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); + } catch (IOException ioe) { + LoadingUtils.makeACrash(file + " Can't be created, check your file system!", clazz, ioe, true); + } + } + + private static void restoreFileFromDir(File file) { + Notifier.notifyError(file + " Is a directory, and should not be. Trying to resolve the issue..."); + try { + file.delete(); + file.createNewFile(); + } catch (IOException ioe) { + LoadingUtils.makeACrash(file + " Can't be created, check your file system!", clazz, ioe, true); + } catch (SecurityException se) { + LoadingUtils.makeACrash( + file + " Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); + } + } + + private static void createFile(File file) { + try { + file.createNewFile(); + } catch (IOException ioe) { + LoadingUtils.makeACrash(file + " Can't be created, check your file system!", clazz, ioe, true); + } catch (SecurityException se) { + LoadingUtils.makeACrash( + file + " Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); + } + } + + private static NBTTagCompound createOrLoadTag(File file) { + NBTTagCompound tag = new NBTTagCompound(); + + boolean exists = true; + if (file.isDirectory()) { + restoreFileFromDir(file); + exists = false; + } + + if (!file.exists()) { + exists = false; + createFile(file); + } + + if (exists) { + tag = loadNBTFromFile(file); + } + + return tag; + } + + private static NBTTagCompound loadNBTFromFile(File file) { + try { + FileInputStream iStream = new FileInputStream(file); + try { + NBTTagCompound tag = CompressedStreamTools.readCompressed(iStream); + return tag; + } catch (IOException ioe) { + LoadingUtils.makeACrash( + file + " appears to be damaged, either fix it or delete it!", clazz, ioe, false); + } finally { + iStream.close(); + } + } catch (FileNotFoundException fnfe) { + LoadingUtils.makeACrash( + file + " does not exists. This is an impossible error and should be reported as soon as possible", + clazz, + fnfe, + true); + } catch (SecurityException se) { + LoadingUtils.makeACrash( + file + " Can't be accessed by Java, check your anti-virus and file privelleges!", clazz, se, true); + } catch (IOException ioe) { + LoadingUtils.makeACrash(file + " Can't be created, check your file system!", clazz, ioe, true); + } + + return new NBTTagCompound(); + } + + public static void stop() { + globalConfig = null; + playerFiles.clear(); + playerConfigs.clear(); + getPath = "no path"; + isWorking = false; + directory = null; + MiscUtils.registeredClientData.clear(); + MiscUtils.registeredClientWorldData.clear(); + MiscUtils.registeredServerData.clear(); + MiscUtils.registeredServerWorldData.clear(); + } + + private static File getDataFileForPlayer(String playerName) { + if (!playerFiles.containsKey(playerName)) { + File ret = new File(getPath + "/PlayerData/" + playerName + ".ddat"); + if (!ret.exists()) + try { + ret.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + playerFiles.put(playerName, ret); + return ret; + } else { + return playerFiles.get(playerName); + } + } + + private static NBTTagCompound getDataConfigForPlayer(String playerName) { + if (!canWorkWithData()) return null; + + if (!playerConfigs.containsKey(playerName)) { + playerConfigs.put(playerName, createOrLoadTag(playerFiles.get(playerName))); + } + return playerConfigs.get(playerName); + } + + /** + * Writes the given String to the GlobalData.ddat file with the key of dataName + * @version From DummyCore 1.4 + * @param modid - the id of your mod + * @param dataName - key of the data + * @param dataString - data to store + */ + public static void writeCustomDataForMod(String modid, String dataName, String dataString) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + MiscUtils.registeredClientWorldData.put(modid + "|" + dataName, dataString); + } else { + if (!canWorkWithData()) return; + globalConfig.setString(modid + "|" + dataName, dataString); + MiscUtils.registeredServerWorldData.put(modid + "|" + dataName, dataString); + syncGlobalDataToClient(modid, dataName); + } + } + + public static void loadCustomDataForMod(String modid, String dataName) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + return; + } else { + if (!canWorkWithData()) return; + + MiscUtils.registeredServerWorldData.put( + modid + "|" + dataName, globalConfig.getString(modid + "|" + dataName)); + syncGlobalDataToClient(modid, dataName); + } + } + + public static void loadGlobalDataForMod(String modid) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + return; + } else { + if (!canWorkWithData()) return; + + MiscUtils.registeredServerWorldData.put(modid + "|" + modid, globalConfig.getString(modid + "|" + modid)); + syncGlobalDataToClient(modid, modid); + } + } + + /** + * Writes the given String to the GlobalData.ddat file with the key of modid + * @version From DummyCore 1.4 + * @param modid - the id of your mod + * @param dataString - data to store + */ + public static void writeGlobalDataForMod(String modid, String dataString) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + MiscUtils.registeredClientWorldData.put(modid + "|" + modid, dataString); + } else { + if (!canWorkWithData()) return; + globalConfig.setString(modid + "|" + modid, dataString); + MiscUtils.registeredServerWorldData.put(modid + "|" + modid, dataString); + syncGlobalDataToClient(modid); + } + } + + /** + * Returns the String from the GlobalData.ddat file with the key of modid + * @version From DummyCore 1.4 + * @param modid - the id of your mod + * @return a string with the data, written to the ddat file. Returns "no data" if none was found + */ + public static String getGlobalDataForMod(String modid) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + return MiscUtils.registeredClientWorldData.get(modid + "|" + modid); + } else { + if (!MiscUtils.registeredServerWorldData.containsKey(modid + "|" + modid)) loadGlobalDataForMod(modid); + return MiscUtils.registeredServerWorldData.get(modid + "|" + modid); + } + } + + /** + * Returns the String from the GlobalData.ddat file with the custom key + * @version From DummyCore 1.4 + * @param modid - the id of your mod + * @param dataName - key of the data + * @return a string with the data, written to the ddat file. Returns "no data" if none was found + */ + public static String getCustomDataForMod(String modid, String dataName) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + return MiscUtils.registeredClientWorldData.get(modid + "|" + dataName); + } else { + if (!MiscUtils.registeredServerWorldData.containsKey(modid + "|" + dataName)) + loadCustomDataForMod(modid, dataName); + return MiscUtils.registeredServerWorldData.get(modid + "|" + dataName); + } + } + + /** + * Sets the given data to the ddat file of the player with given name. + * @version From DummyCore 1.4 + * @param playerName - name of the player + * @param modid - id of the mod + * @param dataName - key of the data + * @param dataValue - the data to store + */ + public static void setDataForPlayer(String playerName, String modid, String dataName, String dataValue) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + MiscUtils.registeredClientData.put(playerName + "_" + modid + "|" + dataName, dataValue); + } else { + if (!canWorkWithData()) return; + NBTTagCompound tag = getDataConfigForPlayer(playerName); + tag.setString(modid + "|" + dataName, dataValue); + MiscUtils.registeredServerData.put(playerName + "_" + modid + "|" + dataName, dataValue); + syncPlayerDataToClient(playerName, modid, dataName); + } + } + + public static void loadPlayerDataForMod(String playerName, String modid, String dataName) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + return; + } else { + if (!canWorkWithData()) return; + NBTTagCompound tag = getDataConfigForPlayer(playerName); + MiscUtils.registeredServerData.put( + playerName + "_" + modid + "|" + dataName, tag.getString(modid + "|" + dataName)); + syncPlayerDataToClient(playerName, modid, dataName); + } + } + + /** + * Returns the String from the ddat file of the given player with the custom key + * @version From DummyCore 1.4 + * @param playerName - name of the player + * @param modid - id of the mod + * @param dataName - key of the data + * @return a string with the data, written to the ddat file. Returns "no data" if none was found + */ + public static String getDataForPlayer(String playerName, String modid, String dataName) { + Side s = FMLCommonHandler.instance().getEffectiveSide(); + if (s == Side.CLIENT) { + return MiscUtils.registeredClientData.get(playerName + "_" + modid + "|" + dataName); + } else { + if (!MiscUtils.registeredServerData.containsKey(playerName + "_" + modid + "|" + dataName)) + loadPlayerDataForMod(playerName, modid, dataName); + return MiscUtils.registeredServerData.get(playerName + "_" + modid + "|" + dataName); + } + } + + /** + * Used to check, if current world exists(for example, if the player is in the main menu returns false) + * @version From DummyCore 1.4 + * @return True, if there is a running world, false if not. + */ + public static boolean canWorkWithData() { + return isWorking; + } + + public static void syncGlobalDataToClient(String modid, String dataName) { + SyncUtils.addRequiresSync(modid, dataName); + } + + public static void syncGlobalDataToClient(String modid) { + SyncUtils.addRequiresSync(modid, modid); + } + + public static void syncPlayerDataToClient(String playerName, String modid, String dataName) { + SyncUtils.addRequiresSync(playerName, modid, dataName); + } } diff --git a/src/main/java/DummyCore/Utils/DummyDistance.java b/src/main/java/DummyCore/Utils/DummyDistance.java index fac36b3..26283a9 100644 --- a/src/main/java/DummyCore/Utils/DummyDistance.java +++ b/src/main/java/DummyCore/Utils/DummyDistance.java @@ -1,41 +1,36 @@ package DummyCore.Utils; /** - * + * * @author Modbder * @version From DummyCore 1.2 * @Description Used to store the distance betwenn 2 points. */ public class DummyDistance { - private final float distance; - - public DummyDistance() - { - distance = 0; - } - - public DummyDistance(Coord3D first, Coord3D second) - { - float diffX = MathUtils.getDifference(first.x, second.x); - float diffY = MathUtils.getDifference(first.y, second.y); - float diffZ = MathUtils.getDifference(first.z, second.z); - distance = (float) Math.sqrt(diffX*diffX+diffY*diffY+diffZ*diffZ); - } - - public DummyDistance(Coord2D first, Coord2D second) - { - float diffX = MathUtils.getDifference(first.x, second.x); - float diffZ = MathUtils.getDifference(first.z, second.z); - distance = (float) Math.sqrt(diffX*diffX+diffZ*diffZ); - } - - public DummyDistance(float first, float second) - { - distance = MathUtils.getDifference(first, second); - } - - public float getDistance() - { - return this.distance; - } + private final float distance; + + public DummyDistance() { + distance = 0; + } + + public DummyDistance(Coord3D first, Coord3D second) { + float diffX = MathUtils.getDifference(first.x, second.x); + float diffY = MathUtils.getDifference(first.y, second.y); + float diffZ = MathUtils.getDifference(first.z, second.z); + distance = (float) Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ); + } + + public DummyDistance(Coord2D first, Coord2D second) { + float diffX = MathUtils.getDifference(first.x, second.x); + float diffZ = MathUtils.getDifference(first.z, second.z); + distance = (float) Math.sqrt(diffX * diffX + diffZ * diffZ); + } + + public DummyDistance(float first, float second) { + distance = MathUtils.getDifference(first, second); + } + + public float getDistance() { + return this.distance; + } } diff --git a/src/main/java/DummyCore/Utils/DummyEventHandler.java b/src/main/java/DummyCore/Utils/DummyEventHandler.java index 5a001d4..9a2d666 100644 --- a/src/main/java/DummyCore/Utils/DummyEventHandler.java +++ b/src/main/java/DummyCore/Utils/DummyEventHandler.java @@ -1,19 +1,5 @@ package DummyCore.Utils; -import java.util.Arrays; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.management.ServerConfigurationManager; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.entity.EntityJoinWorldEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; import DummyCore.Client.GuiButton_ChangeGUI; import DummyCore.Client.MainMenuRegistry; import DummyCore.Core.CoreInitialiser; @@ -26,6 +12,19 @@ import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Arrays; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.management.ServerConfigurationManager; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.EntityJoinWorldEvent; +import net.minecraftforge.event.entity.player.PlayerEvent; /** * @author Modbder @@ -33,213 +32,189 @@ import cpw.mods.fml.relauncher.SideOnly; * @Description Used for internal DummyCore features. Do NOT change! */ public class DummyEventHandler { - - public static int syncTime; - public static boolean[] isKeyPressed; - - public void onBlockBeeingBroken(PlayerEvent.BreakSpeed event) - { - if(MiscUtils.isBlockUnbreakable(event.entityPlayer.worldObj, event.x, event.y, event.z)) - { - event.setCanceled(true); - } - } - - @SideOnly(Side.CLIENT) - @SubscribeEvent - public void onMainMenuGUISetup(InitGuiEvent.Pre event) - { - if(!CoreInitialiser.cfg.allowCustomMainMenu) - return; - if(event.gui.getClass() == GuiMainMenu.class) - { - event.setCanceled(true); - MainMenuRegistry.newMainMenu(DummyConfig.getMainMenu()); - } - if(event.gui instanceof IMainMenu) - { - if(MainMenuRegistry.menuList.get(DummyConfig.getMainMenu()) != event.gui.getClass()) - { - event.setCanceled(true); - MainMenuRegistry.newMainMenu(DummyConfig.getMainMenu()); - } - } - } - - @SuppressWarnings("unchecked") - @SideOnly(Side.CLIENT) - @SubscribeEvent - public void onMainMenuGUISetup(InitGuiEvent.Post event) - { - if(!CoreInitialiser.cfg.allowCustomMainMenu) - return; - - if(event.gui instanceof IMainMenu) - { - boolean add = true; - for(int i = 0; i < event.buttonList.size(); ++i) - { - Object obj = event.buttonList.get(i); - if(obj instanceof GuiButton && GuiButton.class.cast(obj).id == 65536) - { - add = false; - break; - } - } - if(add) - event.buttonList.add(new GuiButton_ChangeGUI(65535, event.gui.width/2 + 104, event.gui.height/4 + 24 + 72, 100, 20, "Change Main Menu")); - } - } - - @SubscribeEvent - public void onPacketRecieved(DummyEvent_OnPacketRecieved event) - { - DummyData[] packetData = DataStorage.parseData(event.recievedData); - if(packetData != null && packetData.length > 0) - { - try { - DummyData modData = packetData[0]; - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummycore.tilesync")) - { - int x = Integer.parseInt(packetData[1].fieldValue); - int y = Integer.parseInt(packetData[2].fieldValue); - int z = Integer.parseInt(packetData[3].fieldValue); - TileEntity tile = event.recievedEntity.worldObj.getTileEntity(x, y, z); - if(tile != null && tile instanceof ITEHasGameData) - { - DummyData[] tileShouldRecieve = Arrays.copyOfRange(packetData, 4, packetData.length); - ((ITEHasGameData)tile).setData(tileShouldRecieve); - } - } - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummycore.particle")) - { - String type = packetData[1].fieldValue; - float x = Float.parseFloat(packetData[2].fieldValue); - float y = Float.parseFloat(packetData[3].fieldValue); - float z = Float.parseFloat(packetData[4].fieldValue); - double r = Double.parseDouble(packetData[5].fieldValue); - double g = Double.parseDouble(packetData[6].fieldValue); - double b = Double.parseDouble(packetData[7].fieldValue); - event.recievedEntity.worldObj.spawnParticle(type, x, y, z, r, g, b); - } - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummycore.sound")) - { - double x = Double.parseDouble(packetData[1].fieldValue); - double y = Double.parseDouble(packetData[2].fieldValue); - double z = Double.parseDouble(packetData[3].fieldValue); - float vol = Float.parseFloat(packetData[4].fieldValue); - float pitch = Float.parseFloat(packetData[5].fieldValue); - String snd = packetData[6].fieldValue; - event.recievedEntity.worldObj.playSound(x, y, z, snd, vol, pitch, false); - } - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummycore.infosync")) - { - String modName = packetData[1].fieldName; - String dataName = packetData[1].fieldValue; - String dataItself = event.recievedData.substring(event.recievedData.indexOf("||ddata:")+8); - MiscUtils.registeredClientWorldData.put(modName+"|"+dataName, dataItself); - } - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummycore.playerinfosync")) - { - String playerName = packetData[1].fieldValue; - String modName = packetData[2].fieldName; - String dataName = packetData[2].fieldValue; - String dataItself = event.recievedData.substring(event.recievedData.indexOf("||ddata:")+8); - MiscUtils.registeredClientData.put(playerName+"_"+modName+"|"+dataName, dataItself); - } - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummycore.biomechange")) - { - int x = Integer.parseInt(packetData[1].fieldValue); - int z = Integer.parseInt(packetData[2].fieldValue); - int id = Integer.parseInt(packetData[3].fieldValue); - World world = event.recievedEntity.worldObj; - Chunk chunk = world.getChunkFromBlockCoords(x,z); - byte[] biome = chunk.getBiomeArray(); - int cbiome = biome[(z & 0xf) << 4 | x & 0xf]; - cbiome = id & 0xff; - biome[(z & 0xf) << 4 | x & 0xf] = (byte) cbiome; - chunk.setBiomeArray(biome); - world.markBlocksDirtyVertical(x, z, 16, 16); - } - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummyCore.buttonpress")) - { - int id = Integer.parseInt(packetData[1].fieldValue); - String name = packetData[2].fieldValue; - String username = packetData[3].fieldValue; - boolean pressed = Boolean.parseBoolean(packetData[4].fieldValue); - Side side = FMLCommonHandler.instance().getEffectiveSide(); - if(side == Side.SERVER) - { - MinecraftServer server = MinecraftServer.getServer(); - ServerConfigurationManager manager = server.getConfigurationManager(); - EntityPlayer player = manager.func_152612_a(username); - MinecraftForge.EVENT_BUS.post(new DummyEvent_OnKeyboardKeyPressed_Server(id, name, player,pressed)); - } - } - if(modData.fieldName.equalsIgnoreCase("mod") && modData.fieldValue.equalsIgnoreCase("dummyCore.guiButton")) - { - int id = Integer.parseInt(packetData[1].fieldValue); - String pClName = packetData[2].fieldValue; - String bClName = packetData[3].fieldValue; - String username = packetData[4].fieldValue; - int x = Integer.parseInt(packetData[5].fieldValue); - int y = Integer.parseInt(packetData[6].fieldValue); - int z = Integer.parseInt(packetData[7].fieldValue); - DummyData[] data = new DummyData[packetData.length-8]; - for(int i = 8; i < packetData.length; ++i) - data[i-8] = packetData[i]; - Side side = FMLCommonHandler.instance().getEffectiveSide(); - if(side == Side.SERVER) - { - MinecraftServer server = MinecraftServer.getServer(); - ServerConfigurationManager manager = server.getConfigurationManager(); - EntityPlayer player = manager.func_152612_a(username); - MinecraftForge.EVENT_BUS.post(new DummyEvent_OnClientGUIButtonPress(id, pClName, bClName, player,x,y,z,data)); - } - } - - } catch (Exception e) { - e.printStackTrace(); - return; - } - } - } - - @SubscribeEvent - public void onServerTick(TickEvent.ServerTickEvent event) - { - if(event.phase == Phase.END) - { - ++syncTime; - if(syncTime >= DummyConfig.dummyCoreSyncTimer) - { - syncTime = 0; - SyncUtils.makeSync_LotsSmallPackets(); - } - actionsTick(); - } - } - - private void actionsTick() - { - if(!MiscUtils.actions.isEmpty()) - for(int i = 0; i < MiscUtils.actions.size(); ++i) - { - ScheduledServerAction ssa = MiscUtils.actions.get(i); - --ssa.actionTime; - if(ssa.actionTime <= 0) - { - ssa.execute(); - MiscUtils.actions.remove(i); - } - } - } - - @SubscribeEvent - public void clientWorldLoad(EntityJoinWorldEvent event) - { - if(event.entity instanceof EntityPlayer && event.world.isRemote) - ModVersionChecker.dispatchModChecks(); - } + public static int syncTime; + public static boolean[] isKeyPressed; + + public void onBlockBeeingBroken(PlayerEvent.BreakSpeed event) { + if (MiscUtils.isBlockUnbreakable(event.entityPlayer.worldObj, event.x, event.y, event.z)) { + event.setCanceled(true); + } + } + + @SideOnly(Side.CLIENT) + @SubscribeEvent + public void onMainMenuGUISetup(InitGuiEvent.Pre event) { + if (!CoreInitialiser.cfg.allowCustomMainMenu) return; + if (event.gui.getClass() == GuiMainMenu.class) { + event.setCanceled(true); + MainMenuRegistry.newMainMenu(DummyConfig.getMainMenu()); + } + if (event.gui instanceof IMainMenu) { + if (MainMenuRegistry.menuList.get(DummyConfig.getMainMenu()) != event.gui.getClass()) { + event.setCanceled(true); + MainMenuRegistry.newMainMenu(DummyConfig.getMainMenu()); + } + } + } + + @SuppressWarnings("unchecked") + @SideOnly(Side.CLIENT) + @SubscribeEvent + public void onMainMenuGUISetup(InitGuiEvent.Post event) { + if (!CoreInitialiser.cfg.allowCustomMainMenu) return; + + if (event.gui instanceof IMainMenu) { + boolean add = true; + for (int i = 0; i < event.buttonList.size(); ++i) { + Object obj = event.buttonList.get(i); + if (obj instanceof GuiButton && GuiButton.class.cast(obj).id == 65536) { + add = false; + break; + } + } + if (add) + event.buttonList.add(new GuiButton_ChangeGUI( + 65535, event.gui.width / 2 + 104, event.gui.height / 4 + 24 + 72, 100, 20, "Change Main Menu")); + } + } + + @SubscribeEvent + public void onPacketRecieved(DummyEvent_OnPacketRecieved event) { + DummyData[] packetData = DataStorage.parseData(event.recievedData); + if (packetData != null && packetData.length > 0) { + try { + DummyData modData = packetData[0]; + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummycore.tilesync")) { + int x = Integer.parseInt(packetData[1].fieldValue); + int y = Integer.parseInt(packetData[2].fieldValue); + int z = Integer.parseInt(packetData[3].fieldValue); + TileEntity tile = event.recievedEntity.worldObj.getTileEntity(x, y, z); + if (tile != null && tile instanceof ITEHasGameData) { + DummyData[] tileShouldRecieve = Arrays.copyOfRange(packetData, 4, packetData.length); + ((ITEHasGameData) tile).setData(tileShouldRecieve); + } + } + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummycore.particle")) { + String type = packetData[1].fieldValue; + float x = Float.parseFloat(packetData[2].fieldValue); + float y = Float.parseFloat(packetData[3].fieldValue); + float z = Float.parseFloat(packetData[4].fieldValue); + double r = Double.parseDouble(packetData[5].fieldValue); + double g = Double.parseDouble(packetData[6].fieldValue); + double b = Double.parseDouble(packetData[7].fieldValue); + event.recievedEntity.worldObj.spawnParticle(type, x, y, z, r, g, b); + } + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummycore.sound")) { + double x = Double.parseDouble(packetData[1].fieldValue); + double y = Double.parseDouble(packetData[2].fieldValue); + double z = Double.parseDouble(packetData[3].fieldValue); + float vol = Float.parseFloat(packetData[4].fieldValue); + float pitch = Float.parseFloat(packetData[5].fieldValue); + String snd = packetData[6].fieldValue; + event.recievedEntity.worldObj.playSound(x, y, z, snd, vol, pitch, false); + } + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummycore.infosync")) { + String modName = packetData[1].fieldName; + String dataName = packetData[1].fieldValue; + String dataItself = event.recievedData.substring(event.recievedData.indexOf("||ddata:") + 8); + MiscUtils.registeredClientWorldData.put(modName + "|" + dataName, dataItself); + } + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummycore.playerinfosync")) { + String playerName = packetData[1].fieldValue; + String modName = packetData[2].fieldName; + String dataName = packetData[2].fieldValue; + String dataItself = event.recievedData.substring(event.recievedData.indexOf("||ddata:") + 8); + MiscUtils.registeredClientData.put(playerName + "_" + modName + "|" + dataName, dataItself); + } + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummycore.biomechange")) { + int x = Integer.parseInt(packetData[1].fieldValue); + int z = Integer.parseInt(packetData[2].fieldValue); + int id = Integer.parseInt(packetData[3].fieldValue); + World world = event.recievedEntity.worldObj; + Chunk chunk = world.getChunkFromBlockCoords(x, z); + byte[] biome = chunk.getBiomeArray(); + int cbiome = biome[(z & 0xf) << 4 | x & 0xf]; + cbiome = id & 0xff; + biome[(z & 0xf) << 4 | x & 0xf] = (byte) cbiome; + chunk.setBiomeArray(biome); + world.markBlocksDirtyVertical(x, z, 16, 16); + } + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummyCore.buttonpress")) { + int id = Integer.parseInt(packetData[1].fieldValue); + String name = packetData[2].fieldValue; + String username = packetData[3].fieldValue; + boolean pressed = Boolean.parseBoolean(packetData[4].fieldValue); + Side side = FMLCommonHandler.instance().getEffectiveSide(); + if (side == Side.SERVER) { + MinecraftServer server = MinecraftServer.getServer(); + ServerConfigurationManager manager = server.getConfigurationManager(); + EntityPlayer player = manager.func_152612_a(username); + MinecraftForge.EVENT_BUS.post( + new DummyEvent_OnKeyboardKeyPressed_Server(id, name, player, pressed)); + } + } + if (modData.fieldName.equalsIgnoreCase("mod") + && modData.fieldValue.equalsIgnoreCase("dummyCore.guiButton")) { + int id = Integer.parseInt(packetData[1].fieldValue); + String pClName = packetData[2].fieldValue; + String bClName = packetData[3].fieldValue; + String username = packetData[4].fieldValue; + int x = Integer.parseInt(packetData[5].fieldValue); + int y = Integer.parseInt(packetData[6].fieldValue); + int z = Integer.parseInt(packetData[7].fieldValue); + DummyData[] data = new DummyData[packetData.length - 8]; + for (int i = 8; i < packetData.length; ++i) data[i - 8] = packetData[i]; + Side side = FMLCommonHandler.instance().getEffectiveSide(); + if (side == Side.SERVER) { + MinecraftServer server = MinecraftServer.getServer(); + ServerConfigurationManager manager = server.getConfigurationManager(); + EntityPlayer player = manager.func_152612_a(username); + MinecraftForge.EVENT_BUS.post( + new DummyEvent_OnClientGUIButtonPress(id, pClName, bClName, player, x, y, z, data)); + } + } + + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + } + + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent event) { + if (event.phase == Phase.END) { + ++syncTime; + if (syncTime >= DummyConfig.dummyCoreSyncTimer) { + syncTime = 0; + SyncUtils.makeSync_LotsSmallPackets(); + } + actionsTick(); + } + } + + private void actionsTick() { + if (!MiscUtils.actions.isEmpty()) + for (int i = 0; i < MiscUtils.actions.size(); ++i) { + ScheduledServerAction ssa = MiscUtils.actions.get(i); + --ssa.actionTime; + if (ssa.actionTime <= 0) { + ssa.execute(); + MiscUtils.actions.remove(i); + } + } + } + + @SubscribeEvent + public void clientWorldLoad(EntityJoinWorldEvent event) { + if (event.entity instanceof EntityPlayer && event.world.isRemote) ModVersionChecker.dispatchModChecks(); + } } diff --git a/src/main/java/DummyCore/Utils/DummyFakePlayerFactory.java b/src/main/java/DummyCore/Utils/DummyFakePlayerFactory.java index 9e7621f..9d4fa64 100644 --- a/src/main/java/DummyCore/Utils/DummyFakePlayerFactory.java +++ b/src/main/java/DummyCore/Utils/DummyFakePlayerFactory.java @@ -1,20 +1,17 @@ package DummyCore.Utils; +import com.mojang.authlib.GameProfile; import java.util.Hashtable; import java.util.UUID; -import com.mojang.authlib.GameProfile; - public class DummyFakePlayerFactory { - - public static Hashtable, GameProfile> fakeProfiles = new Hashtable, GameProfile>(); - - public static GameProfile getGameProfile(Class mod) - { - if(fakeProfiles.get(mod) == null) - { - fakeProfiles.put(mod, new GameProfile(UUID.randomUUID(), "[DC]["+mod.getSimpleName()+"]")); - } - return fakeProfiles.get(mod); - } + + public static Hashtable, GameProfile> fakeProfiles = new Hashtable, GameProfile>(); + + public static GameProfile getGameProfile(Class mod) { + if (fakeProfiles.get(mod) == null) { + fakeProfiles.put(mod, new GameProfile(UUID.randomUUID(), "[DC][" + mod.getSimpleName() + "]")); + } + return fakeProfiles.get(mod); + } } diff --git a/src/main/java/DummyCore/Utils/DummyPacketHandler.java b/src/main/java/DummyCore/Utils/DummyPacketHandler.java index 952b92b..d45b3b7 100644 --- a/src/main/java/DummyCore/Utils/DummyPacketHandler.java +++ b/src/main/java/DummyCore/Utils/DummyPacketHandler.java @@ -2,55 +2,48 @@ package DummyCore.Utils; import DummyCore.Core.CoreInitialiser; import DummyCore.Events.DummyEvent_OnPacketRecieved; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.relauncher.Side; import io.netty.channel.ChannelHandler; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraftforge.common.MinecraftForge; @ChannelHandler.Sharable public class DummyPacketHandler implements IMessageHandler { - @Override - public IMessage onMessage(DummyPacketIMSG message, MessageContext ctx) - { - Side s = ctx.side; - if(s == Side.CLIENT) - { - MinecraftForge.EVENT_BUS.post(new DummyEvent_OnPacketRecieved(s, message.dataStr, CoreInitialiser.proxy.getPlayerOnSide(ctx.getClientHandler()))); - }else - { - MinecraftForge.EVENT_BUS.post(new DummyEvent_OnPacketRecieved(s, message.dataStr, CoreInitialiser.proxy.getPlayerOnSide(ctx.getServerHandler()))); - } - return null; - } - - public static void sendToAll(DummyPacketIMSG message) - { - CoreInitialiser.network.sendToAll(message); - } - - public static void sendToAllAround(DummyPacketIMSG message, TargetPoint pnt) - { - CoreInitialiser.network.sendToAllAround(message, pnt); - } - - public static void sendToAllAround(DummyPacketIMSG message, int dim) - { - CoreInitialiser.network.sendToDimension(message, dim); - } - - public static void sendToPlayer(DummyPacketIMSG message, EntityPlayerMP player) - { - CoreInitialiser.network.sendTo(message, (EntityPlayerMP) player); - } - - public static void sendToServer(DummyPacketIMSG message) - { - CoreInitialiser.network.sendToServer(message); - } + @Override + public IMessage onMessage(DummyPacketIMSG message, MessageContext ctx) { + Side s = ctx.side; + if (s == Side.CLIENT) { + MinecraftForge.EVENT_BUS.post(new DummyEvent_OnPacketRecieved( + s, message.dataStr, CoreInitialiser.proxy.getPlayerOnSide(ctx.getClientHandler()))); + } else { + MinecraftForge.EVENT_BUS.post(new DummyEvent_OnPacketRecieved( + s, message.dataStr, CoreInitialiser.proxy.getPlayerOnSide(ctx.getServerHandler()))); + } + return null; + } -} \ No newline at end of file + public static void sendToAll(DummyPacketIMSG message) { + CoreInitialiser.network.sendToAll(message); + } + + public static void sendToAllAround(DummyPacketIMSG message, TargetPoint pnt) { + CoreInitialiser.network.sendToAllAround(message, pnt); + } + + public static void sendToAllAround(DummyPacketIMSG message, int dim) { + CoreInitialiser.network.sendToDimension(message, dim); + } + + public static void sendToPlayer(DummyPacketIMSG message, EntityPlayerMP player) { + CoreInitialiser.network.sendTo(message, (EntityPlayerMP) player); + } + + public static void sendToServer(DummyPacketIMSG message) { + CoreInitialiser.network.sendToServer(message); + } +} diff --git a/src/main/java/DummyCore/Utils/DummyPacketIMSG.java b/src/main/java/DummyCore/Utils/DummyPacketIMSG.java index 05aa44c..8863cd2 100644 --- a/src/main/java/DummyCore/Utils/DummyPacketIMSG.java +++ b/src/main/java/DummyCore/Utils/DummyPacketIMSG.java @@ -1,32 +1,26 @@ package DummyCore.Utils; -import io.netty.buffer.ByteBuf; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; +import io.netty.buffer.ByteBuf; -public class DummyPacketIMSG implements IMessage{ - - public String dataStr; - - public DummyPacketIMSG() - { - - } - - public DummyPacketIMSG(String data) - { - dataStr = data; - } +public class DummyPacketIMSG implements IMessage { - @Override - public void fromBytes(ByteBuf buf) { - dataStr = ByteBufUtils.readUTF8String(buf); - } + public String dataStr; - @Override - public void toBytes(ByteBuf buf) { - ByteBufUtils.writeUTF8String(buf, dataStr); - - } + public DummyPacketIMSG() {} + public DummyPacketIMSG(String data) { + dataStr = data; + } + + @Override + public void fromBytes(ByteBuf buf) { + dataStr = ByteBufUtils.readUTF8String(buf); + } + + @Override + public void toBytes(ByteBuf buf) { + ByteBufUtils.writeUTF8String(buf, dataStr); + } } diff --git a/src/main/java/DummyCore/Utils/DummyPacketIMSG_Tile.java b/src/main/java/DummyCore/Utils/DummyPacketIMSG_Tile.java index 692b0e9..f805b41 100644 --- a/src/main/java/DummyCore/Utils/DummyPacketIMSG_Tile.java +++ b/src/main/java/DummyCore/Utils/DummyPacketIMSG_Tile.java @@ -1,39 +1,32 @@ package DummyCore.Utils; -import net.minecraft.nbt.NBTTagCompound; -import io.netty.buffer.ByteBuf; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; +import io.netty.buffer.ByteBuf; +import net.minecraft.nbt.NBTTagCompound; -public class DummyPacketIMSG_Tile implements IMessage{ - - public NBTTagCompound dataTag; - - public DummyPacketIMSG_Tile() - { - - } - - public DummyPacketIMSG_Tile(NBTTagCompound data, int id) - { - dataTag = data; - dataTag.setInteger("packetID", id); - } - - public DummyPacketIMSG_Tile(NBTTagCompound data) - { - dataTag = data; - } +public class DummyPacketIMSG_Tile implements IMessage { - @Override - public void fromBytes(ByteBuf buf) { - dataTag = ByteBufUtils.readTag(buf); - } + public NBTTagCompound dataTag; - @Override - public void toBytes(ByteBuf buf) { - ByteBufUtils.writeTag(buf, dataTag); - - } + public DummyPacketIMSG_Tile() {} + public DummyPacketIMSG_Tile(NBTTagCompound data, int id) { + dataTag = data; + dataTag.setInteger("packetID", id); + } + + public DummyPacketIMSG_Tile(NBTTagCompound data) { + dataTag = data; + } + + @Override + public void fromBytes(ByteBuf buf) { + dataTag = ByteBufUtils.readTag(buf); + } + + @Override + public void toBytes(ByteBuf buf) { + ByteBufUtils.writeTag(buf, dataTag); + } } diff --git a/src/main/java/DummyCore/Utils/DummyPlayerTickTracker.java b/src/main/java/DummyCore/Utils/DummyPlayerTickTracker.java index b1ae5b2..c13ba39 100644 --- a/src/main/java/DummyCore/Utils/DummyPlayerTickTracker.java +++ b/src/main/java/DummyCore/Utils/DummyPlayerTickTracker.java @@ -1,6 +1,4 @@ package DummyCore.Utils; @Deprecated -public class DummyPlayerTickTracker { - -} +public class DummyPlayerTickTracker {} diff --git a/src/main/java/DummyCore/Utils/DummyTilePacketHandler.java b/src/main/java/DummyCore/Utils/DummyTilePacketHandler.java index 5dab249..298d9e1 100644 --- a/src/main/java/DummyCore/Utils/DummyTilePacketHandler.java +++ b/src/main/java/DummyCore/Utils/DummyTilePacketHandler.java @@ -1,62 +1,57 @@ package DummyCore.Utils; import DummyCore.Core.CoreInitialiser; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.relauncher.Side; import io.netty.channel.ChannelHandler; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.play.server.S35PacketUpdateTileEntity; @ChannelHandler.Sharable public class DummyTilePacketHandler implements IMessageHandler { - @Override - public IMessage onMessage(DummyPacketIMSG_Tile message, MessageContext ctx) - { - Side s = ctx.side; - int packetID = -10; - if(message.dataTag.hasKey("packetID")) - { - packetID = message.dataTag.getInteger("packetID"); - message.dataTag.removeTag("packetID"); - } - S35PacketUpdateTileEntity genPkt = new S35PacketUpdateTileEntity(message.dataTag.getInteger("x"),message.dataTag.getInteger("y"),message.dataTag.getInteger("z"),packetID,message.dataTag); - if(s == Side.CLIENT) - { - ctx.getClientHandler().handleUpdateTileEntity(genPkt); - }else - { - - } - return null; - } - - public static void sendToAll(DummyPacketIMSG_Tile message) - { - CoreInitialiser.network.sendToAll(message); - } - - public static void sendToAllAround(DummyPacketIMSG_Tile message, TargetPoint pnt) - { - CoreInitialiser.network.sendToAllAround(message, pnt); - } - - public static void sendToAllAround(DummyPacketIMSG_Tile message, int dim) - { - CoreInitialiser.network.sendToDimension(message, dim); - } - - public static void sendToPlayer(DummyPacketIMSG_Tile message, EntityPlayerMP player) - { - CoreInitialiser.network.sendTo(message, (EntityPlayerMP) player); - } - - public static void sendToServer(DummyPacketIMSG_Tile message) - { - CoreInitialiser.network.sendToServer(message); - } + @Override + public IMessage onMessage(DummyPacketIMSG_Tile message, MessageContext ctx) { + Side s = ctx.side; + int packetID = -10; + if (message.dataTag.hasKey("packetID")) { + packetID = message.dataTag.getInteger("packetID"); + message.dataTag.removeTag("packetID"); + } + S35PacketUpdateTileEntity genPkt = new S35PacketUpdateTileEntity( + message.dataTag.getInteger("x"), + message.dataTag.getInteger("y"), + message.dataTag.getInteger("z"), + packetID, + message.dataTag); + if (s == Side.CLIENT) { + ctx.getClientHandler().handleUpdateTileEntity(genPkt); + } else { -} \ No newline at end of file + } + return null; + } + + public static void sendToAll(DummyPacketIMSG_Tile message) { + CoreInitialiser.network.sendToAll(message); + } + + public static void sendToAllAround(DummyPacketIMSG_Tile message, TargetPoint pnt) { + CoreInitialiser.network.sendToAllAround(message, pnt); + } + + public static void sendToAllAround(DummyPacketIMSG_Tile message, int dim) { + CoreInitialiser.network.sendToDimension(message, dim); + } + + public static void sendToPlayer(DummyPacketIMSG_Tile message, EntityPlayerMP player) { + CoreInitialiser.network.sendTo(message, (EntityPlayerMP) player); + } + + public static void sendToServer(DummyPacketIMSG_Tile message) { + CoreInitialiser.network.sendToServer(message); + } +} diff --git a/src/main/java/DummyCore/Utils/EnumGuiPosition.java b/src/main/java/DummyCore/Utils/EnumGuiPosition.java index 3c58f4f..94c4cd7 100644 --- a/src/main/java/DummyCore/Utils/EnumGuiPosition.java +++ b/src/main/java/DummyCore/Utils/EnumGuiPosition.java @@ -2,18 +2,14 @@ package DummyCore.Utils; @Deprecated public enum EnumGuiPosition { - TOPLEFT, - TOPRIGHT, - BOTLEFT, - BOTRIGHT, - CENTER; - - public int x; - public int y; - EnumGuiPosition() - { - } - - + TOPLEFT, + TOPRIGHT, + BOTLEFT, + BOTRIGHT, + CENTER; + public int x; + public int y; + + EnumGuiPosition() {} } diff --git a/src/main/java/DummyCore/Utils/EnumLightColor.java b/src/main/java/DummyCore/Utils/EnumLightColor.java index ca247c4..716aae1 100644 --- a/src/main/java/DummyCore/Utils/EnumLightColor.java +++ b/src/main/java/DummyCore/Utils/EnumLightColor.java @@ -1,53 +1,48 @@ package DummyCore.Utils; /** - * + * * @author Modbder * @version From DummyCore 1.1 * @Description Used to work with multi-colored light system. */ public enum EnumLightColor { - BLACK(51,51,51), - RED(255,51,51), - GREEN(51,255,51), - BROWN(102,51,51), - BLUE(51,51,255), - PURPLE(255,51,255), - CYAN(51,153,255), - SILVER(153,153,153), - GRAY(102,102,102), - PINK(255,102,102), - LIME(102,255,51), - YELLOW(255,255,51), - LIGHTBLUE(153,153,255), - MAGENTA(255,51,204), - ORANGE(255,153,51), - WHITE(204,204,204) - ; - private EnumLightColor(int red, int green, int blue) - { - mainColor = new DummyColor(red, green, blue); - colorID = setGlobal(); - } - - private DummyColor mainColor; - - public DummyColor getColor() - { - return mainColor; - } - - private int setGlobal() - { - return ++globalID; - } - - public int getLightID() - { - return colorID; - } - - private int colorID = 0; - private static int globalID = -1; + BLACK(51, 51, 51), + RED(255, 51, 51), + GREEN(51, 255, 51), + BROWN(102, 51, 51), + BLUE(51, 51, 255), + PURPLE(255, 51, 255), + CYAN(51, 153, 255), + SILVER(153, 153, 153), + GRAY(102, 102, 102), + PINK(255, 102, 102), + LIME(102, 255, 51), + YELLOW(255, 255, 51), + LIGHTBLUE(153, 153, 255), + MAGENTA(255, 51, 204), + ORANGE(255, 153, 51), + WHITE(204, 204, 204); + private EnumLightColor(int red, int green, int blue) { + mainColor = new DummyColor(red, green, blue); + colorID = setGlobal(); + } + + private DummyColor mainColor; + + public DummyColor getColor() { + return mainColor; + } + + private int setGlobal() { + return ++globalID; + } + + public int getLightID() { + return colorID; + } + + private int colorID = 0; + private static int globalID = -1; } diff --git a/src/main/java/DummyCore/Utils/EnumRarityColor.java b/src/main/java/DummyCore/Utils/EnumRarityColor.java index d88beb7..493748e 100644 --- a/src/main/java/DummyCore/Utils/EnumRarityColor.java +++ b/src/main/java/DummyCore/Utils/EnumRarityColor.java @@ -1,51 +1,45 @@ package DummyCore.Utils; public enum EnumRarityColor { - BROKEN("8","Broken"), - COMMON("f","Common"), - GOOD("a","Good"), - UNCOMMON("2","Uncommon"), - RARE("9","Rare"), - UNIQUE("d","Unique"), - EPIC("e","Epic"), - LEGENDARY("6","Legendary"), - EXCEPTIONAL("b","Exceptional"), - PERFECT("3","Perfect"), - ULTIMATE("c","Ultimate"), - TURQUOISE("4","Turquoise"), - ; - EnumRarityColor(String s, String s1) - { - value = s; - name = s1; - } - - private String value; - private String name; - - public String getRarityColor() - { - String ret = new String(); - ret += "\247"; - ret+=value; - return ret; - } - - public String getName() - { - return name; - } - - public static EnumRarityColor getColorByHex(String hex) - { - EnumRarityColor retColor = BROKEN; - for(int i = 0; i < values().length;++i) - { - EnumRarityColor color = values()[i]; - if(color.value.equalsIgnoreCase(hex)) - return color; - } - return retColor; - } + BROKEN("8", "Broken"), + COMMON("f", "Common"), + GOOD("a", "Good"), + UNCOMMON("2", "Uncommon"), + RARE("9", "Rare"), + UNIQUE("d", "Unique"), + EPIC("e", "Epic"), + LEGENDARY("6", "Legendary"), + EXCEPTIONAL("b", "Exceptional"), + PERFECT("3", "Perfect"), + ULTIMATE("c", "Ultimate"), + TURQUOISE("4", "Turquoise"), + ; + EnumRarityColor(String s, String s1) { + value = s; + name = s1; + } + + private String value; + private String name; + + public String getRarityColor() { + String ret = new String(); + ret += "\247"; + ret += value; + return ret; + } + + public String getName() { + return name; + } + + public static EnumRarityColor getColorByHex(String hex) { + EnumRarityColor retColor = BROKEN; + for (int i = 0; i < values().length; ++i) { + EnumRarityColor color = values()[i]; + if (color.value.equalsIgnoreCase(hex)) return color; + } + return retColor; + } } diff --git a/src/main/java/DummyCore/Utils/ExistanceCheck.java b/src/main/java/DummyCore/Utils/ExistanceCheck.java index bfbb382..97559ab 100644 --- a/src/main/java/DummyCore/Utils/ExistanceCheck.java +++ b/src/main/java/DummyCore/Utils/ExistanceCheck.java @@ -1,7 +1,6 @@ package DummyCore.Utils; public @interface ExistanceCheck { - - String[] classPath(); + String[] classPath(); } diff --git a/src/main/java/DummyCore/Utils/GIFImage.java b/src/main/java/DummyCore/Utils/GIFImage.java index ade7791..5c4f492 100644 --- a/src/main/java/DummyCore/Utils/GIFImage.java +++ b/src/main/java/DummyCore/Utils/GIFImage.java @@ -5,108 +5,103 @@ import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Iterator; - import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; - import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; - import org.apache.commons.io.IOUtils; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -public class GIFImage -{ - public int frames; - public BufferedImage[] images; - public int[] imagesGLIDs; - - public GIFImage(ResourceLocation texture) - { - InputStream is = null; - try - { - //Start of Forge's code - is = Minecraft.getMinecraft().mcDefaultResourcePack.getInputStream(texture); - ImageInputStream stream = ImageIO.createImageInputStream(is); - Iterator readers = ImageIO.getImageReaders(stream); - if(!readers.hasNext()) throw new IOException("No suitable reader found for image" + texture); +public class GIFImage { + public int frames; + public BufferedImage[] images; + public int[] imagesGLIDs; + + public GIFImage(ResourceLocation texture) { + InputStream is = null; + try { + // Start of Forge's code + is = Minecraft.getMinecraft().mcDefaultResourcePack.getInputStream(texture); + ImageInputStream stream = ImageIO.createImageInputStream(is); + Iterator readers = ImageIO.getImageReaders(stream); + if (!readers.hasNext()) throw new IOException("No suitable reader found for image" + texture); ImageReader reader = readers.next(); reader.setInput(stream); frames = reader.getNumImages(true); - //End of Forge's code - + // End of Forge's code + BufferedImage[] images = new BufferedImage[frames]; imagesGLIDs = new int[frames]; - for(int i = 0; i < frames; i++) - images[i] = reader.read(i); - + for (int i = 0; i < frames; i++) images[i] = reader.read(i); + reader.dispose(); - - for(int i = 0; i < frames; i++) - imagesGLIDs[i] = loadTexture(images[i]); - } - catch(Exception e) - { - e.printStackTrace(); - } - finally - { - IOUtils.closeQuietly(is); - } - } - - public void drawOnScreen(int frame, double minU, double minV, double maxU, double maxV, int sizeX, int sizeY) - { - GL11.glBindTexture(GL11.GL_TEXTURE_2D, imagesGLIDs[frame]); - GL11.glBegin(GL11.GL_QUADS); + + for (int i = 0; i < frames; i++) imagesGLIDs[i] = loadTexture(images[i]); + } catch (Exception e) { + e.printStackTrace(); + } finally { + IOUtils.closeQuietly(is); + } + } + + public void drawOnScreen(int frame, double minU, double minV, double maxU, double maxV, int sizeX, int sizeY) { + GL11.glBindTexture(GL11.GL_TEXTURE_2D, imagesGLIDs[frame]); + GL11.glBegin(GL11.GL_QUADS); { - GL11.glTexCoord2d(minU, minV); - GL11.glVertex2f(0, 0); - - GL11.glTexCoord2d(maxU, minV); + GL11.glTexCoord2d(minU, minV); + GL11.glVertex2f(0, 0); + + GL11.glTexCoord2d(maxU, minV); GL11.glVertex2f(sizeX, 0); - + GL11.glTexCoord2d(maxU, maxV); GL11.glVertex2f(sizeX, sizeY); - + GL11.glTexCoord2d(minU, maxV); GL11.glVertex2f(0, sizeY); } GL11.glEnd(); - } - - public static final int PIXEL_FORMAT_RGBA = 4; - private int loadTexture(BufferedImage image) - { - int[] pixels = new int[image.getWidth() * image.getHeight()]; - image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); - ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * PIXEL_FORMAT_RGBA); - - for(int y = 0; y < image.getHeight(); y++){ - for(int x = 0; x < image.getWidth(); x++){ - int pixel = pixels[y * image.getWidth() + x]; - buffer.put((byte) ((pixel >> 16) & 0xFF)); - buffer.put((byte) ((pixel >> 8) & 0xFF)); - buffer.put((byte) (pixel & 0xFF)); - buffer.put((byte) ((pixel >> 24) & 0xFF)); - } - } - - buffer.flip(); - int textureID = GL11.glGenTextures(); - GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID); - - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); - - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer); - return textureID; - } - -} \ No newline at end of file + } + + public static final int PIXEL_FORMAT_RGBA = 4; + + private int loadTexture(BufferedImage image) { + int[] pixels = new int[image.getWidth() * image.getHeight()]; + image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); + ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * PIXEL_FORMAT_RGBA); + + for (int y = 0; y < image.getHeight(); y++) { + for (int x = 0; x < image.getWidth(); x++) { + int pixel = pixels[y * image.getWidth() + x]; + buffer.put((byte) ((pixel >> 16) & 0xFF)); + buffer.put((byte) ((pixel >> 8) & 0xFF)); + buffer.put((byte) (pixel & 0xFF)); + buffer.put((byte) ((pixel >> 24) & 0xFF)); + } + } + + buffer.flip(); + int textureID = GL11.glGenTextures(); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID); + + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + + GL11.glTexImage2D( + GL11.GL_TEXTURE_2D, + 0, + GL11.GL_RGBA8, + image.getWidth(), + image.getHeight(), + 0, + GL11.GL_RGBA, + GL11.GL_UNSIGNED_BYTE, + buffer); + return textureID; + } +} diff --git a/src/main/java/DummyCore/Utils/Generator.java b/src/main/java/DummyCore/Utils/Generator.java index f04c0bb..3e16733 100644 --- a/src/main/java/DummyCore/Utils/Generator.java +++ b/src/main/java/DummyCore/Utils/Generator.java @@ -1,543 +1,561 @@ package DummyCore.Utils; import java.util.ArrayList; - import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -public class Generator -{ - public static final Generator instance = new Generator(); - - public World worldObj; - public boolean isWorking; - public boolean hasOffset; - - public Coord3D offset; - - public Block setTo; - public int genMetadata; - - public int flag; - - public static AxisAlignedBB centerBB(AxisAlignedBB genBox) - { - return AxisAlignedBB.getBoundingBox(genBox.minX-((genBox.maxX-genBox.minX)/2), genBox.minY-((genBox.maxY-genBox.minY)/2), genBox.minZ-((genBox.maxZ-genBox.minZ)/2), genBox.maxX-((genBox.maxX-genBox.minX)/2), genBox.maxY-((genBox.maxY-genBox.minY)/2), genBox.maxZ-((genBox.maxZ-genBox.minZ)/2)); - } - - public static AxisAlignedBB normaliseBB(AxisAlignedBB genBox) - { - double minX = genBox.minX; - double minY = genBox.minY; - double minZ = genBox.minZ; - double maxX = genBox.maxX; - double maxY = genBox.maxY; - double maxZ = genBox.maxZ; - - return AxisAlignedBB.getBoundingBox(maxX < minX ? genBox.maxX : genBox.minX, maxY < minY ? genBox.maxY : genBox.minY, maxZ < minZ ? genBox.maxZ : genBox.minZ, maxX < minX ? genBox.minX : genBox.maxX, maxY < minY ? genBox.minY : genBox.maxY, maxZ < minZ ? genBox.minZ : genBox.maxZ); - } - - public ArrayList getBlocksOfType(AxisAlignedBB genBox) - { - gen(); - - prepareBB(genBox); - - ArrayList lst = new ArrayList(); - - for(int x = MathHelper.floor_double(genBox.minX); x <= MathHelper.floor_double(genBox.maxX); ++x) - { - for(int y = MathHelper.floor_double(genBox.minY); y <= MathHelper.floor_double(genBox.maxY); ++y) - { - for(int z = MathHelper.floor_double(genBox.minZ); z <= MathHelper.floor_double(genBox.maxZ); ++z) - { - if(worldObj.getBlock(x, y, z) == setTo && worldObj.getBlockMetadata(x, y, z) == genMetadata) - { - Coord3D c = new Coord3D(x,y,z); - lst.add(c); - } - } - } - } - - restoreBB(genBox); - - return lst; - } - - public void setOffset(Coord3D coord) - { - offset = coord; - hasOffset = true; - } - - public void setOffset(int x, int y, int z) - { - offset = new Coord3D(x,y,z); - hasOffset = true; - } - - public void startWorldgen(World world) - { - if(world.isRemote) - throw new IllegalArgumentException("Worldgen on CLIENT side is not allowed!"); - - if(isWorking) - throw new IllegalStateException("Already generating!"); - - offset = null; - hasOffset = false; - isWorking = true; - worldObj = world; - setTo = Blocks.air; - genMetadata = 0; - flag = 2; - } - - public void endWorldgen() - { - if(!isWorking) - throw new IllegalStateException("Not generating!"); - - offset = null; - isWorking = false; - worldObj = null; - hasOffset = false; - setTo = null; - genMetadata = 0; - flag = 0; - } - - public void setFlag(int i) - { - gen(); - - flag = i; - } - - public boolean gen() - { - if(!isWorking) - throw new IllegalStateException("Can't worlgen if not generating!"); - - if(worldObj.isRemote) - throw new IllegalArgumentException("Worldgen on CLIENT side is not allowed!"); - - return isWorking; - } - - - - public void restoreBB(AxisAlignedBB genBox) - { - gen(); - - if(hasOffset) - { - genBox.minX -= offset.x; - genBox.minY -= offset.y; - genBox.minZ -= offset.z; - genBox.maxX -= offset.x; - genBox.maxY -= offset.y; - genBox.maxZ -= offset.z; - } - } - - public void prepareBB(AxisAlignedBB genBox) - { - gen(); - - if(hasOffset) - { - genBox.minX += offset.x; - genBox.minY += offset.y; - genBox.minZ += offset.z; - genBox.maxX += offset.x; - genBox.maxY += offset.y; - genBox.maxZ += offset.z; - } - } - - public void setBlock(Block b) - { - gen(); - - setTo = b; - genMetadata = 0; - } - - public void setMeta(int i) - { - gen(); - - genMetadata = i; - } - - @SuppressWarnings("unchecked") - public void randomiseCuboid(AxisAlignedBB genBox, Pair...pairs) - { - gen(); - - prepareBB(genBox); - - int x = MathHelper.floor_double(genBox.minX); - int y = MathHelper.floor_double(genBox.minY); - int z = MathHelper.floor_double(genBox.minZ); - int eX = MathHelper.floor_double(genBox.maxX); - int eY = MathHelper.floor_double(genBox.maxY); - int eZ = MathHelper.floor_double(genBox.maxZ); - - for(int dx = x; dx <= eX; ++dx) - { - for(int dy = y; dy <= eY; ++dy) - { - for(int dz = z; dz <= eZ; ++dz) - { - int i = worldObj.rand.nextInt(pairs.length); - if(worldObj.getBlock(dx,dy,dz) == setTo) - worldObj.setBlock(dx, dy, dz, pairs[i].obj1, pairs[i].obj2, flag); - } - } - } - - restoreBB(genBox); - } - - public void addFullSphere(AxisAlignedBB genBox) - { - gen(); - - genBox = normaliseBB(genBox); - prepareBB(genBox); +public class Generator { + public static final Generator instance = new Generator(); - double radiusX = (genBox.maxX-genBox.minX)/2; - double radiusY = (genBox.maxY-genBox.minY)/2; - double radiusZ = (genBox.maxZ-genBox.minZ)/2; - - int dx = MathHelper.floor_double(genBox.minX+radiusX); - int dy = MathHelper.floor_double(genBox.minY+radiusY); - int dz = MathHelper.floor_double(genBox.minZ+radiusZ); - - double invRadiusX = 1.0D / radiusX; - double invRadiusY = 1.0D / radiusY; - double invRadiusZ = 1.0D / radiusZ; - int ceilRadiusX = (int)Math.ceil(radiusX); - int ceilRadiusY = (int)Math.ceil(radiusY); - int ceilRadiusZ = (int)Math.ceil(radiusZ); - double nextXn = 0.0D; - boolean filled = true; - - fX:for(int x = 0; x <= ceilRadiusX; x++) - { - double xn = nextXn; - nextXn = (double)(x + 1) * invRadiusX; - double nextYn = 0.0D; - fZ:for(int y = 0; y <= ceilRadiusY; y++) - { - double yn = nextYn; - nextYn = (double)(y + 1) * invRadiusY; - double nextZn = 0.0D; - for(int z = 0; z <= ceilRadiusZ; z++) - { - double zn = nextZn; - nextZn = (double)(z + 1) * invRadiusZ; - double distanceSq = lengthSq(xn, yn, zn); - if(distanceSq > 1.0D) - { - if(z != 0) - break; - if(y == 0) - break fX; - else - break fZ; - } - if(!filled && lengthSq(nextXn, yn, zn) <= 1.0D && lengthSq(xn, nextYn, zn) <= 1.0D && lengthSq(xn, yn, nextZn) <= 1.0D) - continue; - - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz-z)); - } - } - } - restoreBB(genBox); - } - - public void addHollowCylinder(AxisAlignedBB genBox) - { - gen(); - - genBox = normaliseBB(genBox); - prepareBB(genBox); - - double radiusX = (genBox.maxX-genBox.minX)/2; - double height = genBox.maxY-genBox.minY; - double radiusZ = (genBox.maxZ-genBox.minZ)/2; - - int dx = MathHelper.floor_double(genBox.minX+radiusX); - int dy = MathHelper.floor_double(genBox.minY); - int dz = MathHelper.floor_double(genBox.minZ+radiusZ); - - boolean filled = false; - - radiusX += 0.5D; - radiusZ += 0.5D; - if(height == 0) - return; - - if(height < 0) - { - height = -height; - dy = MathHelper.floor_double(-height); - } - if(dy < 0) - dy = 0; - else - if((dy + height) - 1 > worldObj.getActualHeight()) - height = (int) ((worldObj.getActualHeight() - dy) + 1); - double invRadiusX = 1.0D / radiusX; - double invRadiusZ = 1.0D / radiusZ; - int ceilRadiusX = (int)Math.ceil(radiusX); - int ceilRadiusZ = (int)Math.ceil(radiusZ); - double nextXn = 0.0D; - D:for(int x = 0; x <= ceilRadiusX; x++) - { - double xn = nextXn; - nextXn = (double)(x + 1) * invRadiusX; - double nextZn = 0.0D; - for(int z = 0; z <= ceilRadiusZ; z++) - { - double zn = nextZn; - nextZn = (double)(z + 1) * invRadiusZ; - double distanceSq = lengthSq(xn, zn); - if(distanceSq > 1.0D) - if(z == 0) - break D; - else - break; - if(!filled && lengthSq(nextXn, zn) <= 1.0D && lengthSq(xn, nextZn) <= 1.0D) - continue; - - for(int y = 0; y < height; y++) - { - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); + public World worldObj; + public boolean isWorking; + public boolean hasOffset; + + public Coord3D offset; + + public Block setTo; + public int genMetadata; + + public int flag; + + public static AxisAlignedBB centerBB(AxisAlignedBB genBox) { + return AxisAlignedBB.getBoundingBox( + genBox.minX - ((genBox.maxX - genBox.minX) / 2), + genBox.minY - ((genBox.maxY - genBox.minY) / 2), + genBox.minZ - ((genBox.maxZ - genBox.minZ) / 2), + genBox.maxX - ((genBox.maxX - genBox.minX) / 2), + genBox.maxY - ((genBox.maxY - genBox.minY) / 2), + genBox.maxZ - ((genBox.maxZ - genBox.minZ) / 2)); + } + + public static AxisAlignedBB normaliseBB(AxisAlignedBB genBox) { + double minX = genBox.minX; + double minY = genBox.minY; + double minZ = genBox.minZ; + double maxX = genBox.maxX; + double maxY = genBox.maxY; + double maxZ = genBox.maxZ; + + return AxisAlignedBB.getBoundingBox( + maxX < minX ? genBox.maxX : genBox.minX, + maxY < minY ? genBox.maxY : genBox.minY, + maxZ < minZ ? genBox.maxZ : genBox.minZ, + maxX < minX ? genBox.minX : genBox.maxX, + maxY < minY ? genBox.minY : genBox.maxY, + maxZ < minZ ? genBox.minZ : genBox.maxZ); + } + + public ArrayList getBlocksOfType(AxisAlignedBB genBox) { + gen(); + + prepareBB(genBox); + + ArrayList lst = new ArrayList(); + + for (int x = MathHelper.floor_double(genBox.minX); x <= MathHelper.floor_double(genBox.maxX); ++x) { + for (int y = MathHelper.floor_double(genBox.minY); y <= MathHelper.floor_double(genBox.maxY); ++y) { + for (int z = MathHelper.floor_double(genBox.minZ); z <= MathHelper.floor_double(genBox.maxZ); ++z) { + if (worldObj.getBlock(x, y, z) == setTo && worldObj.getBlockMetadata(x, y, z) == genMetadata) { + Coord3D c = new Coord3D(x, y, z); + lst.add(c); + } } } } - + restoreBB(genBox); - } - - public void addFullCylinder(AxisAlignedBB genBox) - { - gen(); - - genBox = normaliseBB(genBox); - prepareBB(genBox); - - double radiusX = (genBox.maxX-genBox.minX)/2; - double height = genBox.maxY-genBox.minY; - double radiusZ = (genBox.maxZ-genBox.minZ)/2; - - int dx = MathHelper.floor_double(genBox.minX+radiusX); - int dy = MathHelper.floor_double(genBox.minY); - int dz = MathHelper.floor_double(genBox.minZ+radiusZ); - - boolean filled = true; - - radiusX += 0.5D; - radiusZ += 0.5D; - if(height == 0) - return; - - if(height < 0) - { - height = -height; - dy = MathHelper.floor_double(-height); + + return lst; + } + + public void setOffset(Coord3D coord) { + offset = coord; + hasOffset = true; + } + + public void setOffset(int x, int y, int z) { + offset = new Coord3D(x, y, z); + hasOffset = true; + } + + public void startWorldgen(World world) { + if (world.isRemote) throw new IllegalArgumentException("Worldgen on CLIENT side is not allowed!"); + + if (isWorking) throw new IllegalStateException("Already generating!"); + + offset = null; + hasOffset = false; + isWorking = true; + worldObj = world; + setTo = Blocks.air; + genMetadata = 0; + flag = 2; + } + + public void endWorldgen() { + if (!isWorking) throw new IllegalStateException("Not generating!"); + + offset = null; + isWorking = false; + worldObj = null; + hasOffset = false; + setTo = null; + genMetadata = 0; + flag = 0; + } + + public void setFlag(int i) { + gen(); + + flag = i; + } + + public boolean gen() { + if (!isWorking) throw new IllegalStateException("Can't worlgen if not generating!"); + + if (worldObj.isRemote) throw new IllegalArgumentException("Worldgen on CLIENT side is not allowed!"); + + return isWorking; + } + + public void restoreBB(AxisAlignedBB genBox) { + gen(); + + if (hasOffset) { + genBox.minX -= offset.x; + genBox.minY -= offset.y; + genBox.minZ -= offset.z; + genBox.maxX -= offset.x; + genBox.maxY -= offset.y; + genBox.maxZ -= offset.z; } - if(dy < 0) - dy = 0; - else - if((dy + height) - 1 > worldObj.getActualHeight()) - height = (int) ((worldObj.getActualHeight() - dy) + 1); - double invRadiusX = 1.0D / radiusX; - double invRadiusZ = 1.0D / radiusZ; - int ceilRadiusX = (int)Math.ceil(radiusX); - int ceilRadiusZ = (int)Math.ceil(radiusZ); - double nextXn = 0.0D; - D:for(int x = 0; x <= ceilRadiusX; x++) - { - double xn = nextXn; - nextXn = (double)(x + 1) * invRadiusX; - double nextZn = 0.0D; - for(int z = 0; z <= ceilRadiusZ; z++) - { - double zn = nextZn; - nextZn = (double)(z + 1) * invRadiusZ; - double distanceSq = lengthSq(xn, zn); - if(distanceSq > 1.0D) - if(z == 0) - break D; - else - break; - if(!filled && lengthSq(nextXn, zn) <= 1.0D && lengthSq(xn, nextZn) <= 1.0D) - continue; - - for(int y = 0; y < height; y++) - { - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); + } + + public void prepareBB(AxisAlignedBB genBox) { + gen(); + + if (hasOffset) { + genBox.minX += offset.x; + genBox.minY += offset.y; + genBox.minZ += offset.z; + genBox.maxX += offset.x; + genBox.maxY += offset.y; + genBox.maxZ += offset.z; + } + } + + public void setBlock(Block b) { + gen(); + + setTo = b; + genMetadata = 0; + } + + public void setMeta(int i) { + gen(); + + genMetadata = i; + } + + @SuppressWarnings("unchecked") + public void randomiseCuboid(AxisAlignedBB genBox, Pair... pairs) { + gen(); + + prepareBB(genBox); + + int x = MathHelper.floor_double(genBox.minX); + int y = MathHelper.floor_double(genBox.minY); + int z = MathHelper.floor_double(genBox.minZ); + int eX = MathHelper.floor_double(genBox.maxX); + int eY = MathHelper.floor_double(genBox.maxY); + int eZ = MathHelper.floor_double(genBox.maxZ); + + for (int dx = x; dx <= eX; ++dx) { + for (int dy = y; dy <= eY; ++dy) { + for (int dz = z; dz <= eZ; ++dz) { + int i = worldObj.rand.nextInt(pairs.length); + if (worldObj.getBlock(dx, dy, dz) == setTo) + worldObj.setBlock(dx, dy, dz, pairs[i].obj1, pairs[i].obj2, flag); } } } - + restoreBB(genBox); - } - - public void addHollowSphere(AxisAlignedBB genBox) - { - gen(); - - genBox = normaliseBB(genBox); - prepareBB(genBox); + } - double radiusX = (genBox.maxX-genBox.minX)/2; - double radiusY = (genBox.maxY-genBox.minY)/2; - double radiusZ = (genBox.maxZ-genBox.minZ)/2; - - int dx = MathHelper.floor_double(genBox.minX+radiusX); - int dy = MathHelper.floor_double(genBox.minY+radiusY); - int dz = MathHelper.floor_double(genBox.minZ+radiusZ); - - double invRadiusX = 1.0D / radiusX; - double invRadiusY = 1.0D / radiusY; - double invRadiusZ = 1.0D / radiusZ; - int ceilRadiusX = (int)Math.ceil(radiusX); - int ceilRadiusY = (int)Math.ceil(radiusY); - int ceilRadiusZ = (int)Math.ceil(radiusZ); - double nextXn = 0.0D; - boolean filled = false; - - fX:for(int x = 0; x <= ceilRadiusX; x++) - { - double xn = nextXn; - nextXn = (double)(x + 1) * invRadiusX; - double nextYn = 0.0D; - fZ:for(int y = 0; y <= ceilRadiusY; y++) - { - double yn = nextYn; - nextYn = (double)(y + 1) * invRadiusY; - double nextZn = 0.0D; - for(int z = 0; z <= ceilRadiusZ; z++) - { - double zn = nextZn; - nextZn = (double)(z + 1) * invRadiusZ; - double distanceSq = lengthSq(xn, yn, zn); - if(distanceSq > 1.0D) - { - if(z != 0) - break; - if(y == 0) - break fX; - else - break fZ; - } - if(!filled && lengthSq(nextXn, yn, zn) <= 1.0D && lengthSq(xn, nextYn, zn) <= 1.0D && lengthSq(xn, yn, nextZn) <= 1.0D) - continue; - - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz+z)); - block(MathHelper.floor_float(dx+x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy+y), MathHelper.floor_float(dz-z)); - block(MathHelper.floor_float(dx-x), MathHelper.floor_float(dy-y), MathHelper.floor_float(dz-z)); - } - } - } - restoreBB(genBox); - } - - public void addWallsCuboid(AxisAlignedBB genBox) - { - gen(); - - //Bottom - addCuboid(AxisAlignedBB.getBoundingBox(genBox.minX, genBox.minY, genBox.minZ, genBox.maxX, genBox.minY, genBox.maxZ)); - //Top - addCuboid(AxisAlignedBB.getBoundingBox(genBox.minX, genBox.maxY, genBox.minZ, genBox.maxX, genBox.maxY, genBox.maxZ)); - //X Neg - addCuboid(AxisAlignedBB.getBoundingBox(genBox.minX, genBox.minY, genBox.minZ, genBox.minX, genBox.maxY, genBox.maxZ)); - //X Pos - addCuboid(AxisAlignedBB.getBoundingBox(genBox.maxX, genBox.minY, genBox.minZ, genBox.maxX, genBox.maxY, genBox.maxZ)); - //Z Neg - addCuboid(AxisAlignedBB.getBoundingBox(genBox.minX, genBox.minY, genBox.minZ, genBox.maxX, genBox.maxY, genBox.minZ)); - //Z Pos - addCuboid(AxisAlignedBB.getBoundingBox(genBox.minX, genBox.minY, genBox.maxZ, genBox.maxX, genBox.maxY, genBox.maxZ)); - - } - - public boolean block(int x, int y, int z) - { - gen(); - - return worldObj.setBlock(x, y, z, setTo, genMetadata, flag); - } - - public void addCuboid(AxisAlignedBB genBox) - { - gen(); - prepareBB(genBox); - - int x = MathHelper.floor_double(genBox.minX); - int y = MathHelper.floor_double(genBox.minY); - int z = MathHelper.floor_double(genBox.minZ); - int eX = MathHelper.floor_double(genBox.maxX); - int eY = MathHelper.floor_double(genBox.maxY); - int eZ = MathHelper.floor_double(genBox.maxZ); - - addCuboid(x,y,z,eX,eY,eZ); - - restoreBB(genBox); - } - - public void addCuboid(int x, int y, int z, int eX, int eY, int eZ) - { - gen(); - - for(int dx = x; dx <= eX; ++dx) - { - for(int dy = y; dy <= eY; ++dy) - { - for(int dz = z; dz <= eZ; ++dz) - { - block(dx,dy,dz); - } - } - } - } + public void addFullSphere(AxisAlignedBB genBox) { + gen(); - private static double lengthSq(double x, double y, double z) - { + genBox = normaliseBB(genBox); + prepareBB(genBox); + + double radiusX = (genBox.maxX - genBox.minX) / 2; + double radiusY = (genBox.maxY - genBox.minY) / 2; + double radiusZ = (genBox.maxZ - genBox.minZ) / 2; + + int dx = MathHelper.floor_double(genBox.minX + radiusX); + int dy = MathHelper.floor_double(genBox.minY + radiusY); + int dz = MathHelper.floor_double(genBox.minZ + radiusZ); + + double invRadiusX = 1.0D / radiusX; + double invRadiusY = 1.0D / radiusY; + double invRadiusZ = 1.0D / radiusZ; + int ceilRadiusX = (int) Math.ceil(radiusX); + int ceilRadiusY = (int) Math.ceil(radiusY); + int ceilRadiusZ = (int) Math.ceil(radiusZ); + double nextXn = 0.0D; + boolean filled = true; + + fX: + for (int x = 0; x <= ceilRadiusX; x++) { + double xn = nextXn; + nextXn = (double) (x + 1) * invRadiusX; + double nextYn = 0.0D; + fZ: + for (int y = 0; y <= ceilRadiusY; y++) { + double yn = nextYn; + nextYn = (double) (y + 1) * invRadiusY; + double nextZn = 0.0D; + for (int z = 0; z <= ceilRadiusZ; z++) { + double zn = nextZn; + nextZn = (double) (z + 1) * invRadiusZ; + double distanceSq = lengthSq(xn, yn, zn); + if (distanceSq > 1.0D) { + if (z != 0) break; + if (y == 0) break fX; + else break fZ; + } + if (!filled + && lengthSq(nextXn, yn, zn) <= 1.0D + && lengthSq(xn, nextYn, zn) <= 1.0D + && lengthSq(xn, yn, nextZn) <= 1.0D) continue; + + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz - z)); + } + } + } + restoreBB(genBox); + } + + public void addHollowCylinder(AxisAlignedBB genBox) { + gen(); + + genBox = normaliseBB(genBox); + prepareBB(genBox); + + double radiusX = (genBox.maxX - genBox.minX) / 2; + double height = genBox.maxY - genBox.minY; + double radiusZ = (genBox.maxZ - genBox.minZ) / 2; + + int dx = MathHelper.floor_double(genBox.minX + radiusX); + int dy = MathHelper.floor_double(genBox.minY); + int dz = MathHelper.floor_double(genBox.minZ + radiusZ); + + boolean filled = false; + + radiusX += 0.5D; + radiusZ += 0.5D; + if (height == 0) return; + + if (height < 0) { + height = -height; + dy = MathHelper.floor_double(-height); + } + if (dy < 0) dy = 0; + else if ((dy + height) - 1 > worldObj.getActualHeight()) height = (int) ((worldObj.getActualHeight() - dy) + 1); + double invRadiusX = 1.0D / radiusX; + double invRadiusZ = 1.0D / radiusZ; + int ceilRadiusX = (int) Math.ceil(radiusX); + int ceilRadiusZ = (int) Math.ceil(radiusZ); + double nextXn = 0.0D; + D: + for (int x = 0; x <= ceilRadiusX; x++) { + double xn = nextXn; + nextXn = (double) (x + 1) * invRadiusX; + double nextZn = 0.0D; + for (int z = 0; z <= ceilRadiusZ; z++) { + double zn = nextZn; + nextZn = (double) (z + 1) * invRadiusZ; + double distanceSq = lengthSq(xn, zn); + if (distanceSq > 1.0D) + if (z == 0) break D; + else break; + if (!filled && lengthSq(nextXn, zn) <= 1.0D && lengthSq(xn, nextZn) <= 1.0D) continue; + + for (int y = 0; y < height; y++) { + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + } + } + } + + restoreBB(genBox); + } + + public void addFullCylinder(AxisAlignedBB genBox) { + gen(); + + genBox = normaliseBB(genBox); + prepareBB(genBox); + + double radiusX = (genBox.maxX - genBox.minX) / 2; + double height = genBox.maxY - genBox.minY; + double radiusZ = (genBox.maxZ - genBox.minZ) / 2; + + int dx = MathHelper.floor_double(genBox.minX + radiusX); + int dy = MathHelper.floor_double(genBox.minY); + int dz = MathHelper.floor_double(genBox.minZ + radiusZ); + + boolean filled = true; + + radiusX += 0.5D; + radiusZ += 0.5D; + if (height == 0) return; + + if (height < 0) { + height = -height; + dy = MathHelper.floor_double(-height); + } + if (dy < 0) dy = 0; + else if ((dy + height) - 1 > worldObj.getActualHeight()) height = (int) ((worldObj.getActualHeight() - dy) + 1); + double invRadiusX = 1.0D / radiusX; + double invRadiusZ = 1.0D / radiusZ; + int ceilRadiusX = (int) Math.ceil(radiusX); + int ceilRadiusZ = (int) Math.ceil(radiusZ); + double nextXn = 0.0D; + D: + for (int x = 0; x <= ceilRadiusX; x++) { + double xn = nextXn; + nextXn = (double) (x + 1) * invRadiusX; + double nextZn = 0.0D; + for (int z = 0; z <= ceilRadiusZ; z++) { + double zn = nextZn; + nextZn = (double) (z + 1) * invRadiusZ; + double distanceSq = lengthSq(xn, zn); + if (distanceSq > 1.0D) + if (z == 0) break D; + else break; + if (!filled && lengthSq(nextXn, zn) <= 1.0D && lengthSq(xn, nextZn) <= 1.0D) continue; + + for (int y = 0; y < height; y++) { + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + } + } + } + + restoreBB(genBox); + } + + public void addHollowSphere(AxisAlignedBB genBox) { + gen(); + + genBox = normaliseBB(genBox); + prepareBB(genBox); + + double radiusX = (genBox.maxX - genBox.minX) / 2; + double radiusY = (genBox.maxY - genBox.minY) / 2; + double radiusZ = (genBox.maxZ - genBox.minZ) / 2; + + int dx = MathHelper.floor_double(genBox.minX + radiusX); + int dy = MathHelper.floor_double(genBox.minY + radiusY); + int dz = MathHelper.floor_double(genBox.minZ + radiusZ); + + double invRadiusX = 1.0D / radiusX; + double invRadiusY = 1.0D / radiusY; + double invRadiusZ = 1.0D / radiusZ; + int ceilRadiusX = (int) Math.ceil(radiusX); + int ceilRadiusY = (int) Math.ceil(radiusY); + int ceilRadiusZ = (int) Math.ceil(radiusZ); + double nextXn = 0.0D; + boolean filled = false; + + fX: + for (int x = 0; x <= ceilRadiusX; x++) { + double xn = nextXn; + nextXn = (double) (x + 1) * invRadiusX; + double nextYn = 0.0D; + fZ: + for (int y = 0; y <= ceilRadiusY; y++) { + double yn = nextYn; + nextYn = (double) (y + 1) * invRadiusY; + double nextZn = 0.0D; + for (int z = 0; z <= ceilRadiusZ; z++) { + double zn = nextZn; + nextZn = (double) (z + 1) * invRadiusZ; + double distanceSq = lengthSq(xn, yn, zn); + if (distanceSq > 1.0D) { + if (z != 0) break; + if (y == 0) break fX; + else break fZ; + } + if (!filled + && lengthSq(nextXn, yn, zn) <= 1.0D + && lengthSq(xn, nextYn, zn) <= 1.0D + && lengthSq(xn, yn, nextZn) <= 1.0D) continue; + + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz + z)); + block( + MathHelper.floor_float(dx + x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy + y), + MathHelper.floor_float(dz - z)); + block( + MathHelper.floor_float(dx - x), + MathHelper.floor_float(dy - y), + MathHelper.floor_float(dz - z)); + } + } + } + restoreBB(genBox); + } + + public void addWallsCuboid(AxisAlignedBB genBox) { + gen(); + + // Bottom + addCuboid(AxisAlignedBB.getBoundingBox( + genBox.minX, genBox.minY, genBox.minZ, genBox.maxX, genBox.minY, genBox.maxZ)); + // Top + addCuboid(AxisAlignedBB.getBoundingBox( + genBox.minX, genBox.maxY, genBox.minZ, genBox.maxX, genBox.maxY, genBox.maxZ)); + // X Neg + addCuboid(AxisAlignedBB.getBoundingBox( + genBox.minX, genBox.minY, genBox.minZ, genBox.minX, genBox.maxY, genBox.maxZ)); + // X Pos + addCuboid(AxisAlignedBB.getBoundingBox( + genBox.maxX, genBox.minY, genBox.minZ, genBox.maxX, genBox.maxY, genBox.maxZ)); + // Z Neg + addCuboid(AxisAlignedBB.getBoundingBox( + genBox.minX, genBox.minY, genBox.minZ, genBox.maxX, genBox.maxY, genBox.minZ)); + // Z Pos + addCuboid(AxisAlignedBB.getBoundingBox( + genBox.minX, genBox.minY, genBox.maxZ, genBox.maxX, genBox.maxY, genBox.maxZ)); + } + + public boolean block(int x, int y, int z) { + gen(); + + return worldObj.setBlock(x, y, z, setTo, genMetadata, flag); + } + + public void addCuboid(AxisAlignedBB genBox) { + gen(); + prepareBB(genBox); + + int x = MathHelper.floor_double(genBox.minX); + int y = MathHelper.floor_double(genBox.minY); + int z = MathHelper.floor_double(genBox.minZ); + int eX = MathHelper.floor_double(genBox.maxX); + int eY = MathHelper.floor_double(genBox.maxY); + int eZ = MathHelper.floor_double(genBox.maxZ); + + addCuboid(x, y, z, eX, eY, eZ); + + restoreBB(genBox); + } + + public void addCuboid(int x, int y, int z, int eX, int eY, int eZ) { + gen(); + + for (int dx = x; dx <= eX; ++dx) { + for (int dy = y; dy <= eY; ++dy) { + for (int dz = z; dz <= eZ; ++dz) { + block(dx, dy, dz); + } + } + } + } + + private static double lengthSq(double x, double y, double z) { return x * x + y * y + z * z; } - private static double lengthSq(double x, double z) - { + private static double lengthSq(double x, double z) { return x * x + z * z; } } diff --git a/src/main/java/DummyCore/Utils/GuiContainerLibrary.java b/src/main/java/DummyCore/Utils/GuiContainerLibrary.java index b2ee27d..d97588f 100644 --- a/src/main/java/DummyCore/Utils/GuiContainerLibrary.java +++ b/src/main/java/DummyCore/Utils/GuiContainerLibrary.java @@ -4,28 +4,25 @@ import java.util.ArrayList; import java.util.List; public class GuiContainerLibrary { - public static List guis = new ArrayList(); - public static List containers = new ArrayList(); - - /** - * Can be used for easier GUI opening, if you do not want to make a Proxy for that. This method should only be used to open simple GUIs(tile entity ones) - * @param guiClassPath - the path to GUI class. Gui class should extend GuiCommon! - * @param containerClassPath - the path to your Container class. - * @return the ID with which you should use to open your GUI on block right-click. - */ - public static int registerGuiContainer(String guiClassPath, String containerClassPath) - { - int lstSize = guis.size(); - try - { - guis.add(guiClassPath); - containers.add(containerClassPath); - }catch(Exception e) - { - Notifier.notifySimple("Unable to register GUI-Container with ID "+lstSize); - e.printStackTrace(); - return -1; - } - return lstSize; - } + public static List guis = new ArrayList(); + public static List containers = new ArrayList(); + + /** + * Can be used for easier GUI opening, if you do not want to make a Proxy for that. This method should only be used to open simple GUIs(tile entity ones) + * @param guiClassPath - the path to GUI class. Gui class should extend GuiCommon! + * @param containerClassPath - the path to your Container class. + * @return the ID with which you should use to open your GUI on block right-click. + */ + public static int registerGuiContainer(String guiClassPath, String containerClassPath) { + int lstSize = guis.size(); + try { + guis.add(guiClassPath); + containers.add(containerClassPath); + } catch (Exception e) { + Notifier.notifySimple("Unable to register GUI-Container with ID " + lstSize); + e.printStackTrace(); + return -1; + } + return lstSize; + } } diff --git a/src/main/java/DummyCore/Utils/IAttributeModifier.java b/src/main/java/DummyCore/Utils/IAttributeModifier.java index 14ecb3f..f20df5a 100644 --- a/src/main/java/DummyCore/Utils/IAttributeModifier.java +++ b/src/main/java/DummyCore/Utils/IAttributeModifier.java @@ -5,15 +5,14 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public interface IAttributeModifier { - - public abstract String getType(ItemStack stack, EntityPlayer p); - - public abstract double getValue(ItemStack stack, EntityPlayer p); - - public abstract IAttribute getAttribute(ItemStack stack, EntityPlayer p); - - public abstract String last5OfUUID(ItemStack stack, EntityPlayer p); - - public abstract int getOperation(ItemStack stack, EntityPlayer p); + public abstract String getType(ItemStack stack, EntityPlayer p); + + public abstract double getValue(ItemStack stack, EntityPlayer p); + + public abstract IAttribute getAttribute(ItemStack stack, EntityPlayer p); + + public abstract String last5OfUUID(ItemStack stack, EntityPlayer p); + + public abstract int getOperation(ItemStack stack, EntityPlayer p); } diff --git a/src/main/java/DummyCore/Utils/IDummyConfig.java b/src/main/java/DummyCore/Utils/IDummyConfig.java index eb32d59..258b962 100644 --- a/src/main/java/DummyCore/Utils/IDummyConfig.java +++ b/src/main/java/DummyCore/Utils/IDummyConfig.java @@ -3,18 +3,17 @@ package DummyCore.Utils; import net.minecraftforge.common.config.Configuration; /** - * + * * @author Modbder * @version From DummyCore 1.0 * @Description Your config class must implement this to work. Used for easier way of working with configs and for DummyCore handling. */ public interface IDummyConfig { - - /** - * Automatically called every time your mod is registered in the DummyCore. - * @version From DummyCore 1.0 - * @param config - Forge configuration file automatically created. - */ - public abstract void load(Configuration config); + /** + * Automatically called every time your mod is registered in the DummyCore. + * @version From DummyCore 1.0 + * @param config - Forge configuration file automatically created. + */ + public abstract void load(Configuration config); } diff --git a/src/main/java/DummyCore/Utils/IMainMenu.java b/src/main/java/DummyCore/Utils/IMainMenu.java index 1204e01..33c7478 100644 --- a/src/main/java/DummyCore/Utils/IMainMenu.java +++ b/src/main/java/DummyCore/Utils/IMainMenu.java @@ -1,5 +1,3 @@ package DummyCore.Utils; -public interface IMainMenu { - -} +public interface IMainMenu {} diff --git a/src/main/java/DummyCore/Utils/ITEHasGameData.java b/src/main/java/DummyCore/Utils/ITEHasGameData.java index c8b593b..9ba6056 100644 --- a/src/main/java/DummyCore/Utils/ITEHasGameData.java +++ b/src/main/java/DummyCore/Utils/ITEHasGameData.java @@ -1,11 +1,10 @@ package DummyCore.Utils; public interface ITEHasGameData { - - public abstract String getData(); - - public abstract void setData(DummyData[] data); - - public abstract Coord3D getPosition(); + public abstract String getData(); + + public abstract void setData(DummyData[] data); + + public abstract Coord3D getPosition(); } diff --git a/src/main/java/DummyCore/Utils/Lightning.java b/src/main/java/DummyCore/Utils/Lightning.java index 51d0f6d..e2241e4 100644 --- a/src/main/java/DummyCore/Utils/Lightning.java +++ b/src/main/java/DummyCore/Utils/Lightning.java @@ -1,98 +1,113 @@ package DummyCore.Utils; import java.util.Random; - import org.lwjgl.opengl.GL11; /** - * + * * @author Modbder * @version From DummyCore 1.9 * @Description used to create a lightning graphical effect between 2 points. */ public class Lightning { - - public Random rnd; - public Coord3D[] lightningVecsStart; - public Coord3D[] lightningVecsEnd; - public Coord3D start; - public Coord3D end; - public float renderTicksExisted; - public float[] getLightningColor = new float[3]; - - /** - * Creates a lightning - * @param rand - the random on which your lightning will be built upon. - * @param begin - the beginning point of the lightning. This NEVER should relate to coordinates in the world! Instead, it can be 0,0,0, if you want the lightning to be created from the bottom corner of a block, for example. - * @param stop - the end point of the lightning. This NEVER should relate to coordinates in the world! Instead, it can be 0,10,0, if you want the lightning to go 10 blocks higher. - * @param curve - the amount of curving in your lightning. Usually somewhat around 0.3F if you want the lightning to look realistic. If you put 0.0F it will be a straight line, and 1.0F can lead to weird stuff. - * @param color - the color array, representing the color of the lightning. - */ - public Lightning(Random rand, Coord3D begin, Coord3D stop,float curve, float... color) - { - rnd = rand; - start = begin; - end = stop; - getLightningColor = color; - curve(curve); - } - - private void curve(float factor) - { - float distX = end.x-start.x; - float distY = end.y-start.y; - float distZ = end.z-start.z; - float genDistance = (float) Math.sqrt(distX*distX+distY*distY+distZ*distZ); - lightningVecsStart = new Coord3D[64]; - lightningVecsEnd = new Coord3D[64]; - generateLightningBetween2Points(start, end, 0, 8, factor); - generateLightningBetween2Points(lightningVecsStart[3], new Coord3D(end.x*(factor*10),end.y,end.z*(factor*10)), 8, 4, factor*3); - int genIndex = 0; - for(int i = 0; i < 12; ++i) - { - int rndSteps = rnd.nextInt(2); - genIndex += (1+rndSteps); - generateLightningBetween2Points(lightningVecsStart[i], new Coord3D(lightningVecsStart[i].x+MathUtils.randomFloat(rnd)*(genDistance/4), lightningVecsStart[i].y+MathUtils.randomFloat(rnd)*(genDistance/4),lightningVecsStart[i].z+MathUtils.randomFloat(rnd)*(genDistance/4)),12+i,1+rndSteps,factor/2); - } - for(int i = 12; i < 12+genIndex; ++i) - { - if(lightningVecsStart[i] != null) - generateLightningBetween2Points(lightningVecsStart[i], new Coord3D(lightningVecsStart[i].x+MathUtils.randomFloat(rnd)*(genDistance/8), lightningVecsStart[i].y+MathUtils.randomFloat(rnd)*(genDistance/8),lightningVecsStart[i].z+MathUtils.randomFloat(rnd)*(genDistance/8)),12+genIndex+i,0,factor); - } - } - - private void generateLightningBetween2Points(Coord3D from, Coord3D to,int beginVecIndex, int steps, float curve) - { - float distX = to.x-from.x; - float distY = to.y-from.y; - float distZ = to.z-from.z; - for(int i = 0; i < steps; ++i) - { - if(i == 0) - { - lightningVecsStart[beginVecIndex+i] = from; - lightningVecsEnd[beginVecIndex+i] = new Coord3D(lightningVecsStart[beginVecIndex+i].x+distX/steps+MathUtils.randomFloat(rnd)*curve,lightningVecsStart[beginVecIndex+i].y+distY/steps+MathUtils.randomFloat(rnd)*curve,lightningVecsStart[beginVecIndex+i].z+distZ/steps+MathUtils.randomFloat(rnd)*curve); - }else - { - lightningVecsStart[beginVecIndex+i] = lightningVecsEnd[beginVecIndex+i-1]; - lightningVecsEnd[beginVecIndex+i] = new Coord3D(lightningVecsStart[beginVecIndex+i].x+distX/steps+MathUtils.randomFloat(rnd)*curve,lightningVecsStart[beginVecIndex+i].y+distY/steps+MathUtils.randomFloat(rnd)*curve,lightningVecsStart[beginVecIndex+i].z+distZ/steps+MathUtils.randomFloat(rnd)*curve); - } - } - - } - - /** - * Use this anywhere in your render code to actually render the lightning. - * @param x - * @param y - * @param z - * @param partialTicks - */ - public void render(double x, double y, double z, float partialTicks) - { - renderTicksExisted += partialTicks/1F; - if(renderTicksExisted >= this.lightningVecsStart.length) - renderTicksExisted = this.lightningVecsStart.length; + + public Random rnd; + public Coord3D[] lightningVecsStart; + public Coord3D[] lightningVecsEnd; + public Coord3D start; + public Coord3D end; + public float renderTicksExisted; + public float[] getLightningColor = new float[3]; + + /** + * Creates a lightning + * @param rand - the random on which your lightning will be built upon. + * @param begin - the beginning point of the lightning. This NEVER should relate to coordinates in the world! Instead, it can be 0,0,0, if you want the lightning to be created from the bottom corner of a block, for example. + * @param stop - the end point of the lightning. This NEVER should relate to coordinates in the world! Instead, it can be 0,10,0, if you want the lightning to go 10 blocks higher. + * @param curve - the amount of curving in your lightning. Usually somewhat around 0.3F if you want the lightning to look realistic. If you put 0.0F it will be a straight line, and 1.0F can lead to weird stuff. + * @param color - the color array, representing the color of the lightning. + */ + public Lightning(Random rand, Coord3D begin, Coord3D stop, float curve, float... color) { + rnd = rand; + start = begin; + end = stop; + getLightningColor = color; + curve(curve); + } + + private void curve(float factor) { + float distX = end.x - start.x; + float distY = end.y - start.y; + float distZ = end.z - start.z; + float genDistance = (float) Math.sqrt(distX * distX + distY * distY + distZ * distZ); + lightningVecsStart = new Coord3D[64]; + lightningVecsEnd = new Coord3D[64]; + generateLightningBetween2Points(start, end, 0, 8, factor); + generateLightningBetween2Points( + lightningVecsStart[3], + new Coord3D(end.x * (factor * 10), end.y, end.z * (factor * 10)), + 8, + 4, + factor * 3); + int genIndex = 0; + for (int i = 0; i < 12; ++i) { + int rndSteps = rnd.nextInt(2); + genIndex += (1 + rndSteps); + generateLightningBetween2Points( + lightningVecsStart[i], + new Coord3D( + lightningVecsStart[i].x + MathUtils.randomFloat(rnd) * (genDistance / 4), + lightningVecsStart[i].y + MathUtils.randomFloat(rnd) * (genDistance / 4), + lightningVecsStart[i].z + MathUtils.randomFloat(rnd) * (genDistance / 4)), + 12 + i, + 1 + rndSteps, + factor / 2); + } + for (int i = 12; i < 12 + genIndex; ++i) { + if (lightningVecsStart[i] != null) + generateLightningBetween2Points( + lightningVecsStart[i], + new Coord3D( + lightningVecsStart[i].x + MathUtils.randomFloat(rnd) * (genDistance / 8), + lightningVecsStart[i].y + MathUtils.randomFloat(rnd) * (genDistance / 8), + lightningVecsStart[i].z + MathUtils.randomFloat(rnd) * (genDistance / 8)), + 12 + genIndex + i, + 0, + factor); + } + } + + private void generateLightningBetween2Points(Coord3D from, Coord3D to, int beginVecIndex, int steps, float curve) { + float distX = to.x - from.x; + float distY = to.y - from.y; + float distZ = to.z - from.z; + for (int i = 0; i < steps; ++i) { + if (i == 0) { + lightningVecsStart[beginVecIndex + i] = from; + lightningVecsEnd[beginVecIndex + i] = new Coord3D( + lightningVecsStart[beginVecIndex + i].x + distX / steps + MathUtils.randomFloat(rnd) * curve, + lightningVecsStart[beginVecIndex + i].y + distY / steps + MathUtils.randomFloat(rnd) * curve, + lightningVecsStart[beginVecIndex + i].z + distZ / steps + MathUtils.randomFloat(rnd) * curve); + } else { + lightningVecsStart[beginVecIndex + i] = lightningVecsEnd[beginVecIndex + i - 1]; + lightningVecsEnd[beginVecIndex + i] = new Coord3D( + lightningVecsStart[beginVecIndex + i].x + distX / steps + MathUtils.randomFloat(rnd) * curve, + lightningVecsStart[beginVecIndex + i].y + distY / steps + MathUtils.randomFloat(rnd) * curve, + lightningVecsStart[beginVecIndex + i].z + distZ / steps + MathUtils.randomFloat(rnd) * curve); + } + } + } + + /** + * Use this anywhere in your render code to actually render the lightning. + * @param x + * @param y + * @param z + * @param partialTicks + */ + public void render(double x, double y, double z, float partialTicks) { + renderTicksExisted += partialTicks / 1F; + if (renderTicksExisted >= this.lightningVecsStart.length) renderTicksExisted = this.lightningVecsStart.length; GL11.glPushMatrix(); GL11.glEnable(2929); GL11.glEnable(3042); @@ -100,50 +115,40 @@ public class Lightning { GL11.glDisable(3553); GL11.glDisable(2896); GL11.glTranslated(x, y, z); - for(int i = 0; i < renderTicksExisted; ++i) - { - if(this.lightningVecsStart[i] != null) - { - this.renderBeam(lightningVecsStart[i], lightningVecsEnd[i], 0.8F); - this.renderBeam(lightningVecsStart[i], lightningVecsEnd[i], 1F); - } - } + for (int i = 0; i < renderTicksExisted; ++i) { + if (this.lightningVecsStart[i] != null) { + this.renderBeam(lightningVecsStart[i], lightningVecsEnd[i], 0.8F); + this.renderBeam(lightningVecsStart[i], lightningVecsEnd[i], 1F); + } + } GL11.glEnable(2896); GL11.glEnable(3553); GL11.glPopMatrix(); - } - - public void renderBeam(Coord3D begin, Coord3D stop, float type) - { - if(type != 1F) - GL11.glLineWidth(3); - else - GL11.glLineWidth(1); - GL11.glPushMatrix(); - GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); - GL11.glEnable(GL11.GL_BLEND); - GL11.glShadeModel(GL11.GL_SMOOTH); - GL11.glEnable(GL11.GL_CULL_FACE); + } + + public void renderBeam(Coord3D begin, Coord3D stop, float type) { + if (type != 1F) GL11.glLineWidth(3); + else GL11.glLineWidth(1); + GL11.glPushMatrix(); + GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); + GL11.glEnable(GL11.GL_BLEND); + GL11.glShadeModel(GL11.GL_SMOOTH); + GL11.glEnable(GL11.GL_CULL_FACE); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glBegin(1); - - if(type != 1) - GL11.glColor4f(1,1,1,0.2F); - else - GL11.glColor4f(this.getLightningColor[0],this.getLightningColor[1],this.getLightningColor[2],0.8F); + + if (type != 1) GL11.glColor4f(1, 1, 1, 0.2F); + else GL11.glColor4f(this.getLightningColor[0], this.getLightningColor[1], this.getLightningColor[2], 0.8F); GL11.glVertex3d(begin.x, begin.y, begin.z); GL11.glVertex3d(stop.x, stop.y, stop.z); GL11.glColor3d(1.0D, 1.0D, 1.0D); - - + GL11.glEnd(); GL11.glShadeModel(GL11.GL_FLAT); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glPopMatrix(); - } - - + } } diff --git a/src/main/java/DummyCore/Utils/LoadingUtils.java b/src/main/java/DummyCore/Utils/LoadingUtils.java index c450435..c731d61 100644 --- a/src/main/java/DummyCore/Utils/LoadingUtils.java +++ b/src/main/java/DummyCore/Utils/LoadingUtils.java @@ -1,109 +1,127 @@ package DummyCore.Utils; -import java.util.ArrayList; - -import org.apache.logging.log4j.Level; - import DummyCore.Core.Core; import DummyCore.Core.DCMod; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModContainer; - +import java.util.ArrayList; +import org.apache.logging.log4j.Level; public class LoadingUtils { - - public static final ArrayList knownBigASMModifiers = new ArrayList(); - - public static void makeACrash(String message,Class thrower, Throwable t, boolean shutdown) - { - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]",message); - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]","Loading errors were detected at state "+Loader.instance().getLoaderState()+"!"); - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]","The class that has thrown the error: "+thrower); - DCMod[] ofsetters = tryDetermineOffendorsFromClasses(tryDetermineOffendorsFromTrace(t)); - for(DCMod mod : ofsetters) - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]","Likely involved mod registered via DummyCore: "+mod); - for(ModContainer mCon : tryDetermineModOffendorsFromClasses(tryDetermineOffendorsFromTrace(t))) - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]","Likely involved mod: "+mCon.getName()+"[modid:"+mCon.getModId()+",modClasspath:"+(mCon.getMod() != null ? mCon.getMod().getClass() : "NULL{mod has no mod instance?}")+"]"); - - if(shutdown) - FMLCommonHandler.instance().getSidedDelegate().haltGame(message, t); - } - - public static void makeACrash(String message,Throwable t, boolean shutdown) - { - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]","Loading errors were detected at state "+Loader.instance().getLoaderState()+"!"); - DCMod[] ofsetters = tryDetermineOffendorsFromClasses(tryDetermineOffendorsFromTrace(t)); - for(DCMod mod : ofsetters) - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]","Likely involved mod registered via DummyCore: "+mod); - for(ModContainer mCon : tryDetermineModOffendorsFromClasses(tryDetermineOffendorsFromTrace(t))) - Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error,"[DummyCoreLoader]","Likely involved mod: "+mCon.getName()+"[modid:"+mCon.getModId()+",modClasspath:"+(mCon.getMod() != null ? mCon.getMod().getClass() : "NULL{mod has no mod instance?}")+"]"); - - if(shutdown) - FMLCommonHandler.instance().getSidedDelegate().haltGame(message, t); - } - - public static Class[] tryDetermineOffendorsFromTrace(Throwable t) - { - StackTraceElement[] elements = t.getStackTrace(); - Class[] offendors = new Class[elements.length]; - int i = -1; - for(StackTraceElement ste : elements) - { - ++i; - String clsName = ste.getClassName(); - try - { - Class offendor = Class.forName(clsName); - if(offendor != null) - offendors[i] = offendor; - } - catch(ClassNotFoundException cnfe) - { - continue; - } - } - return offendors; - } - - public static DCMod[] tryDetermineOffendorsFromClasses(Class... detectedInTrace) - { - DCMod[] retMods = new DCMod[0]; - - for(Class clazz : detectedInTrace) - { - if(Core.isModRegistered(clazz)) - { - DCMod[] newArray = new DCMod[retMods.length+1]; - System.arraycopy(retMods, 0, newArray, 0, retMods.length); - newArray[newArray.length-1] = Core.getModFromClass(clazz); - retMods = newArray; - } - } - - return retMods; - } - - public static ModContainer[] tryDetermineModOffendorsFromClasses(Class... detectedInTrace) - { - ModContainer[] retMods = new ModContainer[0]; - - for(Class clazz : detectedInTrace) - { - for(int i = 0; i < Loader.instance().getActiveModList().size(); ++i) - { - ModContainer mc = Loader.instance().getActiveModList().get(i); - if(mc.getMod() != null && mc.getMod().getClass().equals(clazz)) - { - ModContainer[] newArray = new ModContainer[retMods.length+1]; - System.arraycopy(retMods, 0, newArray, 0, retMods.length); - newArray[newArray.length-1] = mc; - retMods = newArray; - } - } - } - - return retMods; - } + public static final ArrayList knownBigASMModifiers = new ArrayList(); + + public static void makeACrash(String message, Class thrower, Throwable t, boolean shutdown) { + Notifier.notify(shutdown ? Level.FATAL : Level.ERROR, "", Notifier.error, "[DummyCoreLoader]", message); + Notifier.notify( + shutdown ? Level.FATAL : Level.ERROR, + "", + Notifier.error, + "[DummyCoreLoader]", + "Loading errors were detected at state " + Loader.instance().getLoaderState() + "!"); + Notifier.notify( + shutdown ? Level.FATAL : Level.ERROR, + "", + Notifier.error, + "[DummyCoreLoader]", + "The class that has thrown the error: " + thrower); + DCMod[] ofsetters = tryDetermineOffendorsFromClasses(tryDetermineOffendorsFromTrace(t)); + for (DCMod mod : ofsetters) + Notifier.notify( + shutdown ? Level.FATAL : Level.ERROR, + "", + Notifier.error, + "[DummyCoreLoader]", + "Likely involved mod registered via DummyCore: " + mod); + for (ModContainer mCon : tryDetermineModOffendorsFromClasses(tryDetermineOffendorsFromTrace(t))) + Notifier.notify( + shutdown ? Level.FATAL : Level.ERROR, + "", + Notifier.error, + "[DummyCoreLoader]", + "Likely involved mod: " + mCon.getName() + "[modid:" + mCon.getModId() + ",modClasspath:" + + (mCon.getMod() != null ? mCon.getMod().getClass() : "NULL{mod has no mod instance?}") + + "]"); + + if (shutdown) FMLCommonHandler.instance().getSidedDelegate().haltGame(message, t); + } + + public static void makeACrash(String message, Throwable t, boolean shutdown) { + Notifier.notify( + shutdown ? Level.FATAL : Level.ERROR, + "", + Notifier.error, + "[DummyCoreLoader]", + "Loading errors were detected at state " + Loader.instance().getLoaderState() + "!"); + DCMod[] ofsetters = tryDetermineOffendorsFromClasses(tryDetermineOffendorsFromTrace(t)); + for (DCMod mod : ofsetters) + Notifier.notify( + shutdown ? Level.FATAL : Level.ERROR, + "", + Notifier.error, + "[DummyCoreLoader]", + "Likely involved mod registered via DummyCore: " + mod); + for (ModContainer mCon : tryDetermineModOffendorsFromClasses(tryDetermineOffendorsFromTrace(t))) + Notifier.notify( + shutdown ? Level.FATAL : Level.ERROR, + "", + Notifier.error, + "[DummyCoreLoader]", + "Likely involved mod: " + mCon.getName() + "[modid:" + mCon.getModId() + ",modClasspath:" + + (mCon.getMod() != null ? mCon.getMod().getClass() : "NULL{mod has no mod instance?}") + + "]"); + + if (shutdown) FMLCommonHandler.instance().getSidedDelegate().haltGame(message, t); + } + + public static Class[] tryDetermineOffendorsFromTrace(Throwable t) { + StackTraceElement[] elements = t.getStackTrace(); + Class[] offendors = new Class[elements.length]; + int i = -1; + for (StackTraceElement ste : elements) { + ++i; + String clsName = ste.getClassName(); + try { + Class offendor = Class.forName(clsName); + if (offendor != null) offendors[i] = offendor; + } catch (ClassNotFoundException cnfe) { + continue; + } + } + return offendors; + } + + public static DCMod[] tryDetermineOffendorsFromClasses(Class... detectedInTrace) { + DCMod[] retMods = new DCMod[0]; + + for (Class clazz : detectedInTrace) { + if (Core.isModRegistered(clazz)) { + DCMod[] newArray = new DCMod[retMods.length + 1]; + System.arraycopy(retMods, 0, newArray, 0, retMods.length); + newArray[newArray.length - 1] = Core.getModFromClass(clazz); + retMods = newArray; + } + } + + return retMods; + } + + public static ModContainer[] tryDetermineModOffendorsFromClasses(Class... detectedInTrace) { + ModContainer[] retMods = new ModContainer[0]; + + for (Class clazz : detectedInTrace) { + for (int i = 0; i < Loader.instance().getActiveModList().size(); ++i) { + ModContainer mc = Loader.instance().getActiveModList().get(i); + if (mc.getMod() != null && mc.getMod().getClass().equals(clazz)) { + ModContainer[] newArray = new ModContainer[retMods.length + 1]; + System.arraycopy(retMods, 0, newArray, 0, retMods.length); + newArray[newArray.length - 1] = mc; + retMods = newArray; + } + } + } + + return retMods; + } } diff --git a/src/main/java/DummyCore/Utils/MathUtils.java b/src/main/java/DummyCore/Utils/MathUtils.java index 0a9ab0a..57fd6ef 100644 --- a/src/main/java/DummyCore/Utils/MathUtils.java +++ b/src/main/java/DummyCore/Utils/MathUtils.java @@ -3,172 +3,149 @@ package DummyCore.Utils; import java.util.Random; /** - * + * * @author Modbder * @version From DummyCore 1.0 * @Description can be used to save you some time writing mathematical functions. * */ public class MathUtils { - /** - * Used to get the size of a texture in pixels using current values. Very useful in any kind of progress bars in GUI - * @version From DummyCore 1.0 - * @param current - the current value - * @param max - the maximum value - * @param textureSize - the maximum texture size - * @return Percentage-based int. For example, if the textureSize is 50, current is 100 and max is 200 this will return 25 - that is 50% of your texture size. - */ - public static int pixelatedTextureSize(int current, int max, int textureSize) - { - if(current > max) - current = max; - float m = (float)current/max*100; - float n = m/100*textureSize; - return (int)n; - } - - /** - * Used to get the persentage between 2 numbers - * @version From DummyCore 1.0 - * @param current - the current value - * @param max - the maximum value - * @return Percentage-based int. For example, if current is 100 and max is 200 this will return 50. - */ - public static int getPercentage(int current, int max) - { - float m = (float)current/max*100; - return (int)m; - } - - /** - * Used to get the polar-based offset between 2 points in vec2D coord system. - * @version From DummyCore 1.0 - * @param position - the current vec2D - * @param angle - the angle of offset - * @param distance - the distance the point will be offset - * @return new Coord2D with offset coords. - */ - public static Coord2D polarOffset(Coord2D position, float angle, float distance) - { - float d0 = (float) (position.x + Math.cos(angle * Math.PI / 180.0D) * distance); - float d1 = (float) (position.z + Math.sin(angle * Math.PI / 180.0D) * distance); - return new Coord2D(d0,d1); - } - - /** - * Used to get a completely(-1.0D - 1.0D) random double. - * @version From DummyCore 1.0 - * @param rand - the Random, that will randomise this. - * @return a random Double - */ - public static double randomDouble(Random rand) - { - return rand.nextDouble()-rand.nextDouble(); - } - - /** - * Used to get a completely(-1.0F - 1.0F) random float. - * @version From DummyCore 1.0 - * @param rand - the Random, that will randomise this. - * @return a random Float - */ - public static float randomFloat(Random rand) - { - return rand.nextFloat()-rand.nextFloat(); - } - - /** - * Used to calculate difference between 2 float. - * @version From DummyCore 1.0 - * @param pos1 - float #1 - * @param pos2 - float #2 - * @return always positive value of difference. - */ - public static float getDifference(float pos1, float pos2) - { - float diff = pos1-pos2; - return (float)module(diff); - } - - /** - * Swaps 2 integers between eachother. - * @version From DummyCore 1.1 - * @param a - first int to swap - * @param b - second int to swap - * @return int[2] with this 2 values swapped. - */ - @Deprecated - public static int[] swap(int a, int b) - { - return new int[]{b,a}; - } - - /** - * Used to convert deciminal number to the Hexadeciminal. - * @version From DummyCore 1.1 - * @param a - the int to be converted - * @return this integer, converted into hexadeciminal - */ - public static int convertToHex(int a) - { - return Integer.parseInt(Integer.toString(a),16); - } - - /** - * Used to get the always positive value of a double. - * @version From DummyCore 1.2 - * @param a - the double to be converted - * @return this double, but positive(>0) - */ - public static double module(double a) - { - if(a < 0) a = -a; - return a; - } - - public static boolean arrayContains(Object[] array, Object searched) - { - for(int i = 0; i < array.length; ++i) - { - if(array[i].equals(searched)) - return true; - } - return false; - } - - public static boolean arrayContains(int[] array, int searched) - { - for(int i = 0; i < array.length; ++i) - { - if(array[i] == searched) - return true; - } - return false; - } - - public static int getIntInArray(int[] array, int searched) - { - for(int i = 0; i < array.length; ++i) - { - if(array[i] == searched) - return i; - } - return -1; - } - - public static boolean isArrayTheSame(boolean[] array) - { - boolean previous = array[0]; - for(int i = 0; i < array.length; ++i) - { - if(array[i] == previous) - { - previous = array[i]; - }else - { - return false; - } - } - return true; - } + /** + * Used to get the size of a texture in pixels using current values. Very useful in any kind of progress bars in GUI + * @version From DummyCore 1.0 + * @param current - the current value + * @param max - the maximum value + * @param textureSize - the maximum texture size + * @return Percentage-based int. For example, if the textureSize is 50, current is 100 and max is 200 this will return 25 - that is 50% of your texture size. + */ + public static int pixelatedTextureSize(int current, int max, int textureSize) { + if (current > max) current = max; + float m = (float) current / max * 100; + float n = m / 100 * textureSize; + return (int) n; + } + + /** + * Used to get the persentage between 2 numbers + * @version From DummyCore 1.0 + * @param current - the current value + * @param max - the maximum value + * @return Percentage-based int. For example, if current is 100 and max is 200 this will return 50. + */ + public static int getPercentage(int current, int max) { + float m = (float) current / max * 100; + return (int) m; + } + + /** + * Used to get the polar-based offset between 2 points in vec2D coord system. + * @version From DummyCore 1.0 + * @param position - the current vec2D + * @param angle - the angle of offset + * @param distance - the distance the point will be offset + * @return new Coord2D with offset coords. + */ + public static Coord2D polarOffset(Coord2D position, float angle, float distance) { + float d0 = (float) (position.x + Math.cos(angle * Math.PI / 180.0D) * distance); + float d1 = (float) (position.z + Math.sin(angle * Math.PI / 180.0D) * distance); + return new Coord2D(d0, d1); + } + + /** + * Used to get a completely(-1.0D - 1.0D) random double. + * @version From DummyCore 1.0 + * @param rand - the Random, that will randomise this. + * @return a random Double + */ + public static double randomDouble(Random rand) { + return rand.nextDouble() - rand.nextDouble(); + } + + /** + * Used to get a completely(-1.0F - 1.0F) random float. + * @version From DummyCore 1.0 + * @param rand - the Random, that will randomise this. + * @return a random Float + */ + public static float randomFloat(Random rand) { + return rand.nextFloat() - rand.nextFloat(); + } + + /** + * Used to calculate difference between 2 float. + * @version From DummyCore 1.0 + * @param pos1 - float #1 + * @param pos2 - float #2 + * @return always positive value of difference. + */ + public static float getDifference(float pos1, float pos2) { + float diff = pos1 - pos2; + return (float) module(diff); + } + + /** + * Swaps 2 integers between eachother. + * @version From DummyCore 1.1 + * @param a - first int to swap + * @param b - second int to swap + * @return int[2] with this 2 values swapped. + */ + @Deprecated + public static int[] swap(int a, int b) { + return new int[] {b, a}; + } + + /** + * Used to convert deciminal number to the Hexadeciminal. + * @version From DummyCore 1.1 + * @param a - the int to be converted + * @return this integer, converted into hexadeciminal + */ + public static int convertToHex(int a) { + return Integer.parseInt(Integer.toString(a), 16); + } + + /** + * Used to get the always positive value of a double. + * @version From DummyCore 1.2 + * @param a - the double to be converted + * @return this double, but positive(>0) + */ + public static double module(double a) { + if (a < 0) a = -a; + return a; + } + + public static boolean arrayContains(Object[] array, Object searched) { + for (int i = 0; i < array.length; ++i) { + if (array[i].equals(searched)) return true; + } + return false; + } + + public static boolean arrayContains(int[] array, int searched) { + for (int i = 0; i < array.length; ++i) { + if (array[i] == searched) return true; + } + return false; + } + + public static int getIntInArray(int[] array, int searched) { + for (int i = 0; i < array.length; ++i) { + if (array[i] == searched) return i; + } + return -1; + } + + public static boolean isArrayTheSame(boolean[] array) { + boolean previous = array[0]; + for (int i = 0; i < array.length; ++i) { + if (array[i] == previous) { + previous = array[i]; + } else { + return false; + } + } + return true; + } } diff --git a/src/main/java/DummyCore/Utils/MiscUtils.java b/src/main/java/DummyCore/Utils/MiscUtils.java index 015cce1..280e06a 100644 --- a/src/main/java/DummyCore/Utils/MiscUtils.java +++ b/src/main/java/DummyCore/Utils/MiscUtils.java @@ -1,5 +1,12 @@ package DummyCore.Utils; +import DummyCore.Core.CoreInitialiser; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.ObfuscationReflectionHelper; +import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; +import cpw.mods.fml.relauncher.ReflectionHelper; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -7,7 +14,6 @@ import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.UUID; - import net.minecraft.block.Block; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiButton; @@ -39,389 +45,403 @@ import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.oredict.OreDictionary; -import DummyCore.Core.CoreInitialiser; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.ObfuscationReflectionHelper; -import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; -import cpw.mods.fml.relauncher.ReflectionHelper; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; /** - * + * * @author Modbder * @version From DummyCore 1.0 * @Description can be used to save you some time writing different functions. * */ public class MiscUtils { - public static final String genUUIDString = "CB3F55A9-6DCC-4FF8-AAC7-9B87A33"; - public static final Hashtable descriptionTable = new Hashtable(); - public static final Hashtable descriptionCTable = new Hashtable(); - public static final Hashtable, String> descriptionNTable = new Hashtable, String>(); - public static final Hashtable, EnumChatFormatting> descriptionNCTable = new Hashtable, EnumChatFormatting>(); - public static final Hashtable registeredClientData = new Hashtable(); - public static final Hashtable registeredClientWorldData = new Hashtable(); - public static final Hashtable registeredServerData = new Hashtable(); - public static final Hashtable registeredServerWorldData = new Hashtable(); - public static final List unbreakableBlocks = new ArrayList(); - public static final List actions = new ArrayList(); - - //ShaderGroups IDs - - //0 - Pixelated - //1 - Smooth - //2 - Bright, Highly blured - //3 - High contrast, Pixel outline - //4 - Bright, Medium blured - //5 - Bright, Black&white only, Pixel Outline - //6 - Default, ++Colors - //7 - 3D anaglyph - //8 - Upside-down - //9 - Inverted Colors - //10 - Television Screen - //11 - Small pixel outline, Small blur - //12 - Moving image overlay - //13 - Default, Television screen overlay - //14 - Pixel outline, White-Black colors inverted, other stay the same - //15 - Highly pixelated - //16 - Default, --Colors - //17 - Television Screen, Green vision, Highly pixelated - //18 - Blured vision - //19 - Drugs - //20 - Pixels highly smoothened - //21 - Small blur - //22 - List Index End - public static final ResourceLocation[] defaultShaders = new ResourceLocation[] {new ResourceLocation("shaders/post/notch.json"), new ResourceLocation("shaders/post/fxaa.json"), new ResourceLocation("shaders/post/art.json"), new ResourceLocation("shaders/post/bumpy.json"), new ResourceLocation("shaders/post/blobs2.json"), new ResourceLocation("shaders/post/pencil.json"), new ResourceLocation("shaders/post/color_convolve.json"), new ResourceLocation("shaders/post/deconverge.json"), new ResourceLocation("shaders/post/flip.json"), new ResourceLocation("shaders/post/invert.json"), new ResourceLocation("shaders/post/ntsc.json"), new ResourceLocation("shaders/post/outline.json"), new ResourceLocation("shaders/post/phosphor.json"), new ResourceLocation("shaders/post/scan_pincushion.json"), new ResourceLocation("shaders/post/sobel.json"), new ResourceLocation("shaders/post/bits.json"), new ResourceLocation("shaders/post/desaturate.json"), new ResourceLocation("shaders/post/green.json"), new ResourceLocation("shaders/post/blur.json"), new ResourceLocation("shaders/post/wobble.json"), new ResourceLocation("shaders/post/blobs.json"), new ResourceLocation("shaders/post/antialias.json")}; + public static final String genUUIDString = "CB3F55A9-6DCC-4FF8-AAC7-9B87A33"; + public static final Hashtable descriptionTable = new Hashtable(); + public static final Hashtable descriptionCTable = + new Hashtable(); + public static final Hashtable, String> descriptionNTable = new Hashtable, String>(); + public static final Hashtable, EnumChatFormatting> descriptionNCTable = + new Hashtable, EnumChatFormatting>(); + public static final Hashtable registeredClientData = new Hashtable(); + public static final Hashtable registeredClientWorldData = new Hashtable(); + public static final Hashtable registeredServerData = new Hashtable(); + public static final Hashtable registeredServerWorldData = new Hashtable(); + public static final List unbreakableBlocks = new ArrayList(); + public static final List actions = new ArrayList(); - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated - @SideOnly(Side.CLIENT) - public static void bindTexture(String mod, String texture) - { - DrawUtils.bindTexture(mod, texture); - } - - /** - * Creates a new NBTTagCompound for the given ItemStack - * @version From DummyCore 1.0 - * @param stack - the ItemStack to work with. - */ - public static void createNBTTag(ItemStack stack) - { - if(stack.hasTagCompound()) - { - return; - } - NBTTagCompound itemTag = new NBTTagCompound(); - stack.setTagCompound(itemTag); - } - - /** - * used to get the ItemStack's tag compound. - * @version From DummyCore 1.0 - * @param stack - the ItemStack to work with. - * @return NBTTagCompound of the ItemStack - */ - public static NBTTagCompound getStackTag(ItemStack stack) - { - createNBTTag(stack); - return stack.getTagCompound(); - } - - /** - * Used to drop items from IInventory when the block is broken. - * @version From DummyCore 1.0 - * @param par1World - the World object - * @param par2 - X coordinate of the block - * @param par3 - Y coordinate of the block - * @param par4 - Z coordinate of the block - */ - public static void dropItemsOnBlockBreak(World par1World, int par2, int par3, int par4, Block par5, int par6) - { - //Was causing too much issues, had to add a try/catch statement... - try - { - IInventory inv = (IInventory)par1World.getTileEntity(par2, par3, par4); - - if (inv != null) - { - for (int j1 = 0; j1 < inv.getSizeInventory(); ++j1) - { - ItemStack itemstack = inv.getStackInSlot(j1); - - if (itemstack != null) - { - float f = par1World.rand.nextFloat() * 0.8F + 0.1F; - float f1 = par1World.rand.nextFloat() * 0.8F + 0.1F; - float f2 = par1World.rand.nextFloat() * 0.8F + 0.1F; - - while (itemstack.stackSize > 0) - { - int k1 = par1World.rand.nextInt(21) + 10; - - if (k1 > itemstack.stackSize) - { - k1 = itemstack.stackSize; - } - - itemstack.stackSize -= k1; - EntityItem entityitem = new EntityItem(par1World, (double)((float)par2 + f), (double)((float)par3 + f1), (double)((float)par4 + f2), new ItemStack(itemstack.getItem(), k1, itemstack.getItemDamage())); - - if (itemstack.hasTagCompound()) - { - entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy()); - } - - float f3 = 0.05F; - entityitem.motionX = (double)((float)par1World.rand.nextGaussian() * f3); - entityitem.motionY = (double)((float)par1World.rand.nextGaussian() * f3 + 0.2F); - entityitem.motionZ = (double)((float)par1World.rand.nextGaussian() * f3); - par1World.spawnEntityInWorld(entityitem); - } - } - } - } - }catch(Exception ex) - { - Notifier.notifyCustomMod("DummyCore", "[ERROR]Trying to drop items upon block breaking, but caught an exception:"); - ex.printStackTrace(); - return; - } - } - - /** - * Used to check, if the Forge Ore Dictionary contains the given name in it. - * @version From DummyCore 1.4 - * @param oreName - the ore name to search - * @return true if OreDictionary cantains the given ore, false if not. - */ - public static boolean oreDictionaryContains(String oreName) - { - return !OreDictionary.getOres(oreName).isEmpty(); - } - - /** - * Used to sync the given tile entity with the given side using DummyCore packet handler. - * @version From DummyCore 1.4 - * @param t - the tileentity to sync. - * @param s - the side, that will accept the packet. - */ - public static void syncTileEntity(ITEHasGameData t, Side s) - { - String dataString = "||mod:DummyCore.TileSync"+t.getPosition()+t.getData(); - DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); - if(s == Side.CLIENT) - { - DummyPacketHandler.sendToAll(simplePacket); - } - if(s == Side.SERVER) - { - DummyPacketHandler.sendToServer(simplePacket); - } - } - - public static void syncTileEntity(NBTTagCompound tileTag, int packetID) - { - DummyPacketIMSG_Tile simplePacket = new DummyPacketIMSG_Tile(tileTag); - CoreInitialiser.network.sendToAll(simplePacket); - } - - /** - * No longer functional. Please, remove the references from your code and use Minecraft's attrubute system instead! - * */ - @Deprecated - public static void makeItemIgnoreDamage(Item i){} - - /** - * No longer functional. Please, remove the references from your code and use Minecraft's attrubute system instead! - * */ - @Deprecated - public static void registerItemModifier(Item id, int meta,String type, String last5ofUUID,double value,IAttribute attrib,int operation){} - - /** - * Used to apply any attribute to the Player. - * - * @param p - The player to apply the attribute at - * @param attrib - the attribute to modify - * @param uuidLast5Symbols - last 5 symbols of the unique ID of your modifier. Should be unique per item, however not required strictly. The String needs to hold 5 symbols, and allowed symbols are - 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F - * @param modifier - the value, that the attribute will get modified for - * @param remove - should actually remove the attribute from the player, and not add it - * @param operation - the operation on the attribute(0 is numberical modification(aka currentAttributeValue+yourValue) and 2 is percentage modification(aka currentAttributeValue*yourValue)) - * @param type - the condition, at which the modifier should be applied. 3 Conditions exist - inventory(the item needs to be in Player's inventory),hold(Player needs to hold the item) and armor(item needs to be in Player's armor slots) - */ - public static void applyPlayerModifier(EntityPlayer p,IAttribute attrib, String uuidLast5Symbols, double modifier, boolean remove, int operation, String type) - { - if(p.getAttributeMap().getAttributeInstance(attrib).getModifier(UUID.fromString(genUUIDString+uuidLast5Symbols)) == null) - { - if(!remove) - p.getAttributeMap().getAttributeInstance(attrib).applyModifier(new AttributeModifier(UUID.fromString(genUUIDString+uuidLast5Symbols),"dam."+type+"."+attrib.getAttributeUnlocalizedName(), modifier, operation)); - }else if(remove) - { - if(p.getAttributeMap().getAttributeInstance(attrib).getModifier(UUID.fromString(genUUIDString+uuidLast5Symbols)) != null) - p.getAttributeMap().getAttributeInstance(attrib).removeModifier(p.getAttributeMap().getAttributeInstance(attrib).getModifier(UUID.fromString(genUUIDString+uuidLast5Symbols))); - } - } - - @Deprecated - public static void registerDescriptionFor(String unlocalisedName, String descr, EnumChatFormatting color){} + // ShaderGroups IDs - + // 0 - Pixelated + // 1 - Smooth + // 2 - Bright, Highly blured + // 3 - High contrast, Pixel outline + // 4 - Bright, Medium blured + // 5 - Bright, Black&white only, Pixel Outline + // 6 - Default, ++Colors + // 7 - 3D anaglyph + // 8 - Upside-down + // 9 - Inverted Colors + // 10 - Television Screen + // 11 - Small pixel outline, Small blur + // 12 - Moving image overlay + // 13 - Default, Television screen overlay + // 14 - Pixel outline, White-Black colors inverted, other stay the same + // 15 - Highly pixelated + // 16 - Default, --Colors + // 17 - Television Screen, Green vision, Highly pixelated + // 18 - Blured vision + // 19 - Drugs + // 20 - Pixels highly smoothened + // 21 - Small blur + // 22 - List Index End + public static final ResourceLocation[] defaultShaders = new ResourceLocation[] { + new ResourceLocation("shaders/post/notch.json"), + new ResourceLocation("shaders/post/fxaa.json"), + new ResourceLocation("shaders/post/art.json"), + new ResourceLocation("shaders/post/bumpy.json"), + new ResourceLocation("shaders/post/blobs2.json"), + new ResourceLocation("shaders/post/pencil.json"), + new ResourceLocation("shaders/post/color_convolve.json"), + new ResourceLocation("shaders/post/deconverge.json"), + new ResourceLocation("shaders/post/flip.json"), + new ResourceLocation("shaders/post/invert.json"), + new ResourceLocation("shaders/post/ntsc.json"), + new ResourceLocation("shaders/post/outline.json"), + new ResourceLocation("shaders/post/phosphor.json"), + new ResourceLocation("shaders/post/scan_pincushion.json"), + new ResourceLocation("shaders/post/sobel.json"), + new ResourceLocation("shaders/post/bits.json"), + new ResourceLocation("shaders/post/desaturate.json"), + new ResourceLocation("shaders/post/green.json"), + new ResourceLocation("shaders/post/blur.json"), + new ResourceLocation("shaders/post/wobble.json"), + new ResourceLocation("shaders/post/blobs.json"), + new ResourceLocation("shaders/post/antialias.json") + }; - @Deprecated - public static void registerDescriptionFor(String id, int meta, String descr, EnumChatFormatting color){} - - /** - * Used to send packets from SERVER to CLIENT. - * @version From DummyCore 1.7 - * @param w - the worldObj that we are operating in - * @param pkt - the packet to send - * @param x - the X coordinate - * @param y - the Y coordinate - * @param z - the Z coordinate - * @param dimId - the ID of the dimension to look the players. - * @param distance - the distance at which the players will get found. - */ - @SuppressWarnings("unchecked") - public static void sendPacketToAllAround(World w,Packet pkt, int x, int y, int z, int dimId, double distance) - { - List playerLst = w.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.getBoundingBox(x-0.5D, y-0.5D, z-0.5D, x+0.5D, y+0.5D, z+0.5D).expand(distance, distance, distance)); - if(!playerLst.isEmpty()) - { - for(int i = 0; i < playerLst.size(); ++i) - { - EntityPlayer player = playerLst.get(i); - if(player instanceof EntityPlayerMP) - { - if(pkt instanceof S35PacketUpdateTileEntity) - { - NBTTagCompound tileTag = new NBTTagCompound(); - w.getTileEntity(x, y, z).writeToNBT(tileTag); - CoreInitialiser.network.sendTo(new DummyPacketIMSG_Tile(tileTag,-10), (EntityPlayerMP) player); - }else - { - if(player.dimension == dimId) - ((EntityPlayerMP)player).getServerForPlayer().func_73046_m().getConfigurationManager().sendPacketToAllPlayers(pkt); - } - }else - { - Notifier.notifyDebug("Trying to send packet "+pkt+" to all around on Client side, probably a bug, ending the packet send try"); - } - } - } - } - - /** - * Used to send packets from SERVER to CLIENT. - * @version From DummyCore 1.7 - * @param w - the worldObj that we are operating in - * @param distance - the distance at which the players will get found. - */ - @SuppressWarnings("unchecked") - public static void sendPacketToAll(World w,Packet pkt) - { - List playerLst = w.playerEntities; - if(!playerLst.isEmpty()) - { - for(int i = 0; i < playerLst.size(); ++i) - { - EntityPlayer player = playerLst.get(i); - if(player instanceof EntityPlayerMP) - { - ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(pkt); - }else - { - Notifier.notifyDebug("Trying to send packet "+pkt+" to all on Client side, probably a bug, ending the packet send try"); - } - } - } - } - - /** - * Used to send packets from SERVER to CLIENT. - * @version From DummyCore 1.7 - * @param w - the worldObj that we are operating in - * @param pkt - the packet to send - * @param dimId - the ID of the dimension to look the players. - */ - @SuppressWarnings("unchecked") - public static void sendPacketToAllInDim(World w,Packet pkt, int dimId) - { - List playerLst = w.playerEntities; - if(!playerLst.isEmpty()) - { - for(int i = 0; i < playerLst.size(); ++i) - { - EntityPlayer player = playerLst.get(i); - if(player instanceof EntityPlayerMP) - { - if(player.dimension == dimId) - ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(pkt); - }else - { - Notifier.notifyDebug("Trying to send packet "+pkt+" to all in dimension "+dimId+" on Client side, probably a bug, ending the packet send try"); - } - } - } - } - - /** - * Used to send packets from SERVER to CLIENT. - * @version From DummyCore 1.7 - * @param w - the worldObj that we are operating in - * @param pkt - the packet to send - * @param player - the player to whom we are sending the packet. - */ - public static void sendPacketToPlayer(World w,Packet pkt,EntityPlayer player) - { - if(player instanceof EntityPlayerMP) - { - ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(pkt); - }else - { - Notifier.notifyDebug("Trying to send packet "+pkt+" to player "+player+"||"+player.getDisplayName()+" on Client side, probably a bug, ending the packet send try"); - } - } - - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated @SideOnly(Side.CLIENT) - public static boolean drawScaledTexturedRect_Items(int x, int y, IIcon icon, int width, int height, float zLevel) - { - return DrawUtils.drawScaledTexturedRect_Items(x, y, icon, width, height, zLevel); - } - - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated - @SideOnly(Side.CLIENT) - public static boolean drawScaledTexturedRect(int x, int y, IIcon icon, int width, int height, float zLevel) - { - return DrawUtils.drawScaledTexturedRect(x, y, icon, width, height, zLevel); + public static void bindTexture(String mod, String texture) { + DrawUtils.bindTexture(mod, texture); } - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated - @SideOnly(Side.CLIENT) - public static void drawTexture(int x, int y, IIcon icon, int width, int height, float zLevel) - { - DrawUtils.drawTexture(x, y, icon, width, height, zLevel); + /** + * Creates a new NBTTagCompound for the given ItemStack + * @version From DummyCore 1.0 + * @param stack - the ItemStack to work with. + */ + public static void createNBTTag(ItemStack stack) { + if (stack.hasTagCompound()) { + return; + } + NBTTagCompound itemTag = new NBTTagCompound(); + stack.setTagCompound(itemTag); } - - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated - @SideOnly(Side.CLIENT) - public static void drawTexture_Items(int x, int y, IIcon icon, int width, int height, float zLevel) - { - DrawUtils.drawTexture_Items(x, y, icon, width, height, zLevel); + + /** + * used to get the ItemStack's tag compound. + * @version From DummyCore 1.0 + * @param stack - the ItemStack to work with. + * @return NBTTagCompound of the ItemStack + */ + public static NBTTagCompound getStackTag(ItemStack stack) { + createNBTTag(stack); + return stack.getTagCompound(); } - + + /** + * Used to drop items from IInventory when the block is broken. + * @version From DummyCore 1.0 + * @param par1World - the World object + * @param par2 - X coordinate of the block + * @param par3 - Y coordinate of the block + * @param par4 - Z coordinate of the block + */ + public static void dropItemsOnBlockBreak(World par1World, int par2, int par3, int par4, Block par5, int par6) { + // Was causing too much issues, had to add a try/catch statement... + try { + IInventory inv = (IInventory) par1World.getTileEntity(par2, par3, par4); + + if (inv != null) { + for (int j1 = 0; j1 < inv.getSizeInventory(); ++j1) { + ItemStack itemstack = inv.getStackInSlot(j1); + + if (itemstack != null) { + float f = par1World.rand.nextFloat() * 0.8F + 0.1F; + float f1 = par1World.rand.nextFloat() * 0.8F + 0.1F; + float f2 = par1World.rand.nextFloat() * 0.8F + 0.1F; + + while (itemstack.stackSize > 0) { + int k1 = par1World.rand.nextInt(21) + 10; + + if (k1 > itemstack.stackSize) { + k1 = itemstack.stackSize; + } + + itemstack.stackSize -= k1; + EntityItem entityitem = new EntityItem( + par1World, + (double) ((float) par2 + f), + (double) ((float) par3 + f1), + (double) ((float) par4 + f2), + new ItemStack(itemstack.getItem(), k1, itemstack.getItemDamage())); + + if (itemstack.hasTagCompound()) { + entityitem.getEntityItem().setTagCompound((NBTTagCompound) + itemstack.getTagCompound().copy()); + } + + float f3 = 0.05F; + entityitem.motionX = (double) ((float) par1World.rand.nextGaussian() * f3); + entityitem.motionY = (double) ((float) par1World.rand.nextGaussian() * f3 + 0.2F); + entityitem.motionZ = (double) ((float) par1World.rand.nextGaussian() * f3); + par1World.spawnEntityInWorld(entityitem); + } + } + } + } + } catch (Exception ex) { + Notifier.notifyCustomMod( + "DummyCore", "[ERROR]Trying to drop items upon block breaking, but caught an exception:"); + ex.printStackTrace(); + return; + } + } + + /** + * Used to check, if the Forge Ore Dictionary contains the given name in it. + * @version From DummyCore 1.4 + * @param oreName - the ore name to search + * @return true if OreDictionary cantains the given ore, false if not. + */ + public static boolean oreDictionaryContains(String oreName) { + return !OreDictionary.getOres(oreName).isEmpty(); + } + + /** + * Used to sync the given tile entity with the given side using DummyCore packet handler. + * @version From DummyCore 1.4 + * @param t - the tileentity to sync. + * @param s - the side, that will accept the packet. + */ + public static void syncTileEntity(ITEHasGameData t, Side s) { + String dataString = "||mod:DummyCore.TileSync" + t.getPosition() + t.getData(); + DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); + if (s == Side.CLIENT) { + DummyPacketHandler.sendToAll(simplePacket); + } + if (s == Side.SERVER) { + DummyPacketHandler.sendToServer(simplePacket); + } + } + + public static void syncTileEntity(NBTTagCompound tileTag, int packetID) { + DummyPacketIMSG_Tile simplePacket = new DummyPacketIMSG_Tile(tileTag); + CoreInitialiser.network.sendToAll(simplePacket); + } + + /** + * No longer functional. Please, remove the references from your code and use Minecraft's attrubute system instead! + * */ + @Deprecated + public static void makeItemIgnoreDamage(Item i) {} + + /** + * No longer functional. Please, remove the references from your code and use Minecraft's attrubute system instead! + * */ + @Deprecated + public static void registerItemModifier( + Item id, int meta, String type, String last5ofUUID, double value, IAttribute attrib, int operation) {} + + /** + * Used to apply any attribute to the Player. + * + * @param p - The player to apply the attribute at + * @param attrib - the attribute to modify + * @param uuidLast5Symbols - last 5 symbols of the unique ID of your modifier. Should be unique per item, however not required strictly. The String needs to hold 5 symbols, and allowed symbols are - 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F + * @param modifier - the value, that the attribute will get modified for + * @param remove - should actually remove the attribute from the player, and not add it + * @param operation - the operation on the attribute(0 is numberical modification(aka currentAttributeValue+yourValue) and 2 is percentage modification(aka currentAttributeValue*yourValue)) + * @param type - the condition, at which the modifier should be applied. 3 Conditions exist - inventory(the item needs to be in Player's inventory),hold(Player needs to hold the item) and armor(item needs to be in Player's armor slots) + */ + public static void applyPlayerModifier( + EntityPlayer p, + IAttribute attrib, + String uuidLast5Symbols, + double modifier, + boolean remove, + int operation, + String type) { + if (p.getAttributeMap() + .getAttributeInstance(attrib) + .getModifier(UUID.fromString(genUUIDString + uuidLast5Symbols)) + == null) { + if (!remove) + p.getAttributeMap() + .getAttributeInstance(attrib) + .applyModifier(new AttributeModifier( + UUID.fromString(genUUIDString + uuidLast5Symbols), + "dam." + type + "." + attrib.getAttributeUnlocalizedName(), + modifier, + operation)); + } else if (remove) { + if (p.getAttributeMap() + .getAttributeInstance(attrib) + .getModifier(UUID.fromString(genUUIDString + uuidLast5Symbols)) + != null) + p.getAttributeMap() + .getAttributeInstance(attrib) + .removeModifier(p.getAttributeMap() + .getAttributeInstance(attrib) + .getModifier(UUID.fromString(genUUIDString + uuidLast5Symbols))); + } + } + + @Deprecated + public static void registerDescriptionFor(String unlocalisedName, String descr, EnumChatFormatting color) {} + + @Deprecated + public static void registerDescriptionFor(String id, int meta, String descr, EnumChatFormatting color) {} + + /** + * Used to send packets from SERVER to CLIENT. + * @version From DummyCore 1.7 + * @param w - the worldObj that we are operating in + * @param pkt - the packet to send + * @param x - the X coordinate + * @param y - the Y coordinate + * @param z - the Z coordinate + * @param dimId - the ID of the dimension to look the players. + * @param distance - the distance at which the players will get found. + */ + @SuppressWarnings("unchecked") + public static void sendPacketToAllAround(World w, Packet pkt, int x, int y, int z, int dimId, double distance) { + List playerLst = w.getEntitiesWithinAABB( + EntityPlayer.class, + AxisAlignedBB.getBoundingBox(x - 0.5D, y - 0.5D, z - 0.5D, x + 0.5D, y + 0.5D, z + 0.5D) + .expand(distance, distance, distance)); + if (!playerLst.isEmpty()) { + for (int i = 0; i < playerLst.size(); ++i) { + EntityPlayer player = playerLst.get(i); + if (player instanceof EntityPlayerMP) { + if (pkt instanceof S35PacketUpdateTileEntity) { + NBTTagCompound tileTag = new NBTTagCompound(); + w.getTileEntity(x, y, z).writeToNBT(tileTag); + CoreInitialiser.network.sendTo(new DummyPacketIMSG_Tile(tileTag, -10), (EntityPlayerMP) player); + } else { + if (player.dimension == dimId) + ((EntityPlayerMP) player) + .getServerForPlayer() + .func_73046_m() + .getConfigurationManager() + .sendPacketToAllPlayers(pkt); + } + } else { + Notifier.notifyDebug("Trying to send packet " + pkt + + " to all around on Client side, probably a bug, ending the packet send try"); + } + } + } + } + + /** + * Used to send packets from SERVER to CLIENT. + * @version From DummyCore 1.7 + * @param w - the worldObj that we are operating in + * @param distance - the distance at which the players will get found. + */ + @SuppressWarnings("unchecked") + public static void sendPacketToAll(World w, Packet pkt) { + List playerLst = w.playerEntities; + if (!playerLst.isEmpty()) { + for (int i = 0; i < playerLst.size(); ++i) { + EntityPlayer player = playerLst.get(i); + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(pkt); + } else { + Notifier.notifyDebug("Trying to send packet " + pkt + + " to all on Client side, probably a bug, ending the packet send try"); + } + } + } + } + + /** + * Used to send packets from SERVER to CLIENT. + * @version From DummyCore 1.7 + * @param w - the worldObj that we are operating in + * @param pkt - the packet to send + * @param dimId - the ID of the dimension to look the players. + */ + @SuppressWarnings("unchecked") + public static void sendPacketToAllInDim(World w, Packet pkt, int dimId) { + List playerLst = w.playerEntities; + if (!playerLst.isEmpty()) { + for (int i = 0; i < playerLst.size(); ++i) { + EntityPlayer player = playerLst.get(i); + if (player instanceof EntityPlayerMP) { + if (player.dimension == dimId) ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(pkt); + } else { + Notifier.notifyDebug("Trying to send packet " + pkt + " to all in dimension " + dimId + + " on Client side, probably a bug, ending the packet send try"); + } + } + } + } + + /** + * Used to send packets from SERVER to CLIENT. + * @version From DummyCore 1.7 + * @param w - the worldObj that we are operating in + * @param pkt - the packet to send + * @param player - the player to whom we are sending the packet. + */ + public static void sendPacketToPlayer(World w, Packet pkt, EntityPlayer player) { + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(pkt); + } else { + Notifier.notifyDebug("Trying to send packet " + pkt + " to player " + player + "||" + + player.getDisplayName() + " on Client side, probably a bug, ending the packet send try"); + } + } + + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated + @SideOnly(Side.CLIENT) + public static boolean drawScaledTexturedRect_Items(int x, int y, IIcon icon, int width, int height, float zLevel) { + return DrawUtils.drawScaledTexturedRect_Items(x, y, icon, width, height, zLevel); + } + + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated + @SideOnly(Side.CLIENT) + public static boolean drawScaledTexturedRect(int x, int y, IIcon icon, int width, int height, float zLevel) { + return DrawUtils.drawScaledTexturedRect(x, y, icon, width, height, zLevel); + } + + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated + @SideOnly(Side.CLIENT) + public static void drawTexture(int x, int y, IIcon icon, int width, int height, float zLevel) { + DrawUtils.drawTexture(x, y, icon, width, height, zLevel); + } + + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated + @SideOnly(Side.CLIENT) + public static void drawTexture_Items(int x, int y, IIcon icon, int width, int height, float zLevel) { + DrawUtils.drawTexture_Items(x, y, icon, width, height, zLevel); + } + /** * Used to check if the given class actually has the named method. Used when working with APIs of different mods(actually not) * @param c - the class @@ -429,280 +449,321 @@ public class MiscUtils { * @param classes - actual parameters of the method * @return true if the given method exist, false if not */ - public static boolean classHasMethod(Class c, String mName, Class... classes) - { - try { - Method m = c.getMethod(mName, classes); - return m != null; - } catch (Exception e) { - return false; - } + public static boolean classHasMethod(Class c, String mName, Class... classes) { + try { + Method m = c.getMethod(mName, classes); + return m != null; + } catch (Exception e) { + return false; + } } - - /** - * Have you ever thought that saving inventories to NBTTag takes too much code? Here is a nifty solution to do so! - * @param t - the TileEntity - * @param saveTag - the tag - */ - public static void saveInventory(TileEntity t, NBTTagCompound saveTag) - { - if(t instanceof IInventory) - { - IInventory tile = (IInventory) t; - NBTTagList nbttaglist = new NBTTagList(); - for (int i = 0; i < tile.getSizeInventory(); ++i) - { - if (tile.getStackInSlot(i) != null) - { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte)i); - tile.getStackInSlot(i).writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - saveTag.setTag("Items", nbttaglist); - } - } - - /** - * Have you ever thought that loading inventories from NBTTag takes too much code? Here is a nifty solution to do so! - * @param t - the TileEntity - * @param loadTag - the tag - */ - public static void loadInventory(TileEntity t, NBTTagCompound loadTag) - { - if(t instanceof IInventory) - { - IInventory tile = (IInventory) t; - for(int i = 0; i < tile.getSizeInventory(); ++i) - { - tile.setInventorySlotContents(i, null); - } - NBTTagList nbttaglist = loadTag.getTagList("Items", 10); - for (int i = 0; i < nbttaglist.tagCount(); ++i) - { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - byte b0 = nbttagcompound1.getByte("Slot"); - - if (b0 >= 0 && b0 < tile.getSizeInventory()) - { - tile.setInventorySlotContents(b0, ItemStack.loadItemStackFromNBT(nbttagcompound1)); - } - } - } - } - - /** - * Actually changes the BiomeGenBase at the given coordinates. It still requires Client to update the BlockRenderer at the position! - * @param w - World - * @param biome - the biome you are changing to - * @param x - xCoordinate of the BLOCK - * @param z - zCoordinate of the BLOCK - */ - public static void changeBiome(World w, BiomeGenBase biome, int x, int z) - { - Chunk chunk = w.getChunkFromBlockCoords(x,z); - byte[] b = chunk.getBiomeArray(); - byte cbiome = b[(z & 0xf) << 4 | x & 0xf]; //What is even going on here? Can this code be a little bit more readable? - cbiome = (byte)(biome.biomeID & 0xff); - b[(z & 0xf) << 4 | x & 0xf] = cbiome; //Looks like not. - chunk.setBiomeArray(b); - notifyBiomeChange(x,z,biome.biomeID); - } - - /** - * Actually creates the given particles for ALL players - * @param particleName - the name of the particle - * @param posX - xCoord of the particle - * @param posY - yCoord of the particle - * @param posZ - zCoord of the particle - * @param par5 - particle 1 gen int. Can be motion or color(depends on the particle). - * @param par6 - particle 1 gen int. Can be motion or color(depends on the particle). - * @param par7 - particle 1 gen int. Can be motion or color(depends on the particle). - */ - public static void spawnParticlesOnServer(String particleName, float posX, float posY, float posZ, double par5, double par6, double par7) - { - String dataString = "||mod:DummyCore.Particle"; - DummyData name = new DummyData("particleName",particleName); - DummyData xpos = new DummyData("positionX",posX); - DummyData ypos = new DummyData("positionX",posY); - DummyData zpos = new DummyData("positionX",posZ); - DummyData xmot = new DummyData("par1",par5); - DummyData ymot = new DummyData("par2",par6); - DummyData zmot = new DummyData("par3",par7); - DataStorage.addDataToString(name); - DataStorage.addDataToString(xpos); - DataStorage.addDataToString(ypos); - DataStorage.addDataToString(zpos); - DataStorage.addDataToString(xmot); - DataStorage.addDataToString(ymot); - DataStorage.addDataToString(zmot); - String newDataString = DataStorage.getDataString(); - dataString+=newDataString; - DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); - DummyPacketHandler.sendToAll(simplePacket); - } - - /** - * Plays a sound to all players nearby - * @version From DummyFore 2.0 - * @param x - sound x - * @param y - sound y - * @param z - sound z - * @param sound - the sound itself - * @param volume - sound volume - * @param pitch - sound pitch - * @param radius - radius to play the sound in - * @param dim - dimension to play the sound in - */ - public static void playSoundOnServerToAllNearby(double x, double y, double z, String sound, float volume, float pitch, double radius, int dim) - { - DummyData aaa = new DummyData("x",x); - DummyData aab = new DummyData("y",y); - DummyData aac = new DummyData("z",z); - DummyData aad = new DummyData("vol",volume); - DummyData aae = new DummyData("pitch",pitch); - DummyData aaf = new DummyData("sound",sound); - DummyPacketIMSG pkt = new DummyPacketIMSG("||mod:DummyCore.Sound"+aaa+""+aab+""+aac+""+aad+""+aae+""+aaf); - DummyPacketHandler.sendToAllAround(pkt, new TargetPoint(dim, x, y, z, radius)); - } - - /** - * Adds a potion effect to the player.
If the effect exists - increases the duration.
If the duration is over specified amount adds +1 level. - * @param mob - the entity to add the effect - * @param potion - the potion to apply - * @param index - the duration - * @param index2 - the duration to add +1 level at - * @version From DummyCore 2.0 - */ - public static void calculateAndAddPE(EntityLivingBase mob, Potion potion, int index, int index2) - { - boolean hasEffect = mob.getActivePotionEffect(potion) != null; - if(hasEffect) - { - int currentDuration = mob.getActivePotionEffect(potion).getDuration(); - int newDuration = currentDuration+index2; - int newModifier = currentDuration/index; - mob.removePotionEffect(potion.id); - mob.addPotionEffect(new PotionEffect(potion.id,newDuration,newModifier)); - }else - { - mob.addPotionEffect(new PotionEffect(potion.id,index2,0)); - } - } - - /** - * Compares if 2 itemstacks are equal on the oredict side - * @param stk - * @param stk1 - * @return - * @version From DummyCore 2.0 - */ - public static boolean oreDictionaryCompare(ItemStack stk, ItemStack stk1) - { - if(stk == null || stk1 == null) - return false; - - if(OreDictionary.getOreIDs(stk) == null || OreDictionary.getOreIDs(stk).length == 0 || OreDictionary.getOreIDs(stk1) == null || OreDictionary.getOreIDs(stk1).length == 0) - return false; - - int[] ids = OreDictionary.getOreIDs(stk); - int[] ids1 = OreDictionary.getOreIDs(stk1); - - for(int i = 0; i < ids.length; ++i) - { - for(int j = 0; j < ids1.length; ++j) - { - if(ids[i] == ids1[j]) - return true; - } - } - - return false; - } - - /** - * Adds a specific action for the server to execute after some time - * @param ssa - */ - public static void addScheduledAction(ScheduledServerAction ssa) - { - if(FMLCommonHandler.instance().getEffectiveSide() != Side.SERVER) - Notifier.notifyError("Trying to add a scheduled server action not on server side, aborting!"); - - actions.add(ssa); - } - - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated - public static void drawTexturedModalRect(int p_73729_1_, int p_73729_2_, int p_73729_3_, int p_73729_4_, int p_73729_5_, int p_73729_6_, int zLevel) - { - DrawUtils.drawTexturedModalRect(p_73729_1_, p_73729_2_, p_73729_3_, p_73729_4_, p_73729_5_, p_73729_6_, zLevel); + + /** + * Have you ever thought that saving inventories to NBTTag takes too much code? Here is a nifty solution to do so! + * @param t - the TileEntity + * @param saveTag - the tag + */ + public static void saveInventory(TileEntity t, NBTTagCompound saveTag) { + if (t instanceof IInventory) { + IInventory tile = (IInventory) t; + NBTTagList nbttaglist = new NBTTagList(); + for (int i = 0; i < tile.getSizeInventory(); ++i) { + if (tile.getStackInSlot(i) != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + tile.getStackInSlot(i).writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + saveTag.setTag("Items", nbttaglist); + } } - - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated + + /** + * Have you ever thought that loading inventories from NBTTag takes too much code? Here is a nifty solution to do so! + * @param t - the TileEntity + * @param loadTag - the tag + */ + public static void loadInventory(TileEntity t, NBTTagCompound loadTag) { + if (t instanceof IInventory) { + IInventory tile = (IInventory) t; + for (int i = 0; i < tile.getSizeInventory(); ++i) { + tile.setInventorySlotContents(i, null); + } + NBTTagList nbttaglist = loadTag.getTagList("Items", 10); + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + byte b0 = nbttagcompound1.getByte("Slot"); + + if (b0 >= 0 && b0 < tile.getSizeInventory()) { + tile.setInventorySlotContents(b0, ItemStack.loadItemStackFromNBT(nbttagcompound1)); + } + } + } + } + + /** + * Actually changes the BiomeGenBase at the given coordinates. It still requires Client to update the BlockRenderer at the position! + * @param w - World + * @param biome - the biome you are changing to + * @param x - xCoordinate of the BLOCK + * @param z - zCoordinate of the BLOCK + */ + public static void changeBiome(World w, BiomeGenBase biome, int x, int z) { + Chunk chunk = w.getChunkFromBlockCoords(x, z); + byte[] b = chunk.getBiomeArray(); + byte cbiome = + b[(z & 0xf) << 4 | x & 0xf]; // What is even going on here? Can this code be a little bit more readable? + cbiome = (byte) (biome.biomeID & 0xff); + b[(z & 0xf) << 4 | x & 0xf] = cbiome; // Looks like not. + chunk.setBiomeArray(b); + notifyBiomeChange(x, z, biome.biomeID); + } + + /** + * Actually creates the given particles for ALL players + * @param particleName - the name of the particle + * @param posX - xCoord of the particle + * @param posY - yCoord of the particle + * @param posZ - zCoord of the particle + * @param par5 - particle 1 gen int. Can be motion or color(depends on the particle). + * @param par6 - particle 1 gen int. Can be motion or color(depends on the particle). + * @param par7 - particle 1 gen int. Can be motion or color(depends on the particle). + */ + public static void spawnParticlesOnServer( + String particleName, float posX, float posY, float posZ, double par5, double par6, double par7) { + String dataString = "||mod:DummyCore.Particle"; + DummyData name = new DummyData("particleName", particleName); + DummyData xpos = new DummyData("positionX", posX); + DummyData ypos = new DummyData("positionX", posY); + DummyData zpos = new DummyData("positionX", posZ); + DummyData xmot = new DummyData("par1", par5); + DummyData ymot = new DummyData("par2", par6); + DummyData zmot = new DummyData("par3", par7); + DataStorage.addDataToString(name); + DataStorage.addDataToString(xpos); + DataStorage.addDataToString(ypos); + DataStorage.addDataToString(zpos); + DataStorage.addDataToString(xmot); + DataStorage.addDataToString(ymot); + DataStorage.addDataToString(zmot); + String newDataString = DataStorage.getDataString(); + dataString += newDataString; + DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); + DummyPacketHandler.sendToAll(simplePacket); + } + + /** + * Plays a sound to all players nearby + * @version From DummyFore 2.0 + * @param x - sound x + * @param y - sound y + * @param z - sound z + * @param sound - the sound itself + * @param volume - sound volume + * @param pitch - sound pitch + * @param radius - radius to play the sound in + * @param dim - dimension to play the sound in + */ + public static void playSoundOnServerToAllNearby( + double x, double y, double z, String sound, float volume, float pitch, double radius, int dim) { + DummyData aaa = new DummyData("x", x); + DummyData aab = new DummyData("y", y); + DummyData aac = new DummyData("z", z); + DummyData aad = new DummyData("vol", volume); + DummyData aae = new DummyData("pitch", pitch); + DummyData aaf = new DummyData("sound", sound); + DummyPacketIMSG pkt = new DummyPacketIMSG( + "||mod:DummyCore.Sound" + aaa + "" + aab + "" + aac + "" + aad + "" + aae + "" + aaf); + DummyPacketHandler.sendToAllAround(pkt, new TargetPoint(dim, x, y, z, radius)); + } + + /** + * Adds a potion effect to the player.
If the effect exists - increases the duration.
If the duration is over specified amount adds +1 level. + * @param mob - the entity to add the effect + * @param potion - the potion to apply + * @param index - the duration + * @param index2 - the duration to add +1 level at + * @version From DummyCore 2.0 + */ + public static void calculateAndAddPE(EntityLivingBase mob, Potion potion, int index, int index2) { + boolean hasEffect = mob.getActivePotionEffect(potion) != null; + if (hasEffect) { + int currentDuration = mob.getActivePotionEffect(potion).getDuration(); + int newDuration = currentDuration + index2; + int newModifier = currentDuration / index; + mob.removePotionEffect(potion.id); + mob.addPotionEffect(new PotionEffect(potion.id, newDuration, newModifier)); + } else { + mob.addPotionEffect(new PotionEffect(potion.id, index2, 0)); + } + } + + /** + * Compares if 2 itemstacks are equal on the oredict side + * @param stk + * @param stk1 + * @return + * @version From DummyCore 2.0 + */ + public static boolean oreDictionaryCompare(ItemStack stk, ItemStack stk1) { + if (stk == null || stk1 == null) return false; + + if (OreDictionary.getOreIDs(stk) == null + || OreDictionary.getOreIDs(stk).length == 0 + || OreDictionary.getOreIDs(stk1) == null + || OreDictionary.getOreIDs(stk1).length == 0) return false; + + int[] ids = OreDictionary.getOreIDs(stk); + int[] ids1 = OreDictionary.getOreIDs(stk1); + + for (int i = 0; i < ids.length; ++i) { + for (int j = 0; j < ids1.length; ++j) { + if (ids[i] == ids1[j]) return true; + } + } + + return false; + } + + /** + * Adds a specific action for the server to execute after some time + * @param ssa + */ + public static void addScheduledAction(ScheduledServerAction ssa) { + if (FMLCommonHandler.instance().getEffectiveSide() != Side.SERVER) + Notifier.notifyError("Trying to add a scheduled server action not on server side, aborting!"); + + actions.add(ssa); + } + + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated + public static void drawTexturedModalRect( + int p_73729_1_, + int p_73729_2_, + int p_73729_3_, + int p_73729_4_, + int p_73729_5_, + int p_73729_6_, + int zLevel) { + DrawUtils.drawTexturedModalRect(p_73729_1_, p_73729_2_, p_73729_3_, p_73729_4_, p_73729_5_, p_73729_6_, zLevel); + } + + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated @SideOnly(Side.CLIENT) - public static void renderItemStack_Full(ItemStack stk,double posX, double posY, double posZ, double screenPosX, double screenPosY, double screenPosZ, float rotation, float rotationZ, float colorRed, float colorGreen, float colorBlue, float offsetX, float offsetY, float offsetZ) - { - DrawUtils.renderItemStack_Full(stk, posX, posY, posZ, screenPosX, screenPosY, screenPosZ, rotation, rotationZ, colorRed, colorGreen, colorBlue, offsetX, offsetY, offsetZ, false); + public static void renderItemStack_Full( + ItemStack stk, + double posX, + double posY, + double posZ, + double screenPosX, + double screenPosY, + double screenPosZ, + float rotation, + float rotationZ, + float colorRed, + float colorGreen, + float colorBlue, + float offsetX, + float offsetY, + float offsetZ) { + DrawUtils.renderItemStack_Full( + stk, + posX, + posY, + posZ, + screenPosX, + screenPosY, + screenPosZ, + rotation, + rotationZ, + colorRed, + colorGreen, + colorBlue, + offsetX, + offsetY, + offsetZ, + false); } - - /** - * Deprecated! Use DrawUtils from now! - */ - @Deprecated + + /** + * Deprecated! Use DrawUtils from now! + */ + @Deprecated @SideOnly(Side.CLIENT) - public static void renderItemStack(ItemStack stk,double posX, double posY, double posZ, double screenPosX, double screenPosY, double screenPosZ, float rotation, float colorRed, float colorGreen, float colorBlue, int renderPass, int itemsAmount) - { - DrawUtils.renderItemStack(stk, posX, posY, posZ, screenPosX, screenPosY, screenPosZ, rotation, colorRed, colorGreen, colorBlue, renderPass, itemsAmount, false); + public static void renderItemStack( + ItemStack stk, + double posX, + double posY, + double posZ, + double screenPosX, + double screenPosY, + double screenPosZ, + float rotation, + float colorRed, + float colorGreen, + float colorBlue, + int renderPass, + int itemsAmount) { + DrawUtils.renderItemStack( + stk, + posX, + posY, + posZ, + screenPosX, + screenPosY, + screenPosZ, + rotation, + colorRed, + colorGreen, + colorBlue, + renderPass, + itemsAmount, + false); } - + /** * Clones the given Entity, including it's full NBTTag * @param e - the entity to clone * @return The cloned entity */ - public static Entity cloneEntity(Entity e) - { - Entity retEntity = null; - try - { - retEntity = e.getClass().getConstructor(World.class).newInstance(e.worldObj); - retEntity.copyDataFrom(e, true); - } - catch(Exception exc) - { - return retEntity; - } - return retEntity; + public static Entity cloneEntity(Entity e) { + Entity retEntity = null; + try { + retEntity = e.getClass().getConstructor(World.class).newInstance(e.worldObj); + retEntity.copyDataFrom(e, true); + } catch (Exception exc) { + return retEntity; + } + return retEntity; } - + /** * Changes biome at the given coordinates. Unlike the previous function this one takes the biomeID, not the biome itself and isn't world dependant * @param x - x position of the block * @param z - z position of the block * @param biomeID - the new BiomeID */ - public static void notifyBiomeChange(int x, int z, int biomeID) - { - String dataString = "||mod:DummyCore.BiomeChange"; - DummyData xpos = new DummyData("positionX",x); - DummyData zpos = new DummyData("positionZ",z); - DummyData id = new DummyData("biomeID",biomeID); - DataStorage.addDataToString(xpos); - DataStorage.addDataToString(zpos); - DataStorage.addDataToString(id); - String newDataString = DataStorage.getDataString(); - dataString+=newDataString; - DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); - DummyPacketHandler.sendToAll(simplePacket); + public static void notifyBiomeChange(int x, int z, int biomeID) { + String dataString = "||mod:DummyCore.BiomeChange"; + DummyData xpos = new DummyData("positionX", x); + DummyData zpos = new DummyData("positionZ", z); + DummyData id = new DummyData("biomeID", biomeID); + DataStorage.addDataToString(xpos); + DataStorage.addDataToString(zpos); + DataStorage.addDataToString(id); + String newDataString = DataStorage.getDataString(); + dataString += newDataString; + DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); + DummyPacketHandler.sendToAll(simplePacket); } - + /** * Imitates the armor absorbption for the given damage. Can be used, if you damage your target inderectly, but still want the damage to get reduced by armor * @param base - The damaged Entity @@ -710,61 +771,49 @@ public class MiscUtils { * @param amount - the amount of the damage * @return New amount of damage(the old one reduced by armor) */ - public static float multiplyDamageByArmorAbsorbption(EntityLivingBase base, DamageSource dam, float amount) - { - if (!dam.isUnblockable()) - { + public static float multiplyDamageByArmorAbsorbption(EntityLivingBase base, DamageSource dam, float amount) { + if (!dam.isUnblockable()) { int i = 25 - base.getTotalArmorValue(); - float f1 = amount * (float)i; + float f1 = amount * (float) i; amount = f1 / 25.0F; } return amount; } - + /** - * Imitates the damage increasement by things like Strength potion and Sharpness|Power enchantments. + * Imitates the damage increasement by things like Strength potion and Sharpness|Power enchantments. * @param base - The damaged Entity * @param dam - the damage source * @param amount - the amount of the damage * @return New amount of damage(the old one reduced by armor) */ - public static float applyPotionDamageCalculations(EntityLivingBase base, DamageSource dam, float amount) - { - if (dam.isDamageAbsolute()) - { + public static float applyPotionDamageCalculations(EntityLivingBase base, DamageSource dam, float amount) { + if (dam.isDamageAbsolute()) { return amount; - } - else - { + } else { int i; int j; float f1; - if (base.isPotionActive(Potion.resistance) && dam != DamageSource.outOfWorld) - { + if (base.isPotionActive(Potion.resistance) && dam != DamageSource.outOfWorld) { i = (base.getActivePotionEffect(Potion.resistance).getAmplifier() + 1) * 5; j = 25 - i; - f1 = amount * (float)j; + f1 = amount * (float) j; amount = f1 / 25.0F; } - if (amount <= 0.0F) - { + if (amount <= 0.0F) { return 0.0F; - } - else - { + } else { i = EnchantmentHelper.getEnchantmentModifierDamage(base.getLastActiveItems(), dam); - if (i > 20) - { + if (i > 20) { i = 20; } - if (i > 0 && i <= 20) - { + if (i > 0 && i <= 20) { j = 25 - i; - f1 = amount * (float)j; + f1 = amount * (float) j; amount = f1 / 25.0F; } @@ -772,26 +821,23 @@ public class MiscUtils { } } } - + /** * Damages the given Entity ignoring the Forge EntityHurt and EntityBeeingDamaged events. * @param base - The damaged Entity * @param dam - the damage source * @param amount - the amount of the damage */ - public static void damageEntityIgnoreEvent(EntityLivingBase base, DamageSource dam, float amount) - { - if (!base.isEntityInvulnerable()) - { + public static void damageEntityIgnoreEvent(EntityLivingBase base, DamageSource dam, float amount) { + if (!base.isEntityInvulnerable()) { if (amount <= 0) return; - amount = multiplyDamageByArmorAbsorbption(base,dam,amount); - amount = applyPotionDamageCalculations(base,dam,amount); + amount = multiplyDamageByArmorAbsorbption(base, dam, amount); + amount = applyPotionDamageCalculations(base, dam, amount); float f1 = amount; amount = Math.max(amount - base.getAbsorptionAmount(), 0.0F); base.setAbsorptionAmount(base.getAbsorptionAmount() - (f1 - amount)); - if (amount != 0.0F) - { + if (amount != 0.0F) { float f2 = base.getHealth(); base.setHealth(f2 - amount); base.func_110142_aN().func_94547_a(dam, f2, amount); @@ -799,7 +845,7 @@ public class MiscUtils { } } } - + /** * Allows changes of variables declared like private final || private static final. Advanced. Do not use if you do not know what you are doing! * Sometimes considered as a dirty hacking of the java code. I agree. There is nothing more dirty, than just removing the FINAL modifier of the variable. It's like Java can't even do anything, no matter the protection given. @@ -810,40 +856,40 @@ public class MiscUtils { * @param value - what you actually want to be set in the variable field * @param fieldNames - the names of the field you are changing. Should be both for obfuscated and compiled code. */ - public static void setPrivateFinalValue(Class classToAccess, Object instance, Object value, String fieldNames[]) - { - Field field = ReflectionHelper.findField(classToAccess, ObfuscationReflectionHelper.remapFieldNames(classToAccess.getName(), fieldNames)); - try - { + public static void setPrivateFinalValue( + Class classToAccess, Object instance, Object value, String fieldNames[]) { + Field field = ReflectionHelper.findField( + classToAccess, ObfuscationReflectionHelper.remapFieldNames(classToAccess.getName(), fieldNames)); + try { Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(instance, value); - } - catch(Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } - + /** * Extends the default mc potionArray(which is declared as public static final Potion[] potionTypes = new Potion[32]) by the given amount * @param byAmount - how much to extends for * @return the first free index in the new potionArray. */ - public static int extendPotionArray(int byAmount) - { - int potionOffset = Potion.potionTypes.length; - Potion[] potionTypes = new Potion[potionOffset + byAmount]; - System.arraycopy(Potion.potionTypes, 0, potionTypes, 0, potionOffset); - setPrivateFinalValue(Potion.class,null,potionTypes,ObfuscationReflectionHelper.remapFieldNames(Potion.class.getName(), new String[] {"potionTypes","field_76425_a","a"})); - for(int i = 0; i < Potion.potionTypes.length; ++i) - if(Potion.potionTypes[i] == null) - return i; - - return -1; + public static int extendPotionArray(int byAmount) { + int potionOffset = Potion.potionTypes.length; + Potion[] potionTypes = new Potion[potionOffset + byAmount]; + System.arraycopy(Potion.potionTypes, 0, potionTypes, 0, potionOffset); + setPrivateFinalValue( + Potion.class, + null, + potionTypes, + ObfuscationReflectionHelper.remapFieldNames( + Potion.class.getName(), new String[] {"potionTypes", "field_76425_a", "a"})); + for (int i = 0; i < Potion.potionTypes.length; ++i) if (Potion.potionTypes[i] == null) return i; + + return -1; } - + /** * Sets the block at the given coordinates to unbreakable || breakable * @param w - the World @@ -852,26 +898,21 @@ public class MiscUtils { * @param z - the z of the block * @param remove - should actually set the block to breakable(true) of to unbreakable(false) */ - public static void setBlockUnbreakable(World w, int x, int y, int z, boolean remove) - { - if(!isBlockUnbreakable(w,x,y,z) && !remove) - { - BlockPosition pos = new BlockPosition(w, x, y, z); - unbreakableBlocks.add(pos); - }else - { - for(int i = 0; i < unbreakableBlocks.size(); ++i) - { - BlockPosition pos = unbreakableBlocks.get(i); - if(pos.x == x && pos.y == y && pos.z == z && pos.wrld.provider.dimensionId == w.provider.dimensionId) - { - unbreakableBlocks.remove(pos); - break; - } - } - } + public static void setBlockUnbreakable(World w, int x, int y, int z, boolean remove) { + if (!isBlockUnbreakable(w, x, y, z) && !remove) { + BlockPosition pos = new BlockPosition(w, x, y, z); + unbreakableBlocks.add(pos); + } else { + for (int i = 0; i < unbreakableBlocks.size(); ++i) { + BlockPosition pos = unbreakableBlocks.get(i); + if (pos.x == x && pos.y == y && pos.z == z && pos.wrld.provider.dimensionId == w.provider.dimensionId) { + unbreakableBlocks.remove(pos); + break; + } + } + } } - + /** * Checks if the block at the given coordinates is unbreakable * @param w - the World @@ -880,17 +921,15 @@ public class MiscUtils { * @param z - the z of the block * @return True if the player can break the block, false if not */ - public static boolean isBlockUnbreakable(World w, int x, int y, int z) - { - for(int i = 0; i < unbreakableBlocks.size(); ++i) - { - BlockPosition pos = unbreakableBlocks.get(i); - if(pos.x == x && pos.y == y && pos.z == z && pos.wrld.provider.dimensionId == w.provider.dimensionId) - return true; - } - return false; + public static boolean isBlockUnbreakable(World w, int x, int y, int z) { + for (int i = 0; i < unbreakableBlocks.size(); ++i) { + BlockPosition pos = unbreakableBlocks.get(i); + if (pos.x == x && pos.y == y && pos.z == z && pos.wrld.provider.dimensionId == w.provider.dimensionId) + return true; + } + return false; } - + /** * Sends the packet to the server, that notifies the server about GUI button pressed. This can be actually used for any GUI, not only in world, but why would you like to do it? * @param buttonID - the ID on the button in the code. Can be get via yourGuiButton.id @@ -899,11 +938,17 @@ public class MiscUtils { * @param presser - the player, who presses the button. Usually Minecraft.getMinecraft().thePlayer but sometimes you may want to send packets of other SMP players(maybe?) */ @SideOnly(Side.CLIENT) - public static void handleButtonPress(int buttonID, Class parentClass, Class buttonClass, EntityPlayer presser, int bX, int bY, int bZ) - { - handleButtonPress(buttonID, parentClass, buttonClass, presser, bX, bY, bZ, "||data:no data"); + public static void handleButtonPress( + int buttonID, + Class parentClass, + Class buttonClass, + EntityPlayer presser, + int bX, + int bY, + int bZ) { + handleButtonPress(buttonID, parentClass, buttonClass, presser, bX, bY, bZ, "||data:no data"); } - + /** * Sends the packet to the server, that notifies the server about GUI button pressed. This can be actually used for any GUI, not only in world, but why would you like to do it? * @param buttonID - the ID on the button in the code. Can be get via yourGuiButton.id @@ -913,106 +958,100 @@ public class MiscUtils { * @param additionalData - Some additional data, that you might want to carry around. Should be a String, representing the DummyData, otherwise will get added tp the Z coordinate and make it unreadable. */ @SideOnly(Side.CLIENT) - public static void handleButtonPress(int buttonID, Class parentClass, Class buttonClass, EntityPlayer presser, int bX, int bY, int bZ, String additionalData) - { - String dataString = "||mod:DummyCore.guiButton"; - DummyData id = new DummyData("id",buttonID); - DummyData parent = new DummyData("parent",parentClass.getName()); - DummyData button = new DummyData("button",buttonClass.getName()); - DummyData player = new DummyData("player",presser.getCommandSenderName()); - DummyData dx = new DummyData("x",bX); - DummyData dy = new DummyData("y",bY); - DummyData dz = new DummyData("z",bZ); - DataStorage.addDataToString(id); - DataStorage.addDataToString(parent); - DataStorage.addDataToString(button); - DataStorage.addDataToString(player); - DataStorage.addDataToString(dx); - DataStorage.addDataToString(dy); - DataStorage.addDataToString(dz); - String newDataString = DataStorage.getDataString(); - dataString+=newDataString+additionalData; - DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); - DummyPacketHandler.sendToServer(simplePacket); + public static void handleButtonPress( + int buttonID, + Class parentClass, + Class buttonClass, + EntityPlayer presser, + int bX, + int bY, + int bZ, + String additionalData) { + String dataString = "||mod:DummyCore.guiButton"; + DummyData id = new DummyData("id", buttonID); + DummyData parent = new DummyData("parent", parentClass.getName()); + DummyData button = new DummyData("button", buttonClass.getName()); + DummyData player = new DummyData("player", presser.getCommandSenderName()); + DummyData dx = new DummyData("x", bX); + DummyData dy = new DummyData("y", bY); + DummyData dz = new DummyData("z", bZ); + DataStorage.addDataToString(id); + DataStorage.addDataToString(parent); + DataStorage.addDataToString(button); + DataStorage.addDataToString(player); + DataStorage.addDataToString(dx); + DataStorage.addDataToString(dy); + DataStorage.addDataToString(dz); + String newDataString = DataStorage.getDataString(); + dataString += newDataString + additionalData; + DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); + DummyPacketHandler.sendToServer(simplePacket); } - + /** - * Searches for the first block, that matches the given condition at the given coordinates in the given Y range. + * Searches for the first block, that matches the given condition at the given coordinates in the given Y range. * @param w - the WorldObj where we are searching the block at * @param toSearch - the block that we are searching for * @param x - the X coordinate * @param z - the Z coordinate - * @param maxY - max Y value to search. + * @param maxY - max Y value to search. * @param minY - min Y value to search * @param metadata - the metadata of the block to search. can be -1 or OreDectionary.WILDCARD_VALUE to ignore metadata * @param shouldHaveAirAbove - should the block that we find have only air blocks above it * @return the actual Y coordinate, or -1 if no blocks were found. */ - public static int search_firstBlock(World w,Block toSearch,int x, int z, int maxY, int minY, int metadata, boolean shouldHaveAirAbove) - { - int y = maxY; - while(y > minY) - { - Block b = w.getBlock(x, y, z); - int meta = w.getBlockMetadata(x, y, z); - if(b != null && b != Blocks.air) - { - if(b == toSearch && (metadata == -1 || metadata == OreDictionary.WILDCARD_VALUE || metadata == meta)) - { - return y; - }else if(shouldHaveAirAbove) - { - return -1; - } - } - --y; - } - return -1; + public static int search_firstBlock( + World w, Block toSearch, int x, int z, int maxY, int minY, int metadata, boolean shouldHaveAirAbove) { + int y = maxY; + while (y > minY) { + Block b = w.getBlock(x, y, z); + int meta = w.getBlockMetadata(x, y, z); + if (b != null && b != Blocks.air) { + if (b == toSearch && (metadata == -1 || metadata == OreDictionary.WILDCARD_VALUE || metadata == meta)) { + return y; + } else if (shouldHaveAirAbove) { + return -1; + } + } + --y; + } + return -1; } - - public static void openGui(World w, int x, int y, int z, EntityPlayer player, int guiID) - { - player.openGui(CoreInitialiser.instance, guiID, w, x, y, z); + + public static void openGui(World w, int x, int y, int z, EntityPlayer player, int guiID) { + player.openGui(CoreInitialiser.instance, guiID, w, x, y, z); } - - public static void setShaders(int shaderID) - { - if(shaderID >= defaultShaders.length)shaderID = defaultShaders.length-1; - if(shaderID < 0)setShaders(null);else CoreInitialiser.proxy.initShaders(defaultShaders[shaderID]); + + public static void setShaders(int shaderID) { + if (shaderID >= defaultShaders.length) shaderID = defaultShaders.length - 1; + if (shaderID < 0) setShaders(null); + else CoreInitialiser.proxy.initShaders(defaultShaders[shaderID]); } - - public static void setShaders(ResourceLocation shaders) - { - CoreInitialiser.proxy.initShaders(shaders); + + public static void setShaders(ResourceLocation shaders) { + CoreInitialiser.proxy.initShaders(shaders); } - - public static boolean classExists(String className) - { - try - { - return Class.forName(className) != null; - } - catch(ClassNotFoundException cnfe) - { - return false; - } + + public static boolean classExists(String className) { + try { + return Class.forName(className) != null; + } catch (ClassNotFoundException cnfe) { + return false; + } + } + + public static EntityLivingBase getClosestEntity(List mobs, double x, double y, double z) { + double minDistance = Double.MAX_VALUE; + EntityLivingBase retEntity = null; + + for (EntityLivingBase elb : mobs) { + double distance = elb.getDistance(x, y, z); + if (distance < minDistance) { + retEntity = elb; + minDistance = distance; + } + } + + return retEntity; } - - public static EntityLivingBase getClosestEntity(List mobs, double x, double y, double z) - { - double minDistance = Double.MAX_VALUE; - EntityLivingBase retEntity = null; - - for(EntityLivingBase elb : mobs) - { - double distance = elb.getDistance(x, y, z); - if(distance < minDistance) - { - retEntity = elb; - minDistance = distance; - } - } - - return retEntity; - } } diff --git a/src/main/java/DummyCore/Utils/ModVersionChecker.java b/src/main/java/DummyCore/Utils/ModVersionChecker.java index 69de497..8c650ac 100644 --- a/src/main/java/DummyCore/Utils/ModVersionChecker.java +++ b/src/main/java/DummyCore/Utils/ModVersionChecker.java @@ -1,5 +1,8 @@ package DummyCore.Utils; +import DummyCore.Core.Core; +import DummyCore.Core.CoreInitialiser; +import DummyCore.Core.DCMod; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -10,196 +13,170 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Hashtable; import java.util.regex.PatternSyntaxException; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; -import DummyCore.Core.Core; -import DummyCore.Core.CoreInitialiser; -import DummyCore.Core.DCMod; public class ModVersionChecker { - - public static final ArrayList vCheckRequesters = new ArrayList(); - public static final Hashtable latestVersions = new Hashtable(); - public static final Hashtable modsURIs = new Hashtable(); - - public static void addRequest(Class mod, String uri) - { - if(Core.isModRegistered(mod)) - { - DCMod dcmod = Core.getModFromClass(mod); - vCheckRequesters.add(dcmod); - modsURIs.put(dcmod, uri); - }else - Notifier.notifyError("[DCVersionChecker]Catched an attempt to add a version check request for a non registered mod!"); - } - - public static void dispatchModChecks() - { - for(int i = 0; i < vCheckRequesters.size(); ++i) - requestModVCheck(vCheckRequesters.get(i)); - } - - public static void requestModVCheck(DCMod mod) - { - if(vCheckRequesters.contains(mod)) - new ThreadURICheck(mod,modsURIs.get(mod)).start(); - } - - public static void respondToURICheckSuccess(DCMod mod) - { - String currentVersion = mod.version; - String checkedVersion = latestVersions.get(mod); - if(isVersionDMValid(checkedVersion) && isVersionDMValid(currentVersion)) - { - String[] versions = checkedVersion.split("."); - String[] cVersions = mod.version.split("."); - for(int i = 0; i < versions.length; ++i) - versions[i] = removeButNumbers(versions[i]); - - for(int i = 0; i < cVersions.length; ++i) - cVersions[i] = removeButNumbers(cVersions[i]); - - for(int i = 0; i < 4; ++i) - { - int ii = i; - if(ii == 0) - ii = 2; - else - if(ii == 2) - ii = 0; - String pcurrentVersion = cVersions[ii]; - String pcheckedVersion = versions[ii]; - int current = Integer.parseInt(pcurrentVersion); - int latest = Integer.parseInt(pcheckedVersion); - if(current < latest) - { - tryNotifyDMOutdatedMod(mod,checkedVersion,ii); - break; - } - } - }else - { - String pcurrentVersion = removeButNumbers(currentVersion); - String pcheckedVersion = removeButNumbers(checkedVersion); - int current = Integer.parseInt(pcurrentVersion); - int latest = Integer.parseInt(pcheckedVersion); - if(current < latest) - tryNotifySimpleOutdatedMod(mod,checkedVersion); - } - vCheckRequesters.remove(mod); - latestVersions.remove(mod); - modsURIs.remove(mod); - } - - public static void tryNotifyDMOutdatedMod(DCMod mod, String latest, int step) - { - EntityPlayer player = CoreInitialiser.proxy.getClientPlayer(); - if(player != null) - { - String steppedString = ""; - switch(step) - { - case 0: - { - steppedString = String.format("%s is horribly outdated(Your version is %s, latest is %s) has bugs and no longer supported! Update as soon as possible!", mod.ufName, mod.version, latest); - break; - } - case 1: - { - steppedString = String.format("%s is outdated(Your version is %s, latest is %s)! Consider updating!", mod.ufName, mod.version, latest); - break; - } - case 2: - { - steppedString = String.format("%s is available for another version of the game(Your version is %s, latest is %s)!", mod.ufName, mod.version, latest); - break; - } - case 3: - { - steppedString = String.format("%s has a new version available(Your version is %s, latest is %s)!", mod.ufName, mod.version, latest); - break; - } - } - player.addChatMessage(new ChatComponentText(steppedString).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); - } - } - - - public static void tryNotifySimpleOutdatedMod(DCMod mod, String latest) - { - EntityPlayer player = CoreInitialiser.proxy.getClientPlayer(); - if(player != null) - player.addChatMessage(new ChatComponentText(String.format("%s is outdated(Your version is %s, latest is %s)! Consider updating!", mod.ufName, mod.version, latest)).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); - } - - public static boolean isVersionDMValid(String version) - { - try{ - return version.split(".").length >= 4; - }catch(PatternSyntaxException pse) - { - pse.printStackTrace(); - Notifier.notifyError("[DCVersionChecker]"+version+" is not a valid DM version"); - } - return false; - } - - public static String removeButNumbers(String s) - { - String result = ""; - - char[] chars = s.toCharArray(); - for(char c : chars) - if(Character.isDigit(c)) - result += c; - - return result; - } - - public static class ThreadURICheck extends Thread - { - public String uristr; - public DCMod mod; - public ThreadURICheck(DCMod mod, String uri) - { - super("[DCVercionCheckDaemon]For mod: "+mod.ufName); - this.setDaemon(true); //<- if this thread is forever asleep due to network issues - this.setPriority(MIN_PRIORITY); //<- we do not need to rush - this.mod = mod; - this.uristr = uri; - } - - @Override - public void run() - { - try - { - URI uri = new URI(uristr); - InputStream is = uri.toURL().openStream(); - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - String version = br.readLine(); - ModVersionChecker.latestVersions.put(mod, version); - is.close(); - ModVersionChecker.respondToURICheckSuccess(mod); - interrupt(); - }catch(URISyntaxException urise){ - urise.printStackTrace(); - Notifier.notifyErrorCustomMod("[DCVercionCheckDaemon]"+mod.ufName, uristr+" is not a valid URI!"); - interrupt(); - }catch (MalformedURLException murle){ - murle.printStackTrace(); - Notifier.notifyErrorCustomMod("[DCVercionCheckDaemon]"+mod.ufName, uristr+" is not a valid URL!"); - interrupt(); - }catch (IOException ioe){ - ioe.printStackTrace(); - Notifier.notifyErrorCustomMod("[DCVercionCheckDaemon]"+mod.ufName, "Couldn't read file at "+uristr); - interrupt(); - } - } - } + public static final ArrayList vCheckRequesters = new ArrayList(); + public static final Hashtable latestVersions = new Hashtable(); + public static final Hashtable modsURIs = new Hashtable(); + + public static void addRequest(Class mod, String uri) { + if (Core.isModRegistered(mod)) { + DCMod dcmod = Core.getModFromClass(mod); + vCheckRequesters.add(dcmod); + modsURIs.put(dcmod, uri); + } else + Notifier.notifyError( + "[DCVersionChecker]Catched an attempt to add a version check request for a non registered mod!"); + } + + public static void dispatchModChecks() { + for (int i = 0; i < vCheckRequesters.size(); ++i) requestModVCheck(vCheckRequesters.get(i)); + } + + public static void requestModVCheck(DCMod mod) { + if (vCheckRequesters.contains(mod)) new ThreadURICheck(mod, modsURIs.get(mod)).start(); + } + + public static void respondToURICheckSuccess(DCMod mod) { + String currentVersion = mod.version; + String checkedVersion = latestVersions.get(mod); + if (isVersionDMValid(checkedVersion) && isVersionDMValid(currentVersion)) { + String[] versions = checkedVersion.split("."); + String[] cVersions = mod.version.split("."); + for (int i = 0; i < versions.length; ++i) versions[i] = removeButNumbers(versions[i]); + + for (int i = 0; i < cVersions.length; ++i) cVersions[i] = removeButNumbers(cVersions[i]); + + for (int i = 0; i < 4; ++i) { + int ii = i; + if (ii == 0) ii = 2; + else if (ii == 2) ii = 0; + String pcurrentVersion = cVersions[ii]; + String pcheckedVersion = versions[ii]; + int current = Integer.parseInt(pcurrentVersion); + int latest = Integer.parseInt(pcheckedVersion); + if (current < latest) { + tryNotifyDMOutdatedMod(mod, checkedVersion, ii); + break; + } + } + } else { + String pcurrentVersion = removeButNumbers(currentVersion); + String pcheckedVersion = removeButNumbers(checkedVersion); + int current = Integer.parseInt(pcurrentVersion); + int latest = Integer.parseInt(pcheckedVersion); + if (current < latest) tryNotifySimpleOutdatedMod(mod, checkedVersion); + } + vCheckRequesters.remove(mod); + latestVersions.remove(mod); + modsURIs.remove(mod); + } + + public static void tryNotifyDMOutdatedMod(DCMod mod, String latest, int step) { + EntityPlayer player = CoreInitialiser.proxy.getClientPlayer(); + if (player != null) { + String steppedString = ""; + switch (step) { + case 0: { + steppedString = String.format( + "%s is horribly outdated(Your version is %s, latest is %s) has bugs and no longer supported! Update as soon as possible!", + mod.ufName, mod.version, latest); + break; + } + case 1: { + steppedString = String.format( + "%s is outdated(Your version is %s, latest is %s)! Consider updating!", + mod.ufName, mod.version, latest); + break; + } + case 2: { + steppedString = String.format( + "%s is available for another version of the game(Your version is %s, latest is %s)!", + mod.ufName, mod.version, latest); + break; + } + case 3: { + steppedString = String.format( + "%s has a new version available(Your version is %s, latest is %s)!", + mod.ufName, mod.version, latest); + break; + } + } + player.addChatMessage(new ChatComponentText(steppedString) + .setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); + } + } + + public static void tryNotifySimpleOutdatedMod(DCMod mod, String latest) { + EntityPlayer player = CoreInitialiser.proxy.getClientPlayer(); + if (player != null) + player.addChatMessage(new ChatComponentText(String.format( + "%s is outdated(Your version is %s, latest is %s)! Consider updating!", + mod.ufName, mod.version, latest)) + .setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); + } + + public static boolean isVersionDMValid(String version) { + try { + return version.split(".").length >= 4; + } catch (PatternSyntaxException pse) { + pse.printStackTrace(); + Notifier.notifyError("[DCVersionChecker]" + version + " is not a valid DM version"); + } + return false; + } + + public static String removeButNumbers(String s) { + String result = ""; + + char[] chars = s.toCharArray(); + for (char c : chars) if (Character.isDigit(c)) result += c; + + return result; + } + + public static class ThreadURICheck extends Thread { + public String uristr; + public DCMod mod; + + public ThreadURICheck(DCMod mod, String uri) { + super("[DCVercionCheckDaemon]For mod: " + mod.ufName); + this.setDaemon(true); // <- if this thread is forever asleep due to network issues + this.setPriority(MIN_PRIORITY); // <- we do not need to rush + this.mod = mod; + this.uristr = uri; + } + + @Override + public void run() { + try { + URI uri = new URI(uristr); + InputStream is = uri.toURL().openStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String version = br.readLine(); + ModVersionChecker.latestVersions.put(mod, version); + is.close(); + ModVersionChecker.respondToURICheckSuccess(mod); + interrupt(); + } catch (URISyntaxException urise) { + urise.printStackTrace(); + Notifier.notifyErrorCustomMod("[DCVercionCheckDaemon]" + mod.ufName, uristr + " is not a valid URI!"); + interrupt(); + } catch (MalformedURLException murle) { + murle.printStackTrace(); + Notifier.notifyErrorCustomMod("[DCVercionCheckDaemon]" + mod.ufName, uristr + " is not a valid URL!"); + interrupt(); + } catch (IOException ioe) { + ioe.printStackTrace(); + Notifier.notifyErrorCustomMod("[DCVercionCheckDaemon]" + mod.ufName, "Couldn't read file at " + uristr); + interrupt(); + } + } + } } diff --git a/src/main/java/DummyCore/Utils/NetProxy_Client.java b/src/main/java/DummyCore/Utils/NetProxy_Client.java index 30e4a58..0eb7384 100644 --- a/src/main/java/DummyCore/Utils/NetProxy_Client.java +++ b/src/main/java/DummyCore/Utils/NetProxy_Client.java @@ -1,11 +1,19 @@ package DummyCore.Utils; +import DummyCore.Client.GuiMainMenuOld; +import DummyCore.Client.GuiMainMenuVanilla; +import DummyCore.Client.MainMenuRegistry; +import DummyCore.Core.CoreInitialiser; +import DummyCore.CreativeTabs.CreativePageBlocks; +import DummyCore.CreativeTabs.CreativePageItems; +import com.google.common.collect.SetMultimap; +import com.google.common.collect.Table; +import cpw.mods.fml.client.FMLClientHandler; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.Hashtable; import java.util.Random; import java.util.Set; - import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.renderer.EntityRenderer; @@ -19,211 +27,160 @@ import net.minecraft.network.INetHandler; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; - import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.Logger; -import DummyCore.Client.GuiMainMenuOld; -import DummyCore.Client.GuiMainMenuVanilla; -import DummyCore.Client.MainMenuRegistry; -import DummyCore.Core.CoreInitialiser; -import DummyCore.CreativeTabs.CreativePageBlocks; -import DummyCore.CreativeTabs.CreativePageItems; +public class NetProxy_Client extends NetProxy_Server { -import com.google.common.collect.SetMultimap; -import com.google.common.collect.Table; + public static final Hashtable shaders = new Hashtable(); -import cpw.mods.fml.client.FMLClientHandler; + @Override + public EntityPlayer getPlayerOnSide(INetHandler handler) { + if (handler instanceof NetHandlerPlayClient) { + return Minecraft.getMinecraft().thePlayer; + } + return null; + } -public class NetProxy_Client extends NetProxy_Server{ - - public static final Hashtable shaders = new Hashtable(); + public EntityPlayer getClientPlayer() { + return Minecraft.getMinecraft().thePlayer; + } - @Override - public EntityPlayer getPlayerOnSide(INetHandler handler) - { - if(handler instanceof NetHandlerPlayClient) - { - return Minecraft.getMinecraft().thePlayer; - } - return null; - } - - public EntityPlayer getClientPlayer() - { - return Minecraft.getMinecraft().thePlayer; - } - - @Override - public void registerInfo() - { - MainMenuRegistry.initMenuConfigs(); - MainMenuRegistry.registerNewGui(GuiMainMenuVanilla.class,"[DC] Vanilla","Just a simple vanilla MC gui."); - MainMenuRegistry.registerNewGui(GuiMainMenuOld.class,"[DC] Old Vanilla","An old MC gui."); - TimerHijack.initMCTimer(); - } - - @Override - public void registerInit() - { - if(CoreInitialiser.cfg.removeMissingTexturesErrors) - { - try - { - Class textureMap = TextureMap.class; - Field logger = textureMap.getDeclaredFields()[0]; - boolean canAccess = logger.isAccessible(); - if(!canAccess) - logger.setAccessible(true); - Logger lg = Logger.class.cast(logger.get(null)); - lg.setLevel(Level.OFF); - - if(!canAccess) - logger.setAccessible(false); - } - catch(Exception e) - { - Notifier.notifyError("DummyCore was sadly unable to remove missing texture errors :("); - } - } - MainMenuRegistry.registerMenuConfigs(); - } - - @Override - public Object getClientGuiElement(int ID, EntityPlayer player, World world, - int x, int y, int z) { - try - { - Class guiClass = Class.forName(GuiContainerLibrary.guis.get(ID)); - Constructor constrctr_gui = guiClass.getConstructor(Container.class, TileEntity.class); - Class containerClass = Class.forName(GuiContainerLibrary.containers.get(ID)); - Constructor constrctr = containerClass.getConstructor(InventoryPlayer.class, TileEntity.class); - Object obj = constrctr.newInstance(player.inventory,world.getTileEntity(x, y, z)); - return constrctr_gui.newInstance(obj,world.getTileEntity(x, y, z)); - }catch(Exception e) - { - Notifier.notifySimple("Unable to open GUI for ID "+ID); - e.printStackTrace(); - return null; - } - } - - @SuppressWarnings("unchecked") - @Override - public void removeMissingTextureErrors() - { - if(CoreInitialiser.cfg.removeMissingTexturesErrors) - { - try - { - Class fmlClientHandler = FMLClientHandler.class; - Field missingTextures = fmlClientHandler.getDeclaredField("missingTextures"); - Field badTextureDomains = fmlClientHandler.getDeclaredField("badTextureDomains"); - Field brokenTextures = fmlClientHandler.getDeclaredField("brokenTextures"); - boolean canAccess = missingTextures.isAccessible(); - if(!canAccess) - missingTextures.setAccessible(true); - - SetMultimap smmp = SetMultimap.class.cast(missingTextures.get(FMLClientHandler.instance())); - smmp.clear(); - - if(!canAccess) - missingTextures.setAccessible(false); - - canAccess = badTextureDomains.isAccessible(); - if(!canAccess) - badTextureDomains.setAccessible(true); - - Set set = Set.class.cast(badTextureDomains.get(FMLClientHandler.instance())); - set.clear(); - - if(!canAccess) - badTextureDomains.setAccessible(false); - - canAccess = brokenTextures.isAccessible(); - if(!canAccess) - brokenTextures.setAccessible(true); - - Table> table = Table.class.cast(brokenTextures.get(FMLClientHandler.instance())); - table.clear(); - - if(!canAccess) - brokenTextures.setAccessible(false); - - Notifier.notifyWarn("DummyCore has removed all possible texture errors the FML could output to the console!"); - } - catch(Exception e) - { - Notifier.notifyError("DummyCore was sadly unable to remove missing texture errors :("); - e.printStackTrace(); - } - } - } - - @Override - public void initShaders(ResourceLocation rLoc) - { - Minecraft mc = Minecraft.getMinecraft(); - EntityRenderer er = mc.entityRenderer; - try - { - if(rLoc == null) - { - er.deactivateShader(); - }else - { - er.theShaderGroup = new ShaderGroup(mc.getTextureManager(), mc.getResourceManager(), mc.getFramebuffer(), rLoc); - er.theShaderGroup.createBindFramebuffers(mc.displayWidth, mc.displayHeight); - } - }catch(Exception e) - { - return; - } - } - - @Override - public void choseDisplayStack(CreativePageBlocks blocks) - { - World w = Minecraft.getMinecraft().theWorld; - if(w.isRemote && w.getWorldTime() % 60 == 0) - { - blocks.delayTime = 0; - blocks.blockList = blocks.initialiseBlocksList(); - if(blocks.blockList != null && !blocks.blockList.isEmpty()) - { - Random rand; - if(DummyConfig.shouldChangeImage) - rand = new Random(w.getWorldTime()); - else - rand = new Random(0); - int random = rand.nextInt(blocks.blockList.size()); - ItemStack itm = blocks.blockList.get(random); - if(itm != null && itm.getItem() != null) - blocks.displayStack = itm; - } - } - } - - @Override - public void choseDisplayStack(CreativePageItems items) - { - World w = Minecraft.getMinecraft().theWorld; - if(w.isRemote && w.getWorldTime() % 60 == 0) - { - items.delayTime = 0; - items.itemList = items.initialiseItemsList(); - if(items.itemList != null && !items.itemList.isEmpty()) - { - Random rand; - if(DummyConfig.shouldChangeImage) - rand = new Random(w.getWorldTime()); - else - rand = new Random(0); - int random = rand.nextInt(items.itemList.size()); - ItemStack itm = items.itemList.get(random); - if(itm != null && itm.getItem() != null) - items.displayStack = itm; - } - } - } + @Override + public void registerInfo() { + MainMenuRegistry.initMenuConfigs(); + MainMenuRegistry.registerNewGui(GuiMainMenuVanilla.class, "[DC] Vanilla", "Just a simple vanilla MC gui."); + MainMenuRegistry.registerNewGui(GuiMainMenuOld.class, "[DC] Old Vanilla", "An old MC gui."); + TimerHijack.initMCTimer(); + } + + @Override + public void registerInit() { + if (CoreInitialiser.cfg.removeMissingTexturesErrors) { + try { + Class textureMap = TextureMap.class; + Field logger = textureMap.getDeclaredFields()[0]; + boolean canAccess = logger.isAccessible(); + if (!canAccess) logger.setAccessible(true); + Logger lg = Logger.class.cast(logger.get(null)); + lg.setLevel(Level.OFF); + + if (!canAccess) logger.setAccessible(false); + } catch (Exception e) { + Notifier.notifyError("DummyCore was sadly unable to remove missing texture errors :("); + } + } + MainMenuRegistry.registerMenuConfigs(); + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + try { + Class guiClass = Class.forName(GuiContainerLibrary.guis.get(ID)); + Constructor constrctr_gui = guiClass.getConstructor(Container.class, TileEntity.class); + Class containerClass = Class.forName(GuiContainerLibrary.containers.get(ID)); + Constructor constrctr = containerClass.getConstructor(InventoryPlayer.class, TileEntity.class); + Object obj = constrctr.newInstance(player.inventory, world.getTileEntity(x, y, z)); + return constrctr_gui.newInstance(obj, world.getTileEntity(x, y, z)); + } catch (Exception e) { + Notifier.notifySimple("Unable to open GUI for ID " + ID); + e.printStackTrace(); + return null; + } + } + + @SuppressWarnings("unchecked") + @Override + public void removeMissingTextureErrors() { + if (CoreInitialiser.cfg.removeMissingTexturesErrors) { + try { + Class fmlClientHandler = FMLClientHandler.class; + Field missingTextures = fmlClientHandler.getDeclaredField("missingTextures"); + Field badTextureDomains = fmlClientHandler.getDeclaredField("badTextureDomains"); + Field brokenTextures = fmlClientHandler.getDeclaredField("brokenTextures"); + boolean canAccess = missingTextures.isAccessible(); + if (!canAccess) missingTextures.setAccessible(true); + + SetMultimap smmp = + SetMultimap.class.cast(missingTextures.get(FMLClientHandler.instance())); + smmp.clear(); + + if (!canAccess) missingTextures.setAccessible(false); + + canAccess = badTextureDomains.isAccessible(); + if (!canAccess) badTextureDomains.setAccessible(true); + + Set set = Set.class.cast(badTextureDomains.get(FMLClientHandler.instance())); + set.clear(); + + if (!canAccess) badTextureDomains.setAccessible(false); + + canAccess = brokenTextures.isAccessible(); + if (!canAccess) brokenTextures.setAccessible(true); + + Table> table = + Table.class.cast(brokenTextures.get(FMLClientHandler.instance())); + table.clear(); + + if (!canAccess) brokenTextures.setAccessible(false); + + Notifier.notifyWarn( + "DummyCore has removed all possible texture errors the FML could output to the console!"); + } catch (Exception e) { + Notifier.notifyError("DummyCore was sadly unable to remove missing texture errors :("); + e.printStackTrace(); + } + } + } + + @Override + public void initShaders(ResourceLocation rLoc) { + Minecraft mc = Minecraft.getMinecraft(); + EntityRenderer er = mc.entityRenderer; + try { + if (rLoc == null) { + er.deactivateShader(); + } else { + er.theShaderGroup = + new ShaderGroup(mc.getTextureManager(), mc.getResourceManager(), mc.getFramebuffer(), rLoc); + er.theShaderGroup.createBindFramebuffers(mc.displayWidth, mc.displayHeight); + } + } catch (Exception e) { + return; + } + } + + @Override + public void choseDisplayStack(CreativePageBlocks blocks) { + World w = Minecraft.getMinecraft().theWorld; + if (w.isRemote && w.getWorldTime() % 60 == 0) { + blocks.delayTime = 0; + blocks.blockList = blocks.initialiseBlocksList(); + if (blocks.blockList != null && !blocks.blockList.isEmpty()) { + Random rand; + if (DummyConfig.shouldChangeImage) rand = new Random(w.getWorldTime()); + else rand = new Random(0); + int random = rand.nextInt(blocks.blockList.size()); + ItemStack itm = blocks.blockList.get(random); + if (itm != null && itm.getItem() != null) blocks.displayStack = itm; + } + } + } + + @Override + public void choseDisplayStack(CreativePageItems items) { + World w = Minecraft.getMinecraft().theWorld; + if (w.isRemote && w.getWorldTime() % 60 == 0) { + items.delayTime = 0; + items.itemList = items.initialiseItemsList(); + if (items.itemList != null && !items.itemList.isEmpty()) { + Random rand; + if (DummyConfig.shouldChangeImage) rand = new Random(w.getWorldTime()); + else rand = new Random(0); + int random = rand.nextInt(items.itemList.size()); + ItemStack itm = items.itemList.get(random); + if (itm != null && itm.getItem() != null) items.displayStack = itm; + } + } + } } diff --git a/src/main/java/DummyCore/Utils/NetProxy_Server.java b/src/main/java/DummyCore/Utils/NetProxy_Server.java index a832944..79ddc5b 100644 --- a/src/main/java/DummyCore/Utils/NetProxy_Server.java +++ b/src/main/java/DummyCore/Utils/NetProxy_Server.java @@ -1,10 +1,9 @@ package DummyCore.Utils; -import java.lang.reflect.Constructor; - import DummyCore.CreativeTabs.CreativePageBlocks; import DummyCore.CreativeTabs.CreativePageItems; import cpw.mods.fml.common.network.IGuiHandler; +import java.lang.reflect.Constructor; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.network.INetHandler; @@ -13,73 +12,47 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -public class NetProxy_Server implements IGuiHandler{ - - public EntityPlayer getPlayerOnSide(INetHandler handler) - { - if(handler instanceof NetHandlerPlayServer) - { - return ((NetHandlerPlayServer)handler).playerEntity; - } - return null; - } - - public EntityPlayer getClientPlayer() - { - return null; - } - - public void registerInfo() - { - - } - - public void registerInit() - { - - } - - public void removeMissingTextureErrors() - { - - } +public class NetProxy_Server implements IGuiHandler { - @Override - public Object getServerGuiElement(int ID, EntityPlayer player, World world,int x, int y, int z) { - try - { - Class containerClass = Class.forName(GuiContainerLibrary.containers.get(ID)); - Constructor constrctr = containerClass.getConstructor(InventoryPlayer.class, TileEntity.class); - return constrctr.newInstance(player.inventory,world.getTileEntity(x, y, z)); - }catch(Exception e) - { - Notifier.notifySimple("Unable to open Container for ID "+ID); - e.printStackTrace(); - return null; - } + public EntityPlayer getPlayerOnSide(INetHandler handler) { + if (handler instanceof NetHandlerPlayServer) { + return ((NetHandlerPlayServer) handler).playerEntity; + } + return null; + } - } + public EntityPlayer getClientPlayer() { + return null; + } - @Override - public Object getClientGuiElement(int ID, EntityPlayer player, World world, - int x, int y, int z) { + public void registerInfo() {} - return null; - } - - public void initShaders(ResourceLocation rLoc) - { - - } - - public void choseDisplayStack(CreativePageBlocks blocks) - { - - } - - public void choseDisplayStack(CreativePageItems items) - { - - } + public void registerInit() {} + public void removeMissingTextureErrors() {} + + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + try { + Class containerClass = Class.forName(GuiContainerLibrary.containers.get(ID)); + Constructor constrctr = containerClass.getConstructor(InventoryPlayer.class, TileEntity.class); + return constrctr.newInstance(player.inventory, world.getTileEntity(x, y, z)); + } catch (Exception e) { + Notifier.notifySimple("Unable to open Container for ID " + ID); + e.printStackTrace(); + return null; + } + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + + return null; + } + + public void initShaders(ResourceLocation rLoc) {} + + public void choseDisplayStack(CreativePageBlocks blocks) {} + + public void choseDisplayStack(CreativePageItems items) {} } diff --git a/src/main/java/DummyCore/Utils/Notifier.java b/src/main/java/DummyCore/Utils/Notifier.java index 9fdd7d7..e2bbbf2 100644 --- a/src/main/java/DummyCore/Utils/Notifier.java +++ b/src/main/java/DummyCore/Utils/Notifier.java @@ -5,117 +5,97 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Notifier { - - //======================================String Beginning Indexes===============================================// - public static final String info = "[INFO]"; - public static final String warning = "[WARNING]"; - public static final String error = "[ERROR]"; - public static final String severe = "[SEVERE]"; - //======================================String Second Indexes===============================================// - public static final String dev = "[DEV]"; - public static final String debug = "[DEBUG]"; - public static final String stdout = "[STDOUT]"; - //======================================String Ending Indexes===============================================// - public static final String system = "[SYSTEM]"; - public static final String mod = "[DummyCore]"; - - public static final Logger logger = LogManager.getLogger(); - - public static void notify(String... s) - { - notify(Level.TRACE,s); - } - - public static void notify(Level l,String... s) - { - publish(l,buildString("[DCNotifier]",s[1],s[2],s[3])); - } - - public static void notifyDev(String s) - { - notify(Level.DEBUG,"",dev,mod,s); - } - - public static void notifyDevCustomMod(String modname, String s) - { - modname = "["+modname+"]"; - notify(Level.DEBUG,"",dev,modname,s); - } - - public static void notifyDebugCustomMod(String modname, String s) - { - modname = "["+modname+"]"; - notify(Level.DEBUG,"",debug,modname,s); - } - - public static void notifyDebug(String s) - { - notify(Level.DEBUG,"",debug,mod,s); - } - - public static void notifyWarnCustomMod(String modname, String s) - { - modname = "["+modname+"]"; - notify(Level.WARN,"",debug,modname,s); - } - - public static void notifyWarn(String s) - { - notify(Level.WARN,"",debug,mod,s); - } - - public static void notifyErrorCustomMod(String modname, String s) - { - modname = "["+modname+"]"; - notify(Level.ERROR,"",debug,modname,s); - } - - public static void notifyError(String s) - { - notify(Level.ERROR,"",debug,mod,s); - } - - public static void notifyFatalCustomMod(String modname, String s) - { - modname = "["+modname+"]"; - notify(Level.FATAL,"",debug,modname,s); - } - - public static void notifyFatal(String s) - { - notify(Level.FATAL,"",debug,mod,s); - } - - public static void notifySystem(String s) - { - notify(Level.TRACE,"","",system,s); - } - - public static void notifySimple(String s) - { - notify(Level.TRACE,"","",mod,s); - } - - public static void notifyCustomMod(String modname,String s) - { - modname = "["+modname+"]"; - notify(Level.INFO,"","",modname,s); - } - - public static String buildString(String...strings) - { - return strings[0] + " " + strings[1] + " " + strings[2] + " " + strings[3] + " "; - } - - public static void publish(Level l,String s) - { - if(DummyConfig.enableNotifierLogging) - logger.log(l, s); - } - - public static void publish(String s) - { - publish(Level.TRACE,s); - } + // ======================================String Beginning Indexes===============================================// + public static final String info = "[INFO]"; + public static final String warning = "[WARNING]"; + public static final String error = "[ERROR]"; + public static final String severe = "[SEVERE]"; + // ======================================String Second Indexes===============================================// + public static final String dev = "[DEV]"; + public static final String debug = "[DEBUG]"; + public static final String stdout = "[STDOUT]"; + // ======================================String Ending Indexes===============================================// + public static final String system = "[SYSTEM]"; + public static final String mod = "[DummyCore]"; + + public static final Logger logger = LogManager.getLogger(); + + public static void notify(String... s) { + notify(Level.TRACE, s); + } + + public static void notify(Level l, String... s) { + publish(l, buildString("[DCNotifier]", s[1], s[2], s[3])); + } + + public static void notifyDev(String s) { + notify(Level.DEBUG, "", dev, mod, s); + } + + public static void notifyDevCustomMod(String modname, String s) { + modname = "[" + modname + "]"; + notify(Level.DEBUG, "", dev, modname, s); + } + + public static void notifyDebugCustomMod(String modname, String s) { + modname = "[" + modname + "]"; + notify(Level.DEBUG, "", debug, modname, s); + } + + public static void notifyDebug(String s) { + notify(Level.DEBUG, "", debug, mod, s); + } + + public static void notifyWarnCustomMod(String modname, String s) { + modname = "[" + modname + "]"; + notify(Level.WARN, "", debug, modname, s); + } + + public static void notifyWarn(String s) { + notify(Level.WARN, "", debug, mod, s); + } + + public static void notifyErrorCustomMod(String modname, String s) { + modname = "[" + modname + "]"; + notify(Level.ERROR, "", debug, modname, s); + } + + public static void notifyError(String s) { + notify(Level.ERROR, "", debug, mod, s); + } + + public static void notifyFatalCustomMod(String modname, String s) { + modname = "[" + modname + "]"; + notify(Level.FATAL, "", debug, modname, s); + } + + public static void notifyFatal(String s) { + notify(Level.FATAL, "", debug, mod, s); + } + + public static void notifySystem(String s) { + notify(Level.TRACE, "", "", system, s); + } + + public static void notifySimple(String s) { + notify(Level.TRACE, "", "", mod, s); + } + + public static void notifyCustomMod(String modname, String s) { + modname = "[" + modname + "]"; + notify(Level.INFO, "", "", modname, s); + } + + public static String buildString(String... strings) { + return strings[0] + " " + strings[1] + " " + strings[2] + " " + strings[3] + " "; + } + + public static void publish(Level l, String s) { + if (DummyConfig.enableNotifierLogging) logger.log(l, s); + } + + public static void publish(String s) { + publish(Level.TRACE, s); + } } diff --git a/src/main/java/DummyCore/Utils/Pair.java b/src/main/java/DummyCore/Utils/Pair.java index d99fefd..50e51bc 100644 --- a/src/main/java/DummyCore/Utils/Pair.java +++ b/src/main/java/DummyCore/Utils/Pair.java @@ -1,24 +1,20 @@ package DummyCore.Utils; public class Pair { - - public T1 obj1; - public T2 obj2; - - public T1 getFirst() - { - return obj1; - } - - public T2 getSecond() - { - return obj2; - } - - public Pair(T1 o1, T2 o2) - { - obj1 = o1; - obj2 = o2; - } + public T1 obj1; + public T2 obj2; + + public T1 getFirst() { + return obj1; + } + + public T2 getSecond() { + return obj2; + } + + public Pair(T1 o1, T2 o2) { + obj1 = o1; + obj2 = o2; + } } diff --git a/src/main/java/DummyCore/Utils/ReflectionProvider.java b/src/main/java/DummyCore/Utils/ReflectionProvider.java index ac90610..be57b98 100644 --- a/src/main/java/DummyCore/Utils/ReflectionProvider.java +++ b/src/main/java/DummyCore/Utils/ReflectionProvider.java @@ -5,335 +5,273 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflectionProvider { - - public static final ReflectionProvider instance = new ReflectionProvider(); - - private Class workingWith; - private Object accessed; - - private boolean isAccessing; - private boolean hardAccess; - - public boolean setTo(String name, Object setTo) - { - c(); - - try - { - Field f = getField(name); - boolean accessed = f.isAccessible(); - if(!accessed && hardAccess) - f.setAccessible(true); - - f.set(accessed, setTo); - - if(hardAccess) - f.setAccessible(accessed); - - return true; - } - catch(Exception e) - { - return false; - } - } - - public float getFloatFrom(String name) - { - c(); - - try - { - Field f = getField(name); - boolean accessed = f.isAccessible(); - if(!accessed && hardAccess) - f.setAccessible(true); - - float ret = f.getFloat(accessed); - - if(hardAccess) - f.setAccessible(accessed); - - return ret; - } - catch(Exception e) - { - return Float.NaN; - } - } - - public double getDoubleFrom(String name) - { - c(); - - try - { - Field f = getField(name); - boolean accessed = f.isAccessible(); - if(!accessed && hardAccess) - f.setAccessible(true); - - double ret = f.getDouble(accessed); - - if(hardAccess) - f.setAccessible(accessed); - - return ret; - } - catch(Exception e) - { - return Double.NaN; - } - } - - public int getIntFrom(String name) - { - c(); - - try - { - Field f = getField(name); - boolean accessed = f.isAccessible(); - if(!accessed && hardAccess) - f.setAccessible(true); - - int ret = f.getInt(accessed); - - if(hardAccess) - f.setAccessible(accessed); - - return ret; - } - catch(Exception e) - { - return Integer.MIN_VALUE; - } - } - - public boolean getBoolFrom(String name) - { - c(); - - try - { - Field f = getField(name); - boolean accessed = f.isAccessible(); - if(!accessed && hardAccess) - f.setAccessible(true); - - boolean ret = f.getBoolean(accessed); - - if(hardAccess) - f.setAccessible(accessed); - - return ret; - } - catch(Exception e) - { - return false; - } - } - - public Object getFrom(String name) - { - c(); - - try - { - Field f = getField(name); - boolean accessed = f.isAccessible(); - if(!accessed && hardAccess) - f.setAccessible(true); - - Object ret = f.get(accessed); - - if(hardAccess) - f.setAccessible(accessed); - - return ret; - } - catch(Exception e) - { - return null; - } - } - - public Object create(Class[] parParams, Object[] parObj) - { - c(); - - try{ - - Constructor c = getConstructor(parParams); - boolean accessed = c.isAccessible(); - if(!accessed && hardAccess) - c.setAccessible(true); - - Object ret = c.newInstance(parObj); - - if(hardAccess) - c.setAccessible(accessed); - - return ret; - - }catch(Exception e){ - return null; - } - } - - public Object invoke(String name, Class[] parParams, Object[] parObj) - { - c(); - - try{ - - Method m = getMethod(name,parParams); - boolean accessed = m.isAccessible(); - if(!accessed && hardAccess) - m.setAccessible(true); - - Object ret = m.invoke(accessed, parObj); - - if(hardAccess) - m.setAccessible(accessed); - - return ret; - - }catch(Exception e){ - return null; - } - } - - public Constructor getConstructor(Class... params) - { - c(); - - try{ - return workingWith.getConstructor(params); - }catch(Exception e){ - try{ - return workingWith.getDeclaredConstructor(params); - }catch(Exception e1){ - return null; - } - } - } - - public Method getMethod(String name, Class... params) - { - c(); - - try{ - return workingWith.getMethod(name, params); - }catch(Exception e){ - try{ - return workingWith.getDeclaredMethod(name, params); - }catch(Exception e1){ - return null; - } - } - } - - public Field getField(String name) - { - c(); - - try{ - return workingWith.getField(name); - }catch(Exception e){ - try{ - return workingWith.getDeclaredField(name); - }catch(Exception e1){ - return null; - } - } - } - - public Class getSetClass() - { - c(); - - return workingWith; - } - - public boolean setClass(String classPath) - { - c(); - - try - { - workingWith = Class.forName(classPath); - return true; - } - catch(Exception e) - { - return false; - } - } - - public boolean setClass(Object clazz) - { - c(); - workingWith = clazz.getClass(); - accessed = clazz; - - return true; - } - - public void access(Object obj) - { - c(); - - accessed = obj; - } - - private boolean c() - { - if(!isAccessing) - throw new IllegalStateException("Reflection Provider not running!"); - - return isAccessing; - } - - public void start() - { - if(isAccessing) - throw new IllegalStateException("Reflection Provider already running!"); - - isAccessing = true; - } - - public void end() - { - if(!isAccessing) - throw new IllegalStateException("Reflection Provider not running!"); - - isAccessing = false; - workingWith = null; - accessed = null; - hardAccess = false; - } - - public void enableHardAccess(boolean b) - { - c(); - - hardAccess = b; - } - - public Object getCurrentObj() - { - c(); - - return accessed; - } - - public Object setCurrentObj(Object obj) - { - c(); - accessed = obj; - return accessed; - } + public static final ReflectionProvider instance = new ReflectionProvider(); + private Class workingWith; + private Object accessed; + + private boolean isAccessing; + private boolean hardAccess; + + public boolean setTo(String name, Object setTo) { + c(); + + try { + Field f = getField(name); + boolean accessed = f.isAccessible(); + if (!accessed && hardAccess) f.setAccessible(true); + + f.set(accessed, setTo); + + if (hardAccess) f.setAccessible(accessed); + + return true; + } catch (Exception e) { + return false; + } + } + + public float getFloatFrom(String name) { + c(); + + try { + Field f = getField(name); + boolean accessed = f.isAccessible(); + if (!accessed && hardAccess) f.setAccessible(true); + + float ret = f.getFloat(accessed); + + if (hardAccess) f.setAccessible(accessed); + + return ret; + } catch (Exception e) { + return Float.NaN; + } + } + + public double getDoubleFrom(String name) { + c(); + + try { + Field f = getField(name); + boolean accessed = f.isAccessible(); + if (!accessed && hardAccess) f.setAccessible(true); + + double ret = f.getDouble(accessed); + + if (hardAccess) f.setAccessible(accessed); + + return ret; + } catch (Exception e) { + return Double.NaN; + } + } + + public int getIntFrom(String name) { + c(); + + try { + Field f = getField(name); + boolean accessed = f.isAccessible(); + if (!accessed && hardAccess) f.setAccessible(true); + + int ret = f.getInt(accessed); + + if (hardAccess) f.setAccessible(accessed); + + return ret; + } catch (Exception e) { + return Integer.MIN_VALUE; + } + } + + public boolean getBoolFrom(String name) { + c(); + + try { + Field f = getField(name); + boolean accessed = f.isAccessible(); + if (!accessed && hardAccess) f.setAccessible(true); + + boolean ret = f.getBoolean(accessed); + + if (hardAccess) f.setAccessible(accessed); + + return ret; + } catch (Exception e) { + return false; + } + } + + public Object getFrom(String name) { + c(); + + try { + Field f = getField(name); + boolean accessed = f.isAccessible(); + if (!accessed && hardAccess) f.setAccessible(true); + + Object ret = f.get(accessed); + + if (hardAccess) f.setAccessible(accessed); + + return ret; + } catch (Exception e) { + return null; + } + } + + public Object create(Class[] parParams, Object[] parObj) { + c(); + + try { + + Constructor c = getConstructor(parParams); + boolean accessed = c.isAccessible(); + if (!accessed && hardAccess) c.setAccessible(true); + + Object ret = c.newInstance(parObj); + + if (hardAccess) c.setAccessible(accessed); + + return ret; + + } catch (Exception e) { + return null; + } + } + + public Object invoke(String name, Class[] parParams, Object[] parObj) { + c(); + + try { + + Method m = getMethod(name, parParams); + boolean accessed = m.isAccessible(); + if (!accessed && hardAccess) m.setAccessible(true); + + Object ret = m.invoke(accessed, parObj); + + if (hardAccess) m.setAccessible(accessed); + + return ret; + + } catch (Exception e) { + return null; + } + } + + public Constructor getConstructor(Class... params) { + c(); + + try { + return workingWith.getConstructor(params); + } catch (Exception e) { + try { + return workingWith.getDeclaredConstructor(params); + } catch (Exception e1) { + return null; + } + } + } + + public Method getMethod(String name, Class... params) { + c(); + + try { + return workingWith.getMethod(name, params); + } catch (Exception e) { + try { + return workingWith.getDeclaredMethod(name, params); + } catch (Exception e1) { + return null; + } + } + } + + public Field getField(String name) { + c(); + + try { + return workingWith.getField(name); + } catch (Exception e) { + try { + return workingWith.getDeclaredField(name); + } catch (Exception e1) { + return null; + } + } + } + + public Class getSetClass() { + c(); + + return workingWith; + } + + public boolean setClass(String classPath) { + c(); + + try { + workingWith = Class.forName(classPath); + return true; + } catch (Exception e) { + return false; + } + } + + public boolean setClass(Object clazz) { + c(); + + workingWith = clazz.getClass(); + accessed = clazz; + + return true; + } + + public void access(Object obj) { + c(); + + accessed = obj; + } + + private boolean c() { + if (!isAccessing) throw new IllegalStateException("Reflection Provider not running!"); + + return isAccessing; + } + + public void start() { + if (isAccessing) throw new IllegalStateException("Reflection Provider already running!"); + + isAccessing = true; + } + + public void end() { + if (!isAccessing) throw new IllegalStateException("Reflection Provider not running!"); + + isAccessing = false; + workingWith = null; + accessed = null; + hardAccess = false; + } + + public void enableHardAccess(boolean b) { + c(); + + hardAccess = b; + } + + public Object getCurrentObj() { + c(); + + return accessed; + } + + public Object setCurrentObj(Object obj) { + c(); + accessed = obj; + return accessed; + } } diff --git a/src/main/java/DummyCore/Utils/ScheduledServerAction.java b/src/main/java/DummyCore/Utils/ScheduledServerAction.java index ee8b61f..f99dab4 100644 --- a/src/main/java/DummyCore/Utils/ScheduledServerAction.java +++ b/src/main/java/DummyCore/Utils/ScheduledServerAction.java @@ -1,13 +1,11 @@ package DummyCore.Utils; -public abstract class ScheduledServerAction -{ - public int actionTime; - - public ScheduledServerAction(int time) - { - actionTime = time; - } - - public abstract void execute(); +public abstract class ScheduledServerAction { + public int actionTime; + + public ScheduledServerAction(int time) { + actionTime = time; + } + + public abstract void execute(); } diff --git a/src/main/java/DummyCore/Utils/StructureApi.java b/src/main/java/DummyCore/Utils/StructureApi.java index 33e7364..2af2cf8 100644 --- a/src/main/java/DummyCore/Utils/StructureApi.java +++ b/src/main/java/DummyCore/Utils/StructureApi.java @@ -1,10 +1,9 @@ package DummyCore.Utils; +import cpw.mods.fml.common.registry.GameRegistry; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; - -import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagByte; @@ -21,345 +20,283 @@ import net.minecraft.nbt.NBTTagString; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -public class StructureApi -{ - - public static NBTTagCompound createStructureTagIgnoreMetadata(World w,AxisAlignedBB aabb, boolean whitelist, Block... blocks) - { - NBTTagCompound tag = new NBTTagCompound(); - - if(aabb.minX > aabb.maxX) - { - double mX = aabb.minX; - aabb.minX = aabb.maxX; - aabb.maxX = mX; - } - - if(aabb.minY > aabb.maxY) - { - double mY = aabb.minY; - aabb.minY = aabb.maxY; - aabb.maxY = mY; - } - - if(aabb.minZ > aabb.maxZ) - { - double mZ = aabb.minZ; - aabb.minZ = aabb.maxZ; - aabb.maxZ = mZ; - } - - for(int dx = (int) aabb.minX; dx <= aabb.maxX; ++dx) - { - for(int dy = (int) aabb.minY; dy <= aabb.maxY; ++dy) - { - for(int dz = (int) aabb.minZ; dz <= aabb.maxZ; ++dz) - { - Block b = w.getBlock(dx, dy, dz); - if(b != null) - { - boolean include = false; - if(whitelist) - { - for(int i = 0; i < blocks.length; ++i) - { - if(blocks[i].equals(b)) - { - include = true; - break; - } - } - }else - { - include = true; - for(int i = 0; i < blocks.length; ++i) - { - if(blocks[i].equals(b)) - { - include = false; - break; - } - } - } - - if(include) - { - String coords = String.valueOf(dx-aabb.minX-(aabb.maxX-aabb.minX)/2)+"|"+String.valueOf(dy-aabb.minY)+"|"+String.valueOf(dz-aabb.minZ-(aabb.maxZ-aabb.minZ)/2); - if(!tag.hasKey(coords)) - tag.setString(coords, GameRegistry.findUniqueIdentifierFor(b).toString()); - } - } - } - } - } - - return tag; - } - - public static NBTTagCompound createStructureTag(World w,AxisAlignedBB aabb, boolean whitelist, Block... blocks) - { - NBTTagCompound tag = new NBTTagCompound(); - - if(aabb.minX > aabb.maxX) - { - double mX = aabb.minX; - aabb.minX = aabb.maxX; - aabb.maxX = mX; - } - - if(aabb.minY > aabb.maxY) - { - double mY = aabb.minY; - aabb.minY = aabb.maxY; - aabb.maxY = mY; - } - - if(aabb.minZ > aabb.maxZ) - { - double mZ = aabb.minZ; - aabb.minZ = aabb.maxZ; - aabb.maxZ = mZ; - } - - for(int dx = (int) aabb.minX; dx <= aabb.maxX; ++dx) - { - for(int dy = (int) aabb.minY; dy <= aabb.maxY; ++dy) - { - for(int dz = (int) aabb.minZ; dz <= aabb.maxZ; ++dz) - { - Block b = w.getBlock(dx, dy, dz); - if(b != null) - { - boolean include = false; - if(whitelist) - { - for(int i = 0; i < blocks.length; ++i) - { - if(blocks[i].equals(b)) - { - include = true; - break; - } - } - }else - { - include = true; - for(int i = 0; i < blocks.length; ++i) - { - if(blocks[i].equals(b)) - { - include = false; - break; - } - } - } - - if(include) - { - String coords = String.valueOf(dx-aabb.minX-(aabb.maxX-aabb.minX)/2)+"|"+String.valueOf(dy-aabb.minY)+"|"+String.valueOf(dz-aabb.minZ-(aabb.maxZ-aabb.minZ)/2); - if(!tag.hasKey(coords)) - tag.setString(coords, GameRegistry.findUniqueIdentifierFor(b).toString()+"|"+w.getBlockMetadata(dx, dy, dz)); - } - } - } - } - } - - return tag; - } - - @SuppressWarnings("unchecked") - public static void nbtStructureIntoWorld(World w, int x, int y, int z, NBTTagCompound structureTag) - { - Set keySet = structureTag.func_150296_c(); - ArrayList keys = new ArrayList(); - ArrayList>> structure = new ArrayList>>(); - Iterator $i = keySet.iterator(); - while($i.hasNext()) - keys.add($i.next()); - - for(String s : keys) - { - int dx = (int) Double.parseDouble(s.substring(0, s.indexOf('|'))); - int dy = (int) Double.parseDouble(s.substring(s.indexOf('|')+1,s.lastIndexOf('|'))); - int dz = (int) Double.parseDouble(s.substring(s.lastIndexOf('|')+1)); - Coord3D blockCoord = new Coord3D(dx,dy,dz); - String st = structureTag.getString(s); - String bid; - if(st.indexOf('|') != -1) - bid = st.substring(0, st.indexOf('|')); - else - bid = st; - - Block b = GameRegistry.findBlock(bid.substring(0,bid.indexOf(':')), bid.substring(bid.indexOf(':')+1)); - int meta; - if(st.indexOf('|') != -1) - meta = Integer.parseInt(st.substring(st.indexOf('|')+1)); - else - meta = 0; - - Pair blockAndMeta = new Pair(b,meta); - structure.add(new Pair>(blockCoord,blockAndMeta)); - } - - keys.clear(); - keys = null; - - for(Pair> put : structure) - { - Coord3D c = put.getFirst(); - int dx = (int) (c.x+x); - int dy = (int) (c.y+y); - int dz = (int) (c.z+z); - Pair pa = put.getSecond(); - w.setBlock(dx, dy, dz, pa.getFirst(), pa.getSecond(), 2); - } - - structure.clear(); - structure = null; - } +public class StructureApi { - @SuppressWarnings("unchecked") - public static boolean areNBTTagsEqual(NBTTagCompound tag1, NBTTagCompound tag2) - { - if(tag1.hasNoTags() || tag2.hasNoTags()) - return false; - - Set keys = tag1.func_150296_c(); - Iterator $i = keys.iterator(); - - while($i.hasNext()) - { - String key = $i.next(); - NBTBase base1 = tag1.getTag(key); - if(!tag2.hasKey(key)) - return false; - NBTBase base2 = tag2.getTag(key); - if(!compareTagsPrimitive(base1,base2)) - return false; - } - - return true; - } - - public static boolean compareTagsPrimitive(NBTBase base1, NBTBase base2) - { - byte id1 = base1.getId(); - byte id2 = base2.getId(); - - if(id1 != id2) - return false; - - switch(id1) - { - case 0: - { - return true; - } - case 1: - { - NBTTagByte byte1 = (NBTTagByte) base1; - NBTTagByte byte2 = (NBTTagByte) base2; - if(byte1.func_150290_f() != byte2.func_150290_f()) - return false; - - return true; - } - case 2: - { - NBTTagShort short1 = (NBTTagShort) base1; - NBTTagShort short2 = (NBTTagShort) base2; - if(short1.func_150289_e() != short2.func_150289_e()) - return false; - - return true; - } - case 3: - { - NBTTagInt int1 = (NBTTagInt) base1; - NBTTagInt int2 = (NBTTagInt) base2; - if(int1.func_150287_d() != int2.func_150287_d()) - return false; - - return true; - } - case 4: - { - NBTTagLong long1 = (NBTTagLong) base1; - NBTTagLong long2 = (NBTTagLong) base2; - if(long1.func_150291_c() != long2.func_150291_c()) - return false; - - return true; - } - case 5: - { - NBTTagFloat float1 = (NBTTagFloat) base1; - NBTTagFloat float2 = (NBTTagFloat) base2; - if(float1.func_150288_h() != float2.func_150288_h()) - return false; - - return true; - } - case 6: - { - NBTTagDouble double1 = (NBTTagDouble) base1; - NBTTagDouble double2 = (NBTTagDouble) base2; - if(double1.func_150286_g() != double2.func_150286_g()) - return false; - - return true; - } - case 7: - { - NBTTagByteArray byteArray1 = (NBTTagByteArray) base1; - NBTTagByteArray byteArray2 = (NBTTagByteArray) base2; - if(!byteArray1.equals(byteArray2)) - return false; - - return true; - } - case 8: - { - NBTTagString string1 = (NBTTagString) base1; - NBTTagString string2 = (NBTTagString) base2; - if(!string1.equals(string2)) - return false; - - return true; - } - case 9: - { - NBTTagList list1 = (NBTTagList) base1; - NBTTagList list2 = (NBTTagList) base2; - if(!list1.equals(list2)) - return false; - - return true; - } - case 10: - { - NBTTagCompound tag1 = (NBTTagCompound) base1; - NBTTagCompound tag2 = (NBTTagCompound) base2; - if(!tag1.equals(tag2)) - return false; - - return true; - } - case 11: - { - NBTTagIntArray intArray1 = (NBTTagIntArray) base1; - NBTTagIntArray intArray2 = (NBTTagIntArray) base2; - if(!intArray1.equals(intArray2)) - return false; - - return true; - } - default: - { - return true; - } - } - } + public static NBTTagCompound createStructureTagIgnoreMetadata( + World w, AxisAlignedBB aabb, boolean whitelist, Block... blocks) { + NBTTagCompound tag = new NBTTagCompound(); + + if (aabb.minX > aabb.maxX) { + double mX = aabb.minX; + aabb.minX = aabb.maxX; + aabb.maxX = mX; + } + + if (aabb.minY > aabb.maxY) { + double mY = aabb.minY; + aabb.minY = aabb.maxY; + aabb.maxY = mY; + } + + if (aabb.minZ > aabb.maxZ) { + double mZ = aabb.minZ; + aabb.minZ = aabb.maxZ; + aabb.maxZ = mZ; + } + + for (int dx = (int) aabb.minX; dx <= aabb.maxX; ++dx) { + for (int dy = (int) aabb.minY; dy <= aabb.maxY; ++dy) { + for (int dz = (int) aabb.minZ; dz <= aabb.maxZ; ++dz) { + Block b = w.getBlock(dx, dy, dz); + if (b != null) { + boolean include = false; + if (whitelist) { + for (int i = 0; i < blocks.length; ++i) { + if (blocks[i].equals(b)) { + include = true; + break; + } + } + } else { + include = true; + for (int i = 0; i < blocks.length; ++i) { + if (blocks[i].equals(b)) { + include = false; + break; + } + } + } + + if (include) { + String coords = String.valueOf(dx - aabb.minX - (aabb.maxX - aabb.minX) / 2) + "|" + + String.valueOf(dy - aabb.minY) + "|" + + String.valueOf(dz - aabb.minZ - (aabb.maxZ - aabb.minZ) / 2); + if (!tag.hasKey(coords)) + tag.setString( + coords, + GameRegistry.findUniqueIdentifierFor(b).toString()); + } + } + } + } + } + + return tag; + } + + public static NBTTagCompound createStructureTag(World w, AxisAlignedBB aabb, boolean whitelist, Block... blocks) { + NBTTagCompound tag = new NBTTagCompound(); + + if (aabb.minX > aabb.maxX) { + double mX = aabb.minX; + aabb.minX = aabb.maxX; + aabb.maxX = mX; + } + + if (aabb.minY > aabb.maxY) { + double mY = aabb.minY; + aabb.minY = aabb.maxY; + aabb.maxY = mY; + } + + if (aabb.minZ > aabb.maxZ) { + double mZ = aabb.minZ; + aabb.minZ = aabb.maxZ; + aabb.maxZ = mZ; + } + + for (int dx = (int) aabb.minX; dx <= aabb.maxX; ++dx) { + for (int dy = (int) aabb.minY; dy <= aabb.maxY; ++dy) { + for (int dz = (int) aabb.minZ; dz <= aabb.maxZ; ++dz) { + Block b = w.getBlock(dx, dy, dz); + if (b != null) { + boolean include = false; + if (whitelist) { + for (int i = 0; i < blocks.length; ++i) { + if (blocks[i].equals(b)) { + include = true; + break; + } + } + } else { + include = true; + for (int i = 0; i < blocks.length; ++i) { + if (blocks[i].equals(b)) { + include = false; + break; + } + } + } + + if (include) { + String coords = String.valueOf(dx - aabb.minX - (aabb.maxX - aabb.minX) / 2) + "|" + + String.valueOf(dy - aabb.minY) + "|" + + String.valueOf(dz - aabb.minZ - (aabb.maxZ - aabb.minZ) / 2); + if (!tag.hasKey(coords)) + tag.setString( + coords, + GameRegistry.findUniqueIdentifierFor(b).toString() + "|" + + w.getBlockMetadata(dx, dy, dz)); + } + } + } + } + } + + return tag; + } + + @SuppressWarnings("unchecked") + public static void nbtStructureIntoWorld(World w, int x, int y, int z, NBTTagCompound structureTag) { + Set keySet = structureTag.func_150296_c(); + ArrayList keys = new ArrayList(); + ArrayList>> structure = new ArrayList>>(); + Iterator $i = keySet.iterator(); + while ($i.hasNext()) keys.add($i.next()); + + for (String s : keys) { + int dx = (int) Double.parseDouble(s.substring(0, s.indexOf('|'))); + int dy = (int) Double.parseDouble(s.substring(s.indexOf('|') + 1, s.lastIndexOf('|'))); + int dz = (int) Double.parseDouble(s.substring(s.lastIndexOf('|') + 1)); + Coord3D blockCoord = new Coord3D(dx, dy, dz); + String st = structureTag.getString(s); + String bid; + if (st.indexOf('|') != -1) bid = st.substring(0, st.indexOf('|')); + else bid = st; + + Block b = GameRegistry.findBlock(bid.substring(0, bid.indexOf(':')), bid.substring(bid.indexOf(':') + 1)); + int meta; + if (st.indexOf('|') != -1) meta = Integer.parseInt(st.substring(st.indexOf('|') + 1)); + else meta = 0; + + Pair blockAndMeta = new Pair(b, meta); + structure.add(new Pair>(blockCoord, blockAndMeta)); + } + + keys.clear(); + keys = null; + + for (Pair> put : structure) { + Coord3D c = put.getFirst(); + int dx = (int) (c.x + x); + int dy = (int) (c.y + y); + int dz = (int) (c.z + z); + Pair pa = put.getSecond(); + w.setBlock(dx, dy, dz, pa.getFirst(), pa.getSecond(), 2); + } + + structure.clear(); + structure = null; + } + + @SuppressWarnings("unchecked") + public static boolean areNBTTagsEqual(NBTTagCompound tag1, NBTTagCompound tag2) { + if (tag1.hasNoTags() || tag2.hasNoTags()) return false; + + Set keys = tag1.func_150296_c(); + Iterator $i = keys.iterator(); + + while ($i.hasNext()) { + String key = $i.next(); + NBTBase base1 = tag1.getTag(key); + if (!tag2.hasKey(key)) return false; + NBTBase base2 = tag2.getTag(key); + if (!compareTagsPrimitive(base1, base2)) return false; + } + + return true; + } + + public static boolean compareTagsPrimitive(NBTBase base1, NBTBase base2) { + byte id1 = base1.getId(); + byte id2 = base2.getId(); + + if (id1 != id2) return false; + + switch (id1) { + case 0: { + return true; + } + case 1: { + NBTTagByte byte1 = (NBTTagByte) base1; + NBTTagByte byte2 = (NBTTagByte) base2; + if (byte1.func_150290_f() != byte2.func_150290_f()) return false; + + return true; + } + case 2: { + NBTTagShort short1 = (NBTTagShort) base1; + NBTTagShort short2 = (NBTTagShort) base2; + if (short1.func_150289_e() != short2.func_150289_e()) return false; + + return true; + } + case 3: { + NBTTagInt int1 = (NBTTagInt) base1; + NBTTagInt int2 = (NBTTagInt) base2; + if (int1.func_150287_d() != int2.func_150287_d()) return false; + + return true; + } + case 4: { + NBTTagLong long1 = (NBTTagLong) base1; + NBTTagLong long2 = (NBTTagLong) base2; + if (long1.func_150291_c() != long2.func_150291_c()) return false; + + return true; + } + case 5: { + NBTTagFloat float1 = (NBTTagFloat) base1; + NBTTagFloat float2 = (NBTTagFloat) base2; + if (float1.func_150288_h() != float2.func_150288_h()) return false; + + return true; + } + case 6: { + NBTTagDouble double1 = (NBTTagDouble) base1; + NBTTagDouble double2 = (NBTTagDouble) base2; + if (double1.func_150286_g() != double2.func_150286_g()) return false; + + return true; + } + case 7: { + NBTTagByteArray byteArray1 = (NBTTagByteArray) base1; + NBTTagByteArray byteArray2 = (NBTTagByteArray) base2; + if (!byteArray1.equals(byteArray2)) return false; + + return true; + } + case 8: { + NBTTagString string1 = (NBTTagString) base1; + NBTTagString string2 = (NBTTagString) base2; + if (!string1.equals(string2)) return false; + + return true; + } + case 9: { + NBTTagList list1 = (NBTTagList) base1; + NBTTagList list2 = (NBTTagList) base2; + if (!list1.equals(list2)) return false; + + return true; + } + case 10: { + NBTTagCompound tag1 = (NBTTagCompound) base1; + NBTTagCompound tag2 = (NBTTagCompound) base2; + if (!tag1.equals(tag2)) return false; + + return true; + } + case 11: { + NBTTagIntArray intArray1 = (NBTTagIntArray) base1; + NBTTagIntArray intArray2 = (NBTTagIntArray) base2; + if (!intArray1.equals(intArray2)) return false; + + return true; + } + default: { + return true; + } + } + } } - diff --git a/src/main/java/DummyCore/Utils/SyncUtils.java b/src/main/java/DummyCore/Utils/SyncUtils.java index 4d6e233..59e41a3 100644 --- a/src/main/java/DummyCore/Utils/SyncUtils.java +++ b/src/main/java/DummyCore/Utils/SyncUtils.java @@ -4,68 +4,63 @@ import java.util.ArrayList; import java.util.List; public class SyncUtils { - - public static List needsSyncing_Global = new ArrayList(); - public static List needsSyncing_Player = new ArrayList(); - - public static void addRequiresSync(String playerName, String modid, String dataName) - { - String mainSyncString = playerName+"|"+modid+":"+dataName; - if(!needsSyncing_Player.contains(mainSyncString)) - needsSyncing_Player.add(mainSyncString); - } - - public static void addRequiresSync(String modid, String dataName) - { - String mainSyncString = modid+":"+dataName; - if(!needsSyncing_Global.contains(mainSyncString)) - needsSyncing_Global.add(mainSyncString); - } - - public static void makeSync_LotsSmallPackets() - { - for(int i = 0; i < needsSyncing_Global.size(); ++i) - { - String syncID = needsSyncing_Global.get(i); - int indexOfStrip = syncID.indexOf(":"); - if(indexOfStrip != -1) - { - String modid = syncID.substring(0,indexOfStrip); - String dataName = syncID.substring(indexOfStrip+1); - if(MiscUtils.registeredServerWorldData.containsKey(modid+"|"+dataName)) - { - String dataString = "||mod:DummyCore.InfoSync"+"||"+modid+":"+dataName+"||ddata:"+MiscUtils.registeredServerWorldData.get(modid+"|"+dataName); - DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); - DummyPacketHandler.sendToAll(simplePacket); - }else - { - Notifier.notifyCustomMod(modid, "The sync packet for data "+modid+"|"+dataName+" could not be generated - the requested server data does not exist!"); - } - } - } - for(int i = 0; i < needsSyncing_Player.size(); ++i) - { - String syncID = needsSyncing_Player.get(i); - int indexOfStrip = syncID.indexOf(":"); - int indexOfPlayer = syncID.indexOf("|"); - if(indexOfPlayer != -1 && indexOfStrip != -1) - { - String playerName = syncID.substring(0, indexOfPlayer); - String modid = syncID.substring(indexOfPlayer+1,indexOfStrip); - String dataName = syncID.substring(indexOfStrip+1); - if(MiscUtils.registeredServerData.containsKey(playerName+"_"+modid+"|"+dataName)) - { - String dataString = "||mod:DummyCore.PlayerInfoSync"+"||"+"playerName:"+playerName+"||"+modid+ ":" + dataName+"||ddata:"+MiscUtils.registeredServerData.get(playerName+"_"+modid+"|"+dataName); - DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); - DummyPacketHandler.sendToAll(simplePacket); - }else - { - Notifier.notifyCustomMod(modid, "The sync packet for data "+playerName+"_"+modid+ "could not be generated - the requested server data does not exist!"); - } - } - } - needsSyncing_Global.clear(); - needsSyncing_Player.clear(); - } + public static List needsSyncing_Global = new ArrayList(); + public static List needsSyncing_Player = new ArrayList(); + + public static void addRequiresSync(String playerName, String modid, String dataName) { + String mainSyncString = playerName + "|" + modid + ":" + dataName; + if (!needsSyncing_Player.contains(mainSyncString)) needsSyncing_Player.add(mainSyncString); + } + + public static void addRequiresSync(String modid, String dataName) { + String mainSyncString = modid + ":" + dataName; + if (!needsSyncing_Global.contains(mainSyncString)) needsSyncing_Global.add(mainSyncString); + } + + public static void makeSync_LotsSmallPackets() { + for (int i = 0; i < needsSyncing_Global.size(); ++i) { + String syncID = needsSyncing_Global.get(i); + int indexOfStrip = syncID.indexOf(":"); + if (indexOfStrip != -1) { + String modid = syncID.substring(0, indexOfStrip); + String dataName = syncID.substring(indexOfStrip + 1); + if (MiscUtils.registeredServerWorldData.containsKey(modid + "|" + dataName)) { + String dataString = "||mod:DummyCore.InfoSync" + "||" + modid + ":" + dataName + "||ddata:" + + MiscUtils.registeredServerWorldData.get(modid + "|" + dataName); + DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); + DummyPacketHandler.sendToAll(simplePacket); + } else { + Notifier.notifyCustomMod( + modid, + "The sync packet for data " + modid + "|" + dataName + + " could not be generated - the requested server data does not exist!"); + } + } + } + for (int i = 0; i < needsSyncing_Player.size(); ++i) { + String syncID = needsSyncing_Player.get(i); + int indexOfStrip = syncID.indexOf(":"); + int indexOfPlayer = syncID.indexOf("|"); + if (indexOfPlayer != -1 && indexOfStrip != -1) { + String playerName = syncID.substring(0, indexOfPlayer); + String modid = syncID.substring(indexOfPlayer + 1, indexOfStrip); + String dataName = syncID.substring(indexOfStrip + 1); + if (MiscUtils.registeredServerData.containsKey(playerName + "_" + modid + "|" + dataName)) { + String dataString = "||mod:DummyCore.PlayerInfoSync" + "||" + "playerName:" + playerName + "||" + + modid + ":" + dataName + "||ddata:" + + MiscUtils.registeredServerData.get(playerName + "_" + modid + "|" + dataName); + DummyPacketIMSG simplePacket = new DummyPacketIMSG(dataString); + DummyPacketHandler.sendToAll(simplePacket); + } else { + Notifier.notifyCustomMod( + modid, + "The sync packet for data " + playerName + "_" + modid + + "could not be generated - the requested server data does not exist!"); + } + } + } + needsSyncing_Global.clear(); + needsSyncing_Player.clear(); + } } diff --git a/src/main/java/DummyCore/Utils/TileStatTracker.java b/src/main/java/DummyCore/Utils/TileStatTracker.java index e738dfe..b1ee5b5 100644 --- a/src/main/java/DummyCore/Utils/TileStatTracker.java +++ b/src/main/java/DummyCore/Utils/TileStatTracker.java @@ -3,38 +3,30 @@ package DummyCore.Utils; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; -public class TileStatTracker -{ - public TileEntity trackedTile; - public NBTTagCompound trackedTag; - - public TileStatTracker(TileEntity tracked) - { - trackedTile = tracked; - } - - public boolean tileNeedsSyncing() - { - if(trackedTile == null) return false; - NBTTagCompound currentTag = new NBTTagCompound(); - if(trackedTag == null) - { - trackedTag = new NBTTagCompound(); - trackedTile.writeToNBT(trackedTag); - return true; - }else - { - trackedTile.writeToNBT(currentTag); - if(currentTag.equals(trackedTag)) - { - trackedTile.writeToNBT(trackedTag); - return false; - }else - { - trackedTile.writeToNBT(trackedTag); - return true; - } - } - } - +public class TileStatTracker { + public TileEntity trackedTile; + public NBTTagCompound trackedTag; + + public TileStatTracker(TileEntity tracked) { + trackedTile = tracked; + } + + public boolean tileNeedsSyncing() { + if (trackedTile == null) return false; + NBTTagCompound currentTag = new NBTTagCompound(); + if (trackedTag == null) { + trackedTag = new NBTTagCompound(); + trackedTile.writeToNBT(trackedTag); + return true; + } else { + trackedTile.writeToNBT(currentTag); + if (currentTag.equals(trackedTag)) { + trackedTile.writeToNBT(trackedTag); + return false; + } else { + trackedTile.writeToNBT(trackedTag); + return true; + } + } + } } diff --git a/src/main/java/DummyCore/Utils/TimerHijack.java b/src/main/java/DummyCore/Utils/TimerHijack.java index 9e637c3..6a5baf9 100644 --- a/src/main/java/DummyCore/Utils/TimerHijack.java +++ b/src/main/java/DummyCore/Utils/TimerHijack.java @@ -7,17 +7,17 @@ import net.minecraft.client.Minecraft; import net.minecraft.util.Timer; public class TimerHijack { - - public static final String mcpName = "timer"; - public static final String deobfName = "field_71428_T"; - public static final String obfName = "Q"; - - @SideOnly(Side.CLIENT) - public static Timer mcTimer; - @SideOnly(Side.CLIENT) - public static void initMCTimer() - { - mcTimer = ReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), new String[]{mcpName, obfName, deobfName}); - } + public static final String mcpName = "timer"; + public static final String deobfName = "field_71428_T"; + public static final String obfName = "Q"; + + @SideOnly(Side.CLIENT) + public static Timer mcTimer; + + @SideOnly(Side.CLIENT) + public static void initMCTimer() { + mcTimer = ReflectionHelper.getPrivateValue( + Minecraft.class, Minecraft.getMinecraft(), new String[] {mcpName, obfName, deobfName}); + } } diff --git a/src/main/java/DummyCore/Utils/UnformedItemStack.java b/src/main/java/DummyCore/Utils/UnformedItemStack.java index a327b56..274f529 100644 --- a/src/main/java/DummyCore/Utils/UnformedItemStack.java +++ b/src/main/java/DummyCore/Utils/UnformedItemStack.java @@ -3,7 +3,6 @@ package DummyCore.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -12,144 +11,117 @@ import net.minecraft.nbt.NBTTagList; import net.minecraftforge.oredict.OreDictionary; /** - * + * * @author Modbder * * @Description Used in code where you want to reference either ItemStack or it's OreDictionary replacement. */ public class UnformedItemStack { - - public List possibleStacks = new ArrayList(); - - public UnformedItemStack() - { - - } - - public UnformedItemStack(ItemStack is) - { - possibleStacks.add(is); - sort(); - } - - public UnformedItemStack(String oreDictName) - { - possibleStacks.addAll(OreDictionary.getOres(oreDictName)); - sort(); - } - - public UnformedItemStack(List lst) - { - possibleStacks.addAll(lst); - sort(); - } - - public UnformedItemStack(ItemStack[] stk) - { - possibleStacks.addAll(Arrays.asList(stk)); - sort(); - } - - public UnformedItemStack(Block b) - { - possibleStacks.add(new ItemStack(b,1,OreDictionary.WILDCARD_VALUE)); - sort(); - } - - public UnformedItemStack(Item i) - { - possibleStacks.add(new ItemStack(i,1,OreDictionary.WILDCARD_VALUE)); - sort(); - } - - @SuppressWarnings("unchecked") - public UnformedItemStack(Object obj) - { - if(obj instanceof ItemStack) - possibleStacks.add((ItemStack)obj); - if(obj instanceof String) - possibleStacks.addAll(OreDictionary.getOres((String)obj)); - if(obj instanceof List) - possibleStacks.addAll((List)obj); - if(obj instanceof ItemStack[]) - possibleStacks.addAll(Arrays.asList((ItemStack[])obj)); - if(obj instanceof Block) - possibleStacks.add(new ItemStack((Block)obj,1,OreDictionary.WILDCARD_VALUE)); - if(obj instanceof Item) - possibleStacks.add(new ItemStack((Item)obj,1,OreDictionary.WILDCARD_VALUE)); - sort(); - } - - public boolean itemStackMatches(ItemStack is) - { - if(is == null) - return false; - for(ItemStack s : possibleStacks) - { - if(is.isItemEqual(s) || (is.getItem().equals(s.getItem()) && s.getItemDamage() == OreDictionary.WILDCARD_VALUE)) - return true; - } - return false; - } - - public String toString() - { - String str = ""; - for(ItemStack s : possibleStacks)str += s; - return str; - } - public UnformedItemStack copy() - { - return new UnformedItemStack(this.possibleStacks); - } - - public void nullify() - { - for(ItemStack s : possibleStacks)s.stackSize = 0; - } - - public void sort() - { - List possibleStacksCopy = new ArrayList(); - possibleStacksCopy.addAll(possibleStacks); - possibleStacks.clear(); - for(int i = 0; i < possibleStacksCopy.size();++i) - { - ItemStack is = possibleStacksCopy.get(i); - if(is != null)possibleStacks.add(is); - } - possibleStacksCopy.clear();possibleStacksCopy = null; - } - - public ItemStack getISToDraw(long time) - { - int size = this.possibleStacks.size(); - if(size <= 0)return null; - return this.possibleStacks.get((int)(((int)(time/30))%size)); - } - - public void writeToNBTTagCompound(NBTTagCompound tag) - { - NBTTagList items = new NBTTagList(); - for(ItemStack is : this.possibleStacks) - { - NBTTagCompound itemTag = new NBTTagCompound(); - is.writeToNBT(itemTag); - items.appendTag(itemTag); - } - tag.setTag("unformedISList", items); - } - - public void readFromNBTTagCompound(NBTTagCompound tag) - { - NBTTagList items = tag.getTagList("unformedISList", 10); - for(int i = 0; i < items.tagCount(); ++i) - { - NBTTagCompound itemTag = items.getCompoundTagAt(i); - ItemStack is = ItemStack.loadItemStackFromNBT(itemTag); - this.possibleStacks.add(is); - } - this.sort(); - } + public List possibleStacks = new ArrayList(); + + public UnformedItemStack() {} + + public UnformedItemStack(ItemStack is) { + possibleStacks.add(is); + sort(); + } + + public UnformedItemStack(String oreDictName) { + possibleStacks.addAll(OreDictionary.getOres(oreDictName)); + sort(); + } + + public UnformedItemStack(List lst) { + possibleStacks.addAll(lst); + sort(); + } + + public UnformedItemStack(ItemStack[] stk) { + possibleStacks.addAll(Arrays.asList(stk)); + sort(); + } + + public UnformedItemStack(Block b) { + possibleStacks.add(new ItemStack(b, 1, OreDictionary.WILDCARD_VALUE)); + sort(); + } + + public UnformedItemStack(Item i) { + possibleStacks.add(new ItemStack(i, 1, OreDictionary.WILDCARD_VALUE)); + sort(); + } + + @SuppressWarnings("unchecked") + public UnformedItemStack(Object obj) { + if (obj instanceof ItemStack) possibleStacks.add((ItemStack) obj); + if (obj instanceof String) possibleStacks.addAll(OreDictionary.getOres((String) obj)); + if (obj instanceof List) possibleStacks.addAll((List) obj); + if (obj instanceof ItemStack[]) possibleStacks.addAll(Arrays.asList((ItemStack[]) obj)); + if (obj instanceof Block) possibleStacks.add(new ItemStack((Block) obj, 1, OreDictionary.WILDCARD_VALUE)); + if (obj instanceof Item) possibleStacks.add(new ItemStack((Item) obj, 1, OreDictionary.WILDCARD_VALUE)); + sort(); + } + + public boolean itemStackMatches(ItemStack is) { + if (is == null) return false; + for (ItemStack s : possibleStacks) { + if (is.isItemEqual(s) + || (is.getItem().equals(s.getItem()) && s.getItemDamage() == OreDictionary.WILDCARD_VALUE)) + return true; + } + return false; + } + + public String toString() { + String str = ""; + for (ItemStack s : possibleStacks) str += s; + return str; + } + + public UnformedItemStack copy() { + return new UnformedItemStack(this.possibleStacks); + } + + public void nullify() { + for (ItemStack s : possibleStacks) s.stackSize = 0; + } + + public void sort() { + List possibleStacksCopy = new ArrayList(); + possibleStacksCopy.addAll(possibleStacks); + possibleStacks.clear(); + for (int i = 0; i < possibleStacksCopy.size(); ++i) { + ItemStack is = possibleStacksCopy.get(i); + if (is != null) possibleStacks.add(is); + } + possibleStacksCopy.clear(); + possibleStacksCopy = null; + } + + public ItemStack getISToDraw(long time) { + int size = this.possibleStacks.size(); + if (size <= 0) return null; + return this.possibleStacks.get((int) (((int) (time / 30)) % size)); + } + + public void writeToNBTTagCompound(NBTTagCompound tag) { + NBTTagList items = new NBTTagList(); + for (ItemStack is : this.possibleStacks) { + NBTTagCompound itemTag = new NBTTagCompound(); + is.writeToNBT(itemTag); + items.appendTag(itemTag); + } + tag.setTag("unformedISList", items); + } + + public void readFromNBTTagCompound(NBTTagCompound tag) { + NBTTagList items = tag.getTagList("unformedISList", 10); + for (int i = 0; i < items.tagCount(); ++i) { + NBTTagCompound itemTag = items.getCompoundTagAt(i); + ItemStack is = ItemStack.loadItemStackFromNBT(itemTag); + this.possibleStacks.add(is); + } + this.sort(); + } }