From a309488cdf7837ae1a27fab25305405ca7fe34e9 Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Sun, 29 Jan 2023 11:36:41 +0000 Subject: [PATCH] [ci skip] spotlessApply with the new settings --- src/main/java/minetweaker/ClassRegistry.java | 10 +- .../java/minetweaker/IBracketHandler.java | 33 +- .../java/minetweaker/IPlatformFunctions.java | 46 +- src/main/java/minetweaker/IRecipeRemover.java | 17 +- .../java/minetweaker/IUndoableAction.java | 120 +- src/main/java/minetweaker/MineTweakerAPI.java | 690 ++++++------ .../MineTweakerImplementation.java | 5 +- .../MineTweakerImplementationAPI.java | 1001 +++++++++-------- src/main/java/minetweaker/OneWayAction.java | 22 +- .../annotations/BracketHandler.java | 20 +- .../java/minetweaker/annotations/ModOnly.java | 8 +- .../minetweaker/annotations/OnRegister.java | 5 +- .../minetweaker/api/block/BlockPatternOr.java | 17 +- .../minetweaker/api/block/IBlockPattern.java | 4 +- .../minetweaker/api/chat/IChatMessage.java | 11 +- .../java/minetweaker/api/client/IClient.java | 4 +- .../api/compat/DummyJEIRecipeRegistry.java | 40 +- .../api/compat/IJEIRecipeRegistry.java | 25 +- .../minetweaker/api/container/IContainer.java | 3 +- .../minetweaker/api/data/DataByteArray.java | 16 +- .../minetweaker/api/data/DataIntArray.java | 12 +- .../java/minetweaker/api/data/DataList.java | 47 +- .../java/minetweaker/api/data/DataMap.java | 60 +- .../java/minetweaker/api/data/DataString.java | 2 +- src/main/java/minetweaker/api/data/IData.java | 21 +- .../api/data/IllegalDataException.java | 5 +- .../java/minetweaker/api/entity/IEntity.java | 8 +- .../api/entity/IEntityDefinition.java | 27 +- .../minetweaker/api/entity/IEntityItem.java | 4 +- .../minetweaker/api/event/IEventHandle.java | 4 +- .../minetweaker/api/event/IEventManager.java | 96 +- .../api/event/PlayerDeathDropsEvent.java | 4 +- .../api/event/PlayerInteractEvent.java | 34 +- .../api/event/PlayerLoggedInEvent.java | 6 +- .../api/event/PlayerLoggedOutEvent.java | 6 +- .../api/event/PlayerOpenContainerEvent.java | 14 +- .../api/formatting/IFormatter.java | 44 +- src/main/java/minetweaker/api/game/IGame.java | 33 +- .../minetweaker/api/item/IIngredient.java | 80 +- .../minetweaker/api/item/IItemCondition.java | 5 +- .../minetweaker/api/item/IItemDefinition.java | 22 +- .../java/minetweaker/api/item/IItemStack.java | 102 +- .../api/item/IItemTransformer.java | 8 +- .../minetweaker/api/item/IngredientAny.java | 12 +- .../api/item/IngredientAnyAdvanced.java | 24 +- .../api/item/IngredientCondition.java | 22 +- .../minetweaker/api/item/IngredientItem.java | 27 +- .../minetweaker/api/item/IngredientOr.java | 37 +- .../minetweaker/api/item/IngredientStack.java | 9 +- .../api/item/IngredientTransform.java | 34 +- .../api/item/IngredientUnknown.java | 5 +- .../api/item/WeightedItemStack.java | 39 +- .../api/liquid/ILiquidDefinition.java | 7 +- .../minetweaker/api/liquid/ILiquidStack.java | 26 +- .../api/liquid/WeightedLiquidStack.java | 19 +- .../minetweaker/api/logger/FileLogger.java | 20 +- .../java/minetweaker/api/logger/MTLogger.java | 22 +- .../api/minecraft/MineTweakerMC.java | 765 ++++++------- .../minetweaker/api/mods/ILoadedMods.java | 4 +- src/main/java/minetweaker/api/mods/IMod.java | 8 +- .../minetweaker/api/oredict/IOreDict.java | 8 +- .../api/oredict/IOreDictEntry.java | 1 - .../api/oredict/IngredientOreDict.java | 25 +- .../api/recipes/BrewingRecipe.java | 6 +- .../minetweaker/api/recipes/CraftingInfo.java | 10 +- .../api/recipes/FurnaceRecipe.java | 8 +- .../api/recipes/IBrewingManager.java | 18 +- .../api/recipes/IBrewingRecipe.java | 2 +- .../api/recipes/ICraftingInfo.java | 6 +- .../api/recipes/ICraftingInventory.java | 34 +- .../api/recipes/ICraftingRecipe.java | 10 +- .../api/recipes/IFurnaceManager.java | 14 +- .../api/recipes/IFurnaceRecipe.java | 3 +- .../minetweaker/api/recipes/IMTRecipe.java | 3 +- .../api/recipes/IRecipeAction.java | 4 +- .../api/recipes/IRecipeFunction.java | 6 +- .../api/recipes/IRecipeManager.java | 34 +- .../minetweaker/api/recipes/ShapedRecipe.java | 259 ++--- .../api/recipes/ShapelessRecipe.java | 115 +- .../api/recipes/UnknownRecipe.java | 16 +- .../api/server/AbstractServer.java | 3 +- .../java/minetweaker/api/server/IServer.java | 15 +- .../api/tooltip/IngredientTooltips.java | 36 +- .../minetweaker/api/util/IngredientMap.java | 29 +- .../api/vanilla/ILootRegistry.java | 4 +- .../api/vanilla/ISeedRegistry.java | 4 +- .../minetweaker/api/vanilla/IVanilla.java | 4 +- .../api/vanilla/IVillagerRegistry.java | 4 +- .../minetweaker/api/vanilla/LootEntry.java | 2 +- .../minetweaker/expand/ExpandAnyArray.java | 10 +- .../minetweaker/expand/ExpandAnyDict.java | 15 +- .../java/minetweaker/expand/ExpandBool.java | 14 +- .../java/minetweaker/expand/ExpandByte.java | 14 +- .../java/minetweaker/expand/ExpandDouble.java | 14 +- .../java/minetweaker/expand/ExpandFloat.java | 14 +- .../java/minetweaker/expand/ExpandInt.java | 14 +- .../minetweaker/expand/ExpandItemStack.java | 14 +- .../java/minetweaker/expand/ExpandLong.java | 14 +- .../java/minetweaker/expand/ExpandShort.java | 14 +- .../java/minetweaker/expand/ExpandString.java | 113 +- .../minetweaker/mc1710/FMLEventHandler.java | 69 +- .../minetweaker/mc1710/ForgeEventHandler.java | 97 +- .../minetweaker/mc1710/GuiCannotRemodify.java | 74 +- .../mc1710/MCPlatformFunctions.java | 47 +- .../minetweaker/mc1710/MineTweakerConfig.java | 59 +- .../minetweaker/mc1710/MineTweakerMod.java | 265 ++--- .../mc1710/MineTweakerRegistry.java | 12 +- .../actions/SetBlockHardnessAction.java | 9 +- .../mc1710/actions/SetStackSizeAction.java | 76 +- .../actions/SetStackmaxDamageAction.java | 76 +- .../mc1710/actions/SetTranslationAction.java | 88 +- .../mc1710/block/MCBlockDefinition.java | 37 +- .../minetweaker/mc1710/block/MCItemBlock.java | 80 +- .../mc1710/block/MCSpecificBlock.java | 93 +- .../mc1710/block/MCWorldBlock.java | 110 +- .../mc1710/brackets/ItemBracketHandler.java | 184 +-- .../mc1710/brackets/LiquidBracketHandler.java | 9 +- .../mc1710/brackets/OreBracketHandler.java | 94 +- .../mc1710/chat/MCChatMessage.java | 37 +- .../minetweaker/mc1710/client/MCClient.java | 26 +- .../minetweaker/mc1710/data/NBTConverter.java | 223 ++-- .../minetweaker/mc1710/data/NBTUpdater.java | 56 +- .../mc1710/entity/MCEntityDefinition.java | 56 +- .../formatting/FormattedMarkupString.java | 51 +- .../mc1710/formatting/FormattedString.java | 46 +- .../formatting/FormattedStringJoin.java | 88 +- .../mc1710/formatting/IMCFormattedString.java | 10 +- .../mc1710/formatting/MCFormatter.java | 182 +-- .../mc1710/furnace/FuelTweaker.java | 142 +-- .../mc1710/furnace/MCFurnaceManager.java | 39 +- .../mc1710/furnace/SetFuelPattern.java | 25 +- .../java/minetweaker/mc1710/game/MCGame.java | 313 +++--- .../mc1710/item/MCItemDefinition.java | 116 +- .../minetweaker/mc1710/item/MCItemStack.java | 644 +++++------ .../mc1710/liquid/MCLiquidDefinition.java | 789 +++++++------ .../mc1710/liquid/MCLiquidStack.java | 22 +- .../minetweaker/mc1710/mods/MCLoadedMods.java | 56 +- .../java/minetweaker/mc1710/mods/MCMod.java | 48 +- .../MineTweakerCopyClipboardHandler.java | 34 +- .../MineTweakerCopyClipboardPacket.java | 46 +- .../MineTweakerLoadScriptsHandler.java | 28 +- .../network/MineTweakerLoadScriptsPacket.java | 48 +- .../MineTweakerOpenBrowserHandler.java | 38 +- .../network/MineTweakerOpenBrowserPacket.java | 47 +- .../minetweaker/mc1710/oredict/MCOreDict.java | 39 +- .../mc1710/oredict/MCOreDictEntry.java | 47 +- .../mc1710/player/CommandBlockPlayer.java | 55 +- .../minetweaker/mc1710/player/MCPlayer.java | 195 ++-- .../minetweaker/mc1710/player/RconPlayer.java | 14 +- .../mc1710/recipes/MCCraftingInventory.java | 328 +++--- .../mc1710/recipes/MCRecipeManager.java | 171 +-- .../mc1710/recipes/RecipeConverter.java | 279 ++--- .../mc1710/recipes/ShapedRecipeAdvanced.java | 48 +- .../mc1710/recipes/ShapedRecipeBasic.java | 46 +- .../mc1710/recipes/ShapedRecipeOre.java | 12 +- .../recipes/ShapelessRecipeAdvanced.java | 48 +- .../mc1710/recipes/ShapelessRecipeBasic.java | 39 +- .../mc1710/recipes/ShapelessRecipeOre.java | 34 +- .../minetweaker/mc1710/server/MCServer.java | 37 +- .../mc1710/server/ServerPlayer.java | 160 +-- .../mc1710/util/MineTweakerHacks.java | 422 +++---- .../mc1710/util/MineTweakerObfuscation.java | 25 +- .../mc1710/util/MineTweakerPlatformUtils.java | 55 +- .../mc1710/util/ThreadSafeBitSet.java | 173 ++- .../mc1710/vanilla/MCLootRegistry.java | 298 ++--- .../mc1710/vanilla/MCSeedRegistry.java | 208 ++-- .../minetweaker/mc1710/vanilla/MCVanilla.java | 26 +- .../minetweaker/mc1710/world/MCBiome.java | 23 +- .../minetweaker/mc1710/world/MCDimension.java | 47 +- .../mods/ic2/IC2BracketHandler.java | 151 +-- .../mods/ic2/IC2ExplosionWhitelist.java | 266 ++--- .../minetweaker/mods/ic2/IC2RecipeInput.java | 99 +- .../mods/ic2/MachineAddRecipeAction.java | 183 +-- .../java/minetweaker/mods/ic2/crops/Crop.java | 113 +- .../mods/ic2/crops/CropsConfig.java | 442 ++++---- .../mods/ic2/crops/GrowthRequirements.java | 244 ++-- .../mods/ic2/crops/SyntheticCrop.java | 462 ++++---- .../mods/ic2/expand/IngredientExpansion.java | 67 +- .../mods/ic2/expand/ItemExpansion.java | 248 ++-- .../mods/ic2/machines/BlastFurnace.java | 92 +- .../mods/ic2/machines/BlockCutter.java | 92 +- .../minetweaker/mods/ic2/machines/Canner.java | 444 ++++---- .../mods/ic2/machines/Compressor.java | 96 +- .../mods/ic2/machines/Extractor.java | 92 +- .../mods/ic2/machines/FluidHeatGenerator.java | 136 +-- .../mods/ic2/machines/Macerator.java | 90 +- .../mods/ic2/machines/MatterAmplifier.java | 32 +- .../mods/ic2/machines/MetalFormer.java | 191 ++-- .../mods/ic2/machines/OreWasher.java | 51 +- .../mods/ic2/machines/Recycler.java | 111 +- .../mods/ic2/machines/ScrapBox.java | 126 +-- .../mods/ic2/machines/SemiFluidGenerator.java | 136 +-- .../mods/ic2/machines/ThermalCentrifuge.java | 128 ++- src/main/java/minetweaker/mods/nei/NEI.java | 261 ++--- .../minetweaker/runtime/GlobalFunctions.java | 19 +- .../minetweaker/runtime/GlobalRegistry.java | 454 ++++---- .../java/minetweaker/runtime/ILogger.java | 26 +- .../minetweaker/runtime/IScriptIterator.java | 14 +- .../minetweaker/runtime/IScriptProvider.java | 8 +- .../java/minetweaker/runtime/ITweaker.java | 95 +- .../java/minetweaker/runtime/MTTweaker.java | 266 ++--- .../providers/ScriptIteratorDirectory.java | 91 +- .../providers/ScriptIteratorSingle.java | 59 +- .../runtime/providers/ScriptIteratorZip.java | 83 +- .../providers/ScriptProviderCascade.java | 118 +- .../providers/ScriptProviderCustom.java | 114 +- .../providers/ScriptProviderDirectory.java | 47 +- .../providers/ScriptProviderMemory.java | 272 ++--- src/main/java/minetweaker/util/ArrayUtil.java | 51 +- .../util/CloseablePriorityList.java | 17 +- src/main/java/minetweaker/util/EventList.java | 129 +-- src/main/java/minetweaker/util/FileUtil.java | 24 +- .../java/minetweaker/util/IEventHandler.java | 8 +- .../java/minetweaker/util/StringUtil.java | 28 +- 214 files changed, 9283 insertions(+), 9265 deletions(-) diff --git a/src/main/java/minetweaker/ClassRegistry.java b/src/main/java/minetweaker/ClassRegistry.java index ffd8b9d..656ee86 100644 --- a/src/main/java/minetweaker/ClassRegistry.java +++ b/src/main/java/minetweaker/ClassRegistry.java @@ -3,14 +3,14 @@ package minetweaker; import java.util.List; /** - * The class registry provides the list of annotated classes to the scripting - * system. + * The class registry provides the list of annotated classes to the scripting system. * * @author Stan Hebben */ public class ClassRegistry { - public static void getClasses(List output) { - // no longer needed. kept to not break anyone who reference this + + public static void getClasses(List output) { + // no longer needed. kept to not break anyone who reference this // seriously though, why would anyone want to look at this registry anyway - } + } } diff --git a/src/main/java/minetweaker/IBracketHandler.java b/src/main/java/minetweaker/IBracketHandler.java index a61fe75..761d278 100644 --- a/src/main/java/minetweaker/IBracketHandler.java +++ b/src/main/java/minetweaker/IBracketHandler.java @@ -1,6 +1,7 @@ package minetweaker; import java.util.List; + import stanhebben.zenscript.compiler.IEnvironmentGlobal; import stanhebben.zenscript.parser.Token; import stanhebben.zenscript.symbols.IZenSymbol; @@ -8,25 +9,25 @@ import stanhebben.zenscript.symbols.IZenSymbol; /** * Bracket handlers enable processing of the bracket syntax. * - * Inside brackets, any kind of token is acceptable except the closing bracket. - * (>) Bracket handlers (multiple handlers can be registered) will resolve - * these tokens into actual values. Values have to be ZenScript symbols and will - * resolve at compile-time. + * Inside brackets, any kind of token is acceptable except the closing bracket. (>) Bracket handlers (multiple + * handlers can be registered) will resolve these tokens into actual values. Values have to be ZenScript symbols and + * will resolve at compile-time. * - * These may of course return an expression that are executed on run-time, but - * the type of the resulting value must be known compile-time. + * These may of course return an expression that are executed on run-time, but the type of the resulting value must be + * known compile-time. * * @author Stan Hebben */ public interface IBracketHandler { - /** - * Resolves a set of tokens. - * - * If the series of tokens is unrecognized, this method should return null. - * - * @param environment global compilation environment - * @param tokens token stream to be detected - * @return the resolved symbol, or null - */ - public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens); + + /** + * Resolves a set of tokens. + * + * If the series of tokens is unrecognized, this method should return null. + * + * @param environment global compilation environment + * @param tokens token stream to be detected + * @return the resolved symbol, or null + */ + public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens); } diff --git a/src/main/java/minetweaker/IPlatformFunctions.java b/src/main/java/minetweaker/IPlatformFunctions.java index 9836999..f71522f 100644 --- a/src/main/java/minetweaker/IPlatformFunctions.java +++ b/src/main/java/minetweaker/IPlatformFunctions.java @@ -4,33 +4,33 @@ import minetweaker.api.chat.IChatMessage; import minetweaker.api.item.IItemDefinition; /** - * Platform functions are a set of internal functions implemented by the - * platform intended to communicate between API and implementation. + * Platform functions are a set of internal functions implemented by the platform intended to communicate between API + * and implementation. * * @author Stan Hebben */ public interface IPlatformFunctions { - /** - * Converts a string into a chat message. - * - * @param message message string - * @return chat message - */ - public IChatMessage getMessage(String message); - /** - * Distributes the given script data to all connected clients. Automatically - * reloads the scripts from this data. - * - * @param data data to be distributed - */ - public void distributeScripts(byte[] data); + /** + * Converts a string into a chat message. + * + * @param message message string + * @return chat message + */ + public IChatMessage getMessage(String message); - /** - * Finds the item definition with the given ID. - * - * @param id item ID - * @return resulting item definition - */ - public IItemDefinition getItemDefinition(int id); + /** + * Distributes the given script data to all connected clients. Automatically reloads the scripts from this data. + * + * @param data data to be distributed + */ + public void distributeScripts(byte[] data); + + /** + * Finds the item definition with the given ID. + * + * @param id item ID + * @return resulting item definition + */ + public IItemDefinition getItemDefinition(int id); } diff --git a/src/main/java/minetweaker/IRecipeRemover.java b/src/main/java/minetweaker/IRecipeRemover.java index cfb0654..08ea913 100644 --- a/src/main/java/minetweaker/IRecipeRemover.java +++ b/src/main/java/minetweaker/IRecipeRemover.java @@ -3,16 +3,17 @@ package minetweaker; import minetweaker.api.item.IIngredient; /** - * Used to register removable mod recipes for mod machines. Once registered, it - * will be called when minetweaker.remove() is called. + * Used to register removable mod recipes for mod machines. Once registered, it will be called when minetweaker.remove() + * is called. * * @author Stan Hebben */ public interface IRecipeRemover { - /** - * Removes all the items matching the given ingredient. - * - * @param ingredient ingredient - */ - public void remove(IIngredient ingredient); + + /** + * Removes all the items matching the given ingredient. + * + * @param ingredient ingredient + */ + public void remove(IIngredient ingredient); } diff --git a/src/main/java/minetweaker/IUndoableAction.java b/src/main/java/minetweaker/IUndoableAction.java index f860dfc..6752c61 100644 --- a/src/main/java/minetweaker/IUndoableAction.java +++ b/src/main/java/minetweaker/IUndoableAction.java @@ -3,82 +3,70 @@ package minetweaker; /** * Defines a (possibly) undoable action. * - * Every modification made by a command must be registered to the Tweaker with - * the Tweaker.apply method. This enables MineTweaker to keep track of actions - * that have been performed, and enables them to be rolled back later on. + * Every modification made by a command must be registered to the Tweaker with the Tweaker.apply method. This enables + * MineTweaker to keep track of actions that have been performed, and enables them to be rolled back later on. * - * Actions exist in two flavors: undoable and permanent. If an action returns - * canUndo(), the action is undoable, otherwise it is permanent. Permanent - * actions cannot be used in server scripts. + * Actions exist in two flavors: undoable and permanent. If an action returns canUndo(), the action is undoable, + * otherwise it is permanent. Permanent actions cannot be used in server scripts. * - * There also exist semi-permanent actions. Those actions can return an override - * key; if a newer action has the same override key as an old action, the new - * action is considered to override the old one. + * There also exist semi-permanent actions. Those actions can return an override key; if a newer action has the same + * override key as an old action, the new action is considered to override the old one. * - * Likewise, actions can implement hashCode and equals methods to indicate that - * they are equal. If an action is equal to a non-undoable stuck action, it will - * be omitted from execution. + * Likewise, actions can implement hashCode and equals methods to indicate that they are equal. If an action is equal to + * a non-undoable stuck action, it will be omitted from execution. * * @author Stan Hebben */ public interface IUndoableAction { - /** - * Executes what the action is supposed to do. This method can be called - * again if undo() has been called in between. - */ - public void apply(); - /** - * Checks if this action can be undone. If this method returns true, it must - * implement undo() properly. If this method returns false, the action is - * considered permanent, undo() will never be called, and the action cannot - * be executed as part of a server script. Additionally, the - * minetweaker.clear() function will not work and minetweaker.canClear will - * return false. - * - * @return undoable status - */ - public boolean canUndo(); + /** + * Executes what the action is supposed to do. This method can be called again if undo() has been called in between. + */ + public void apply(); - /** - * Undoes the action. Will only be called after apply() has been executed. - * After an undo, apply may be called again. They could be done multiple - * times in certain scenarios. - */ - public void undo(); + /** + * Checks if this action can be undone. If this method returns true, it must implement undo() properly. If this + * method returns false, the action is considered permanent, undo() will never be called, and the action cannot be + * executed as part of a server script. Additionally, the minetweaker.clear() function will not work and + * minetweaker.canClear will return false. + * + * @return undoable status + */ + public boolean canUndo(); - /** - * Describes, in a single human-readable sentence, what this specific action - * is doing. Used in logging messages, lists, ... - * - * Try to be as descriptive as possible without being too verbose. - * - * Examples: - Adding Peach planks to the woodPlanks ore dictionary entry - - * Removing a recipe for Iron Ore - * - * @return the description of this action - */ - public String describe(); + /** + * Undoes the action. Will only be called after apply() has been executed. After an undo, apply may be called again. + * They could be done multiple times in certain scenarios. + */ + public void undo(); - /** - * Describes what this action does if it is undone. Similar to the - * describe() method. No implementation is needed if the action cannot be - * undone. - * - * @return the description of this action, when undone - */ - public String describeUndo(); + /** + * Describes, in a single human-readable sentence, what this specific action is doing. Used in logging messages, + * lists, ... + * + * Try to be as descriptive as possible without being too verbose. + * + * Examples: - Adding Peach planks to the woodPlanks ore dictionary entry - Removing a recipe for Iron Ore + * + * @return the description of this action + */ + public String describe(); - /** - * Returns the override key. Two actions are considered to override each - * other if their override key is equal. You can return null to indicate - * that an action can never be overridden. - * - * This value only makes sense for recipes that are not undoable. For - * undoable recipes, you should return null. - * - * @return override key (null for actions that are undoable or which can - * never be overridden by another action) - */ - public Object getOverrideKey(); + /** + * Describes what this action does if it is undone. Similar to the describe() method. No implementation is needed if + * the action cannot be undone. + * + * @return the description of this action, when undone + */ + public String describeUndo(); + + /** + * Returns the override key. Two actions are considered to override each other if their override key is equal. You + * can return null to indicate that an action can never be overridden. + * + * This value only makes sense for recipes that are not undoable. For undoable recipes, you should return null. + * + * @return override key (null for actions that are undoable or which can never be overridden by another action) + */ + public Object getOverrideKey(); } diff --git a/src/main/java/minetweaker/MineTweakerAPI.java b/src/main/java/minetweaker/MineTweakerAPI.java index 85b003f..1deb554 100644 --- a/src/main/java/minetweaker/MineTweakerAPI.java +++ b/src/main/java/minetweaker/MineTweakerAPI.java @@ -1,5 +1,15 @@ package minetweaker; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + import minetweaker.annotations.BracketHandler; import minetweaker.annotations.ModOnly; import minetweaker.api.client.IClient; @@ -26,427 +36,385 @@ import stanhebben.zenscript.symbols.SymbolJavaStaticMethod; import stanhebben.zenscript.type.natives.IJavaMethod; import stanhebben.zenscript.type.natives.JavaMethod; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - /** * Provides access to the MineTweaker API. * - * An implementing platform needs to do the following: - Set a logger - Set the - * ore dictionary - Set the recipe manager - Set the furnace manager - Set event - * manager - Set resource manager + * An implementing platform needs to do the following: - Set a logger - Set the ore dictionary - Set the recipe manager + * - Set the furnace manager - Set event manager - Set resource manager * - * - Register additional global symbols to the GlobalRegistry (recipes, - * minetweaker, oreDict, logger, as well as the official set of functions) - - * Register native classes using the GlobalRegistry - Register bracket handlers - * to resolve block/item/... references using the bracket syntax + * - Register additional global symbols to the GlobalRegistry (recipes, minetweaker, oreDict, logger, as well as the + * official set of functions) - Register native classes using the GlobalRegistry - Register bracket handlers to resolve + * block/item/... references using the bracket syntax * * @author Stan Hebben */ public class MineTweakerAPI { - public static final String[] COLOR_NAMES = { - "White", - "Orange", - "Magenta", - "Light Blue", - "Yellow", - "Lime", - "Pink", - "Gray", - "Light Gray", - "Cyan", - "Purple", - "Blue", - "Brown", - "Green", - "Red", - "Black" - }; + + public static final String[] COLOR_NAMES = { "White", "Orange", "Magenta", "Light Blue", "Yellow", "Lime", "Pink", + "Gray", "Light Gray", "Cyan", "Purple", "Blue", "Brown", "Green", "Red", "Black" }; private static IJEIRecipeRegistry ijeiRecipeRegistry = new DummyJEIRecipeRegistry(); - + static { - registerClassRegistry(ClassRegistry.class, "MT-API"); + registerClassRegistry(ClassRegistry.class, "MT-API"); - registerGlobalSymbol("logger", getJavaStaticGetterSymbol(MineTweakerAPI.class, "getLogger")); - registerGlobalSymbol("recipes", getJavaStaticFieldSymbol(MineTweakerAPI.class, "recipes")); -// registerGlobalSymbol("brewing", getJavaStaticFieldSymbol(MineTweakerAPI.class, "brewing")); + registerGlobalSymbol("logger", getJavaStaticGetterSymbol(MineTweakerAPI.class, "getLogger")); + registerGlobalSymbol("recipes", getJavaStaticFieldSymbol(MineTweakerAPI.class, "recipes")); + // registerGlobalSymbol("brewing", getJavaStaticFieldSymbol(MineTweakerAPI.class, "brewing")); registerGlobalSymbol("furnace", getJavaStaticFieldSymbol(MineTweakerAPI.class, "furnace")); - registerGlobalSymbol("oreDict", getJavaStaticFieldSymbol(MineTweakerAPI.class, "oreDict")); - registerGlobalSymbol("events", getJavaStaticFieldSymbol(MineTweakerAPI.class, "events")); - registerGlobalSymbol("server", getJavaStaticFieldSymbol(MineTweakerAPI.class, "server")); - registerGlobalSymbol("client", getJavaStaticFieldSymbol(MineTweakerAPI.class, "client")); - registerGlobalSymbol("game", getJavaStaticFieldSymbol(MineTweakerAPI.class, "game")); - registerGlobalSymbol("loadedMods", getJavaStaticFieldSymbol(MineTweakerAPI.class, "loadedMods")); - registerGlobalSymbol("format", getJavaStaticFieldSymbol(MineTweakerAPI.class, "format")); - registerGlobalSymbol("vanilla", getJavaStaticFieldSymbol(MineTweakerAPI.class, "vanilla")); - } + registerGlobalSymbol("oreDict", getJavaStaticFieldSymbol(MineTweakerAPI.class, "oreDict")); + registerGlobalSymbol("events", getJavaStaticFieldSymbol(MineTweakerAPI.class, "events")); + registerGlobalSymbol("server", getJavaStaticFieldSymbol(MineTweakerAPI.class, "server")); + registerGlobalSymbol("client", getJavaStaticFieldSymbol(MineTweakerAPI.class, "client")); + registerGlobalSymbol("game", getJavaStaticFieldSymbol(MineTweakerAPI.class, "game")); + registerGlobalSymbol("loadedMods", getJavaStaticFieldSymbol(MineTweakerAPI.class, "loadedMods")); + registerGlobalSymbol("format", getJavaStaticFieldSymbol(MineTweakerAPI.class, "format")); + registerGlobalSymbol("vanilla", getJavaStaticFieldSymbol(MineTweakerAPI.class, "vanilla")); + } - private MineTweakerAPI() { + private MineTweakerAPI() { - } + } - /** - * The Tweaker is where you apply undoable actions. Any kind of action that - * reloads with the scripts should always be submitted to the tweaker. - */ - @Deprecated - public static final ITweaker tweaker = new MTTweaker(); + /** + * The Tweaker is where you apply undoable actions. Any kind of action that reloads with the scripts should always + * be submitted to the tweaker. + */ + @Deprecated + public static final ITweaker tweaker = new MTTweaker(); - /** - * The logger can be used to write logging messages to the client. Error and - * warning messages should be relayed to admins for further handling. - * - * @return - */ - public static final ILogger getLogger() { - return MineTweakerImplementationAPI.logger; - } + /** + * The logger can be used to write logging messages to the client. Error and warning messages should be relayed to + * admins for further handling. + * + * @return + */ + public static final ILogger getLogger() { + return MineTweakerImplementationAPI.logger; + } - /** - * Access point to the ore dictionary. - */ - public static IOreDict oreDict = null; + /** + * Access point to the ore dictionary. + */ + public static IOreDict oreDict = null; - /** - * Access point to the recipe manager. - */ - public static IRecipeManager recipes = null; + /** + * Access point to the recipe manager. + */ + public static IRecipeManager recipes = null; -// /** -// * Access point to the brewing manager. -// */ -// public static IBrewingManager brewing = null; + // /** + // * Access point to the brewing manager. + // */ + // public static IBrewingManager brewing = null; - /** - * Access point to the furnace manager. - */ - public static IFurnaceManager furnace = null; + /** + * Access point to the furnace manager. + */ + public static IFurnaceManager furnace = null; - /** - * Access point to the events manager. - */ - public static final IEventManager events = MineTweakerImplementationAPI.events; + /** + * Access point to the events manager. + */ + public static final IEventManager events = MineTweakerImplementationAPI.events; - /** - * Access point to the server, if any. - */ - public static IServer server = null; + /** + * Access point to the server, if any. + */ + public static IServer server = null; - /** - * Access point to the client, if any. - */ - public static IClient client = null; + /** + * Access point to the client, if any. + */ + public static IClient client = null; - /** - * Access point to general game data, such as items. - */ - public static IGame game = null; + /** + * Access point to general game data, such as items. + */ + public static IGame game = null; - /** - * Access point to mods list. - */ - public static ILoadedMods loadedMods = null; + /** + * Access point to mods list. + */ + public static ILoadedMods loadedMods = null; - /** - * Access point to the text formatter. - */ - public static IFormatter format = null; + /** + * Access point to the text formatter. + */ + public static IFormatter format = null; - /** - * Access point to the vanilla functions and data. - */ - public static IVanilla vanilla = null; + /** + * Access point to the vanilla functions and data. + */ + public static IVanilla vanilla = null; - /** - * Applies this given action. - * - * @param action action object - */ - public static void apply(IUndoableAction action) { - tweaker.apply(action); - } + /** + * Applies this given action. + * + * @param action action object + */ + public static void apply(IUndoableAction action) { + tweaker.apply(action); + } - /** - * Logs a command message. Commands messages are those generated as output - * in response to a command. - * - * @param message command message - */ - public static void logCommand(String message) { - getLogger().logCommand(message); - } + /** + * Logs a command message. Commands messages are those generated as output in response to a command. + * + * @param message command message + */ + public static void logCommand(String message) { + getLogger().logCommand(message); + } - /** - * Logs an info message. Info messages have low priority and will only be - * displayed in the log files, but not directly to players in-game. - * - * @param message info message - */ - public static void logInfo(String message) { - getLogger().logInfo(message); - } + /** + * Logs an info message. Info messages have low priority and will only be displayed in the log files, but not + * directly to players in-game. + * + * @param message info message + */ + public static void logInfo(String message) { + getLogger().logInfo(message); + } - /** - * Logs a warning message. Warning messages are displayed to admins and - * indicate that there is an issue. However, the issue is not a large - * problem, and everything should run fine - besides perhaps a few things - * not entirely working as expected. - * - * @param message warning message - */ - public static void logWarning(String message) { - getLogger().logWarning(message); - } + /** + * Logs a warning message. Warning messages are displayed to admins and indicate that there is an issue. However, + * the issue is not a large problem, and everything should run fine - besides perhaps a few things not entirely + * working as expected. + * + * @param message warning message + */ + public static void logWarning(String message) { + getLogger().logWarning(message); + } - /** - * Logs an error message. Error messages indicate a real problem and - * indicate that things won't run properly. The scripting system will still - * make a best-effort attempt at executing the rest of the scripts, but that - * might cause additional errors and issues. - * - * @param message error message - */ - public static void logError(String message) { - getLogger().logError(message); - } + /** + * Logs an error message. Error messages indicate a real problem and indicate that things won't run properly. The + * scripting system will still make a best-effort attempt at executing the rest of the scripts, but that might cause + * additional errors and issues. + * + * @param message error message + */ + public static void logError(String message) { + getLogger().logError(message); + } - /** - * Logs an error message. Error messages indicate a real problem and - * indicate that things won't run properly. The scripting system will still - * make a best-effort attempt at executing the rest of the scripts, but that - * might cause additional errors and issues. - * - * @param message error message - * @param exception exception that was caught related to the error - */ - public static void logError(String message, Throwable exception) { - getLogger().logError(message, exception); - } + /** + * Logs an error message. Error messages indicate a real problem and indicate that things won't run properly. The + * scripting system will still make a best-effort attempt at executing the rest of the scripts, but that might cause + * additional errors and issues. + * + * @param message error message + * @param exception exception that was caught related to the error + */ + public static void logError(String message, Throwable exception) { + getLogger().logError(message, exception); + } - // ################################### - // ### Plugin registration methods ### - // ################################### + // ################################### + // ### Plugin registration methods ### + // ################################### - /** - * Register a class registry class. Such class must have (at least) a public - * static method called "getClasses" with accepts a List of classes and - * which stores its classes into that list. - * - * @param registryClass - */ - public static void registerClassRegistry(Class registryClass) { - registerClassRegistry(registryClass, null); - } + /** + * Register a class registry class. Such class must have (at least) a public static method called "getClasses" with + * accepts a List of classes and which stores its classes into that list. + * + * @param registryClass + */ + public static void registerClassRegistry(Class registryClass) { + registerClassRegistry(registryClass, null); + } - /** - * Register a class registry class. Such class must have (at least) a public - * static method called "getClasses" with accepts a List of classes and - * which stores its classes into that list. - * - * @param registryClass - * @param description - */ - public static void registerClassRegistry(Class registryClass, String description) { - try { - Method method = registryClass.getMethod("getClasses", List.class); - if ((method.getModifiers() & Modifier.STATIC) == 0) { - logError("ERROR: getClasses method in " + registryClass.getName() + " isn't static"); - } else { - List classes = new ArrayList(); - method.invoke(null, classes); + /** + * Register a class registry class. Such class must have (at least) a public static method called "getClasses" with + * accepts a List of classes and which stores its classes into that list. + * + * @param registryClass + * @param description + */ + public static void registerClassRegistry(Class registryClass, String description) { + try { + Method method = registryClass.getMethod("getClasses", List.class); + if ((method.getModifiers() & Modifier.STATIC) == 0) { + logError("ERROR: getClasses method in " + registryClass.getName() + " isn't static"); + } else { + List classes = new ArrayList(); + method.invoke(null, classes); - outer: for (Class cls : classes) { - for (Annotation annotation : cls.getAnnotations()) { - if (annotation instanceof ModOnly) { - String[] value = ((ModOnly) annotation).value(); - String version = ((ModOnly) annotation).version(); + outer: for (Class cls : classes) { + for (Annotation annotation : cls.getAnnotations()) { + if (annotation instanceof ModOnly) { + String[] value = ((ModOnly) annotation).value(); + String version = ((ModOnly) annotation).version(); - for (String mod : value) { - if (!loadedMods.contains(mod)) - continue outer; + for (String mod : value) { + if (!loadedMods.contains(mod)) continue outer; - if (!loadedMods.get(mod).getVersion().startsWith(version)) - continue outer; - } - } - } + if (!loadedMods.get(mod).getVersion().startsWith(version)) continue outer; + } + } + } - MineTweakerAPI.registerClass(cls); - } + MineTweakerAPI.registerClass(cls); + } - if (description != null) - logInfo("Loaded class registry: " + description); - } - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { - if(ex.getCause() instanceof NoClassDefFoundError) { - logInfo("Classes for registry " + registryClass + " not found, skipping"); + if (description != null) logInfo("Loaded class registry: " + description); + } + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { + if (ex.getCause() instanceof NoClassDefFoundError) { + logInfo("Classes for registry " + registryClass + " not found, skipping"); } else { logError("Error registering class registry", ex); } - } + } } - /** - * Registers a class registry. Will attempt to resolve the given class name. - * Does nothing if the class could not be loaded. - * - * @param className class name to be loaded - * @return true if registration was successful - */ - public static boolean registerClassRegistry(String className) { - return registerClassRegistry(className, null); - } + /** + * Registers a class registry. Will attempt to resolve the given class name. Does nothing if the class could not be + * loaded. + * + * @param className class name to be loaded + * @return true if registration was successful + */ + public static boolean registerClassRegistry(String className) { + return registerClassRegistry(className, null); + } - /** - * Registers a class registry. Will attempt to resolve the given class name. - * Does nothing if the class could not be loaded. - * - * @param className class name to be loaded - * @param description - * @return true if registration was successful - */ - public static boolean registerClassRegistry(String className, String description) { - try { - registerClassRegistry(Class.forName(className), description); - return true; - } catch (ClassNotFoundException ex) { - return false; - } - } + /** + * Registers a class registry. Will attempt to resolve the given class name. Does nothing if the class could not be + * loaded. + * + * @param className class name to be loaded + * @param description + * @return true if registration was successful + */ + public static boolean registerClassRegistry(String className, String description) { + try { + registerClassRegistry(Class.forName(className), description); + return true; + } catch (ClassNotFoundException ex) { + return false; + } + } - /** - * Registers an annotated class. A class is annotated with either @ZenClass - * or @ZenExpansion. Classes not annotated with either of these will be - * ignored. - * - * @param annotatedClass - */ - public static void registerClass(Class annotatedClass) { - // System.out.println("Registering " + annotatedClass.getName()); + /** + * Registers an annotated class. A class is annotated with either @ZenClass or @ZenExpansion. Classes not annotated + * with either of these will be ignored. + * + * @param annotatedClass + */ + public static void registerClass(Class annotatedClass) { + // System.out.println("Registering " + annotatedClass.getName()); - for (Annotation annotation : annotatedClass.getAnnotations()) { - if (annotation instanceof ZenExpansion) { - GlobalRegistry.registerExpansion(annotatedClass); - } + for (Annotation annotation : annotatedClass.getAnnotations()) { + if (annotation instanceof ZenExpansion) { + GlobalRegistry.registerExpansion(annotatedClass); + } - if (annotation instanceof ZenClass) { - GlobalRegistry.registerNativeClass(annotatedClass); - } - if ((annotation instanceof BracketHandler) && IBracketHandler.class.isAssignableFrom(annotatedClass)) { - try { - IBracketHandler bracketHandler = (IBracketHandler) annotatedClass.newInstance(); - registerBracketHandler(bracketHandler); - } catch (InstantiationException ex) { - Logger.getLogger(MineTweakerAPI.class.getName()).log(Level.SEVERE, null, ex); - } catch (IllegalAccessException ex) { - Logger.getLogger(MineTweakerAPI.class.getName()).log(Level.SEVERE, null, ex); - } - } - } - } + if (annotation instanceof ZenClass) { + GlobalRegistry.registerNativeClass(annotatedClass); + } + if ((annotation instanceof BracketHandler) && IBracketHandler.class.isAssignableFrom(annotatedClass)) { + try { + IBracketHandler bracketHandler = (IBracketHandler) annotatedClass.newInstance(); + registerBracketHandler(bracketHandler); + } catch (InstantiationException ex) { + Logger.getLogger(MineTweakerAPI.class.getName()).log(Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + Logger.getLogger(MineTweakerAPI.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + } - /** - * Registers a global symbol. Global symbols are immediately accessible from - * anywhere in the scripts. - * - * @param name symbol name - * @param symbol symbol - */ - public static void registerGlobalSymbol(String name, IZenSymbol symbol) { - GlobalRegistry.registerGlobal(name, symbol); - } + /** + * Registers a global symbol. Global symbols are immediately accessible from anywhere in the scripts. + * + * @param name symbol name + * @param symbol symbol + */ + public static void registerGlobalSymbol(String name, IZenSymbol symbol) { + GlobalRegistry.registerGlobal(name, symbol); + } - /** - * Registers a recipe remover. Removers are called when the global - * minetweaker.remove() function is called. - * - * @param remover recipe remover - */ - public static void registerRemover(IRecipeRemover remover) { - GlobalRegistry.registerRemover(remover); - } + /** + * Registers a recipe remover. Removers are called when the global minetweaker.remove() function is called. + * + * @param remover recipe remover + */ + public static void registerRemover(IRecipeRemover remover) { + GlobalRegistry.registerRemover(remover); + } - /** - * Registers a bracket handler. Is capable of converting the bracket syntax - * to an actual value. This new handler will be added last - it can thus not - * intercept values that are already handled by the system. - * - * @param handler bracket handler to be added - */ - public static void registerBracketHandler(IBracketHandler handler) { - GlobalRegistry.registerBracketHandler(handler); - } + /** + * Registers a bracket handler. Is capable of converting the bracket syntax to an actual value. This new handler + * will be added last - it can thus not intercept values that are already handled by the system. + * + * @param handler bracket handler to be added + */ + public static void registerBracketHandler(IBracketHandler handler) { + GlobalRegistry.registerBracketHandler(handler); + } - /** - * Creates a symbol that refers to a java method. - * - * @param cls class that contains the method - * @param name method name - * @param arguments method argument types - * @return corresponding symbol - */ - public static IZenSymbol getJavaStaticMethodSymbol(Class cls, String name, Class... arguments) { - IJavaMethod method = JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name, arguments); - return new SymbolJavaStaticMethod(method); - } + /** + * Creates a symbol that refers to a java method. + * + * @param cls class that contains the method + * @param name method name + * @param arguments method argument types + * @return corresponding symbol + */ + public static IZenSymbol getJavaStaticMethodSymbol(Class cls, String name, Class... arguments) { + IJavaMethod method = JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name, arguments); + return new SymbolJavaStaticMethod(method); + } - /** - * Creates a symbol that refers to a java getter. The getter must be a - * method with no arguments. The given symbol will act as a variable of - * which the value can be retrieved but not set. - * - * @param cls class that contains the getter method - * @param name name of the method - * @return corresponding symbol - */ - public static IZenSymbol getJavaStaticGetterSymbol(Class cls, String name) { - IJavaMethod method = JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name); - return new SymbolJavaStaticGetter(method); - } + /** + * Creates a symbol that refers to a java getter. The getter must be a method with no arguments. The given symbol + * will act as a variable of which the value can be retrieved but not set. + * + * @param cls class that contains the getter method + * @param name name of the method + * @return corresponding symbol + */ + public static IZenSymbol getJavaStaticGetterSymbol(Class cls, String name) { + IJavaMethod method = JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name); + return new SymbolJavaStaticGetter(method); + } - /** - * Creates a symbol that refers to a static field. The field must be an - * existing public field in the given class. The field will act as a - * variable that can be retrieved but not set. - * - * @param cls class that contains the field - * @param name field name (must be public) - * @return corresponding symbol - */ - public static IZenSymbol getJavaStaticFieldSymbol(Class cls, String name) { - try { - Field field = cls.getField(name); - return new SymbolJavaStaticField(cls, field, GlobalRegistry.getTypeRegistry()); - } catch (NoSuchFieldException ex) { - return null; - } catch (SecurityException ex) { - return null; - } - } + /** + * Creates a symbol that refers to a static field. The field must be an existing public field in the given class. + * The field will act as a variable that can be retrieved but not set. + * + * @param cls class that contains the field + * @param name field name (must be public) + * @return corresponding symbol + */ + public static IZenSymbol getJavaStaticFieldSymbol(Class cls, String name) { + try { + Field field = cls.getField(name); + return new SymbolJavaStaticField(cls, field, GlobalRegistry.getTypeRegistry()); + } catch (NoSuchFieldException ex) { + return null; + } catch (SecurityException ex) { + return null; + } + } + + /** + * Loads a Java method from an existing class. + * + * @param cls method class + * @param name method name + * @param arguments argument types + * @return java method + */ + public static IJavaMethod getJavaMethod(Class cls, String name, Class... arguments) { + return JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name, arguments); + } - /** - * Loads a Java method from an existing class. - * - * @param cls method class - * @param name method name - * @param arguments argument types - * @return java method - */ - public static IJavaMethod getJavaMethod(Class cls, String name, Class... arguments) { - return JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name, arguments); - } - public static IJEIRecipeRegistry getIjeiRecipeRegistry() { return ijeiRecipeRegistry; } - + public static void setIjeiRecipeRegistry(IJEIRecipeRegistry ijeiRecipeRegistry) { MineTweakerAPI.ijeiRecipeRegistry = ijeiRecipeRegistry; } diff --git a/src/main/java/minetweaker/MineTweakerImplementation.java b/src/main/java/minetweaker/MineTweakerImplementation.java index 2f63b5c..b088022 100644 --- a/src/main/java/minetweaker/MineTweakerImplementation.java +++ b/src/main/java/minetweaker/MineTweakerImplementation.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker; diff --git a/src/main/java/minetweaker/MineTweakerImplementationAPI.java b/src/main/java/minetweaker/MineTweakerImplementationAPI.java index ff62bed..e309ddc 100644 --- a/src/main/java/minetweaker/MineTweakerImplementationAPI.java +++ b/src/main/java/minetweaker/MineTweakerImplementationAPI.java @@ -1,5 +1,14 @@ package minetweaker; +import static minetweaker.MineTweakerAPI.furnace; +import static minetweaker.MineTweakerAPI.server; + +import java.awt.*; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.util.*; +import java.util.List; + import minetweaker.api.block.IBlock; import minetweaker.api.block.IBlockDefinition; import minetweaker.api.data.IData; @@ -28,22 +37,13 @@ import minetweaker.runtime.IScriptProvider; import minetweaker.util.EventList; import minetweaker.util.IEventHandler; -import java.awt.*; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.StringSelection; -import java.util.*; -import java.util.List; - -import static minetweaker.MineTweakerAPI.furnace; -import static minetweaker.MineTweakerAPI.server; - /** - * The implementation API is used by API implementations for internal - * communication and initialization. + * The implementation API is used by API implementations for internal communication and initialization. * * @author Stan Hebben */ public class MineTweakerImplementationAPI { + private static Set blockInfoPlayers = new HashSet(); private static IEventHandle blockEventHandler = null; @@ -64,464 +64,488 @@ public class MineTweakerImplementationAPI { static { minetweakerCommands = new HashMap(); - minetweakerCommands.put("reload", new MineTweakerCommand( + minetweakerCommands.put( "reload", - new String[]{ - "/minetweaker reload", - " Reloads all scripts" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - reload(); - player.sendChat("Scripts reloaded"); - } - })); + new MineTweakerCommand( + "reload", + new String[] { "/minetweaker reload", " Reloads all scripts" }, + new ICommandFunction() { - minetweakerCommands.put("names", new MineTweakerCommand( + @Override + public void execute(String[] arguments, IPlayer player) { + reload(); + player.sendChat("Scripts reloaded"); + } + })); + + minetweakerCommands.put( "names", - new String[]{ - "/minetweaker names", - " Outputs a list of all item names in the game to the minetweaker log" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - List items = MineTweakerAPI.game.getItems(); - Collections.sort(items, ITEM_COMPARATOR); - for (IItemDefinition item : items) { - String displayName; + new MineTweakerCommand( + "names", + new String[] { "/minetweaker names", + " Outputs a list of all item names in the game to the minetweaker log" }, + new ICommandFunction() { - try { - displayName = ", " + item.makeStack(0).getDisplayName(); - } catch (Throwable ex) { - // some mods (such as buildcraft) may throw - // exceptions when calling - // getDisplayName on an item stack that doesn't - // contain valid NBT data - // also seems to cause errors in some other - // cases too - displayName = " -- Name could not be retrieved due to an error: " + ex; - } + @Override + public void execute(String[] arguments, IPlayer player) { + List items = MineTweakerAPI.game.getItems(); + Collections.sort(items, ITEM_COMPARATOR); + for (IItemDefinition item : items) { + String displayName; - MineTweakerAPI.logCommand("<" + item.getId() + ">" + displayName); - } + try { + displayName = ", " + item.makeStack(0).getDisplayName(); + } catch (Throwable ex) { + // some mods (such as buildcraft) may throw + // exceptions when calling + // getDisplayName on an item stack that doesn't + // contain valid NBT data + // also seems to cause errors in some other + // cases too + displayName = " -- Name could not be retrieved due to an error: " + ex; + } - if (player != null) { - player.sendChat("List generated; see minetweaker.log in your minecraft dir"); - } - } - })); - - minetweakerCommands.put("liquids", new MineTweakerCommand( - "liquids", - new String[]{ - "/minetweaker liquids", - " Outputs a list of all liquid names in the game to the minetweaker log" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - List liquids = MineTweakerAPI.game.getLiquids(); - Collections.sort(liquids, LIQUID_COMPARATOR); - - MineTweakerAPI.logCommand("Liquids:"); - for (ILiquidDefinition liquid : liquids) { - MineTweakerAPI.logCommand(", " + liquid.getDisplayName()); - } - - if (player != null) { - player.sendChat("List generated; see minetweaker.log in your minecraft dir"); - } - } - })); - - minetweakerCommands.put("blocks", new MineTweakerCommand( - "blocks", - new String[]{ - "/minetweaker blocks", - " Outputs a list of all blocks in the game to the minetweaker log" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - List blocks = MineTweakerAPI.game.getBlocks(); - Collections.sort(blocks, BLOCK_COMPARATOR); - - MineTweakerAPI.logCommand("Blocks:"); - for (IBlockDefinition block : blocks) { - MineTweakerAPI.logCommand(", " + block.getDisplayName()); - } - - if (player != null) { - player.sendChat("List generated; see minetweaker.log in your minecraft dir"); - } - } - })); - - minetweakerCommands.put("entities", new MineTweakerCommand( - "entities", - new String[]{ - "/minetweaker entities", - " Outputs a list of all entity definitions in the game to the minetweaker log" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - List entities = MineTweakerAPI.game.getEntities(); - Collections.sort(entities, ENTITY_COMPARATOR); - - MineTweakerAPI.logCommand("Entities:"); - for (IEntityDefinition entity : entities) { - MineTweakerAPI.logCommand(entity.getId() + " -- " + entity.getName()); - } - - if (player != null) { - player.sendChat("List generated; see minetweaker.log in your minecraft dir"); - } - } - })); - - minetweakerCommands.put("recipes", new MineTweakerCommand( - "recipes", - new String[]{ - "/minetweaker recipes", - " Lists all crafting recipes in the game", - "/minetweaker recipes hand", - " Lists all crafting recipes for the item in your hand", - " Also copies the recipes to clipboard", - "/minetweaker recipes furnace", - " lists all furnace recipes in the game" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - if (arguments.length == 0) { - if (player != null) { - player.sendChat("Generating recipe list, this could take a while..."); - } - - MineTweakerAPI.logCommand("Recipes:"); - for (ICraftingRecipe recipe : MineTweakerAPI.recipes.getAll()) { - try { - MineTweakerAPI.logCommand(recipe.toCommandString()); - } catch (Throwable ex) { - // Some recipes can result in an NPE :-( - if (recipe instanceof ShapedRecipe) { - ShapedRecipe shaped = (ShapedRecipe) recipe; - IItemStack out = shaped.getOutput(); - MineTweakerAPI.logError("Could not dump recipe for " + out, ex); - } else if (recipe instanceof ShapelessRecipe) { - ShapelessRecipe shapeless = (ShapelessRecipe) recipe; - IItemStack out = shapeless.getOutput(); - MineTweakerAPI.logError("Could not dump recipe for " + out, ex); - } else { - MineTweakerAPI.logError("Could not dump recipe", ex); - } - } - } - - if (player != null) { - player.sendChat("Recipe list generated; see minetweaker.log in your minecraft dir"); - } - } else if (arguments[0].equals("hand") && player != null) { - IItemStack item = player.getCurrentItem(); - if (item != null) { - List recipes = MineTweakerAPI.recipes.getRecipesFor(item.anyAmount()); - if (recipes.isEmpty()) { - player.sendChat("No crafting recipes found for that item"); - } else { - StringBuilder recipesString = new StringBuilder(); - - for (ICraftingRecipe recipe : recipes) { - MineTweakerAPI.logCommand(recipe.toCommandString()); - player.sendChat(recipe.toCommandString()); - recipesString.append(recipe.toCommandString()).append("\n"); - } - - copyToClipboard(recipesString.toString()); - } - } else { - player.sendChat("No item was found"); - } - } else if (arguments[0].equals("furnace") && player != null) { - if (player != null) { - player.sendChat("Generating furnace list, this could take a while..."); - } - - MineTweakerAPI.logCommand("Furnace Recipes:"); - for (IFurnaceRecipe recipe : furnace.getAll()) { - try { - MineTweakerAPI.logCommand(recipe.toCommandString()); - } catch (Throwable ex) { - MineTweakerAPI.logError("Could not dump furnace recipe", ex); - } - } - - if (player != null) { - player.sendChat("Furnace Recipe list generated; see minetweaker.log in your minecraft dir"); - } - } else { - if (player != null) { - player.sendChat("Invalid arguments for recipes command"); - } - } - } - })); - - minetweakerCommands.put("inventory", new MineTweakerCommand( - "inventory", - new String[]{ - "/minetweaker inventory", - " Lists all items in your inventory" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - for (int i = 0; i < player.getInventorySize(); i++) { - IItemStack stack = player.getInventoryStack(i); - if (stack != null) { - player.sendChat(stack.toString()); - } - } - } - })); - - minetweakerCommands.put("hand", new MineTweakerCommand( - "hand", - new String[]{ - "/minetweaker hand", - " Outputs the name of the item in your hand", - " Also copies the name to clipboard and prints", - " oredict entries" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - IItemStack hand = player.getCurrentItem(); - if (hand != null) { - String value = hand.toString(); - player.sendChat(value); - copyToClipboard(value); - - List entries = hand.getOres(); - for (IOreDictEntry entry : entries) { - player.sendChat("Is in "); - } - } - } - })); - - minetweakerCommands.put("oredict", new MineTweakerCommand( - "oredict", - new String[]{ - "/minetweaker oredict", - " Outputs all ore dictionary entries in the game to the minetweaker log", - "/minetweaker oredict ", - " Outputs all items in the given ore dictionary entry to the minetweaker log" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - if (arguments.length > 0) { - String entryName = arguments[0]; - IOreDictEntry entry = MineTweakerAPI.oreDict.get(entryName); - if (entry.isEmpty()) { - player.sendChat("Entry doesn't exist"); - return; - } else { - MineTweakerAPI.logCommand("Ore entries for " + entryName + ":"); - for (IItemStack ore : entry.getItems()) { - MineTweakerAPI.logCommand(" " + ore); - } - } - } else { - for (IOreDictEntry entry : MineTweakerAPI.oreDict.getEntries()) { - if (!entry.isEmpty()) { - MineTweakerAPI.logCommand("Ore entries for :"); - for (IItemStack ore : entry.getItems()) { - MineTweakerAPI.logCommand(" " + ore); - } - } - } - } - player.sendChat("List generated; see minetweaker.log in your minecraft dir"); - } - })); - - minetweakerCommands.put("mods", new MineTweakerCommand( - "mods", - new String[]{ - "/minetweaker mods", - " Outputs all active mod IDs and versions in the game" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - MineTweakerAPI.logCommand("Mods list:"); - for (IMod mod : MineTweakerAPI.loadedMods) { - String message = mod.getId() + " - " + mod.getName() + " - " + mod.getVersion(); - player.sendChat(message); - MineTweakerAPI.logCommand("Mod: " + message); - } - } - })); - - minetweakerCommands.put("name", new MineTweakerCommand( - "name", - new String[]{ - "/minetweaker name ", - " Outputs the name for the given item ID", - }, - new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - if (arguments.length < 1) { - player.sendChat("missing id parameter"); - } else { - try { - int id = Integer.parseInt(arguments[0]); - IItemDefinition definition = platform.getItemDefinition(id); - if (definition == null) { - player.sendChat("no such item"); - } else { - StringBuilder description = new StringBuilder(); - description.append('<'); - description.append(definition.getId()); - description.append('>'); - player.sendChat(description.toString()); + MineTweakerAPI.logCommand("<" + item.getId() + ">" + displayName); + } + + if (player != null) { + player.sendChat("List generated; see minetweaker.log in your minecraft dir"); } - } catch (NumberFormatException e) { - MineTweakerAPI.logCommand("ID must be an integer"); } - } - } - })); + })); - minetweakerCommands.put("seeds", new MineTweakerCommand( + minetweakerCommands.put( + "liquids", + new MineTweakerCommand( + "liquids", + new String[] { "/minetweaker liquids", + " Outputs a list of all liquid names in the game to the minetweaker log" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + List liquids = MineTweakerAPI.game.getLiquids(); + Collections.sort(liquids, LIQUID_COMPARATOR); + + MineTweakerAPI.logCommand("Liquids:"); + for (ILiquidDefinition liquid : liquids) { + MineTweakerAPI.logCommand( + ", " + liquid.getDisplayName()); + } + + if (player != null) { + player.sendChat("List generated; see minetweaker.log in your minecraft dir"); + } + } + })); + + minetweakerCommands.put( + "blocks", + new MineTweakerCommand( + "blocks", + new String[] { "/minetweaker blocks", + " Outputs a list of all blocks in the game to the minetweaker log" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + List blocks = MineTweakerAPI.game.getBlocks(); + Collections.sort(blocks, BLOCK_COMPARATOR); + + MineTweakerAPI.logCommand("Blocks:"); + for (IBlockDefinition block : blocks) { + MineTweakerAPI + .logCommand(", " + block.getDisplayName()); + } + + if (player != null) { + player.sendChat("List generated; see minetweaker.log in your minecraft dir"); + } + } + })); + + minetweakerCommands.put( + "entities", + new MineTweakerCommand( + "entities", + new String[] { "/minetweaker entities", + " Outputs a list of all entity definitions in the game to the minetweaker log" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + List entities = MineTweakerAPI.game.getEntities(); + Collections.sort(entities, ENTITY_COMPARATOR); + + MineTweakerAPI.logCommand("Entities:"); + for (IEntityDefinition entity : entities) { + MineTweakerAPI.logCommand(entity.getId() + " -- " + entity.getName()); + } + + if (player != null) { + player.sendChat("List generated; see minetweaker.log in your minecraft dir"); + } + } + })); + + minetweakerCommands.put( + "recipes", + new MineTweakerCommand( + "recipes", + new String[] { "/minetweaker recipes", " Lists all crafting recipes in the game", + "/minetweaker recipes hand", " Lists all crafting recipes for the item in your hand", + " Also copies the recipes to clipboard", "/minetweaker recipes furnace", + " lists all furnace recipes in the game" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + if (arguments.length == 0) { + if (player != null) { + player.sendChat("Generating recipe list, this could take a while..."); + } + + MineTweakerAPI.logCommand("Recipes:"); + for (ICraftingRecipe recipe : MineTweakerAPI.recipes.getAll()) { + try { + MineTweakerAPI.logCommand(recipe.toCommandString()); + } catch (Throwable ex) { + // Some recipes can result in an NPE :-( + if (recipe instanceof ShapedRecipe) { + ShapedRecipe shaped = (ShapedRecipe) recipe; + IItemStack out = shaped.getOutput(); + MineTweakerAPI.logError("Could not dump recipe for " + out, ex); + } else if (recipe instanceof ShapelessRecipe) { + ShapelessRecipe shapeless = (ShapelessRecipe) recipe; + IItemStack out = shapeless.getOutput(); + MineTweakerAPI.logError("Could not dump recipe for " + out, ex); + } else { + MineTweakerAPI.logError("Could not dump recipe", ex); + } + } + } + + if (player != null) { + player.sendChat( + "Recipe list generated; see minetweaker.log in your minecraft dir"); + } + } else if (arguments[0].equals("hand") && player != null) { + IItemStack item = player.getCurrentItem(); + if (item != null) { + List recipes = MineTweakerAPI.recipes + .getRecipesFor(item.anyAmount()); + if (recipes.isEmpty()) { + player.sendChat("No crafting recipes found for that item"); + } else { + StringBuilder recipesString = new StringBuilder(); + + for (ICraftingRecipe recipe : recipes) { + MineTweakerAPI.logCommand(recipe.toCommandString()); + player.sendChat(recipe.toCommandString()); + recipesString.append(recipe.toCommandString()).append("\n"); + } + + copyToClipboard(recipesString.toString()); + } + } else { + player.sendChat("No item was found"); + } + } else if (arguments[0].equals("furnace") && player != null) { + if (player != null) { + player.sendChat("Generating furnace list, this could take a while..."); + } + + MineTweakerAPI.logCommand("Furnace Recipes:"); + for (IFurnaceRecipe recipe : furnace.getAll()) { + try { + MineTweakerAPI.logCommand(recipe.toCommandString()); + } catch (Throwable ex) { + MineTweakerAPI.logError("Could not dump furnace recipe", ex); + } + } + + if (player != null) { + player.sendChat( + "Furnace Recipe list generated; see minetweaker.log in your minecraft dir"); + } + } else { + if (player != null) { + player.sendChat("Invalid arguments for recipes command"); + } + } + } + })); + + minetweakerCommands.put( + "inventory", + new MineTweakerCommand( + "inventory", + new String[] { "/minetweaker inventory", " Lists all items in your inventory" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + for (int i = 0; i < player.getInventorySize(); i++) { + IItemStack stack = player.getInventoryStack(i); + if (stack != null) { + player.sendChat(stack.toString()); + } + } + } + })); + + minetweakerCommands.put( + "hand", + new MineTweakerCommand( + "hand", + new String[] { "/minetweaker hand", " Outputs the name of the item in your hand", + " Also copies the name to clipboard and prints", " oredict entries" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + IItemStack hand = player.getCurrentItem(); + if (hand != null) { + String value = hand.toString(); + player.sendChat(value); + copyToClipboard(value); + + List entries = hand.getOres(); + for (IOreDictEntry entry : entries) { + player.sendChat("Is in "); + } + } + } + })); + + minetweakerCommands.put( + "oredict", + new MineTweakerCommand( + "oredict", + new String[] { "/minetweaker oredict", + " Outputs all ore dictionary entries in the game to the minetweaker log", + "/minetweaker oredict ", + " Outputs all items in the given ore dictionary entry to the minetweaker log" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + if (arguments.length > 0) { + String entryName = arguments[0]; + IOreDictEntry entry = MineTweakerAPI.oreDict.get(entryName); + if (entry.isEmpty()) { + player.sendChat("Entry doesn't exist"); + return; + } else { + MineTweakerAPI.logCommand("Ore entries for " + entryName + ":"); + for (IItemStack ore : entry.getItems()) { + MineTweakerAPI.logCommand(" " + ore); + } + } + } else { + for (IOreDictEntry entry : MineTweakerAPI.oreDict.getEntries()) { + if (!entry.isEmpty()) { + MineTweakerAPI + .logCommand("Ore entries for :"); + for (IItemStack ore : entry.getItems()) { + MineTweakerAPI.logCommand(" " + ore); + } + } + } + } + player.sendChat("List generated; see minetweaker.log in your minecraft dir"); + } + })); + + minetweakerCommands.put( + "mods", + new MineTweakerCommand( + "mods", + new String[] { "/minetweaker mods", " Outputs all active mod IDs and versions in the game" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + MineTweakerAPI.logCommand("Mods list:"); + for (IMod mod : MineTweakerAPI.loadedMods) { + String message = mod.getId() + " - " + mod.getName() + " - " + mod.getVersion(); + player.sendChat(message); + MineTweakerAPI.logCommand("Mod: " + message); + } + } + })); + + minetweakerCommands.put( + "name", + new MineTweakerCommand( + "name", + new String[] { "/minetweaker name ", " Outputs the name for the given item ID", }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + if (arguments.length < 1) { + player.sendChat("missing id parameter"); + } else { + try { + int id = Integer.parseInt(arguments[0]); + IItemDefinition definition = platform.getItemDefinition(id); + if (definition == null) { + player.sendChat("no such item"); + } else { + StringBuilder description = new StringBuilder(); + description.append('<'); + description.append(definition.getId()); + description.append('>'); + player.sendChat(description.toString()); + } + } catch (NumberFormatException e) { + MineTweakerAPI.logCommand("ID must be an integer"); + } + } + } + })); + + minetweakerCommands.put( "seeds", - new String[]{ - "/minetweaker seeds", - " Prints all seeds registered", - " for tall grass" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - MineTweakerAPI.logCommand("Seeds:"); - for (WeightedItemStack seed : MineTweakerAPI.vanilla.getSeeds().getSeeds()) { - String message = seed.getStack() + " - " + (int) seed.getChance(); - player.sendChat(message); - MineTweakerAPI.logCommand("Seed: " + message); - } - } - })); + new MineTweakerCommand( + "seeds", + new String[] { "/minetweaker seeds", " Prints all seeds registered", " for tall grass" }, + new ICommandFunction() { - minetweakerCommands.put("loot", new MineTweakerCommand( - "seeds", - new String[]{ - "/minetweaker seeds", - " Prints all seeds registered", - " for tall grass" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - if (arguments.length == 0) { - MineTweakerAPI.logCommand("Loot chest contents:"); - List types = MineTweakerAPI.vanilla.getLoot().getLootTypes(); - Collections.sort(types); - for (String lootType : types) { - MineTweakerAPI.logCommand("Loot type: " + lootType); + @Override + public void execute(String[] arguments, IPlayer player) { + MineTweakerAPI.logCommand("Seeds:"); + for (WeightedItemStack seed : MineTweakerAPI.vanilla.getSeeds().getSeeds()) { + String message = seed.getStack() + " - " + (int) seed.getChance(); + player.sendChat(message); + MineTweakerAPI.logCommand("Seed: " + message); + } + } + })); - List entries = MineTweakerAPI.vanilla.getLoot().getLoot(lootType); - for (LootEntry entry : entries) { - MineTweakerAPI.logCommand(" " + entry.toString()); - } - } + minetweakerCommands.put( + "loot", + new MineTweakerCommand( + "seeds", + new String[] { "/minetweaker seeds", " Prints all seeds registered", " for tall grass" }, + new ICommandFunction() { - player.sendChat("List generated; see minetweaker.log in your minecraft dir"); - } else { - MineTweakerAPI.logCommand("Loot for type: " + arguments[0]); + @Override + public void execute(String[] arguments, IPlayer player) { + if (arguments.length == 0) { + MineTweakerAPI.logCommand("Loot chest contents:"); + List types = MineTweakerAPI.vanilla.getLoot().getLootTypes(); + Collections.sort(types); + for (String lootType : types) { + MineTweakerAPI.logCommand("Loot type: " + lootType); - List entries = MineTweakerAPI.vanilla.getLoot().getLoot(arguments[0]); - for (LootEntry entry : entries) { - MineTweakerAPI.logCommand(" " + entry.toString()); - } + List entries = MineTweakerAPI.vanilla.getLoot().getLoot(lootType); + for (LootEntry entry : entries) { + MineTweakerAPI.logCommand(" " + entry.toString()); + } + } - player.sendChat("List generated; see minetweaker.log in your minecraft dir"); - } - } - })); + player.sendChat("List generated; see minetweaker.log in your minecraft dir"); + } else { + MineTweakerAPI.logCommand("Loot for type: " + arguments[0]); - minetweakerCommands.put("wiki", new MineTweakerCommand( + List entries = MineTweakerAPI.vanilla.getLoot().getLoot(arguments[0]); + for (LootEntry entry : entries) { + MineTweakerAPI.logCommand(" " + entry.toString()); + } + + player.sendChat("List generated; see minetweaker.log in your minecraft dir"); + } + } + })); + + minetweakerCommands.put( "wiki", - new String[]{ - "/minetweaker wiki", - " Opens your browser with the wiki" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - player.openBrowser("http://minetweaker3.powerofbytes.com/wiki/"); - } - })); + new MineTweakerCommand( + "wiki", + new String[] { "/minetweaker wiki", " Opens your browser with the wiki" }, + new ICommandFunction() { - minetweakerCommands.put("bugs", new MineTweakerCommand( + @Override + public void execute(String[] arguments, IPlayer player) { + player.openBrowser("http://minetweaker3.powerofbytes.com/wiki/"); + } + })); + + minetweakerCommands.put( "bugs", - new String[]{ - "/minetweaker bugs", - " Opens your browser with the GitHub bug tracker" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - player.openBrowser("https://github.com/stanhebben/MineTweaker3/issues"); - } - })); + new MineTweakerCommand( + "bugs", + new String[] { "/minetweaker bugs", " Opens your browser with the GitHub bug tracker" }, + new ICommandFunction() { - minetweakerCommands.put("forum", new MineTweakerCommand( + @Override + public void execute(String[] arguments, IPlayer player) { + player.openBrowser("https://github.com/stanhebben/MineTweaker3/issues"); + } + })); + + minetweakerCommands.put( "forum", - new String[]{ - "/minetweaker forum", - " Opens your browser with the forum" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - player.openBrowser("http://minetweaker3.powerofbytes.com/forum"); - } - })); + new MineTweakerCommand( + "forum", + new String[] { "/minetweaker forum", " Opens your browser with the forum" }, + new ICommandFunction() { - minetweakerCommands.put("biomes", new MineTweakerCommand( + @Override + public void execute(String[] arguments, IPlayer player) { + player.openBrowser("http://minetweaker3.powerofbytes.com/forum"); + } + })); + + minetweakerCommands.put( "biomes", - new String[]{ - "/minetweaker biomes", - " Lists all the biomes in the game" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - MineTweakerAPI.logCommand("Biomes:"); + new MineTweakerCommand( + "biomes", + new String[] { "/minetweaker biomes", " Lists all the biomes in the game" }, + new ICommandFunction() { - for (IBiome biome : MineTweakerAPI.game.getBiomes()) { - MineTweakerAPI.logCommand(" " + biome.getName()); - } + @Override + public void execute(String[] arguments, IPlayer player) { + MineTweakerAPI.logCommand("Biomes:"); - player.sendChat("Biome list generated; see minetweaker.log in your minecraft dir"); - } - })); + for (IBiome biome : MineTweakerAPI.game.getBiomes()) { + MineTweakerAPI.logCommand(" " + biome.getName()); + } - minetweakerCommands.put("blockinfo", new MineTweakerCommand( + player.sendChat("Biome list generated; see minetweaker.log in your minecraft dir"); + } + })); + + minetweakerCommands.put( "blockinfo", - new String[]{ - "/minetweaker blockinfo", - " Activates or deactivates block reader. In block info mode,", - " right-click a block to see ID, meta and tile entity data" - }, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - if (blockInfoPlayers.isEmpty()) { - blockEventHandler = events.onPlayerInteract(LISTEN_BLOCK_INFO); - } + new MineTweakerCommand( + "blockinfo", + new String[] { "/minetweaker blockinfo", + " Activates or deactivates block reader. In block info mode,", + " right-click a block to see ID, meta and tile entity data" }, + new ICommandFunction() { - if (blockInfoPlayers.contains(player)) { - blockInfoPlayers.remove(player); - player.sendChat("Block info mode deactivated."); - } else { - blockInfoPlayers.add(player); - player.sendChat("Block info mode activated. Right-click a block to see its data."); - } + @Override + public void execute(String[] arguments, IPlayer player) { + if (blockInfoPlayers.isEmpty()) { + blockEventHandler = events.onPlayerInteract(LISTEN_BLOCK_INFO); + } - if (blockInfoPlayers.isEmpty()) { - blockEventHandler.close(); - } - } - })); + if (blockInfoPlayers.contains(player)) { + blockInfoPlayers.remove(player); + player.sendChat("Block info mode deactivated."); + } else { + blockInfoPlayers.add(player); + player.sendChat("Block info mode activated. Right-click a block to see its data."); + } + + if (blockInfoPlayers.isEmpty()) { + blockEventHandler.close(); + } + } + })); } /** @@ -550,14 +574,8 @@ public class MineTweakerImplementationAPI { * @param formatter formatter interface * @param vanilla vanilla interface */ - public static void init( - IOreDict oreDict, - IRecipeManager recipes, - IFurnaceManager furnace, - IGame game, - ILoadedMods mods, - IFormatter formatter, - IVanilla vanilla) { + public static void init(IOreDict oreDict, IRecipeManager recipes, IFurnaceManager furnace, IGame game, + ILoadedMods mods, IFormatter formatter, IVanilla vanilla) { MineTweakerAPI.oreDict = oreDict; MineTweakerAPI.recipes = recipes; MineTweakerAPI.furnace = furnace; @@ -576,6 +594,7 @@ public class MineTweakerImplementationAPI { public static IEventHandle onRollbackEvent(IEventHandler handler) { return ONROLLBACK.add(handler); } + public static IEventHandle onReloadEvent(IEventHandler handler) { return ONRELOAD.add(handler); } @@ -611,8 +630,7 @@ public class MineTweakerImplementationAPI { } /** - * Called to reload scripts. Must be called after setting a new script - * provider in order to reload scripts. + * Called to reload scripts. Must be called after setting a new script provider in order to reload scripts. */ public static void reload() { blockInfoPlayers.clear(); @@ -624,40 +642,50 @@ public class MineTweakerImplementationAPI { events.onPlayerLoggedIn(LISTEN_LOGIN); events.onPlayerLoggedOut(LISTEN_LOGOUT); } - + MineTweakerAPI.tweaker.rollback(); ONROLLBACK.publish(new ReloadEvent()); - + if (MineTweakerAPI.server != null) { if (!MineTweakerAPI.server.isCommandAdded("minetweaker")) { - server.addCommand("minetweaker", "", new String[]{"mt", "crafttweaker", "ct"}, new ICommandFunction() { - @Override - public void execute(String[] arguments, IPlayer player) { - if (arguments.length == 0) { - player.sendChat("Please provide a command. Use /mt help for more info."); - } else if (arguments[0].equals("help")) { - String[] keys = minetweakerCommands.keySet().toArray(new String[minetweakerCommands.size()]); - Arrays.sort(keys); - for (String key : keys) { - for (String helpMessage : minetweakerCommands.get(key).description) { - player.sendChat(helpMessage); + server.addCommand( + "minetweaker", + "", + new String[] { "mt", "crafttweaker", "ct" }, + new ICommandFunction() { + + @Override + public void execute(String[] arguments, IPlayer player) { + if (arguments.length == 0) { + player.sendChat("Please provide a command. Use /mt help for more info."); + } else if (arguments[0].equals("help")) { + String[] keys = minetweakerCommands.keySet() + .toArray(new String[minetweakerCommands.size()]); + Arrays.sort(keys); + for (String key : keys) { + for (String helpMessage : minetweakerCommands.get(key).description) { + player.sendChat(helpMessage); + } + } + } else { + MineTweakerCommand command = minetweakerCommands.get(arguments[0]); + if (command == null) { + player.sendChat("No such minetweaker command available"); + } else { + command.function + .execute(Arrays.copyOfRange(arguments, 1, arguments.length), player); + } } } - } else { - MineTweakerCommand command = minetweakerCommands.get(arguments[0]); - if (command == null) { - player.sendChat("No such minetweaker command available"); - } else { - command.function.execute(Arrays.copyOfRange(arguments, 1, arguments.length), player); + }, + new ICommandValidator() { + + @Override + public boolean canExecute(IPlayer player) { + return server.isOp(player); } - } - } - }, new ICommandValidator() { - @Override - public boolean canExecute(IPlayer player) { - return server.isOp(player); - } - }, null); + }, + null); } } @@ -674,8 +702,7 @@ public class MineTweakerImplementationAPI { } /** - * Adds a new minetweaker command. Can be called with /mt <command&;gt; - * <arguments>. + * Adds a new minetweaker command. Can be called with /mt <command&;gt; <arguments>. * * @param name command name * @param description description strings @@ -705,12 +732,12 @@ public class MineTweakerImplementationAPI { } - // ###################### // ### Action classes ### // ###################### private static class AddMineTweakerCommandAction implements IUndoableAction { + private final MineTweakerCommand command; public AddMineTweakerCommandAction(MineTweakerCommand command) { @@ -721,8 +748,7 @@ public class MineTweakerImplementationAPI { public void apply() { if (!minetweakerCommands.containsKey(command.name)) { minetweakerCommands.put(command.name, command); - } else { - } + } else {} } @Override @@ -731,8 +757,7 @@ public class MineTweakerImplementationAPI { } @Override - public void undo() { - } + public void undo() {} @Override public String describe() { @@ -758,6 +783,7 @@ public class MineTweakerImplementationAPI { // ############################# private static class MineTweakerCommand { + private final String name; private final String[] description; private final ICommandFunction function; @@ -770,6 +796,7 @@ public class MineTweakerImplementationAPI { } private static class ItemComparator implements Comparator { + @Override public int compare(IItemDefinition o1, IItemDefinition o2) { return o1.getId().compareTo(o2.getId()); @@ -777,6 +804,7 @@ public class MineTweakerImplementationAPI { } private static class LiquidComparator implements Comparator { + @Override public int compare(ILiquidDefinition o1, ILiquidDefinition o2) { return o1.getName().compareTo(o2.getName()); @@ -784,6 +812,7 @@ public class MineTweakerImplementationAPI { } private static class BlockComparator implements Comparator { + @Override public int compare(IBlockDefinition o1, IBlockDefinition o2) { return o1.getId().compareTo(o2.getId()); @@ -791,6 +820,7 @@ public class MineTweakerImplementationAPI { } private static class EntityComparator implements Comparator { + @Override public int compare(IEntityDefinition o1, IEntityDefinition o2) { return o1.getId().compareTo(o2.getId()); @@ -798,6 +828,7 @@ public class MineTweakerImplementationAPI { } private static class ListenPlayerLoggedIn implements IEventHandler { + @Override public void handle(PlayerLoggedInEvent event) { if (MineTweakerAPI.server != null && MineTweakerAPI.server.isOp(event.getPlayer())) { @@ -807,6 +838,7 @@ public class MineTweakerImplementationAPI { } private static class ListenPlayerLoggedOut implements IEventHandler { + @Override public void handle(PlayerLoggedOutEvent event) { logger.removePlayer(event.getPlayer()); @@ -814,6 +846,7 @@ public class MineTweakerImplementationAPI { } private static class ListenBlockInfo implements IEventHandler { + @Override public void handle(PlayerInteractEvent event) { if (blockInfoPlayers.contains(event.getPlayer())) { diff --git a/src/main/java/minetweaker/OneWayAction.java b/src/main/java/minetweaker/OneWayAction.java index d10a30b..00c7f98 100644 --- a/src/main/java/minetweaker/OneWayAction.java +++ b/src/main/java/minetweaker/OneWayAction.java @@ -6,17 +6,17 @@ package minetweaker; * @author Stan Hebben */ public abstract class OneWayAction implements IUndoableAction { - @Override - public boolean canUndo() { - return false; - } - @Override - public void undo() { - } + @Override + public boolean canUndo() { + return false; + } - @Override - public String describeUndo() { - return "impossibru!"; - } + @Override + public void undo() {} + + @Override + public String describeUndo() { + return "impossibru!"; + } } diff --git a/src/main/java/minetweaker/annotations/BracketHandler.java b/src/main/java/minetweaker/annotations/BracketHandler.java index 5c1ddfb..430bd11 100644 --- a/src/main/java/minetweaker/annotations/BracketHandler.java +++ b/src/main/java/minetweaker/annotations/BracketHandler.java @@ -6,20 +6,20 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Marks a bracket handler. Bracket handlers are automatically registered. The - * marked class should have an empty constructor. + * Marks a bracket handler. Bracket handlers are automatically registered. The marked class should have an empty + * constructor. * * @author Stan Hebben */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE }) public @interface BracketHandler { - /** - * Indicates priority. A lower value means a higher priority. Only change if - * you have issues, default value is 10. Internal minetweaker handlers have - * priorities up to 100. - * - * @return - */ - public int priority() default 10; + + /** + * Indicates priority. A lower value means a higher priority. Only change if you have issues, default value is 10. + * Internal minetweaker handlers have priorities up to 100. + * + * @return + */ + public int priority() default 10; } diff --git a/src/main/java/minetweaker/annotations/ModOnly.java b/src/main/java/minetweaker/annotations/ModOnly.java index 8d0494c..7e0f86c 100644 --- a/src/main/java/minetweaker/annotations/ModOnly.java +++ b/src/main/java/minetweaker/annotations/ModOnly.java @@ -6,15 +6,15 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Indicates that a certain class is only available when a specific mod is - * available. Multiple mods can be specified. + * Indicates that a certain class is only available when a specific mod is available. Multiple mods can be specified. * * @author Stan Hebben */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface ModOnly { - public String[] value(); - public String version() default ""; + public String[] value(); + + public String version() default ""; } diff --git a/src/main/java/minetweaker/annotations/OnRegister.java b/src/main/java/minetweaker/annotations/OnRegister.java index 45c591b..78edd88 100644 --- a/src/main/java/minetweaker/annotations/OnRegister.java +++ b/src/main/java/minetweaker/annotations/OnRegister.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.annotations; diff --git a/src/main/java/minetweaker/api/block/BlockPatternOr.java b/src/main/java/minetweaker/api/block/BlockPatternOr.java index 1d97e6f..a56c328 100644 --- a/src/main/java/minetweaker/api/block/BlockPatternOr.java +++ b/src/main/java/minetweaker/api/block/BlockPatternOr.java @@ -1,9 +1,9 @@ package minetweaker.api.block; -import minetweaker.util.ArrayUtil; - import java.util.*; +import minetweaker.util.ArrayUtil; + /** * @author Stan */ @@ -16,13 +16,13 @@ public class BlockPatternOr implements IBlockPattern { } public BlockPatternOr(IBlockPattern a, IBlockPattern b) { - this.elements = new IBlockPattern[]{a, b}; + this.elements = new IBlockPattern[] { a, b }; } @Override public List getBlocks() { List blocks = new ArrayList<>(); - for(IBlockPattern pattern : elements) { + for (IBlockPattern pattern : elements) { blocks.addAll(pattern.getBlocks()); } return blocks; @@ -30,9 +30,8 @@ public class BlockPatternOr implements IBlockPattern { @Override public boolean matches(IBlock block) { - for(IBlockPattern pattern : elements) { - if(pattern.matches(block)) - return true; + for (IBlockPattern pattern : elements) { + if (pattern.matches(block)) return true; } return false; @@ -42,8 +41,8 @@ public class BlockPatternOr implements IBlockPattern { public String getDisplayName() { StringBuilder result = new StringBuilder(); boolean first = true; - for(IBlockPattern pattern : elements) { - if(first) { + for (IBlockPattern pattern : elements) { + if (first) { first = false; } else { result.append(" | "); diff --git a/src/main/java/minetweaker/api/block/IBlockPattern.java b/src/main/java/minetweaker/api/block/IBlockPattern.java index 54f89dc..30088b4 100644 --- a/src/main/java/minetweaker/api/block/IBlockPattern.java +++ b/src/main/java/minetweaker/api/block/IBlockPattern.java @@ -1,9 +1,9 @@ package minetweaker.api.block; -import stanhebben.zenscript.annotations.*; - import java.util.List; +import stanhebben.zenscript.annotations.*; + /** * @author Stan */ diff --git a/src/main/java/minetweaker/api/chat/IChatMessage.java b/src/main/java/minetweaker/api/chat/IChatMessage.java index 77d8495..cf05180 100644 --- a/src/main/java/minetweaker/api/chat/IChatMessage.java +++ b/src/main/java/minetweaker/api/chat/IChatMessage.java @@ -3,14 +3,14 @@ package minetweaker.api.chat; import stanhebben.zenscript.annotations.*; /** - * Represents a chat message. Strings can be converted into chat messages, and - * chat messages can be colored and concatenated. + * Represents a chat message. Strings can be converted into chat messages, and chat messages can be colored and + * concatenated. * * @author Stan Hebben */ @ZenClass("minetweaker.chat.IChatMessage") public interface IChatMessage { - + /** * Concatenates two chat messages. * @@ -20,10 +20,9 @@ public interface IChatMessage { */ @ZenOperator(OperatorType.ADD) IChatMessage add(IChatMessage other); - + /** - * Retrieves the internal object backing this object. Must be generated by - * the implementing platform. + * Retrieves the internal object backing this object. Must be generated by the implementing platform. * * @return internal object */ diff --git a/src/main/java/minetweaker/api/client/IClient.java b/src/main/java/minetweaker/api/client/IClient.java index a5c87fe..e6d7e36 100644 --- a/src/main/java/minetweaker/api/client/IClient.java +++ b/src/main/java/minetweaker/api/client/IClient.java @@ -10,7 +10,7 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.api.IClient") public interface IClient { - + /** * Gets the current player. * @@ -18,7 +18,7 @@ public interface IClient { */ @ZenGetter("player") IPlayer getPlayer(); - + @ZenGetter("language") String getLanguage(); } diff --git a/src/main/java/minetweaker/api/compat/DummyJEIRecipeRegistry.java b/src/main/java/minetweaker/api/compat/DummyJEIRecipeRegistry.java index 14d7add..60bc333 100644 --- a/src/main/java/minetweaker/api/compat/DummyJEIRecipeRegistry.java +++ b/src/main/java/minetweaker/api/compat/DummyJEIRecipeRegistry.java @@ -1,45 +1,41 @@ package minetweaker.api.compat; -import minetweaker.api.item.IIngredient; - import java.util.*; +import minetweaker.api.item.IIngredient; + public class DummyJEIRecipeRegistry implements IJEIRecipeRegistry { - + @Override - public void addRecipe(Object object) { - } - + public void addRecipe(Object object) {} + @Override public void addRecipe(Object object, String category) { - + } - + @Override - public void removeRecipe(Object object) { - } - + public void removeRecipe(Object object) {} + @Override public void removeRecipe(Object output, String category) { - + } - + @Override - public void addFurnace(List inputs, Object output) { - } - + public void addFurnace(List inputs, Object output) {} + @Override - public void removeFurnace(Object object) { - } - + public void removeFurnace(Object object) {} + @Override public void addFuel(Collection input, int burnTime) { - + } - + @Override public void removeFuel(Object object) { - + } @Override diff --git a/src/main/java/minetweaker/api/compat/IJEIRecipeRegistry.java b/src/main/java/minetweaker/api/compat/IJEIRecipeRegistry.java index a26ae63..9d468d5 100644 --- a/src/main/java/minetweaker/api/compat/IJEIRecipeRegistry.java +++ b/src/main/java/minetweaker/api/compat/IJEIRecipeRegistry.java @@ -1,34 +1,33 @@ package minetweaker.api.compat; -import minetweaker.api.item.IIngredient; - import java.util.*; +import minetweaker.api.item.IIngredient; + public interface IJEIRecipeRegistry { - + void addRecipe(Object object); - + void addRecipe(Object object, String category); - + void removeRecipe(Object output); - + void removeRecipe(Object output, String category); - - + void addFurnace(List inputs, Object output); - + void removeFurnace(Object output); - + void addFuel(Collection input, int burnTime); - + void removeFuel(Object object); void invalidateTooltips(IIngredient ingredient); - //To update the items in 1.10.2 + // To update the items in 1.10.2 void reloadItemList(); - //To update the items in 1.11.2 both below are used + // To update the items in 1.11.2 both below are used void removeItem(Object stack); void addItem(Object stack); diff --git a/src/main/java/minetweaker/api/container/IContainer.java b/src/main/java/minetweaker/api/container/IContainer.java index fcc49af..dcd6231 100644 --- a/src/main/java/minetweaker/api/container/IContainer.java +++ b/src/main/java/minetweaker/api/container/IContainer.java @@ -20,8 +20,7 @@ public interface IContainer extends Iterable { int getContainerSize(); /** - * Gets the item stack at the given position. Returns null if there is no - * stack at that position. + * Gets the item stack at the given position. Returns null if there is no stack at that position. * * @param i stack position * diff --git a/src/main/java/minetweaker/api/data/DataByteArray.java b/src/main/java/minetweaker/api/data/DataByteArray.java index 20435c0..229979f 100644 --- a/src/main/java/minetweaker/api/data/DataByteArray.java +++ b/src/main/java/minetweaker/api/data/DataByteArray.java @@ -110,11 +110,9 @@ public class DataByteArray implements IData { StringBuilder result = new StringBuilder(); result.append("["); boolean first = true; - for(byte value : data) { - if(first) - first = false; - else - result.append(", "); + for (byte value : data) { + if (first) first = false; + else result.append(", "); result.append(value); } @@ -125,7 +123,7 @@ public class DataByteArray implements IData { @Override public List asList() { List result = new ArrayList(); - for(byte value : data) { + for (byte value : data) { result.add(new DataByte(value)); } return result; @@ -144,7 +142,7 @@ public class DataByteArray implements IData { @Override public int[] asIntArray() { int[] result = new int[data.length]; - for(int i = 0; i < result.length; i++) { + for (int i = 0; i < result.length; i++) { result[i] = data[i]; } return result; @@ -157,7 +155,7 @@ public class DataByteArray implements IData { @Override public void setAt(int i, IData value) { - if(immutable) { + if (immutable) { throw new UnsupportedOperationException("Cannot modify this byte array"); } else { data[i] = value.asByte(); @@ -196,7 +194,7 @@ public class DataByteArray implements IData { @Override public IData immutable() { - if(immutable) { + if (immutable) { return this; } else { return new DataByteArray(Arrays.copyOf(this.data, this.data.length), true); diff --git a/src/main/java/minetweaker/api/data/DataIntArray.java b/src/main/java/minetweaker/api/data/DataIntArray.java index 257f3a7..0b489cb 100644 --- a/src/main/java/minetweaker/api/data/DataIntArray.java +++ b/src/main/java/minetweaker/api/data/DataIntArray.java @@ -110,8 +110,8 @@ public class DataIntArray implements IData { StringBuilder result = new StringBuilder(); result.append('['); boolean first = true; - for(int value : data) { - if(first) { + for (int value : data) { + if (first) { first = false; } else { result.append(", "); @@ -125,7 +125,7 @@ public class DataIntArray implements IData { @Override public List asList() { List result = new ArrayList<>(); - for(int value : data) { + for (int value : data) { result.add(new DataInt(value)); } return result; @@ -139,7 +139,7 @@ public class DataIntArray implements IData { @Override public byte[] asByteArray() { byte[] result = new byte[data.length]; - for(int i = 0; i < result.length; i++) { + for (int i = 0; i < result.length; i++) { result[i] = (byte) data[i]; } return result; @@ -157,7 +157,7 @@ public class DataIntArray implements IData { @Override public void setAt(int i, IData value) { - if(immutable) { + if (immutable) { throw new UnsupportedOperationException("Cannot modify this byte array"); } else { data[i] = value.asInt(); @@ -196,7 +196,7 @@ public class DataIntArray implements IData { @Override public IData immutable() { - if(immutable) { + if (immutable) { return this; } else { return new DataIntArray(Arrays.copyOf(this.data, this.data.length), true); diff --git a/src/main/java/minetweaker/api/data/DataList.java b/src/main/java/minetweaker/api/data/DataList.java index 8b48c28..55b93d3 100644 --- a/src/main/java/minetweaker/api/data/DataList.java +++ b/src/main/java/minetweaker/api/data/DataList.java @@ -54,7 +54,7 @@ public class DataList implements IData { @Override public List asList() { - if(immutable) { + if (immutable) { return Collections.unmodifiableList(values); } else { return values; @@ -71,8 +71,8 @@ public class DataList implements IData { StringBuilder output = new StringBuilder(); output.append('['); boolean first = true; - for(IData value : values) { - if(first) { + for (IData value : values) { + if (first) { first = false; } else { output.append(", "); @@ -87,11 +87,11 @@ public class DataList implements IData { public byte[] asByteArray() { try { byte[] result = new byte[values.size()]; - for(int i = 0; i < values.size(); i++) { + for (int i = 0; i < values.size(); i++) { result[i] = values.get(i).asByte(); } return result; - } catch(IllegalDataException ex) { + } catch (IllegalDataException ex) { return null; } } @@ -100,11 +100,11 @@ public class DataList implements IData { public int[] asIntArray() { try { int[] result = new int[values.size()]; - for(int i = 0; i < values.size(); i++) { + for (int i = 0; i < values.size(); i++) { result[i] = values.get(i).asInt(); } return result; - } catch(IllegalDataException ex) { + } catch (IllegalDataException ex) { return null; } } @@ -116,7 +116,7 @@ public class DataList implements IData { @Override public void setAt(int i, IData value) { - if(immutable) { + if (immutable) { throw new UnsupportedOperationException("this list is immutable"); } else { values.set(i, value); @@ -141,23 +141,19 @@ public class DataList implements IData { @Override public boolean contains(IData data) { List dataValues = data.asList(); - if(dataValues != null && containsList(dataValues)) - return true; + if (dataValues != null && containsList(dataValues)) return true; - for(IData value : values) { - if(value.contains(data)) - return true; + for (IData value : values) { + if (value.contains(data)) return true; } return false; } private boolean containsList(List dataValues) { - outer: - for(IData dataValue : dataValues) { - for(IData value : values) { - if(value.contains(dataValue)) - continue outer; + outer: for (IData dataValue : dataValues) { + for (IData value : values) { + if (value.contains(dataValue)) continue outer; } return false; @@ -169,12 +165,10 @@ public class DataList implements IData { @Override public boolean equals(IData data) { List otherValues = data.asList(); - if(otherValues.size() != values.size()) - return false; + if (otherValues.size() != values.size()) return false; - for(int i = 0; i < values.size(); i++) { - if(!values.get(i).equals(otherValues.get(i))) - return false; + for (int i = 0; i < values.size(); i++) { + if (!values.get(i).equals(otherValues.get(i))) return false; } return true; @@ -187,11 +181,11 @@ public class DataList implements IData { @Override public IData immutable() { - if(immutable) { + if (immutable) { return this; } else { List copy = new ArrayList<>(); - for(IData value : values) { + for (IData value : values) { copy.add(value.immutable()); } return new DataList(copy, true); @@ -200,8 +194,7 @@ public class DataList implements IData { @Override public IData update(IData data) { - if(immutable) - data = data.immutable(); + if (immutable) data = data.immutable(); List result = new ArrayList<>(); result.addAll(values); diff --git a/src/main/java/minetweaker/api/data/DataMap.java b/src/main/java/minetweaker/api/data/DataMap.java index 37be7c5..137d3fd 100644 --- a/src/main/java/minetweaker/api/data/DataMap.java +++ b/src/main/java/minetweaker/api/data/DataMap.java @@ -24,10 +24,10 @@ public class DataMap implements IData { Map result = new HashMap<>(); Map otherMap = other.asMap(); - for(Map.Entry entry : data.entrySet()) { + for (Map.Entry entry : data.entrySet()) { result.put(entry.getKey(), entry.getValue()); } - for(Map.Entry entry : otherMap.entrySet()) { + for (Map.Entry entry : otherMap.entrySet()) { result.put(entry.getKey(), entry.getValue()); } @@ -39,10 +39,10 @@ public class DataMap implements IData { Map result = new HashMap<>(); Map otherMap = other.asMap(); - for(Map.Entry entry : data.entrySet()) { + for (Map.Entry entry : data.entrySet()) { result.put(entry.getKey(), entry.getValue()); } - for(String key : otherMap.keySet()) { + for (String key : otherMap.keySet()) { result.remove(key); } @@ -129,14 +129,14 @@ public class DataMap implements IData { StringBuilder result = new StringBuilder(); result.append('{'); boolean first = true; - for(Map.Entry entry : data.entrySet()) { - if(first) { + for (Map.Entry entry : data.entrySet()) { + if (first) { first = false; } else { result.append(", "); } - if(isValidIdentifier(entry.getKey())) { + if (isValidIdentifier(entry.getKey())) { result.append(entry.getKey()); } else { result.append("\"").append(entry.getKey()).append("\""); @@ -156,7 +156,7 @@ public class DataMap implements IData { @Override public Map asMap() { - if(immutable) { + if (immutable) { return Collections.unmodifiableMap(data); } else { return data; @@ -190,7 +190,7 @@ public class DataMap implements IData { @Override public void memberSet(String name, IData data) { - if(immutable) { + if (immutable) { throw new UnsupportedOperationException("this map is not modifiable"); } else { this.data.put(name, data); @@ -204,18 +204,17 @@ public class DataMap implements IData { @Override public boolean contains(IData data) { - if(data instanceof DataString) { + if (data instanceof DataString) { return this.data.containsKey(data.asString()); } Map dataMap = data.asMap(); - if(dataMap == null) - return false; + if (dataMap == null) return false; - for(Map.Entry dataEntry : dataMap.entrySet()) { - if(!this.data.containsKey(dataEntry.getKey())) { + for (Map.Entry dataEntry : dataMap.entrySet()) { + if (!this.data.containsKey(dataEntry.getKey())) { return false; - } else if(!this.data.get(dataEntry.getKey()).contains(dataEntry.getValue())) { + } else if (!this.data.get(dataEntry.getKey()).contains(dataEntry.getValue())) { return false; } } @@ -230,17 +229,15 @@ public class DataMap implements IData { @Override public boolean equals(IData data) { - if(this == data) - return true; + if (this == data) return true; Map dataMap = data.asMap(); - if(dataMap.size() != this.data.size()) - return false; + if (dataMap.size() != this.data.size()) return false; - for(Map.Entry dataEntry : this.data.entrySet()) { - if(!dataMap.containsKey(dataEntry.getKey())) { + for (Map.Entry dataEntry : this.data.entrySet()) { + if (!dataMap.containsKey(dataEntry.getKey())) { return false; - } else if(!dataMap.get(dataEntry.getKey()).equals(dataEntry.getValue())) { + } else if (!dataMap.get(dataEntry.getKey()).equals(dataEntry.getValue())) { return false; } } @@ -250,11 +247,11 @@ public class DataMap implements IData { @Override public IData immutable() { - if(immutable) { + if (immutable) { return this; } else { Map result = new HashMap<>(); - for(Map.Entry entry : this.data.entrySet()) { + for (Map.Entry entry : this.data.entrySet()) { result.put(entry.getKey(), entry.getValue().immutable()); } return new DataMap(result, true); @@ -263,14 +260,13 @@ public class DataMap implements IData { @Override public IData update(IData data) { - if(immutable) - data = data.immutable(); + if (immutable) data = data.immutable(); Map result = new HashMap<>(); - for(Map.Entry entry : this.data.entrySet()) { + for (Map.Entry entry : this.data.entrySet()) { result.put(entry.getKey(), entry.getValue()); } - for(Map.Entry entry : data.asMap().entrySet()) { + for (Map.Entry entry : data.asMap().entrySet()) { result.put(entry.getKey(), entry.getValue()); } return new DataMap(result, immutable); @@ -287,12 +283,10 @@ public class DataMap implements IData { } private boolean isValidIdentifier(String str) { - if(!Character.isJavaIdentifierStart(str.charAt(0))) - return false; + if (!Character.isJavaIdentifierStart(str.charAt(0))) return false; - for(int i = 1; i < str.length(); i++) { - if(!Character.isJavaIdentifierPart(str.charAt(i))) - return false; + for (int i = 1; i < str.length(); i++) { + if (!Character.isJavaIdentifierPart(str.charAt(i))) return false; } return true; diff --git a/src/main/java/minetweaker/api/data/DataString.java b/src/main/java/minetweaker/api/data/DataString.java index e89afbb..2cc8372 100644 --- a/src/main/java/minetweaker/api/data/DataString.java +++ b/src/main/java/minetweaker/api/data/DataString.java @@ -87,7 +87,7 @@ public class DataString implements IData { @Override public IData memberGet(String name) { - if(name.equals("length")) { + if (name.equals("length")) { return new DataInt(value.length()); } else { throw new UnsupportedOperationException("no such member: " + name); diff --git a/src/main/java/minetweaker/api/data/IData.java b/src/main/java/minetweaker/api/data/IData.java index a357e5b..9045377 100644 --- a/src/main/java/minetweaker/api/data/IData.java +++ b/src/main/java/minetweaker/api/data/IData.java @@ -1,13 +1,12 @@ package minetweaker.api.data; -import stanhebben.zenscript.annotations.*; - import java.util.*; +import stanhebben.zenscript.annotations.*; + /** - * Generic data interface. A data element may contain any kind of basic data - * element (bool, byte, short, int, long, float, double, string, list, map, int - * array or byte array). Used to store data with stacks, blocks, world, ... + * Generic data interface. A data element may contain any kind of basic data element (bool, byte, short, int, long, + * float, double, string, list, map, int array or byte array). Used to store data with stacks, blocks, world, ... * * @author Stan Hebben */ @@ -69,8 +68,7 @@ public interface IData { String asString(); /** - * Attempts to convert this value to a List. Returns null if this value - * cannot be converted to a list. + * Attempts to convert this value to a List. Returns null if this value cannot be converted to a list. * * @return list data of this value, if any */ @@ -78,8 +76,7 @@ public interface IData { List asList(); /** - * Attempts to convert this value to a Map. Returns null if this value - * cannot be converted to a map. + * Attempts to convert this value to a Map. Returns null if this value cannot be converted to a map. * * @return map data of this value, if any */ @@ -87,8 +84,7 @@ public interface IData { Map asMap(); /** - * Attempts to convert this value to a byte array. Returns null if this - * value cannot be converted to a byte array. + * Attempts to convert this value to a byte array. Returns null if this value cannot be converted to a byte array. * * @return byte array data of this value, if any */ @@ -96,8 +92,7 @@ public interface IData { byte[] asByteArray(); /** - * Attempts to convert this value to an int array. Returns null if this - * value cannot be converted to an int array. + * Attempts to convert this value to an int array. Returns null if this value cannot be converted to an int array. * * @return int array data of this value, if any */ diff --git a/src/main/java/minetweaker/api/data/IllegalDataException.java b/src/main/java/minetweaker/api/data/IllegalDataException.java index 02266ef..951a8af 100644 --- a/src/main/java/minetweaker/api/data/IllegalDataException.java +++ b/src/main/java/minetweaker/api/data/IllegalDataException.java @@ -1,7 +1,6 @@ /* - * This file is part of MineTweaker API, licensed under the MIT License (MIT). - * - * Copyright (c) 2014 MineTweaker + * This file is part of MineTweaker API, licensed under the MIT License (MIT). Copyright (c) 2014 MineTweaker + * */ package minetweaker.api.data; diff --git a/src/main/java/minetweaker/api/entity/IEntity.java b/src/main/java/minetweaker/api/entity/IEntity.java index 8e7c09c..9818e62 100644 --- a/src/main/java/minetweaker/api/entity/IEntity.java +++ b/src/main/java/minetweaker/api/entity/IEntity.java @@ -5,9 +5,8 @@ import minetweaker.api.world.IDimension; import stanhebben.zenscript.annotations.*; /** - * Entity interface. Used to obtain information about entities, and modify their - * data. Entities are any item that is freely movable in the world, such as - * players, monsters, items on the ground, ... + * Entity interface. Used to obtain information about entities, and modify their data. Entities are any item that is + * freely movable in the world, such as players, monsters, items on the ground, ... * * @author Stan Hebben */ @@ -55,8 +54,7 @@ public interface IEntity { Position3f getPosition(); /** - * Sets the position of this entity. Instantly moves (teleports) the entity - * to that position. + * Sets the position of this entity. Instantly moves (teleports) the entity to that position. * * @param position entity position */ diff --git a/src/main/java/minetweaker/api/entity/IEntityDefinition.java b/src/main/java/minetweaker/api/entity/IEntityDefinition.java index ded388c..627eecc 100644 --- a/src/main/java/minetweaker/api/entity/IEntityDefinition.java +++ b/src/main/java/minetweaker/api/entity/IEntityDefinition.java @@ -1,38 +1,37 @@ package minetweaker.api.entity; -import minetweaker.api.item.IItemStack; -import stanhebben.zenscript.annotations.Optional; -import stanhebben.zenscript.annotations.*; -import stanhebben.zenscript.value.*; - import java.util.*; +import minetweaker.api.item.IItemStack; +import stanhebben.zenscript.annotations.*; +import stanhebben.zenscript.annotations.Optional; +import stanhebben.zenscript.value.*; /** * @author Stan Hebben */ @ZenClass("minetweaker.entity.IEntityDefinition") public interface IEntityDefinition { - + @ZenGetter("id") String getId(); - + @ZenGetter("name") String getName(); - + @ZenMethod void addDrop(IItemStack stack, @Optional int min, @Optional int max); - + @ZenMethod void addPlayerOnlyDrop(IItemStack stack, @Optional int min, @Optional int max); - + @ZenMethod void removeDrop(IItemStack stack); - + Map getDropsToAdd(); - + Map getDropsToAddPlayerOnly(); - + List getDropsToRemove(); - + } diff --git a/src/main/java/minetweaker/api/entity/IEntityItem.java b/src/main/java/minetweaker/api/entity/IEntityItem.java index 5617528..97b1665 100644 --- a/src/main/java/minetweaker/api/entity/IEntityItem.java +++ b/src/main/java/minetweaker/api/entity/IEntityItem.java @@ -4,8 +4,8 @@ import minetweaker.api.item.IItemStack; import stanhebben.zenscript.annotations.ZenGetter; /** - * Represents an item entity. Item entities are entities representing an item - * stack on the ground (or flying through the air). + * Represents an item entity. Item entities are entities representing an item stack on the ground (or flying through the + * air). * * @author Stan Hebben */ diff --git a/src/main/java/minetweaker/api/event/IEventHandle.java b/src/main/java/minetweaker/api/event/IEventHandle.java index a1c9460..0fa2fda 100644 --- a/src/main/java/minetweaker/api/event/IEventHandle.java +++ b/src/main/java/minetweaker/api/event/IEventHandle.java @@ -1,9 +1,9 @@ package minetweaker.api.event; -import stanhebben.zenscript.annotations.*; - import java.io.Closeable; +import stanhebben.zenscript.annotations.*; + /** * Represents an event handle. Event handles are used to cancel event listeners. * diff --git a/src/main/java/minetweaker/api/event/IEventManager.java b/src/main/java/minetweaker/api/event/IEventManager.java index f10f47a..4d83895 100644 --- a/src/main/java/minetweaker/api/event/IEventManager.java +++ b/src/main/java/minetweaker/api/event/IEventManager.java @@ -10,88 +10,58 @@ import minetweaker.util.IEventHandler; * @author Stan */ public interface IEventManager { - + // implemented IEventHandle onPlayerCrafted(IEventHandler ev); - + // implemented IEventHandle onPlayerSmelted(IEventHandler ev); - + IEventHandle onPlayerChangedDimension(IEventHandler ev); - + IEventHandle onPlayerRespawn(IEventHandler ev); - + IEventHandle onPlayerAttackEntity(IEventHandler ev); - + IEventHandle onPlayerBonemeal(IEventHandler ev); - + IEventHandle onPlayerInteractEntity(IEventHandler ev); - + IEventHandle onPlayerPickup(IEventHandler ev); - + IEventHandle onPlayerPickupItem(IEventHandler ev); - + IEventHandle onPlayerFillBucket(IEventHandler ev); - + IEventHandle onPlayerDeathDrops(IEventHandler ev); - + IEventHandle onPlayerInteract(IEventHandler ev); - + IEventHandle onPlayerOpenContainer(IEventHandler ev); - + IEventHandle onPlayerPickupXp(IEventHandler ev); - + IEventHandle onPlayerSleepInBed(IEventHandler ev); - + IEventHandle onPlayerUseHoe(IEventHandler ev); - + IEventHandle onPlayerUseItemStart(IEventHandler ev); - + IEventHandle onPlayerUseItemTick(IEventHandler ev); - /* - * IEventHandle - * onPlayerUseItemStop(IEventHandler ev); - * - * IEventHandle - * onPlayerUseItemFinish(IPlayerUserItemFinishEventHandler ev); - * - * IEventHandle onPlayerChat(IPlayerChatEventHandler ev); - * - * IEventHandle onTimerSingle(int millis, ITimerEventHandler ev); - * - * IEventHandle onTimerRepeat(int millis, ITimerEventHandler ev); - * - * IEventHandle onEntityJoinWorld(IEntityJoinWorldEventHandler ev); - * - * IEventHandle - * onEntityStruckByLightning(IEntityStruckByLightningEventHandler ev); - * - * IEventHandle - * onLivingEnderTeleport(ILivingEnderTeleportEventHandler ev); - * - * IEventHandle onLivingAttackEvent(ILivingAttackEventHandler ev); - * - * IEventHandle onLivingDeathEvent(ILivingDeathEventHandler ev); - * - * IEventHandle onLivingJumpEvent(ILivingJumpEventHandler ev); - * - * IEventHandle onLivingFallEvent(ILivingFallEventHandler ev); - * - * IEventHandle onLivingHurtEvent(ILivingHurtEventHandler ev); - * - * IEventHandle onLivingDeathDropsEvent(ILivingDeathDropsEventHandler - * ev); - * - * IEventHandle onItemTossed(IItemTossedEventHandler ev); - * - * IEventHandle onItemExpired(IItemExpiredEventHandler ev); - * - * IEventHandle onMinecartCollision(IMinecartCollisionEventHandler - * ev); - * - * IEventHandle onMinecartInteract(IMinecartInteractEventHandler ev); - * - * IEventHandle onCommand(ICommandEventHandler ev); - */ + /* + * IEventHandle onPlayerUseItemStop(IEventHandler ev); IEventHandle + * onPlayerUseItemFinish(IPlayerUserItemFinishEventHandler ev); IEventHandle onPlayerChat(IPlayerChatEventHandler + * ev); IEventHandle onTimerSingle(int millis, ITimerEventHandler ev); IEventHandle onTimerRepeat(int millis, + * ITimerEventHandler ev); IEventHandle onEntityJoinWorld(IEntityJoinWorldEventHandler ev); IEventHandle + * onEntityStruckByLightning(IEntityStruckByLightningEventHandler ev); IEventHandle + * onLivingEnderTeleport(ILivingEnderTeleportEventHandler ev); IEventHandle + * onLivingAttackEvent(ILivingAttackEventHandler ev); IEventHandle onLivingDeathEvent(ILivingDeathEventHandler ev); + * IEventHandle onLivingJumpEvent(ILivingJumpEventHandler ev); IEventHandle + * onLivingFallEvent(ILivingFallEventHandler ev); IEventHandle onLivingHurtEvent(ILivingHurtEventHandler ev); + * IEventHandle onLivingDeathDropsEvent(ILivingDeathDropsEventHandler ev); IEventHandle + * onItemTossed(IItemTossedEventHandler ev); IEventHandle onItemExpired(IItemExpiredEventHandler ev); IEventHandle + * onMinecartCollision(IMinecartCollisionEventHandler ev); IEventHandle + * onMinecartInteract(IMinecartInteractEventHandler ev); IEventHandle onCommand(ICommandEventHandler ev); + */ } diff --git a/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java b/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java index ca36965..a4c59f0 100644 --- a/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java +++ b/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java @@ -1,12 +1,12 @@ package minetweaker.api.event; +import java.util.List; + import minetweaker.api.damage.IDamageSource; import minetweaker.api.entity.IEntityItem; import minetweaker.api.player.IPlayer; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** * @author Stan */ diff --git a/src/main/java/minetweaker/api/event/PlayerInteractEvent.java b/src/main/java/minetweaker/api/event/PlayerInteractEvent.java index c1a83d0..15cd6dc 100644 --- a/src/main/java/minetweaker/api/event/PlayerInteractEvent.java +++ b/src/main/java/minetweaker/api/event/PlayerInteractEvent.java @@ -10,89 +10,89 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.event.PlayerInteractEvent") public class PlayerInteractEvent { - + private final IPlayer player; private final IBlockGroup blocks; private final int x; private final int y; private final int z; - + private boolean canceled; private boolean useBlock; private boolean useItem; - + public PlayerInteractEvent(IPlayer player, IBlockGroup blocks, int x, int y, int z) { this.player = player; this.blocks = blocks; this.x = x; this.y = y; this.z = z; - + canceled = false; useBlock = false; useItem = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenMethod public void useBlock() { useBlock = true; } - + @ZenMethod public void useItem() { useItem = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("usingBlock") public boolean isUsingBlock() { return useBlock; } - + @ZenGetter("usingItem") public boolean isUsingItem() { return useItem; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("blocks") public IBlockGroup getBlocks() { return blocks; } - + @ZenGetter("x") public int getX() { return x; } - + @ZenGetter("y") public int getY() { return y; } - + @ZenGetter("z") public int getZ() { return z; } - + @ZenGetter("block") public IBlock getBlock() { return blocks.getBlock(x, y, z); } - + @ZenGetter("dimension") public IDimension getDimension() { return blocks.getDimension(); diff --git a/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java b/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java index 5251eeb..f344c26 100644 --- a/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java +++ b/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java @@ -8,13 +8,13 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.event.PlayerLoggedInEvent") public class PlayerLoggedInEvent { - + private final IPlayer player; - + public PlayerLoggedInEvent(IPlayer player) { this.player = player; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; diff --git a/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java b/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java index 8d0f479..dc24ec8 100644 --- a/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java +++ b/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java @@ -8,13 +8,13 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.event.PlayerLoggedOutEvent") public class PlayerLoggedOutEvent { - + private final IPlayer player; - + public PlayerLoggedOutEvent(IPlayer player) { this.player = player; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; diff --git a/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java b/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java index ab9b25b..cf7ef2d 100644 --- a/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java +++ b/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java @@ -9,33 +9,33 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.event.PlayerOpenContainerEvent") public class PlayerOpenContainerEvent { - + private final IPlayer player; private final IContainer container; private boolean canceled; - + public PlayerOpenContainerEvent(IPlayer player, IContainer container) { this.player = player; this.container = container; - + canceled = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("container") public IContainer getContainer() { return container; diff --git a/src/main/java/minetweaker/api/formatting/IFormatter.java b/src/main/java/minetweaker/api/formatting/IFormatter.java index 8bc064d..e285312 100644 --- a/src/main/java/minetweaker/api/formatting/IFormatter.java +++ b/src/main/java/minetweaker/api/formatting/IFormatter.java @@ -6,69 +6,69 @@ import stanhebben.zenscript.annotations.ZenMethod; * @author Stan */ public interface IFormatter { - + IFormattedText string(String text); - + @ZenMethod IFormattedText black(IFormattedText text); - + @ZenMethod IFormattedText darkBlue(IFormattedText text); - + @ZenMethod IFormattedText darkGreen(IFormattedText text); - + @ZenMethod IFormattedText darkAqua(IFormattedText text); - + @ZenMethod IFormattedText darkRed(IFormattedText text); - + @ZenMethod IFormattedText darkPurple(IFormattedText text); - + @ZenMethod IFormattedText gold(IFormattedText text); - + @ZenMethod IFormattedText gray(IFormattedText text); - + @ZenMethod IFormattedText darkGray(IFormattedText text); - + @ZenMethod IFormattedText blue(IFormattedText text); - + @ZenMethod IFormattedText green(IFormattedText text); - + @ZenMethod IFormattedText aqua(IFormattedText text); - + @ZenMethod IFormattedText red(IFormattedText text); - + @ZenMethod IFormattedText lightPurple(IFormattedText text); - + @ZenMethod IFormattedText yellow(IFormattedText text); - + @ZenMethod IFormattedText white(IFormattedText text); - + @ZenMethod IFormattedText obfuscated(IFormattedText text); - + @ZenMethod IFormattedText bold(IFormattedText text); - + @ZenMethod IFormattedText strikethrough(IFormattedText text); - + @ZenMethod IFormattedText underline(IFormattedText text); - + @ZenMethod IFormattedText italic(IFormattedText text); } diff --git a/src/main/java/minetweaker/api/game/IGame.java b/src/main/java/minetweaker/api/game/IGame.java index b33b4fb..4819378 100644 --- a/src/main/java/minetweaker/api/game/IGame.java +++ b/src/main/java/minetweaker/api/game/IGame.java @@ -1,5 +1,7 @@ package minetweaker.api.game; +import java.util.List; + import minetweaker.api.block.IBlockDefinition; import minetweaker.api.entity.IEntityDefinition; import minetweaker.api.item.IItemDefinition; @@ -7,8 +9,6 @@ import minetweaker.api.liquid.ILiquidDefinition; import minetweaker.api.world.IBiome; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** * Game interface. Used to obtain general game information. * @@ -16,7 +16,7 @@ import java.util.List; */ @ZenClass("minetweaker.game.IGame") public interface IGame { - + /** * Retrieves the item definitions in this game. * @@ -24,7 +24,7 @@ public interface IGame { */ @ZenGetter("items") List getItems(); - + /** * Retrieves the block definitions in this game. * @@ -32,7 +32,7 @@ public interface IGame { */ @ZenGetter("blocks") List getBlocks(); - + /** * Retrieves the liquids in this game. * @@ -40,7 +40,7 @@ public interface IGame { */ @ZenGetter("liquids") List getLiquids(); - + /** * Retrieves the biomes in this game. * @@ -48,7 +48,7 @@ public interface IGame { */ @ZenGetter("biomes") List getBiomes(); - + /** * Retrieves the entities in this game. * @@ -56,10 +56,10 @@ public interface IGame { */ @ZenGetter("entities") List getEntities(); - + @ZenMethod() IEntityDefinition getEntity(String entityName); - + /** * Sets a localization value. * @@ -68,7 +68,7 @@ public interface IGame { */ @ZenMethod void setLocalization(String key, String value); - + /** * Sets a localization value. * @@ -78,7 +78,7 @@ public interface IGame { */ @ZenMethod void setLocalization(String lang, String key, String value); - + /** * Gets a localized string. * @@ -88,7 +88,7 @@ public interface IGame { */ @ZenMethod String localize(String key); - + /** * Gets a localized string. * @@ -99,16 +99,15 @@ public interface IGame { */ @ZenMethod String localize(String key, String lang); - + /** * Lock the game and disable reload. Recommended for distributed versions. *

- * Once locked, reload cannot be unlocked - a game restart is required to - * alter the scripts. + * Once locked, reload cannot be unlocked - a game restart is required to alter the scripts. */ @ZenMethod void lock(); - + /** * Returns the lock state. True if locked. * @@ -116,7 +115,7 @@ public interface IGame { */ @ZenGetter("locked") boolean isLocked(); - + /** * Signals a modified script while in locked mode. */ diff --git a/src/main/java/minetweaker/api/item/IIngredient.java b/src/main/java/minetweaker/api/item/IIngredient.java index bf1171e..a44ab4c 100644 --- a/src/main/java/minetweaker/api/item/IIngredient.java +++ b/src/main/java/minetweaker/api/item/IIngredient.java @@ -1,66 +1,61 @@ package minetweaker.api.item; +import java.util.List; + import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** - * Represents a recipe ingredient. An ingredient can be an item, an ore - * dictionary entry, an item stack, an ore dictionary entry multiplied with an - * amount, or other kinds of ingredients as offered by the API. + * Represents a recipe ingredient. An ingredient can be an item, an ore dictionary entry, an item stack, an ore + * dictionary entry multiplied with an amount, or other kinds of ingredients as offered by the API. *

- * There is no guarantee that every mod will respect the conditions or - * transformations, or that every mod will support every kind of ingredient. + * There is no guarantee that every mod will respect the conditions or transformations, or that every mod will support + * every kind of ingredient. * * @author Stan Hebben */ @ZenClass("minetweaker.item.IIngredient") public interface IIngredient { - + /** - * Gets the mark of the ingredient. Ingredients can be marked so they can be - * used in crafting functions. + * Gets the mark of the ingredient. Ingredients can be marked so they can be used in crafting functions. * * @return ingredient mark */ @ZenGetter("mark") String getMark(); - + /** * Gets the amount. *

- * Should return -1 if no amount is available and 1 for a single item. - * Stacks return the stack size. + * Should return -1 if no amount is available and 1 for a single item. Stacks return the stack size. * * @return stack size */ @ZenGetter("amount") int getAmount(); - + /** * Gets all possible items for this ingredient. *

- * If there is no item list (for example, it is the <*> wildcard item) - * null should be returned. + * If there is no item list (for example, it is the <*> wildcard item) null should be returned. * * @return the items for this ingredient, or null */ @ZenGetter("items") List getItems(); - + /** * Gets all possible liquids for this ingredient. *

- * If there is no liquid list (for example, it is the <*&ft; wildcard - * item) null should be returned. + * If there is no liquid list (for example, it is the <*&ft; wildcard item) null should be returned. * * @return the liquids for this ingredient, or null */ @ZenGetter("liquids") List getLiquids(); - + /** * Returns a new ingredient with the given stack size. * @@ -71,10 +66,9 @@ public interface IIngredient { @ZenOperator(OperatorType.MUL) @ZenMethod IIngredient amount(int amount); - + /** - * Combines multiple ingredients into a single one. Note that ore dictionary - * entries are preferred to or statements. + * Combines multiple ingredients into a single one. Note that ore dictionary entries are preferred to or statements. * * @param ingredient ingredient to combine with * @@ -83,7 +77,7 @@ public interface IIngredient { @ZenOperator(OperatorType.OR) @ZenMethod IIngredient or(IIngredient ingredient); - + /** * Returns a new ingredient with the given transform added to it. * @@ -93,7 +87,7 @@ public interface IIngredient { */ @ZenMethod IIngredient transform(IItemTransformer transformer); - + /** * Returns a new ingredient with the given condition added to it. * @@ -103,7 +97,7 @@ public interface IIngredient { */ @ZenMethod IIngredient only(IItemCondition condition); - + /** * Returns a new ingredient marked with the given name. * @@ -113,10 +107,9 @@ public interface IIngredient { */ @ZenMethod IIngredient marked(String mark); - + /** - * Checks if this ingredient matches the given item. For liquids, will match - * the item if it is a valid container. + * Checks if this ingredient matches the given item. For liquids, will match the item if it is a valid container. * * @param item item to check * @@ -124,10 +117,9 @@ public interface IIngredient { */ @ZenMethod boolean matches(IItemStack item); - + /** - * Checks if this ingredient matches the given item. For liquids, will match - * the item if it is a valid container. + * Checks if this ingredient matches the given item. For liquids, will match the item if it is a valid container. * * @param item item to check * @@ -135,8 +127,7 @@ public interface IIngredient { */ @ZenMethod boolean matchesExact(IItemStack item); - - + /** * Checks if this ingredient matches the given liquid. * @@ -146,10 +137,9 @@ public interface IIngredient { */ @ZenMethod boolean matches(ILiquidStack liquid); - + /** - * Check if this ingredient contains all possible values for the given - * ingredient. + * Check if this ingredient contains all possible values for the given ingredient. * * @param ingredient ingredient to check * @@ -157,7 +147,7 @@ public interface IIngredient { */ @ZenOperator(OperatorType.CONTAINS) boolean contains(IIngredient ingredient); - + /** * Applies transformations after crafting, if any, to the given item. * @@ -168,25 +158,23 @@ public interface IIngredient { */ @ZenMethod IItemStack applyTransform(IItemStack item, IPlayer byPlayer); - + /** * Checks if this ingredient has (or could have) any transformatiosns. * - * @return true if there are (or could be) any transformations false - * otherwise. + * @return true if there are (or could be) any transformations false otherwise. */ @ZenGetter("hasTransformations") boolean hasTransformers(); - + /** * Gets the internal item backing this ingredient. *

- * The value is implementation-dependent and should only be handled by the - * internal code. Don't use this value - instead, use the version-specific - * helper methods. + * The value is implementation-dependent and should only be handled by the internal code. Don't use this value - + * instead, use the version-specific helper methods. * * @return internal item */ Object getInternal(); - + } diff --git a/src/main/java/minetweaker/api/item/IItemCondition.java b/src/main/java/minetweaker/api/item/IItemCondition.java index bb5ecdf..e0c2aab 100644 --- a/src/main/java/minetweaker/api/item/IItemCondition.java +++ b/src/main/java/minetweaker/api/item/IItemCondition.java @@ -5,9 +5,8 @@ import stanhebben.zenscript.annotations.ZenClass; /** * Item conditions apply additional conditions on item stacks. *

- * They may, for instance, require specific damage ranges or NBT tags. Custom - * implementations of this functional interface may contain any kind of - * condition. + * They may, for instance, require specific damage ranges or NBT tags. Custom implementations of this functional + * interface may contain any kind of condition. * * @author Stan Hebben */ diff --git a/src/main/java/minetweaker/api/item/IItemDefinition.java b/src/main/java/minetweaker/api/item/IItemDefinition.java index 523a332..ed3091a 100644 --- a/src/main/java/minetweaker/api/item/IItemDefinition.java +++ b/src/main/java/minetweaker/api/item/IItemDefinition.java @@ -1,22 +1,21 @@ package minetweaker.api.item; +import java.util.List; + import minetweaker.api.oredict.IOreDictEntry; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** - * Contains an item definition. Item definitions provide general information - * about an item, such as its name and ID. + * Contains an item definition. Item definitions provide general information about an item, such as its name and ID. *

- * Item definitions themselves have no localized name, as it could be different - * for each subitem or even depend on NBT tags. + * Item definitions themselves have no localized name, as it could be different for each subitem or even depend on NBT + * tags. * * @author Stan Hebben */ @ZenClass("minetweaker.item.IItemDefinition") public interface IItemDefinition { - + /** * Gets the item ID. * @@ -24,7 +23,7 @@ public interface IItemDefinition { */ @ZenGetter("id") String getId(); - + /** * Gets the unlocalized item name. * @@ -32,7 +31,7 @@ public interface IItemDefinition { */ @ZenGetter("name") String getName(); - + /** * Makes an item stack from this definition. * @@ -42,10 +41,9 @@ public interface IItemDefinition { */ @ZenMethod IItemStack makeStack(@Optional int meta); - + /** - * Returns all ore entries containing this item. Also contains ore entries - * that refer to a specific sub-item. + * Returns all ore entries containing this item. Also contains ore entries that refer to a specific sub-item. * * @return all the ore entries containing this item. */ diff --git a/src/main/java/minetweaker/api/item/IItemStack.java b/src/main/java/minetweaker/api/item/IItemStack.java index ae15b11..575a541 100644 --- a/src/main/java/minetweaker/api/item/IItemStack.java +++ b/src/main/java/minetweaker/api/item/IItemStack.java @@ -1,31 +1,28 @@ package minetweaker.api.item; +import java.util.List; + import minetweaker.api.block.IBlock; import minetweaker.api.data.IData; import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.oredict.IOreDictEntry; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** - * Contains an item stack. An item stack consists of an item definition, a meta - * or damage value and NBT data. + * Contains an item stack. An item stack consists of an item definition, a meta or damage value and NBT data. *

- * Item stacks can be retrieved using its name (or ID, in 1.6.4) with the - * bracket syntax. When using the bracket syntax, by default, the item stack - * will match any size when used as ingredient. Item stacks can be multiplied - * with an integer to create a stack of different size. + * Item stacks can be retrieved using its name (or ID, in 1.6.4) with the bracket syntax. When using the bracket syntax, + * by default, the item stack will match any size when used as ingredient. Item stacks can be multiplied with an integer + * to create a stack of different size. *

- * Item stacks are immutable. You can, however, easily create modified stacks - * using the helper methods. Adding conditions and transformations will turn the - * item stack into an ingredients. + * Item stacks are immutable. You can, however, easily create modified stacks using the helper methods. Adding + * conditions and transformations will turn the item stack into an ingredients. * * @author Stan Hebben */ @ZenClass("minetweaker.item.IItemStack") public interface IItemStack extends IIngredient { - + /** * Gets the item definition. * @@ -33,7 +30,7 @@ public interface IItemStack extends IIngredient { */ @ZenGetter("definition") IItemDefinition getDefinition(); - + /** * Gets the unlocalized item name. * @@ -41,26 +38,25 @@ public interface IItemStack extends IIngredient { */ @ZenGetter("name") String getName(); - + /** - * Gets the display name. By default, it is the localized item name, but - * could also be the display name from NBT data, or another item-specific - * name. + * Gets the display name. By default, it is the localized item name, but could also be the display name from NBT + * data, or another item-specific name. * * @return item display name */ @ZenGetter("displayName") String getDisplayName(); - + /** - * Sets the display name. Only works if the name is translatable. Does not - * override names set by NBT data or using item-specific logic. + * Sets the display name. Only works if the name is translatable. Does not override names set by NBT data or using + * item-specific logic. * * @param name item display name */ @ZenSetter("displayName") void setDisplayName(String name); - + /** * Gets the max stack size for an item * @@ -68,7 +64,7 @@ public interface IItemStack extends IIngredient { */ @ZenGetter("maxStackSize") int getMaxStackSize(); - + /** * Sets the ItemStack max stack size. * @@ -76,13 +72,13 @@ public interface IItemStack extends IIngredient { */ @ZenSetter("maxStackSize") void setMaxStackSize(int size); - + /** * Gets the block hardness */ @ZenGetter("hardness") float getBlockHardness(); - + /** * Sets the block hardness * @@ -90,7 +86,7 @@ public interface IItemStack extends IIngredient { */ @ZenSetter("hardness") void setBlockHardness(float hardness); - + /** * Gets the item damage. Returns 0 if the item cannot be damaged. * @@ -98,7 +94,7 @@ public interface IItemStack extends IIngredient { */ @ZenGetter("damage") int getDamage(); - + /** * Gets the maximum item damage. Returns 0 if the item cannot be damaged. * @@ -106,7 +102,7 @@ public interface IItemStack extends IIngredient { */ @ZenGetter("maxDamage") int getMaxDamage(); - + /** * Sets the max Itemstack damage * @@ -114,27 +110,25 @@ public interface IItemStack extends IIngredient { */ @ZenSetter("maxDamage") void setMaxDamage(int damage); - + /** - * Gets the item tag. (NBT data) The resulting data is immutable and can - * only be changed with updateTag. Returns empty data if there is no data. - * Never returns null. + * Gets the item tag. (NBT data) The resulting data is immutable and can only be changed with updateTag. Returns + * empty data if there is no data. Never returns null. * * @return item tag */ @ZenGetter("tag") IData getTag(); - + /** - * Gets the liquid contained in this item, if any. If this item stack is not - * an item container, it returns null. Only returns the amount of liquid in - * a single item and doesn't into account stack size. + * Gets the liquid contained in this item, if any. If this item stack is not an item container, it returns null. + * Only returns the amount of liquid in a single item and doesn't into account stack size. * * @return liquid data */ @ZenGetter("liquid") ILiquidStack getLiquid(); - + /** * Creates a new item stack with a different stack size. * @@ -144,10 +138,9 @@ public interface IItemStack extends IIngredient { */ @ZenMethod IItemStack amount(int amount); - + /** - * Creates a weighted item stack with the given percentage chance. Does the - * same as item.weight(p * 0.01). + * Creates a weighted item stack with the given percentage chance. Does the same as item.weight(p * 0.01). * * @param p probability, with percent * @@ -155,7 +148,7 @@ public interface IItemStack extends IIngredient { */ @ZenOperator(OperatorType.MOD) WeightedItemStack percent(float p); - + /** * Creates a weighted item stack with the given weight. * @@ -165,16 +158,16 @@ public interface IItemStack extends IIngredient { */ @ZenMethod WeightedItemStack weight(float p); - + /** - * Creates an item stack with the same item and stack size, but accepting - * any damage value. Only useful for items used as ingredients. + * Creates an item stack with the same item and stack size, but accepting any damage value. Only useful for items + * used as ingredients. * * @return item stack with wildcard damage */ @ZenMethod IIngredient anyDamage(); - + /** * Creates an item stack with the specified damage. * @@ -184,7 +177,7 @@ public interface IItemStack extends IIngredient { */ @ZenMethod IItemStack withDamage(int damage); - + /** * Creates an item stack with the specified stack size. * @@ -195,16 +188,16 @@ public interface IItemStack extends IIngredient { @ZenOperator(OperatorType.MUL) @ZenMethod IItemStack withAmount(int amount); - + /** * Creates an item stack with wildcard stack size. * * @return new, modified item stack */ - + @ZenMethod IItemStack anyAmount(); - + /** * Creates an item stack with the given nbt tag. Ignores existing tags. * @@ -214,7 +207,7 @@ public interface IItemStack extends IIngredient { */ @ZenMethod IItemStack withTag(IData tag); - + /** * Create an item stack with an empty nbt tag. Removes previous tag if any. * @@ -222,7 +215,7 @@ public interface IItemStack extends IIngredient { */ @ZenMethod IItemStack withEmptyTag(); - + /** * Creates an item stack without the given nbt tag. * @@ -232,7 +225,7 @@ public interface IItemStack extends IIngredient { */ @ZenMethod IItemStack removeTag(String tag); - + /** * Creates an item stack with updated nbt tag. Updates existing tags. * @@ -242,7 +235,7 @@ public interface IItemStack extends IIngredient { */ @ZenMethod IItemStack updateTag(IData tagUpdate); - + /** * Converts this item stack into a block. * @@ -250,10 +243,9 @@ public interface IItemStack extends IIngredient { */ @ZenCaster IBlock asBlock(); - + /** - * Retrieves all the ores referring to this item. Includes wildcard ore - * entries. + * Retrieves all the ores referring to this item. Includes wildcard ore entries. * * @return ore entries containing this item stack */ diff --git a/src/main/java/minetweaker/api/item/IItemTransformer.java b/src/main/java/minetweaker/api/item/IItemTransformer.java index 425ae5b..d2c24eb 100644 --- a/src/main/java/minetweaker/api/item/IItemTransformer.java +++ b/src/main/java/minetweaker/api/item/IItemTransformer.java @@ -4,9 +4,8 @@ import minetweaker.api.player.IPlayer; import stanhebben.zenscript.annotations.*; /** - * An item transformer modifies an item stack after crafting. Used to apply - * damage, grab multiple items, change NBT tags, replace the item with something - * else - or whatever else you'd want to happen to the input stack. + * An item transformer modifies an item stack after crafting. Used to apply damage, grab multiple items, change NBT + * tags, replace the item with something else - or whatever else you'd want to happen to the input stack. * * @author Stan Hebben */ @@ -14,8 +13,7 @@ import stanhebben.zenscript.annotations.*; public interface IItemTransformer { /** - * Transforms the specified item. May modify this item (and return it) or - * return an entirely new one. + * Transforms the specified item. May modify this item (and return it) or return an entirely new one. * * @param item input item * @param byPlayer player that performs the crafting diff --git a/src/main/java/minetweaker/api/item/IngredientAny.java b/src/main/java/minetweaker/api/item/IngredientAny.java index 07b574f..2789b1b 100644 --- a/src/main/java/minetweaker/api/item/IngredientAny.java +++ b/src/main/java/minetweaker/api/item/IngredientAny.java @@ -1,11 +1,11 @@ package minetweaker.api.item; +import java.util.List; + import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; import minetweaker.util.ArrayUtil; -import java.util.List; - /** * Represents the wildcard ingredient (<*>). * @@ -18,8 +18,7 @@ public class IngredientAny implements IIngredient { public static Object INTERNAL_ANY = null; // platforms supporting an "any" // item should fill it here - private IngredientAny() { - } + private IngredientAny() {} @Override public String getMark() { @@ -48,12 +47,12 @@ public class IngredientAny implements IIngredient { @Override public IIngredient transform(IItemTransformer transformer) { - return new IngredientAnyAdvanced(null, ArrayUtil.EMPTY_CONDITIONS, new IItemTransformer[]{transformer}); + return new IngredientAnyAdvanced(null, ArrayUtil.EMPTY_CONDITIONS, new IItemTransformer[] { transformer }); } @Override public IIngredient only(IItemCondition condition) { - return new IngredientAnyAdvanced(null, new IItemCondition[]{condition}, ArrayUtil.EMPTY_TRANSFORMERS); + return new IngredientAnyAdvanced(null, new IItemCondition[] { condition }, ArrayUtil.EMPTY_TRANSFORMERS); } @Override @@ -76,7 +75,6 @@ public class IngredientAny implements IIngredient { return true; } - @Override public boolean matches(ILiquidStack liquid) { return true; diff --git a/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java b/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java index 35d2a40..f34d1fe 100644 --- a/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java +++ b/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java @@ -1,14 +1,13 @@ package minetweaker.api.item; +import java.util.List; + import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; import minetweaker.util.ArrayUtil; -import java.util.List; - /** - * Represents the wildcard ingredient, with conditions and/or transformers - * applied to it. + * Represents the wildcard ingredient, with conditions and/or transformers applied to it. * * @author Stan Hebben */ @@ -71,9 +70,8 @@ public class IngredientAnyAdvanced implements IIngredient { @Override public boolean matches(IItemStack item) { - for(IItemCondition condition : conditions) { - if(!condition.matches(item)) - return false; + for (IItemCondition condition : conditions) { + if (!condition.matches(item)) return false; } return true; @@ -81,9 +79,8 @@ public class IngredientAnyAdvanced implements IIngredient { @Override public boolean matchesExact(IItemStack item) { - for(IItemCondition condition : conditions) { - if(!condition.matches(item)) - return false; + for (IItemCondition condition : conditions) { + if (!condition.matches(item)) return false; } return true; @@ -98,9 +95,8 @@ public class IngredientAnyAdvanced implements IIngredient { @Override public boolean contains(IIngredient ingredient) { List iitems = ingredient.getItems(); - for(IItemStack iitem : iitems) { - if(!matches(iitem)) - return false; + for (IItemStack iitem : iitems) { + if (!matches(iitem)) return false; } return true; @@ -108,7 +104,7 @@ public class IngredientAnyAdvanced implements IIngredient { @Override public IItemStack applyTransform(IItemStack item, IPlayer byPlayer) { - for(IItemTransformer transform : transformers) { + for (IItemTransformer transform : transformers) { item = transform.transform(item, byPlayer); } diff --git a/src/main/java/minetweaker/api/item/IngredientCondition.java b/src/main/java/minetweaker/api/item/IngredientCondition.java index 21fc5fb..8566177 100644 --- a/src/main/java/minetweaker/api/item/IngredientCondition.java +++ b/src/main/java/minetweaker/api/item/IngredientCondition.java @@ -4,9 +4,8 @@ import minetweaker.api.data.IData; import stanhebben.zenscript.annotations.*; /** - * Conditions can be used to set requirements for matching items. They can be - * used to require specific NBT tags or damage values, requiring changed items - * or as complement to damage-consuming or stack-consuming recipes. + * Conditions can be used to set requirements for matching items. They can be used to require specific NBT tags or + * damage values, requiring changed items or as complement to damage-consuming or stack-consuming recipes. * * @author Stan Hebben */ @@ -23,6 +22,7 @@ public class IngredientCondition { @ZenMethod public static IIngredient onlyDamaged(IIngredient ingredient) { return ingredient.only(new IItemCondition() { + @Override public boolean matches(IItemStack stack) { return stack.getDamage() > 0; @@ -41,6 +41,7 @@ public class IngredientCondition { @ZenMethod public static IIngredient onlyDamageAtLeast(IIngredient ingredient, final int minDamage) { return ingredient.only(new IItemCondition() { + @Override public boolean matches(IItemStack stack) { return stack.getDamage() >= minDamage; @@ -49,8 +50,7 @@ public class IngredientCondition { } /** - * Requires the item to be damaged with at most a specified amount. An - * undamaged item is accepted. + * Requires the item to be damaged with at most a specified amount. An undamaged item is accepted. * * @param ingredient target value * @param maxDamage maximum damage @@ -60,6 +60,7 @@ public class IngredientCondition { @ZenMethod public static IIngredient onlyDamageAtMost(IIngredient ingredient, final int maxDamage) { return ingredient.only(new IItemCondition() { + @Override public boolean matches(IItemStack stack) { return stack.getDamage() <= maxDamage; @@ -79,6 +80,7 @@ public class IngredientCondition { @ZenMethod public static IIngredient onlyDamageBetween(IIngredient ingredient, final int minDamage, final int maxDamage) { return ingredient.only(new IItemCondition() { + @Override public boolean matches(IItemStack stack) { return stack.getDamage() >= minDamage && stack.getDamage() <= maxDamage; @@ -87,8 +89,8 @@ public class IngredientCondition { } /** - * Requires the item to contain at least the given tags. It is OK for the - * item to contain more data, as remaining data is ignored. + * Requires the item to contain at least the given tags. It is OK for the item to contain more data, as remaining + * data is ignored. * * @param ingredient target value * @param data required data @@ -98,6 +100,7 @@ public class IngredientCondition { @ZenMethod public static IIngredient onlyWithTag(IIngredient ingredient, final IData data) { return ingredient.only(new IItemCondition() { + @Override public boolean matches(IItemStack stack) { return stack.getTag() != null && stack.getTag().contains(data); @@ -106,8 +109,8 @@ public class IngredientCondition { } /** - * Requires the input stack to contain at least the given number of items. - * Used in combination with stack consuming recipes. + * Requires the input stack to contain at least the given number of items. Used in combination with stack consuming + * recipes. * * @param ingredient target value * @param amount required stack size @@ -117,6 +120,7 @@ public class IngredientCondition { @ZenMethod public static IIngredient onlyStack(IIngredient ingredient, final int amount) { return ingredient.only(new IItemCondition() { + @Override public boolean matches(IItemStack stack) { return stack.getAmount() >= amount; diff --git a/src/main/java/minetweaker/api/item/IngredientItem.java b/src/main/java/minetweaker/api/item/IngredientItem.java index 7489bcd..fb32b1a 100644 --- a/src/main/java/minetweaker/api/item/IngredientItem.java +++ b/src/main/java/minetweaker/api/item/IngredientItem.java @@ -1,11 +1,11 @@ package minetweaker.api.item; +import java.util.*; + import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; import minetweaker.util.ArrayUtil; -import java.util.*; - /** * Contains an item stack with modifiers applied to it. * @@ -75,12 +75,10 @@ public class IngredientItem implements IIngredient { @Override public boolean matches(IItemStack item) { - if(!this.item.matches(item)) - return false; + if (!this.item.matches(item)) return false; - for(IItemCondition condition : conditions) { - if(!condition.matches(item)) - return false; + for (IItemCondition condition : conditions) { + if (!condition.matches(item)) return false; } return true; @@ -88,12 +86,10 @@ public class IngredientItem implements IIngredient { @Override public boolean matchesExact(IItemStack item) { - if(!this.item.matchesExact(item)) - return false; + if (!this.item.matchesExact(item)) return false; - for(IItemCondition condition : conditions) { - if(!condition.matches(item)) - return false; + for (IItemCondition condition : conditions) { + if (!condition.matches(item)) return false; } return true; @@ -107,9 +103,8 @@ public class IngredientItem implements IIngredient { @Override public boolean contains(IIngredient ingredient) { List iitems = ingredient.getItems(); - for(IItemStack iitem : iitems) { - if(!matches(iitem)) - return false; + for (IItemStack iitem : iitems) { + if (!matches(iitem)) return false; } return true; @@ -117,7 +112,7 @@ public class IngredientItem implements IIngredient { @Override public IItemStack applyTransform(IItemStack item, IPlayer byPlayer) { - for(IItemTransformer transform : transformers) { + for (IItemTransformer transform : transformers) { item = transform.transform(item, byPlayer); } diff --git a/src/main/java/minetweaker/api/item/IngredientOr.java b/src/main/java/minetweaker/api/item/IngredientOr.java index bd31380..3eb3fa5 100644 --- a/src/main/java/minetweaker/api/item/IngredientOr.java +++ b/src/main/java/minetweaker/api/item/IngredientOr.java @@ -1,11 +1,11 @@ package minetweaker.api.item; +import java.util.*; + import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; import minetweaker.util.ArrayUtil; -import java.util.*; - /** * @author Stan */ @@ -24,10 +24,11 @@ public class IngredientOr implements IIngredient { } public IngredientOr(IIngredient a, IIngredient b) { - this(new IIngredient[]{a, b}); + this(new IIngredient[] { a, b }); } - private IngredientOr(IIngredient[] elements, String mark, IItemCondition[] conditions, IItemTransformer[] transformers) { + private IngredientOr(IIngredient[] elements, String mark, IItemCondition[] conditions, + IItemTransformer[] transformers) { this.elements = elements; this.mark = mark; this.conditions = conditions; @@ -47,7 +48,7 @@ public class IngredientOr implements IIngredient { @Override public List getItems() { List result = new ArrayList<>(); - for(IIngredient element : elements) { + for (IIngredient element : elements) { result.addAll(element.getItems()); } return result; @@ -56,7 +57,7 @@ public class IngredientOr implements IIngredient { @Override public List getLiquids() { List result = new ArrayList<>(); - for(IIngredient element : elements) { + for (IIngredient element : elements) { result.addAll(element.getLiquids()); } return result; @@ -65,7 +66,7 @@ public class IngredientOr implements IIngredient { @Override public IIngredient amount(int amount) { IIngredient[] result = new IIngredient[elements.length]; - for(int i = 0; i < elements.length; i++) { + for (int i = 0; i < elements.length; i++) { result[i] = elements[i].amount(amount); } return new IngredientOr(result); @@ -93,9 +94,8 @@ public class IngredientOr implements IIngredient { @Override public boolean matches(IItemStack item) { - for(IIngredient ingredient : elements) { - if(ingredient.matches(item)) - return true; + for (IIngredient ingredient : elements) { + if (ingredient.matches(item)) return true; } return false; @@ -103,9 +103,8 @@ public class IngredientOr implements IIngredient { @Override public boolean matchesExact(IItemStack item) { - for(IIngredient ingredient : elements) { - if(ingredient.matchesExact(item)) - return true; + for (IIngredient ingredient : elements) { + if (ingredient.matchesExact(item)) return true; } return false; @@ -113,9 +112,8 @@ public class IngredientOr implements IIngredient { @Override public boolean matches(ILiquidStack liquid) { - for(IIngredient ingredient : elements) { - if(ingredient.matches(liquid)) - return true; + for (IIngredient ingredient : elements) { + if (ingredient.matches(liquid)) return true; } return false; @@ -124,9 +122,8 @@ public class IngredientOr implements IIngredient { @Override public boolean contains(IIngredient ingredient) { List items = ingredient.getItems(); - for(IItemStack item : items) { - if(!matches(item)) - return false; + for (IItemStack item : items) { + if (!matches(item)) return false; } return true; @@ -134,7 +131,7 @@ public class IngredientOr implements IIngredient { @Override public IItemStack applyTransform(IItemStack item, IPlayer byPlayer) { - for(IItemTransformer transformer : transformers) { + for (IItemTransformer transformer : transformers) { item = transformer.transform(item, byPlayer); } diff --git a/src/main/java/minetweaker/api/item/IngredientStack.java b/src/main/java/minetweaker/api/item/IngredientStack.java index 3c94d99..618ffc5 100644 --- a/src/main/java/minetweaker/api/item/IngredientStack.java +++ b/src/main/java/minetweaker/api/item/IngredientStack.java @@ -1,13 +1,12 @@ package minetweaker.api.item; +import java.util.*; + import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; -import java.util.*; - /** - * Contains an ingredient stack. Is an ingredient with a specific stack size - * assigned to it. + * Contains an ingredient stack. Is an ingredient with a specific stack size assigned to it. * * @author Stan Hebben */ @@ -110,7 +109,7 @@ public class IngredientStack implements IIngredient { String s = "(Ingredients) "; List names = new ArrayList<>(); - for(IItemStack st : ingredient.getItems()) { + for (IItemStack st : ingredient.getItems()) { names.add(st.getName()); } s += String.join(",", names); diff --git a/src/main/java/minetweaker/api/item/IngredientTransform.java b/src/main/java/minetweaker/api/item/IngredientTransform.java index 4063d66..6b54452 100644 --- a/src/main/java/minetweaker/api/item/IngredientTransform.java +++ b/src/main/java/minetweaker/api/item/IngredientTransform.java @@ -3,9 +3,8 @@ package minetweaker.api.item; import stanhebben.zenscript.annotations.*; /** - * Transformations can be used to modify an ingredient after it is used in a - * crafting recipe. It could reuse the item, damage it or consume multiple - * items. + * Transformations can be used to modify an ingredient after it is used in a crafting recipe. It could reuse the item, + * damage it or consume multiple items. * * @author Stan Hebben */ @@ -25,8 +24,8 @@ public class IngredientTransform { } /** - * Damages the item. Also makes the item reusable. Will damage the item for - * 1 point upon crafting and consume it when broken. + * Damages the item. Also makes the item reusable. Will damage the item for 1 point upon crafting and consume it + * when broken. * * @param ingredient target value * @@ -36,7 +35,7 @@ public class IngredientTransform { public static IIngredient transformDamage(IIngredient ingredient) { return ingredient.transform((item, byPlayer) -> { int newDamage = item.getDamage() + 1; - if(newDamage >= item.getMaxDamage()) { + if (newDamage >= item.getMaxDamage()) { return item.withAmount(item.getAmount()).withDamage(0); } else { return item.withAmount(item.getAmount() + 1).withDamage(newDamage); @@ -45,10 +44,8 @@ public class IngredientTransform { } /** - * Damages the item for a specific amount. Also makes the item reusable. - * Upon reaching maximum damage, the item will be consumed. Take care to set - * the proper condition such that an almost-broken item becomes invalid for - * crafting. + * Damages the item for a specific amount. Also makes the item reusable. Upon reaching maximum damage, the item will + * be consumed. Take care to set the proper condition such that an almost-broken item becomes invalid for crafting. * * @param ingredient target value * @param damage damage to be applied @@ -59,7 +56,7 @@ public class IngredientTransform { public static IIngredient transformDamage(IIngredient ingredient, final int damage) { return ingredient.transform((item, byPlayer) -> { int newDamage = item.getDamage() + damage; - if(newDamage >= item.getMaxDamage()) { + if (newDamage >= item.getMaxDamage()) { return item.withAmount(item.getAmount()).withDamage(0); } else { return item.withAmount(item.getAmount()).withDamage(newDamage); @@ -68,8 +65,7 @@ public class IngredientTransform { } /** - * Causes the item to be replaced upon crafting. Can be used, for instance, - * to return empty bottles or buckets. + * Causes the item to be replaced upon crafting. Can be used, for instance, to return empty bottles or buckets. * * @param ingredient target value * @param withItem replacement item @@ -79,7 +75,7 @@ public class IngredientTransform { @ZenMethod public static IIngredient transformReplace(IIngredient ingredient, final IItemStack withItem) { return ingredient.transform((item, byPlayer) -> { - if(item.getAmount() > 1) { + if (item.getAmount() > 1) { byPlayer.give(withItem); return item; } else { @@ -89,9 +85,8 @@ public class IngredientTransform { } /** - * Causes multiple items to be consumed. Take care to set a condition for a - * minimum stack size too, as otherwise smaller stacks would still be - * accepted for input. + * Causes multiple items to be consumed. Take care to set a condition for a minimum stack size too, as otherwise + * smaller stacks would still be accepted for input. * * @param ingredient target value * @param amount consumption amount @@ -116,8 +111,7 @@ public class IngredientTransform { } /** - * Gives an item back to the player. Also clears the inventory slot at that - * position. + * Gives an item back to the player. Also clears the inventory slot at that position. * * @param ingredient * @param givenItem @@ -127,7 +121,7 @@ public class IngredientTransform { @ZenMethod public static IIngredient giveBack(IIngredient ingredient, @Optional final IItemStack givenItem) { return ingredient.transform((item, byPlayer) -> { - if(givenItem == null) { + if (givenItem == null) { byPlayer.give(item.withAmount(1)); return item; } else { diff --git a/src/main/java/minetweaker/api/item/IngredientUnknown.java b/src/main/java/minetweaker/api/item/IngredientUnknown.java index f37555d..8edd652 100644 --- a/src/main/java/minetweaker/api/item/IngredientUnknown.java +++ b/src/main/java/minetweaker/api/item/IngredientUnknown.java @@ -1,10 +1,10 @@ package minetweaker.api.item; +import java.util.*; + import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; -import java.util.*; - /** * @author Stan */ @@ -73,7 +73,6 @@ public class IngredientUnknown implements IIngredient { return false; } - @Override public boolean matches(ILiquidStack liquid) { return false; diff --git a/src/main/java/minetweaker/api/item/WeightedItemStack.java b/src/main/java/minetweaker/api/item/WeightedItemStack.java index be89c2f..e195809 100644 --- a/src/main/java/minetweaker/api/item/WeightedItemStack.java +++ b/src/main/java/minetweaker/api/item/WeightedItemStack.java @@ -1,56 +1,56 @@ package minetweaker.api.item; -import stanhebben.zenscript.annotations.*; - import java.util.*; +import stanhebben.zenscript.annotations.*; + /** - * Contains a weighted item stack. Weighted item stacks simply contain a stack - * and a weight. + * Contains a weighted item stack. Weighted item stacks simply contain a stack and a weight. * * @author Stan Hebben */ @ZenClass("minetweaker.item.WeightedItemStack") public final class WeightedItemStack { - + private final IItemStack stack; private final float p; + public WeightedItemStack(IItemStack stack, float p) { this.stack = stack; this.p = p; } - + public static List pickRandomDrops(Random random, WeightedItemStack[] items) { ArrayList result = new ArrayList<>(); - - for(WeightedItemStack item : items) { - if(random.nextFloat() <= item.getChance()) { + + for (WeightedItemStack item : items) { + if (random.nextFloat() <= item.getChance()) { result.add(item.getStack()); } } - + return result; } - + @ZenGetter("stack") public IItemStack getStack() { return stack; } - + @ZenGetter("chance") public float getChance() { return p; } - + @ZenGetter("percent") public float getPercent() { return p * 100; } - + // ############################# // ### Object implementation ### // ############################# - + @Override public int hashCode() { int hash = 7; @@ -58,16 +58,17 @@ public final class WeightedItemStack { hash = 29 * hash + Float.floatToIntBits(this.p); return hash; } - + @Override public boolean equals(Object obj) { - if(obj == null) { + if (obj == null) { return false; } - if(getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } final WeightedItemStack other = (WeightedItemStack) obj; - return !(this.stack != other.stack && (this.stack == null || !this.stack.equals(other.stack))) && Float.floatToIntBits(this.p) == Float.floatToIntBits(other.p); + return !(this.stack != other.stack && (this.stack == null || !this.stack.equals(other.stack))) + && Float.floatToIntBits(this.p) == Float.floatToIntBits(other.p); } } diff --git a/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java b/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java index ff2918c..6805f43 100644 --- a/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java +++ b/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java @@ -1,13 +1,12 @@ package minetweaker.api.liquid; +import java.util.List; + import minetweaker.api.item.IItemStack; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** - * Contains a liquid definition. Liquid definitions provide additional - * information about liquids. + * Contains a liquid definition. Liquid definitions provide additional information about liquids. * * @author Stan Hebben */ diff --git a/src/main/java/minetweaker/api/liquid/ILiquidStack.java b/src/main/java/minetweaker/api/liquid/ILiquidStack.java index 69da462..b2d14e9 100644 --- a/src/main/java/minetweaker/api/liquid/ILiquidStack.java +++ b/src/main/java/minetweaker/api/liquid/ILiquidStack.java @@ -9,43 +9,43 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.liquid.ILiquidStack") public interface ILiquidStack extends IIngredient { - + @ZenGetter("definition") ILiquidDefinition getDefinition(); - + @ZenGetter("name") String getName(); - + @ZenGetter("displayName") String getDisplayName(); - + @ZenGetter("amount") int getAmount(); - + @ZenGetter("luminosity") int getLuminosity(); - + @ZenGetter("density") int getDensity(); - + @ZenGetter("temperature") int getTemperature(); - + @ZenGetter("viscosity") int getViscosity(); - + @ZenGetter("gaseous") boolean isGaseous(); - + @ZenGetter("tag") IData getTag(); - + @ZenMethod ILiquidStack withTag(IData data); - + @ZenOperator(OperatorType.MUL) @ZenMethod ILiquidStack withAmount(int amount); - + Object getInternal(); } diff --git a/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java b/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java index f758cb6..97a0309 100644 --- a/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java +++ b/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java @@ -1,12 +1,11 @@ package minetweaker.api.liquid; -import stanhebben.zenscript.annotations.*; - import java.util.*; +import stanhebben.zenscript.annotations.*; + /** - * Contains a weighted item stack. Weighted item stacks simply contain a stack - * and a weight. + * Contains a weighted item stack. Weighted item stacks simply contain a stack and a weight. * * @author Stan Hebben */ @@ -15,6 +14,7 @@ public final class WeightedLiquidStack { private final ILiquidStack stack; private final float p; + public WeightedLiquidStack(ILiquidStack stack, float p) { this.stack = stack; this.p = p; @@ -23,8 +23,8 @@ public final class WeightedLiquidStack { public static List pickRandomDrops(Random random, WeightedLiquidStack[] items) { ArrayList result = new ArrayList<>(); - for(WeightedLiquidStack item : items) { - if(random.nextFloat() <= item.getChance()) { + for (WeightedLiquidStack item : items) { + if (random.nextFloat() <= item.getChance()) { result.add(item.getStack()); } } @@ -61,13 +61,14 @@ public final class WeightedLiquidStack { @Override public boolean equals(Object obj) { - if(obj == null) { + if (obj == null) { return false; } - if(getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) { return false; } final WeightedLiquidStack other = (WeightedLiquidStack) obj; - return !(this.stack != other.stack && (this.stack == null || !this.stack.equals(other.stack))) && Float.floatToIntBits(this.p) == Float.floatToIntBits(other.p); + return !(this.stack != other.stack && (this.stack == null || !this.stack.equals(other.stack))) + && Float.floatToIntBits(this.p) == Float.floatToIntBits(other.p); } } diff --git a/src/main/java/minetweaker/api/logger/FileLogger.java b/src/main/java/minetweaker/api/logger/FileLogger.java index f1a6731..6c7019f 100644 --- a/src/main/java/minetweaker/api/logger/FileLogger.java +++ b/src/main/java/minetweaker/api/logger/FileLogger.java @@ -1,17 +1,17 @@ package minetweaker.api.logger; -import minetweaker.runtime.ILogger; - import java.io.*; import java.util.regex.Pattern; +import minetweaker.runtime.ILogger; /** * @author Stan Hebben */ public class FileLogger implements ILogger { - private static final Pattern FORMATTING_CODE_PATTERN = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); + private static final Pattern FORMATTING_CODE_PATTERN = Pattern + .compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); private final Writer writer; private final PrintWriter printWriter; @@ -19,9 +19,9 @@ public class FileLogger implements ILogger { try { writer = new OutputStreamWriter(new FileOutputStream(output), "utf-8"); printWriter = new PrintWriter(writer); - } catch(UnsupportedEncodingException ex) { + } catch (UnsupportedEncodingException ex) { throw new RuntimeException("What the heck?"); - } catch(FileNotFoundException ex) { + } catch (FileNotFoundException ex) { throw new RuntimeException("Could not open log file " + output); } } @@ -31,7 +31,7 @@ public class FileLogger implements ILogger { try { writer.write(stripMessage(message) + "\n"); writer.flush(); - } catch(IOException ex) { + } catch (IOException ex) { throw new RuntimeException(ex); } } @@ -41,7 +41,7 @@ public class FileLogger implements ILogger { try { writer.write("INFO: " + stripMessage(message) + "\n"); writer.flush(); - } catch(IOException ex) { + } catch (IOException ex) { throw new RuntimeException(ex); } } @@ -51,7 +51,7 @@ public class FileLogger implements ILogger { try { writer.write("WARNING: " + stripMessage(message) + "\n"); writer.flush(); - } catch(IOException ex) { + } catch (IOException ex) { throw new RuntimeException(ex); } } @@ -65,11 +65,11 @@ public class FileLogger implements ILogger { public void logError(String message, Throwable exception) { try { writer.write("ERROR: " + stripMessage(message) + "\n"); - if(exception != null) { + if (exception != null) { exception.printStackTrace(printWriter); } writer.flush(); - } catch(IOException ex) { + } catch (IOException ex) { throw new RuntimeException(ex); } } diff --git a/src/main/java/minetweaker/api/logger/MTLogger.java b/src/main/java/minetweaker/api/logger/MTLogger.java index c5caf8f..f94eac6 100644 --- a/src/main/java/minetweaker/api/logger/MTLogger.java +++ b/src/main/java/minetweaker/api/logger/MTLogger.java @@ -1,10 +1,10 @@ package minetweaker.api.logger; +import java.util.*; + import minetweaker.api.player.IPlayer; import minetweaker.runtime.ILogger; -import java.util.*; - /** * @author Stan */ @@ -25,7 +25,7 @@ public class MTLogger implements ILogger { public void addPlayer(IPlayer player) { players.add(player); - if(!unprocessed.isEmpty()) { + if (!unprocessed.isEmpty()) { unprocessed.forEach(player::sendChat); } } @@ -40,30 +40,30 @@ public class MTLogger implements ILogger { @Override public void logCommand(String message) { - for(ILogger logger : loggers) { + for (ILogger logger : loggers) { logger.logCommand(message); } } @Override public void logInfo(String message) { - for(ILogger logger : loggers) { + for (ILogger logger : loggers) { logger.logInfo(message); } } @Override public void logWarning(String message) { - for(ILogger logger : loggers) { + for (ILogger logger : loggers) { logger.logWarning(message); } String message2 = "WARNING: " + message; - if(players.isEmpty()) { + if (players.isEmpty()) { unprocessed.add(message2); } else { - for(IPlayer player : players) { + for (IPlayer player : players) { player.sendChat(message2); } } @@ -76,16 +76,16 @@ public class MTLogger implements ILogger { @Override public void logError(String message, Throwable exception) { - for(ILogger logger : loggers) { + for (ILogger logger : loggers) { logger.logError(message, exception); } String message2 = "ERROR: " + message; - if(players.isEmpty()) { + if (players.isEmpty()) { unprocessed.add(message2); } else { - for(IPlayer player : players) { + for (IPlayer player : players) { player.sendChat(message2); } } diff --git a/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java b/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java index b48cf2c..6bf0f6e 100644 --- a/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java +++ b/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java @@ -3,6 +3,7 @@ package minetweaker.api.minecraft; import java.util.HashMap; import java.util.List; import java.util.Map; + import minetweaker.MineTweakerAPI; import minetweaker.api.block.IBlock; import minetweaker.api.block.IBlockDefinition; @@ -17,14 +18,15 @@ import minetweaker.api.world.IBiome; import minetweaker.api.world.IDimension; import minetweaker.mc1710.block.MCBlockDefinition; import minetweaker.mc1710.block.MCSpecificBlock; +import minetweaker.mc1710.block.MCWorldBlock; import minetweaker.mc1710.data.NBTConverter; import minetweaker.mc1710.item.MCItemStack; +import minetweaker.mc1710.liquid.MCLiquidStack; import minetweaker.mc1710.oredict.MCOreDictEntry; import minetweaker.mc1710.player.MCPlayer; -import minetweaker.mc1710.world.MCDimension; -import minetweaker.mc1710.block.MCWorldBlock; -import minetweaker.mc1710.liquid.MCLiquidStack; import minetweaker.mc1710.world.MCBiome; +import minetweaker.mc1710.world.MCDimension; + import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; @@ -43,453 +45,428 @@ import net.minecraftforge.oredict.OreDictionary; * @author Stan Hebben */ public class MineTweakerMC { - private static final Map blockDefinitions = new HashMap(); - public static final IBiome[] biomes; - static { - biomes = new IBiome[BiomeGenBase.getBiomeGenArray().length]; - for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { - if (BiomeGenBase.getBiomeGenArray()[i] != null) - biomes[i] = new MCBiome(BiomeGenBase.getBiomeGenArray()[i]); - } - } + private static final Map blockDefinitions = new HashMap(); + public static final IBiome[] biomes; - private MineTweakerMC() { - } + static { + biomes = new IBiome[BiomeGenBase.getBiomeGenArray().length]; + for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { + if (BiomeGenBase.getBiomeGenArray()[i] != null) biomes[i] = new MCBiome(BiomeGenBase.getBiomeGenArray()[i]); + } + } - /** - * Returns the Minecraft item for this MineTweaker item. - * - * @param item minetweaker item stack - * @return minecraft item stack - */ - public static ItemStack getItemStack(IItemStack item) { - if (item == null) - return null; + private MineTweakerMC() {} - Object internal = item.getInternal(); - if (internal == null || !(internal instanceof ItemStack)) { - MineTweakerAPI.logError("Not a valid item stack: " + item); - } - return (ItemStack) internal; - } + /** + * Returns the Minecraft item for this MineTweaker item. + * + * @param item minetweaker item stack + * @return minecraft item stack + */ + public static ItemStack getItemStack(IItemStack item) { + if (item == null) return null; - /** - * Returns the Minecraft ingredient for this ingredient. This method is only - * useful for ingredients that represent a single item stack. - * - * @param ingredient item ingredient - * @return minecraft item stack - */ - public static ItemStack getItemStack(IIngredient ingredient) { - if (ingredient == null) - return null; + Object internal = item.getInternal(); + if (internal == null || !(internal instanceof ItemStack)) { + MineTweakerAPI.logError("Not a valid item stack: " + item); + } + return (ItemStack) internal; + } - List items = ingredient.getItems(); - if (items.size() != 1) { - MineTweakerAPI.logError("Not an ingredient with a single item: " + ingredient); - } - return getItemStack(items.get(0)); - } + /** + * Returns the Minecraft ingredient for this ingredient. This method is only useful for ingredients that represent a + * single item stack. + * + * @param ingredient item ingredient + * @return minecraft item stack + */ + public static ItemStack getItemStack(IIngredient ingredient) { + if (ingredient == null) return null; - /** - * Returns the MineTweaker item stack for this item. - * - * @param item minecraft item stack - * @return minetweaker item stack - */ - public static IItemStack getIItemStack(ItemStack item) { - if (item == null) - return null; + List items = ingredient.getItems(); + if (items.size() != 1) { + MineTweakerAPI.logError("Not an ingredient with a single item: " + ingredient); + } + return getItemStack(items.get(0)); + } - return new MCItemStack(item); - } + /** + * Returns the MineTweaker item stack for this item. + * + * @param item minecraft item stack + * @return minetweaker item stack + */ + public static IItemStack getIItemStack(ItemStack item) { + if (item == null) return null; - /** - * Constructs an item stack with wildcard size. - * - * @param item minecraft item stack - * @return minetweaker stack - */ - public static IItemStack getIItemStackWildcardSize(ItemStack item) { - if (item == null) - return null; + return new MCItemStack(item); + } - return new MCItemStack(item, true); - } + /** + * Constructs an item stack with wildcard size. + * + * @param item minecraft item stack + * @return minetweaker stack + */ + public static IItemStack getIItemStackWildcardSize(ItemStack item) { + if (item == null) return null; - /** - * Constructs an item stack with wildcard size. - * - * @param item - * @param meta - * @return minetweaker stack - */ - public static IItemStack getIItemStackWildcardSize(Item item, int meta) { - if (item == null) - return null; + return new MCItemStack(item, true); + } - return new MCItemStack(new ItemStack(item, 1, meta), true); - } + /** + * Constructs an item stack with wildcard size. + * + * @param item + * @param meta + * @return minetweaker stack + */ + public static IItemStack getIItemStackWildcardSize(Item item, int meta) { + if (item == null) return null; - /** - * Constructs an item stack with wildcard damage. - * - * @param item stack item - * @param amount stack size - * @return minetweaker item stack - */ - public static IItemStack getIItemStackWildcard(Item item, int amount) { - if (item == null) - return null; + return new MCItemStack(new ItemStack(item, 1, meta), true); + } - return new MCItemStack(new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE)); - } + /** + * Constructs an item stack with wildcard damage. + * + * @param item stack item + * @param amount stack size + * @return minetweaker item stack + */ + public static IItemStack getIItemStackWildcard(Item item, int amount) { + if (item == null) return null; - public static ItemStack[] getExamples(IIngredient ingredient) { - List examples = ingredient.getItems(); - ItemStack[] result = new ItemStack[examples.size()]; - for (int i = 0; i < examples.size(); i++) { - result[i] = MineTweakerMC.getItemStack(examples.get(i)); - } - return result; - } + return new MCItemStack(new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE)); + } - /** - * Constructs an item stack with given item, damage and amount. - * - * @param item stack item - * @param damage stack damage - * @param amount stack amount - * @return minetweaker item stack - */ - public static IItemStack getItemStack(Item item, int amount, int damage) { - if (item == null) - return null; + public static ItemStack[] getExamples(IIngredient ingredient) { + List examples = ingredient.getItems(); + ItemStack[] result = new ItemStack[examples.size()]; + for (int i = 0; i < examples.size(); i++) { + result[i] = MineTweakerMC.getItemStack(examples.get(i)); + } + return result; + } - return new MCItemStack(new ItemStack(item, amount, damage)); - } + /** + * Constructs an item stack with given item, damage and amount. + * + * @param item stack item + * @param damage stack damage + * @param amount stack amount + * @return minetweaker item stack + */ + public static IItemStack getItemStack(Item item, int amount, int damage) { + if (item == null) return null; - /** - * Converts an array of minetweaker item stacks into an array of minecraft - * item stacks. - * - * @param items minetweker item stacks - * @return minecraft item stacks - */ - public static ItemStack[] getItemStacks(IItemStack... items) { - if (items == null) - return null; + return new MCItemStack(new ItemStack(item, amount, damage)); + } - ItemStack[] output = new ItemStack[items.length]; - for (int i = 0; i < items.length; i++) { - Object internal = items[i].getInternal(); - if (internal != null && internal instanceof ItemStack) { - output[i] = (ItemStack) internal; - } - } - return output; - } + /** + * Converts an array of minetweaker item stacks into an array of minecraft item stacks. + * + * @param items minetweker item stacks + * @return minecraft item stacks + */ + public static ItemStack[] getItemStacks(IItemStack... items) { + if (items == null) return null; - /** - * Converts a list of minetweaker item stacks into an array of minecraft - * item stacks. - * - * @param items minetweaker items - * @return minecraft items - */ - public static ItemStack[] getItemStacks(List items) { - if (items == null) - return null; + ItemStack[] output = new ItemStack[items.length]; + for (int i = 0; i < items.length; i++) { + Object internal = items[i].getInternal(); + if (internal != null && internal instanceof ItemStack) { + output[i] = (ItemStack) internal; + } + } + return output; + } - ItemStack[] output = new ItemStack[items.size()]; - for (int i = 0; i < items.size(); i++) { - Object internal = items.get(i).getInternal(); - if (internal != null && internal instanceof ItemStack) { - output[i] = (ItemStack) internal; - } else { - MineTweakerAPI.logError("Invalid item stack: " + items.get(i)); - } - } - return output; - } + /** + * Converts a list of minetweaker item stacks into an array of minecraft item stacks. + * + * @param items minetweaker items + * @return minecraft items + */ + public static ItemStack[] getItemStacks(List items) { + if (items == null) return null; - /** - * Converts an array of minecraft item stacks into an array of minetweaker - * item stacks. - * - * @param items minecraft item stacks - * @return minetweaker item stacks - */ - public static IItemStack[] getIItemStacks(ItemStack... items) { - if (items == null) - return null; + ItemStack[] output = new ItemStack[items.size()]; + for (int i = 0; i < items.size(); i++) { + Object internal = items.get(i).getInternal(); + if (internal != null && internal instanceof ItemStack) { + output[i] = (ItemStack) internal; + } else { + MineTweakerAPI.logError("Invalid item stack: " + items.get(i)); + } + } + return output; + } - IItemStack[] result = new IItemStack[items.length]; - for (int i = 0; i < items.length; i++) { - result[i] = new MCItemStack(items[i]); - } - return result; - } + /** + * Converts an array of minecraft item stacks into an array of minetweaker item stacks. + * + * @param items minecraft item stacks + * @return minetweaker item stacks + */ + public static IItemStack[] getIItemStacks(ItemStack... items) { + if (items == null) return null; - /** - * Converts a list of minecraft item stacks into an array of minetweaker - * item stacks. - * - * @param items minecraft item stacks - * @return minetweaker item stacks - */ - public static IItemStack[] getIItemStacks(List items) { - if (items == null) - return null; + IItemStack[] result = new IItemStack[items.length]; + for (int i = 0; i < items.length; i++) { + result[i] = new MCItemStack(items[i]); + } + return result; + } - IItemStack[] result = new IItemStack[items.size()]; - for (int i = 0; i < result.length; i++) { - result[i] = new MCItemStack(items.get(i)); - } - return result; - } + /** + * Converts a list of minecraft item stacks into an array of minetweaker item stacks. + * + * @param items minecraft item stacks + * @return minetweaker item stacks + */ + public static IItemStack[] getIItemStacks(List items) { + if (items == null) return null; - /** - * Gets the ore dictionary entry with the given name. If the entry didn't - * exist yet, it will create it and return an empty entry. - * - * @param name ore entry name - * @return ore dictionary entry - */ - public static IOreDictEntry getOreDict(String name) { - return new MCOreDictEntry(name); - } + IItemStack[] result = new IItemStack[items.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = new MCItemStack(items.get(i)); + } + return result; + } - /** - * Converts a Minecraft player into a MineTweaker player. - * - * @param player minecraft player - * @return minetweaker player - */ - public static IPlayer getIPlayer(EntityPlayer player) { - if (player == null) - return null; + /** + * Gets the ore dictionary entry with the given name. If the entry didn't exist yet, it will create it and return an + * empty entry. + * + * @param name ore entry name + * @return ore dictionary entry + */ + public static IOreDictEntry getOreDict(String name) { + return new MCOreDictEntry(name); + } - return new MCPlayer(player); - } + /** + * Converts a Minecraft player into a MineTweaker player. + * + * @param player minecraft player + * @return minetweaker player + */ + public static IPlayer getIPlayer(EntityPlayer player) { + if (player == null) return null; - /** - * Converts a MineTweaker player into a Minecraft player. - * - * @param player minetweaker player - * @return minecraft player - */ - public static EntityPlayer getPlayer(IPlayer player) { - if (player == null) - return null; + return new MCPlayer(player); + } - if (!(player instanceof MCPlayer)) { - MineTweakerAPI.logError("Invalid player: " + player); - } + /** + * Converts a MineTweaker player into a Minecraft player. + * + * @param player minetweaker player + * @return minecraft player + */ + public static EntityPlayer getPlayer(IPlayer player) { + if (player == null) return null; - return ((MCPlayer) player).getInternal(); - } + if (!(player instanceof MCPlayer)) { + MineTweakerAPI.logError("Invalid player: " + player); + } - /** - * Converts a Minecraft NBT to an IData instance. The IData instance is - * immutable (not modifyiable). - * - * @param nbt nbt data - * @return IData value - */ - public static IData getIData(NBTBase nbt) { - if (nbt == null) - return null; + return ((MCPlayer) player).getInternal(); + } - return NBTConverter.from(nbt, true); - } + /** + * Converts a Minecraft NBT to an IData instance. The IData instance is immutable (not modifyiable). + * + * @param nbt nbt data + * @return IData value + */ + public static IData getIData(NBTBase nbt) { + if (nbt == null) return null; - /** - * Converts a Minecraft NBT to a modifyable IData instance. - * - * @param nbt nbt data - * @return mutable IData value - */ - public static IData getIDataModifyable(NBTBase nbt) { - if (nbt == null) - return null; + return NBTConverter.from(nbt, true); + } - return NBTConverter.from(nbt, false); - } + /** + * Converts a Minecraft NBT to a modifyable IData instance. + * + * @param nbt nbt data + * @return mutable IData value + */ + public static IData getIDataModifyable(NBTBase nbt) { + if (nbt == null) return null; - /** - * Converts an IData instance to an NBT value. - * - * @param data IData value - * @return nbt data - */ - public static NBTBase getNBT(IData data) { - if (data == null) - return null; + return NBTConverter.from(nbt, false); + } - return NBTConverter.from(data); - } + /** + * Converts an IData instance to an NBT value. + * + * @param data IData value + * @return nbt data + */ + public static NBTBase getNBT(IData data) { + if (data == null) return null; - /** - * Converts an IData instance to an NBT Tag compound. - * - * @param data IData value - * @return nbt compound data - */ - public static NBTTagCompound getNBTCompound(IData data) { - if (data == null) - return null; + return NBTConverter.from(data); + } - return (NBTTagCompound) NBTConverter.from(data); - } + /** + * Converts an IData instance to an NBT Tag compound. + * + * @param data IData value + * @return nbt compound data + */ + public static NBTTagCompound getNBTCompound(IData data) { + if (data == null) return null; - /** - * Retrieves the block at the given position. - * - * @param blocks block access - * @param x block x position - * @param y block y position - * @param z block z position - * @return block instance - */ - public static IBlock getBlock(IBlockAccess blocks, int x, int y, int z) { - return new MCWorldBlock(blocks, x, y, z); - } + return (NBTTagCompound) NBTConverter.from(data); + } - /** - * Retrieves the block definition for the given block. - * - * @param block block object - * @return block definition - */ - public static IBlockDefinition getBlockDefinition(Block block) { - if (!blockDefinitions.containsKey(block)) { - blockDefinitions.put(block, new MCBlockDefinition(block)); - } - return blockDefinitions.get(block); - } + /** + * Retrieves the block at the given position. + * + * @param blocks block access + * @param x block x position + * @param y block y position + * @param z block z position + * @return block instance + */ + public static IBlock getBlock(IBlockAccess blocks, int x, int y, int z) { + return new MCWorldBlock(blocks, x, y, z); + } - /** - * Retrieves the dimension instance for a given world. - * - * @param world world - * @return dimension - */ - public static IDimension getDimension(World world) { - if (world == null) - return null; + /** + * Retrieves the block definition for the given block. + * + * @param block block object + * @return block definition + */ + public static IBlockDefinition getBlockDefinition(Block block) { + if (!blockDefinitions.containsKey(block)) { + blockDefinitions.put(block, new MCBlockDefinition(block)); + } + return blockDefinitions.get(block); + } - return new MCDimension(world); - } + /** + * Retrieves the dimension instance for a given world. + * + * @param world world + * @return dimension + */ + public static IDimension getDimension(World world) { + if (world == null) return null; - /** - * Returns an instance of the given block. - * - * @param block MC block definition - * @return MT block instance - */ - public static IBlock getBlockAnyMeta(Block block) { - return new MCSpecificBlock(block, OreDictionary.WILDCARD_VALUE); - } + return new MCDimension(world); + } - /** - * Returns an instance of the given block. - * - * @param block MC block definition - * @param meta block meta value - * @return MT block instance - */ - public static IBlock getBlock(Block block, int meta) { - return new MCSpecificBlock(block, meta); - } + /** + * Returns an instance of the given block. + * + * @param block MC block definition + * @return MT block instance + */ + public static IBlock getBlockAnyMeta(Block block) { + return new MCSpecificBlock(block, OreDictionary.WILDCARD_VALUE); + } - /** - * Retrieves the block from an item stack. - * - * @param itemStack - * @return - */ - public static Block getBlock(IItemStack itemStack) { - return ((MCBlockDefinition) itemStack.asBlock().getDefinition()).getInternalBlock(); - } + /** + * Returns an instance of the given block. + * + * @param block MC block definition + * @param meta block meta value + * @return MT block instance + */ + public static IBlock getBlock(Block block, int meta) { + return new MCSpecificBlock(block, meta); + } - public static Block getBlock(IBlock block) { - return ((MCBlockDefinition) block.getDefinition()).getInternalBlock(); - } + /** + * Retrieves the block from an item stack. + * + * @param itemStack + * @return + */ + public static Block getBlock(IItemStack itemStack) { + return ((MCBlockDefinition) itemStack.asBlock().getDefinition()).getInternalBlock(); + } - /** - * Retrieves the internal fluid stack of the given stack. - * - * @param stack MT liquid stack - * @return MCF fluid stack - */ - public static FluidStack getLiquidStack(ILiquidStack stack) { - if (stack == null) - return null; + public static Block getBlock(IBlock block) { + return ((MCBlockDefinition) block.getDefinition()).getInternalBlock(); + } - return (FluidStack) stack.getInternal(); - } + /** + * Retrieves the internal fluid stack of the given stack. + * + * @param stack MT liquid stack + * @return MCF fluid stack + */ + public static FluidStack getLiquidStack(ILiquidStack stack) { + if (stack == null) return null; - /** - * Converts an array of MT liquid stacks into an array of MCF fluid stacks - * - */ - public static FluidStack[] getLiquidStacks(ILiquidStack[] stacks) { - if (stacks == null) { - return null; - } + return (FluidStack) stack.getInternal(); + } - FluidStack[] res = new FluidStack[stacks.length]; + /** + * Converts an array of MT liquid stacks into an array of MCF fluid stacks + * + */ + public static FluidStack[] getLiquidStacks(ILiquidStack[] stacks) { + if (stacks == null) { + return null; + } - for (int i = 0; i < stacks.length; i++) { - ILiquidStack liquidStack = stacks[i]; - res[i] = getLiquidStack(liquidStack); - } - return res; - } + FluidStack[] res = new FluidStack[stacks.length]; - private static final HashMap oreDictArrays = new HashMap(); + for (int i = 0; i < stacks.length; i++) { + ILiquidStack liquidStack = stacks[i]; + res[i] = getLiquidStack(liquidStack); + } + return res; + } - public static IOreDictEntry getOreDictEntryFromArray(List array) { - if (!oreDictArrays.containsKey(array)) { - for (String ore : OreDictionary.getOreNames()) { - if (OreDictionary.getOres(ore) == array) { - oreDictArrays.put(array, MineTweakerAPI.oreDict.get(ore)); - } - } - } + private static final HashMap oreDictArrays = new HashMap(); - return oreDictArrays.get(array); - } + public static IOreDictEntry getOreDictEntryFromArray(List array) { + if (!oreDictArrays.containsKey(array)) { + for (String ore : OreDictionary.getOreNames()) { + if (OreDictionary.getOres(ore) == array) { + oreDictArrays.put(array, MineTweakerAPI.oreDict.get(ore)); + } + } + } - /** - * Converts a Minecraft ingredient to a MineTweaker ingredient. - * - * @param ingredient minecraft ingredient - * @return minetweaker ingredient - */ - public static IIngredient getIIngredient(Object ingredient) { - if (ingredient == null) { - return null; - } else if (ingredient instanceof String) { - return MineTweakerAPI.oreDict.get((String) ingredient); - } else if (ingredient instanceof Item) { - return getIItemStack(new ItemStack((Item) ingredient, 1, 0)); - } else if (ingredient instanceof ItemStack) { - return getIItemStack((ItemStack) ingredient); - } else if (ingredient instanceof List) { - IOreDictEntry entry = getOreDictEntryFromArray((List) ingredient); + return oreDictArrays.get(array); + } - if (entry == null) { - return IngredientUnknown.INSTANCE; - } + /** + * Converts a Minecraft ingredient to a MineTweaker ingredient. + * + * @param ingredient minecraft ingredient + * @return minetweaker ingredient + */ + public static IIngredient getIIngredient(Object ingredient) { + if (ingredient == null) { + return null; + } else if (ingredient instanceof String) { + return MineTweakerAPI.oreDict.get((String) ingredient); + } else if (ingredient instanceof Item) { + return getIItemStack(new ItemStack((Item) ingredient, 1, 0)); + } else if (ingredient instanceof ItemStack) { + return getIItemStack((ItemStack) ingredient); + } else if (ingredient instanceof List) { + IOreDictEntry entry = getOreDictEntryFromArray((List) ingredient); - return entry; - } else if (ingredient instanceof FluidStack) { - return new MCLiquidStack((FluidStack) ingredient); - } else { - throw new IllegalArgumentException("Not a valid ingredient: " + ingredient); - } - } + if (entry == null) { + return IngredientUnknown.INSTANCE; + } + + return entry; + } else if (ingredient instanceof FluidStack) { + return new MCLiquidStack((FluidStack) ingredient); + } else { + throw new IllegalArgumentException("Not a valid ingredient: " + ingredient); + } + } } diff --git a/src/main/java/minetweaker/api/mods/ILoadedMods.java b/src/main/java/minetweaker/api/mods/ILoadedMods.java index 0642420..a618bc5 100644 --- a/src/main/java/minetweaker/api/mods/ILoadedMods.java +++ b/src/main/java/minetweaker/api/mods/ILoadedMods.java @@ -8,10 +8,10 @@ import stanhebben.zenscript.annotations.*; @ZenClass("minetweaker.mods.ILoadedMods") @IterableSimple("minetweaker.mods.IMod") public interface ILoadedMods extends Iterable { - + @ZenOperator(OperatorType.CONTAINS) boolean contains(String name); - + @ZenOperator(OperatorType.INDEXGET) IMod get(String name); } diff --git a/src/main/java/minetweaker/api/mods/IMod.java b/src/main/java/minetweaker/api/mods/IMod.java index c9aeaa4..8e1c95b 100644 --- a/src/main/java/minetweaker/api/mods/IMod.java +++ b/src/main/java/minetweaker/api/mods/IMod.java @@ -6,16 +6,16 @@ import stanhebben.zenscript.annotations.ZenGetter; * @author Stan Hebben */ public interface IMod { - + @ZenGetter("id") String getId(); - + @ZenGetter("name") String getName(); - + @ZenGetter("version") String getVersion(); - + @ZenGetter("decription") String getDescription(); } diff --git a/src/main/java/minetweaker/api/oredict/IOreDict.java b/src/main/java/minetweaker/api/oredict/IOreDict.java index a93fc80..6807956 100644 --- a/src/main/java/minetweaker/api/oredict/IOreDict.java +++ b/src/main/java/minetweaker/api/oredict/IOreDict.java @@ -1,18 +1,18 @@ package minetweaker.api.oredict; -import stanhebben.zenscript.annotations.*; - import java.util.List; +import stanhebben.zenscript.annotations.*; + /** * @author Stan */ @ZenClass("minetweaker.oredict.IOreDict") public interface IOreDict { - + @ZenMemberGetter IOreDictEntry get(String name); - + @ZenGetter("entries") List getEntries(); } diff --git a/src/main/java/minetweaker/api/oredict/IOreDictEntry.java b/src/main/java/minetweaker/api/oredict/IOreDictEntry.java index 0d699f2..55e796a 100644 --- a/src/main/java/minetweaker/api/oredict/IOreDictEntry.java +++ b/src/main/java/minetweaker/api/oredict/IOreDictEntry.java @@ -33,7 +33,6 @@ public interface IOreDictEntry extends IIngredient { @ZenMethod void removeItems(IItemStack[] items); - @ZenOperator(OperatorType.CONTAINS) boolean contains(IItemStack item); diff --git a/src/main/java/minetweaker/api/oredict/IngredientOreDict.java b/src/main/java/minetweaker/api/oredict/IngredientOreDict.java index 655cfd3..08b4618 100644 --- a/src/main/java/minetweaker/api/oredict/IngredientOreDict.java +++ b/src/main/java/minetweaker/api/oredict/IngredientOreDict.java @@ -1,12 +1,12 @@ package minetweaker.api.oredict; +import java.util.*; + import minetweaker.api.item.*; import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; import minetweaker.util.ArrayUtil; -import java.util.*; - /** * @author Stan Hebben */ @@ -17,7 +17,8 @@ public class IngredientOreDict implements IIngredient { private final IItemCondition[] conditions; private final IItemTransformer[] transformers; - public IngredientOreDict(IOreDictEntry entry, String mark, IItemCondition[] conditions, IItemTransformer[] transformers) { + public IngredientOreDict(IOreDictEntry entry, String mark, IItemCondition[] conditions, + IItemTransformer[] transformers) { this.entry = entry; this.mark = mark; this.conditions = conditions; @@ -71,12 +72,10 @@ public class IngredientOreDict implements IIngredient { @Override public boolean matches(IItemStack item) { - if(!entry.matches(item)) - return false; + if (!entry.matches(item)) return false; - for(IItemCondition condition : conditions) { - if(!condition.matches(item)) - return false; + for (IItemCondition condition : conditions) { + if (!condition.matches(item)) return false; } return true; @@ -84,12 +83,10 @@ public class IngredientOreDict implements IIngredient { @Override public boolean matchesExact(IItemStack item) { - if(!entry.matchesExact(item)) - return false; + if (!entry.matchesExact(item)) return false; - for(IItemCondition condition : conditions) { - if(!condition.matches(item)) - return false; + for (IItemCondition condition : conditions) { + if (!condition.matches(item)) return false; } return true; @@ -107,7 +104,7 @@ public class IngredientOreDict implements IIngredient { @Override public IItemStack applyTransform(IItemStack item, IPlayer byPlayer) { - for(IItemTransformer transformer : transformers) { + for (IItemTransformer transformer : transformers) { item = transformer.transform(item, byPlayer); } diff --git a/src/main/java/minetweaker/api/recipes/BrewingRecipe.java b/src/main/java/minetweaker/api/recipes/BrewingRecipe.java index 239f736..a120913 100644 --- a/src/main/java/minetweaker/api/recipes/BrewingRecipe.java +++ b/src/main/java/minetweaker/api/recipes/BrewingRecipe.java @@ -3,17 +3,17 @@ package minetweaker.api.recipes; import minetweaker.api.item.*; public class BrewingRecipe implements IBrewingRecipe { - + private final IItemStack output; private final IItemStack input; private final IIngredient ingredient; - + public BrewingRecipe(IItemStack output, IItemStack input, IIngredient ingredient) { this.input = input; this.ingredient = ingredient; this.output = output; } - + @Override public String toCommandString() { return String.format("brewing.add(%s, %s, %s)", output, input, ingredient); diff --git a/src/main/java/minetweaker/api/recipes/CraftingInfo.java b/src/main/java/minetweaker/api/recipes/CraftingInfo.java index 6a5f7f0..45c0d3a 100644 --- a/src/main/java/minetweaker/api/recipes/CraftingInfo.java +++ b/src/main/java/minetweaker/api/recipes/CraftingInfo.java @@ -7,25 +7,25 @@ import minetweaker.api.world.IDimension; * @author Stan */ public class CraftingInfo implements ICraftingInfo { - + private final ICraftingInventory inventory; private final IDimension dimension; - + public CraftingInfo(ICraftingInventory inventory, IDimension dimension) { this.inventory = inventory; this.dimension = dimension; } - + @Override public ICraftingInventory getInventory() { return inventory; } - + @Override public IPlayer getPlayer() { return inventory.getPlayer(); } - + @Override public IDimension getDimension() { return dimension; diff --git a/src/main/java/minetweaker/api/recipes/FurnaceRecipe.java b/src/main/java/minetweaker/api/recipes/FurnaceRecipe.java index 3b6d074..42f64a0 100644 --- a/src/main/java/minetweaker/api/recipes/FurnaceRecipe.java +++ b/src/main/java/minetweaker/api/recipes/FurnaceRecipe.java @@ -3,20 +3,20 @@ package minetweaker.api.recipes; import minetweaker.api.item.IItemStack; public class FurnaceRecipe implements IFurnaceRecipe { - + private final IItemStack input; private final IItemStack output; private final float xp; - + public FurnaceRecipe(IItemStack input, IItemStack output, float xp) { this.input = input; this.output = output; this.xp = xp; } - + @Override public String toCommandString() { return String.format("furnace.addRecipe(%s, %s, %s)", output, input, xp); } - + } diff --git a/src/main/java/minetweaker/api/recipes/IBrewingManager.java b/src/main/java/minetweaker/api/recipes/IBrewingManager.java index b868342..906e5c7 100644 --- a/src/main/java/minetweaker/api/recipes/IBrewingManager.java +++ b/src/main/java/minetweaker/api/recipes/IBrewingManager.java @@ -1,19 +1,19 @@ package minetweaker.api.recipes; +import java.util.List; + import minetweaker.api.item.IItemStack; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** - * The BrewingManager adds and removes brewing recipes. The IBrewingManager - * instance is available through the recipes global variable. + * The BrewingManager adds and removes brewing recipes. The IBrewingManager instance is available through the recipes + * global variable. * * @author Jared */ @ZenClass("minetweaker.recipes.IBrewingManager") public interface IBrewingManager { - + /** * Returns all crafting recipes. * @@ -21,7 +21,7 @@ public interface IBrewingManager { */ @ZenGetter("all") List getAll(); - + /** * Removes a brewing recipe from the specified item. * @@ -29,7 +29,7 @@ public interface IBrewingManager { */ @ZenMethod void remove(IItemStack output); - + /** * Adds a recipe. * @@ -39,7 +39,7 @@ public interface IBrewingManager { */ @ZenMethod void add(IItemStack output, IItemStack ingredient, IItemStack input); - + /** * Removes recipes. * @@ -50,5 +50,5 @@ public interface IBrewingManager { */ @ZenMethod int remove(IItemStack output, IItemStack ingredients); - + } diff --git a/src/main/java/minetweaker/api/recipes/IBrewingRecipe.java b/src/main/java/minetweaker/api/recipes/IBrewingRecipe.java index 2d431c0..b049cb6 100644 --- a/src/main/java/minetweaker/api/recipes/IBrewingRecipe.java +++ b/src/main/java/minetweaker/api/recipes/IBrewingRecipe.java @@ -4,6 +4,6 @@ import stanhebben.zenscript.annotations.ZenClass; @ZenClass("minetweaker.recipes.IBrewingRecipe") public interface IBrewingRecipe { - + String toCommandString(); } diff --git a/src/main/java/minetweaker/api/recipes/ICraftingInfo.java b/src/main/java/minetweaker/api/recipes/ICraftingInfo.java index b83c008..f876ca3 100644 --- a/src/main/java/minetweaker/api/recipes/ICraftingInfo.java +++ b/src/main/java/minetweaker/api/recipes/ICraftingInfo.java @@ -9,13 +9,13 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.recipes.ICraftingInfo") public interface ICraftingInfo { - + @ZenGetter("inventory") ICraftingInventory getInventory(); - + @ZenGetter("player") IPlayer getPlayer(); - + @ZenGetter("dimension") IDimension getDimension(); } diff --git a/src/main/java/minetweaker/api/recipes/ICraftingInventory.java b/src/main/java/minetweaker/api/recipes/ICraftingInventory.java index 6828465..2fa5e46 100644 --- a/src/main/java/minetweaker/api/recipes/ICraftingInventory.java +++ b/src/main/java/minetweaker/api/recipes/ICraftingInventory.java @@ -5,14 +5,14 @@ import minetweaker.api.player.IPlayer; import stanhebben.zenscript.annotations.*; /** - * Crafting inventory interface. The crafting inventory is the 2x2 grid in the - * player inventory or the 3x3 grid in the crafting bench. + * Crafting inventory interface. The crafting inventory is the 2x2 grid in the player inventory or the 3x3 grid in the + * crafting bench. * * @author Stan Hebben */ @ZenClass("minetweaker.recipes.ICraftingInventory") public interface ICraftingInventory { - + /** * Gets the player owning this inventory. * @@ -20,7 +20,7 @@ public interface ICraftingInventory { */ @ZenGetter("player") IPlayer getPlayer(); - + /** * Gets the size of this inventory. * @@ -28,7 +28,7 @@ public interface ICraftingInventory { */ @ZenGetter("size") int getSize(); - + /** * Gets the width of this inventory. * @@ -36,7 +36,7 @@ public interface ICraftingInventory { */ @ZenGetter("width") int getWidth(); - + /** * Gets the height of this inventory. * @@ -44,7 +44,7 @@ public interface ICraftingInventory { */ @ZenGetter("height") int getHeight(); - + /** * Gets the number of stacks that are actually filled in. * @@ -52,7 +52,7 @@ public interface ICraftingInventory { */ @ZenGetter("stackCount") int getStackCount(); - + /** * Gets the stack at the given location. * @@ -62,10 +62,9 @@ public interface ICraftingInventory { */ @ZenMethod IItemStack getStack(int i); - + /** - * Gets the stack at the given position. The top left stack is position (0, - * 0). + * Gets the stack at the given position. The top left stack is position (0, 0). * * @param x stack x position * @param y stack y position @@ -74,25 +73,22 @@ public interface ICraftingInventory { */ @ZenMethod IItemStack getStack(int x, int y); - + /** - * Sets the stack at the given position. The top left stack is position (0, - * 0). + * Sets the stack at the given position. The top left stack is position (0, 0). * * @param x stack x position * @param y stack y position - * @param stack item stack to be set, or null to clear the stack at that - * position + * @param stack item stack to be set, or null to clear the stack at that position */ @ZenMethod void setStack(int x, int y, IItemStack stack); - + /** * Sets the stack at the given index. * * @param i stack index - * @param stack item stack to be set, or null to clear the stack at that - * index + * @param stack item stack to be set, or null to clear the stack at that index */ @ZenMethod void setStack(int i, IItemStack stack); diff --git a/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java b/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java index b67cc21..802c8eb 100644 --- a/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java +++ b/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java @@ -9,14 +9,14 @@ import stanhebben.zenscript.annotations.ZenClass; */ @ZenClass("minetweaker.recipes.ICraftingRecipe") public interface ICraftingRecipe { - + boolean matches(ICraftingInventory inventory); - + IItemStack getCraftingResult(ICraftingInventory inventory); - + boolean hasTransformers(); - + void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer); - + String toCommandString(); } diff --git a/src/main/java/minetweaker/api/recipes/IFurnaceManager.java b/src/main/java/minetweaker/api/recipes/IFurnaceManager.java index 6e626ee..5d6a7b6 100644 --- a/src/main/java/minetweaker/api/recipes/IFurnaceManager.java +++ b/src/main/java/minetweaker/api/recipes/IFurnaceManager.java @@ -1,28 +1,28 @@ package minetweaker.api.recipes; +import java.util.List; + import minetweaker.api.item.*; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** * @author Stan */ @ZenClass("minetweaker.recipes.IFurnaceManager") public interface IFurnaceManager { - + @ZenMethod void remove(IIngredient output, @Optional IIngredient input); - + @ZenMethod void addRecipe(IItemStack output, IIngredient input, @Optional double xp); - + @ZenMethod void setFuel(IIngredient item, int fuel); - + @ZenMethod int getFuel(IItemStack item); - + /** * Returns all crafting recipes. * diff --git a/src/main/java/minetweaker/api/recipes/IFurnaceRecipe.java b/src/main/java/minetweaker/api/recipes/IFurnaceRecipe.java index 698903b..84f8bda 100644 --- a/src/main/java/minetweaker/api/recipes/IFurnaceRecipe.java +++ b/src/main/java/minetweaker/api/recipes/IFurnaceRecipe.java @@ -4,7 +4,6 @@ package minetweaker.api.recipes; * Created by Jared on 4/18/2016. */ public interface IFurnaceRecipe { - - + String toCommandString(); } diff --git a/src/main/java/minetweaker/api/recipes/IMTRecipe.java b/src/main/java/minetweaker/api/recipes/IMTRecipe.java index a6a23b5..2a71aad 100644 --- a/src/main/java/minetweaker/api/recipes/IMTRecipe.java +++ b/src/main/java/minetweaker/api/recipes/IMTRecipe.java @@ -1,7 +1,6 @@ package minetweaker.api.recipes; public interface IMTRecipe { - - + ICraftingRecipe getRecipe(); } diff --git a/src/main/java/minetweaker/api/recipes/IRecipeAction.java b/src/main/java/minetweaker/api/recipes/IRecipeAction.java index c49fb98..b5f0bd8 100644 --- a/src/main/java/minetweaker/api/recipes/IRecipeAction.java +++ b/src/main/java/minetweaker/api/recipes/IRecipeAction.java @@ -9,7 +9,7 @@ import stanhebben.zenscript.annotations.ZenClass; */ @ZenClass("minetweaker.recipes.IRecipeAction") public interface IRecipeAction { - + void process(IItemStack output, ICraftingInfo craftingInfo, IPlayer player); - + } diff --git a/src/main/java/minetweaker/api/recipes/IRecipeFunction.java b/src/main/java/minetweaker/api/recipes/IRecipeFunction.java index 1e12999..99b159b 100644 --- a/src/main/java/minetweaker/api/recipes/IRecipeFunction.java +++ b/src/main/java/minetweaker/api/recipes/IRecipeFunction.java @@ -1,15 +1,15 @@ package minetweaker.api.recipes; +import java.util.Map; + import minetweaker.api.item.IItemStack; import stanhebben.zenscript.annotations.ZenClass; -import java.util.Map; - /** * @author Stan */ @ZenClass("minetweaker.recipes.IRecipeFunction") public interface IRecipeFunction { - + IItemStack process(IItemStack output, Map inputs, ICraftingInfo craftingInfo); } diff --git a/src/main/java/minetweaker/api/recipes/IRecipeManager.java b/src/main/java/minetweaker/api/recipes/IRecipeManager.java index 8adba79..ffb55a4 100644 --- a/src/main/java/minetweaker/api/recipes/IRecipeManager.java +++ b/src/main/java/minetweaker/api/recipes/IRecipeManager.java @@ -1,19 +1,19 @@ package minetweaker.api.recipes; +import java.util.List; + import minetweaker.api.item.*; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** - * The RecipeManager adds and removes crafting recipes. The IRecipeManager - * instance is available through the recipes global variable. + * The RecipeManager adds and removes crafting recipes. The IRecipeManager instance is available through the recipes + * global variable. * * @author Stan Hebben */ @ZenClass("minetweaker.recipes.IRecipeManager") public interface IRecipeManager { - + /** * Returns all crafting recipes. * @@ -21,7 +21,7 @@ public interface IRecipeManager { */ @ZenGetter("all") List getAll(); - + /** * Returns all crafting recipes resulting in the given ingredient. * @@ -31,7 +31,7 @@ public interface IRecipeManager { */ @ZenMethod List getRecipesFor(IIngredient ingredient); - + /** * Removes all crafting recipes crafting the specified item. * @@ -52,13 +52,15 @@ public interface IRecipeManager { * @param function recipe function (optional) */ @ZenMethod - void addShaped(IItemStack output, IIngredient[][] ingredients, @Optional IRecipeFunction function, @Optional IRecipeAction action); + void addShaped(IItemStack output, IIngredient[][] ingredients, @Optional IRecipeFunction function, + @Optional IRecipeAction action); void addShaped(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function); void addShaped(IItemStack output, IIngredient[][] ingredients, IRecipeAction action); void addShaped(IItemStack output, IIngredient[][] ingredients); + /** * Adds a mirrored shaped recipe. * @@ -67,13 +69,15 @@ public interface IRecipeManager { * @param function recipe function (optional) */ @ZenMethod - void addShapedMirrored(IItemStack output, IIngredient[][] ingredients, @Optional IRecipeFunction function, @Optional IRecipeAction action); + void addShapedMirrored(IItemStack output, IIngredient[][] ingredients, @Optional IRecipeFunction function, + @Optional IRecipeAction action); void addShapedMirrored(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function); void addShapedMirrored(IItemStack output, IIngredient[][] ingredients, IRecipeAction action); void addShapedMirrored(IItemStack output, IIngredient[][] ingredients); + /** * Adds a shapeless recipe. * @@ -82,7 +86,8 @@ public interface IRecipeManager { * @param function recipe function (optional) */ @ZenMethod - void addShapeless(IItemStack output, IIngredient[] ingredients, @Optional IRecipeFunction function, @Optional IRecipeAction action); + void addShapeless(IItemStack output, IIngredient[] ingredients, @Optional IRecipeFunction function, + @Optional IRecipeAction action); void addShapeless(IItemStack output, IIngredient[] ingredients, IRecipeFunction function); @@ -102,13 +107,13 @@ public interface IRecipeManager { int removeShaped(IIngredient output, @Optional IIngredient[][] ingredients); int removeShaped(IIngredient output); + /** * Removes shapeless recipes. * * @param output recipe output * @param ingredients recipe ingredients - * @param wildcard if the recipe may contain other ingredients too, besides - * the ones specified + * @param wildcard if the recipe may contain other ingredients too, besides the ones specified * * @return number of removed recipes */ @@ -122,8 +127,7 @@ public interface IRecipeManager { int removeShapeless(IIngredient output); /** - * Performs a crafting with the specified ingredients. Returns null if no - * crafting recipe exists. + * Performs a crafting with the specified ingredients. Returns null if no crafting recipe exists. * * @param contents crafting inventory contents * @@ -131,5 +135,5 @@ public interface IRecipeManager { */ @ZenMethod IItemStack craft(IItemStack[][] contents); - + } diff --git a/src/main/java/minetweaker/api/recipes/ShapedRecipe.java b/src/main/java/minetweaker/api/recipes/ShapedRecipe.java index 0d08920..cf80bd4 100644 --- a/src/main/java/minetweaker/api/recipes/ShapedRecipe.java +++ b/src/main/java/minetweaker/api/recipes/ShapedRecipe.java @@ -1,15 +1,15 @@ package minetweaker.api.recipes; +import java.util.*; + import minetweaker.api.item.*; import minetweaker.api.player.IPlayer; -import java.util.*; - /** * @author Stan */ public class ShapedRecipe implements ICraftingRecipe { - + private final int width; private final int height; private final byte[] posx; @@ -17,16 +17,16 @@ public class ShapedRecipe implements ICraftingRecipe { private final boolean mirrored; private final IRecipeFunction function; private final IRecipeAction action; - - + private final IItemStack output; private final IIngredient[] ingredients; - + public ShapedRecipe(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, boolean mirrored) { this(output, ingredients, function, null, mirrored); } - - public ShapedRecipe(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, IRecipeAction action, boolean mirrored) { + + public ShapedRecipe(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, IRecipeAction action, + boolean mirrored) { int numIngredients = 0; for (IIngredient[] ingredient : ingredients) { for (IIngredient iIngredient : ingredient) { @@ -42,17 +42,17 @@ public class ShapedRecipe implements ICraftingRecipe { this.ingredients = new IIngredient[numIngredients]; this.function = function; this.action = action; - + int width1 = 0; int height1 = ingredients.length; - + int ix = 0; - for(int j = 0; j < ingredients.length; j++) { + for (int j = 0; j < ingredients.length; j++) { IIngredient[] row = ingredients[j]; width1 = Math.max(width1, row.length); - - for(int i = 0; i < row.length; i++) { - if(row[i] != null) { + + for (int i = 0; i < row.length; i++) { + if (row[i] != null) { this.posx[ix] = (byte) i; this.posy[ix] = (byte) j; this.ingredients[ix] = row[i]; @@ -60,253 +60,234 @@ public class ShapedRecipe implements ICraftingRecipe { } } } - + this.width = width1; this.height = height1; this.mirrored = mirrored; } - + public int getWidth() { return width; } - + public int getHeight() { return height; } - + public boolean isMirrored() { return mirrored; } - + public IIngredient[] getIngredients() { return ingredients; } - + public byte[] getIngredientsX() { return posx; } - + public byte[] getIngredientsY() { return posy; } - + public IItemStack getOutput() { return output; } - + @Override public boolean matches(ICraftingInventory inventory) { - if(inventory.getStackCount() != ingredients.length) { + if (inventory.getStackCount() != ingredients.length) { return false; } - for(int i = 0; i <= inventory.getWidth() - width; i++) { - out: - for(int j = 0; j <= inventory.getHeight() - height; j++) { - for(int k = 0; k < ingredients.length; k++) { + for (int i = 0; i <= inventory.getWidth() - width; i++) { + out: for (int j = 0; j <= inventory.getHeight() - height; j++) { + for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(posx[k] + i, posy[k] + j); - if(item == null) - continue out; - - if(!ingredients[k].matches(item)) - continue out; + if (item == null) continue out; + + if (!ingredients[k].matches(item)) continue out; } - + return true; } } - - if(mirrored) { - for(int i = 0; i <= inventory.getWidth() - width; i++) { - out: - for(int j = 0; j <= inventory.getHeight() - height; j++) { - for(int k = 0; k < ingredients.length; k++) { + + if (mirrored) { + for (int i = 0; i <= inventory.getWidth() - width; i++) { + out: for (int j = 0; j <= inventory.getHeight() - height; j++) { + for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(inventory.getWidth() - (posx[k] + i) - 1, posy[k] + j); - if(item == null) - continue out; - - if(!ingredients[k].matches(item)) - continue out; + if (item == null) continue out; + + if (!ingredients[k].matches(item)) continue out; } - + return true; } } } - + return false; } - + @Override public IItemStack getCraftingResult(ICraftingInventory inventory) { IItemStack[] stacks = new IItemStack[ingredients.length]; - - for(int i = 0; i <= inventory.getWidth() - width; i++) { - out: - for(int j = 0; j <= inventory.getHeight() - height; j++) { - for(int k = 0; k < ingredients.length; k++) { + + for (int i = 0; i <= inventory.getWidth() - width; i++) { + out: for (int j = 0; j <= inventory.getHeight() - height; j++) { + for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(posx[k] + i, posy[k] + j); - if(item == null) - continue out; - - if(!ingredients[k].matches(item)) - continue out; + if (item == null) continue out; + + if (!ingredients[k].matches(item)) continue out; stacks[k] = item; } - + return doRecipe(inventory, stacks, i, j, output, false); } } - - if(mirrored) { - for(int i = 0; i <= inventory.getWidth() - width; i++) { - out: - for(int j = 0; j <= inventory.getHeight() - height; j++) { - for(int k = 0; k < ingredients.length; k++) { + + if (mirrored) { + for (int i = 0; i <= inventory.getWidth() - width; i++) { + out: for (int j = 0; j <= inventory.getHeight() - height; j++) { + for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(inventory.getWidth() - (posx[k] + i) - 1, posy[k] + j); - if(item == null) - continue out; - - if(!ingredients[k].matches(item)) - continue out; + if (item == null) continue out; + + if (!ingredients[k].matches(item)) continue out; stacks[k] = item; } - + return doRecipe(inventory, stacks, i, j, output, true); } } } - + return null; } - + @Override public boolean hasTransformers() { - for(IIngredient ingredient : ingredients) { - if(ingredient.hasTransformers()) { + for (IIngredient ingredient : ingredients) { + if (ingredient.hasTransformers()) { return true; } } - + return false; } - + @Override public void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer) { IItemStack[] stacks = new IItemStack[ingredients.length]; - - for(int i = 0; i <= inventory.getWidth() - width; i++) { - out: - for(int j = 0; j <= inventory.getHeight() - height; j++) { - for(int k = 0; k < ingredients.length; k++) { + + for (int i = 0; i <= inventory.getWidth() - width; i++) { + out: for (int j = 0; j <= inventory.getHeight() - height; j++) { + for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(posx[k] + i, posy[k] + j); - if(item == null) - continue out; - - if(!ingredients[k].matches(item)) - continue out; + if (item == null) continue out; + + if (!ingredients[k].matches(item)) continue out; stacks[k] = item; } - + doRecipeTransformers(inventory, stacks, i, j, false, byPlayer); return; } } - - if(mirrored) { - for(int i = 0; i <= inventory.getWidth() - width; i++) { - out: - for(int j = 0; j <= inventory.getHeight() - height; j++) { - for(int k = 0; k < ingredients.length; k++) { + + if (mirrored) { + for (int i = 0; i <= inventory.getWidth() - width; i++) { + out: for (int j = 0; j <= inventory.getHeight() - height; j++) { + for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(inventory.getWidth() - (posx[k] + i) - 1, posy[k] + j); - if(item == null) - continue out; - - if(!ingredients[k].matches(item)) - continue out; + if (item == null) continue out; + + if (!ingredients[k].matches(item)) continue out; stacks[k] = item; } - + doRecipeTransformers(inventory, stacks, i, j, true, byPlayer); return; } } } } - + @Override public String toCommandString() { StringBuilder result = new StringBuilder(); result.append("recipes.addShaped("); - if(output != null) { + if (output != null) { result.append(output); } else { result.append("null"); } result.append(", ["); - + IIngredient[][] ingredientsArray = new IIngredient[height][width]; - for(int i = 0; i < ingredients.length; i++) { + for (int i = 0; i < ingredients.length; i++) { ingredientsArray[posy[i]][posx[i]] = ingredients[i]; } - - for(int i = 0; i < ingredientsArray.length; i++) { - if(i > 0) { + + for (int i = 0; i < ingredientsArray.length; i++) { + if (i > 0) { result.append(", "); } - + result.append("["); - - for(int j = 0; j < ingredientsArray[i].length; j++) { - if(j > 0) - result.append(", "); - + + for (int j = 0; j < ingredientsArray[i].length; j++) { + if (j > 0) result.append(", "); + result.append(ingredientsArray[i][j]); } - + result.append("]"); } - + result.append("]);"); return result.toString(); } - - private IItemStack doRecipe(ICraftingInventory inventory, IItemStack[] stacks, int offx, int offy, IItemStack output, boolean mirrored) { + + private IItemStack doRecipe(ICraftingInventory inventory, IItemStack[] stacks, int offx, int offy, + IItemStack output, boolean mirrored) { // determine output and apply transformations - - if(function != null) { + + if (function != null) { Map tagged = new HashMap<>(); - for(int k = 0; k < ingredients.length; k++) { - if(ingredients[k].getMark() != null) { + for (int k = 0; k < ingredients.length; k++) { + if (ingredients[k].getMark() != null) { tagged.put(ingredients[k].getMark(), stacks[k]); } } - + // TODO: supply dimension output = function.process(output, tagged, new CraftingInfo(inventory, null)); System.out.println("Ouput: " + output); } - - if(output == null) { + + if (output == null) { return null; } - /* - * for (int i = 0; i < ingredients.length; i++) { IItemStack transformed - * = ingredients[i].applyTransform(stacks[i]); if (transformed != - * stacks[i]) { if (mirrored) { inventory.setStack( inventory.getWidth() - * - (offx + posx[i]) - 1, offy + posy[i], transformed); } else { - * inventory.setStack( offx + posx[i], offy + posy[i], transformed); } } - * } - */ - + /* + * for (int i = 0; i < ingredients.length; i++) { IItemStack transformed = + * ingredients[i].applyTransform(stacks[i]); if (transformed != stacks[i]) { if (mirrored) { inventory.setStack( + * inventory.getWidth() - (offx + posx[i]) - 1, offy + posy[i], transformed); } else { inventory.setStack( offx + * + posx[i], offy + posy[i], transformed); } } } + */ + return output; } - - private void doRecipeTransformers(ICraftingInventory inventory, IItemStack[] stacks, int offx, int offy, boolean mirrored, IPlayer byPlayer) { - for(int i = 0; i < ingredients.length; i++) { + + private void doRecipeTransformers(ICraftingInventory inventory, IItemStack[] stacks, int offx, int offy, + boolean mirrored, IPlayer byPlayer) { + for (int i = 0; i < ingredients.length; i++) { IItemStack transformed = ingredients[i].applyTransform(stacks[i], byPlayer); - if(transformed != stacks[i]) { - if(mirrored) { + if (transformed != stacks[i]) { + if (mirrored) { inventory.setStack(inventory.getWidth() - (offx + posx[i]) - 1, offy + posy[i], transformed); } else { inventory.setStack(offx + posx[i], offy + posy[i], transformed); @@ -314,7 +295,7 @@ public class ShapedRecipe implements ICraftingRecipe { } } } - + public IRecipeAction getAction() { return action; } diff --git a/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java b/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java index 47e8b21..5b9d5fe 100644 --- a/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java +++ b/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java @@ -1,27 +1,28 @@ package minetweaker.api.recipes; +import java.util.*; + import minetweaker.api.item.*; import minetweaker.api.player.IPlayer; -import java.util.*; - /** * @author Stan */ public class ShapelessRecipe implements ICraftingRecipe { - + private final IItemStack output; private final IRecipeFunction function; private final IRecipeAction action; private final IIngredient[] ingredients; - - public ShapelessRecipe(IItemStack output, IIngredient[] ingredients, IRecipeFunction function, IRecipeAction action) { + + public ShapelessRecipe(IItemStack output, IIngredient[] ingredients, IRecipeFunction function, + IRecipeAction action) { this.output = output; this.function = function; this.ingredients = ingredients; this.action = action; } - + /** * Reorders ingredients to match the given shapeless recipe. * @@ -32,138 +33,134 @@ public class ShapelessRecipe implements ICraftingRecipe { */ private static RecipeMatching matchShapeless(IIngredient[] recipe, ICraftingInventory ingredients) { int numItems = 0; - for(int i = 0; i < ingredients.getSize(); i++) { - if(ingredients.getStack(i) != null) { + for (int i = 0; i < ingredients.getSize(); i++) { + if (ingredients.getStack(i) != null) { numItems++; } } - - if(numItems != recipe.length) { + + if (numItems != recipe.length) { return null; } - + IItemStack[] matched = new IItemStack[recipe.length]; int[] indices = new int[recipe.length]; - - outer: - for(int i = 0; i < ingredients.getSize(); i++) { + + outer: for (int i = 0; i < ingredients.getSize(); i++) { IItemStack ingredient = ingredients.getStack(i); - if(ingredient == null) - continue; - - for(int j = 0; j < recipe.length; j++) { - if(matched[j] != null) - continue; - if(recipe[j].matches(ingredient)) { + if (ingredient == null) continue; + + for (int j = 0; j < recipe.length; j++) { + if (matched[j] != null) continue; + if (recipe[j].matches(ingredient)) { matched[j] = ingredient; indices[j] = i; continue outer; } } - + return null; } - + return new RecipeMatching(matched, indices); } - + public int getSize() { return ingredients.length; } - + public IIngredient[] getIngredients() { return ingredients; } - + public IItemStack getOutput() { return output; } - + @Override public boolean matches(ICraftingInventory inventory) { return matchShapeless(ingredients, inventory) != null; } - + @Override public IItemStack getCraftingResult(ICraftingInventory inventory) { RecipeMatching matching = matchShapeless(ingredients, inventory); - + IItemStack actualOutput = output; - if(function != null) { + if (function != null) { Map map = new HashMap<>(); - for(int i = 0; i < ingredients.length; i++) { - if(ingredients[i].getMark() != null) { + for (int i = 0; i < ingredients.length; i++) { + if (ingredients[i].getMark() != null) { map.put(ingredients[i].getMark(), matching.inputs[i]); } } - + actualOutput = function.process(actualOutput, map, new CraftingInfo(inventory, null)); } - - if(actualOutput == null) { + + if (actualOutput == null) { return null; } - + return actualOutput; } - + @Override public void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer) { RecipeMatching matching = matchShapeless(ingredients, inventory); - - for(int i = 0; i < ingredients.length; i++) { + + for (int i = 0; i < ingredients.length; i++) { IIngredient ingredient = ingredients[i]; IItemStack transformed = ingredient.applyTransform(matching.inputs[i], byPlayer); - if(transformed != matching.inputs[i]) { + if (transformed != matching.inputs[i]) { inventory.setStack(matching.indices[i], transformed); } } } - + @Override public String toCommandString() { StringBuilder result = new StringBuilder(); - + result.append("recipes.addShapeless("); - if(output != null){ + if (output != null) { result.append(output); - }else{ + } else { result.append("null"); } result.append(", ["); - - for(int i = 0; i < ingredients.length; i++) { - if(i > 0) - result.append(", "); - + + for (int i = 0; i < ingredients.length; i++) { + if (i > 0) result.append(", "); + result.append(ingredients[i]); } - + result.append("]);"); - + return result.toString(); } - + @Override public boolean hasTransformers() { - for(IIngredient ingredient : ingredients) { - if(ingredient.hasTransformers()) { + for (IIngredient ingredient : ingredients) { + if (ingredient.hasTransformers()) { return true; } } - + return false; } - + public IRecipeAction getAction() { return action; } - + private static class RecipeMatching { - + public final IItemStack[] inputs; public final int[] indices; - + public RecipeMatching(IItemStack[] inputs, int[] indices) { this.inputs = inputs; this.indices = indices; diff --git a/src/main/java/minetweaker/api/recipes/UnknownRecipe.java b/src/main/java/minetweaker/api/recipes/UnknownRecipe.java index fcc55b8..a669f09 100644 --- a/src/main/java/minetweaker/api/recipes/UnknownRecipe.java +++ b/src/main/java/minetweaker/api/recipes/UnknownRecipe.java @@ -7,33 +7,33 @@ import minetweaker.api.player.IPlayer; * @author Stan */ public class UnknownRecipe implements ICraftingRecipe { - + private final IItemStack output; - + public UnknownRecipe(IItemStack output) { this.output = output; } - + @Override public boolean matches(ICraftingInventory inventory) { return false; } - + @Override public IItemStack getCraftingResult(ICraftingInventory inventory) { return output; } - + @Override public boolean hasTransformers() { return false; } - + @Override public void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer) { - + } - + @Override public String toCommandString() { return "// unknown recipe type for " + output; diff --git a/src/main/java/minetweaker/api/server/AbstractServer.java b/src/main/java/minetweaker/api/server/AbstractServer.java index 4963294..cb24869 100644 --- a/src/main/java/minetweaker/api/server/AbstractServer.java +++ b/src/main/java/minetweaker/api/server/AbstractServer.java @@ -5,8 +5,7 @@ import minetweaker.api.event.*; import minetweaker.util.IEventHandler; /** - * Abstract server implementation. Implements call of which the implementation - * is already fixed by the API. + * Abstract server implementation. Implements call of which the implementation is already fixed by the API. * * @author Stan Hebben */ diff --git a/src/main/java/minetweaker/api/server/IServer.java b/src/main/java/minetweaker/api/server/IServer.java index 9117849..6479736 100644 --- a/src/main/java/minetweaker/api/server/IServer.java +++ b/src/main/java/minetweaker/api/server/IServer.java @@ -10,22 +10,23 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("minetweaker.server.IServer") public interface IServer { - + @ZenMethod - void addCommand(String name, String usage, String[] aliases, ICommandFunction function, @Optional ICommandValidator validator, @Optional ICommandTabCompletion completion); - + void addCommand(String name, String usage, String[] aliases, ICommandFunction function, + @Optional ICommandValidator validator, @Optional ICommandTabCompletion completion); + @ZenMethod void addMineTweakerCommand(String name, String[] usage, ICommandFunction function); - + @ZenMethod boolean isOp(IPlayer player); - + @ZenMethod IEventHandle onPlayerLoggedIn(IEventHandler ev); - + @ZenMethod IEventHandle onPlayerLoggedOut(IEventHandler ev); - + @ZenMethod boolean isCommandAdded(String name); } diff --git a/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java b/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java index b1b9f5a..181544b 100644 --- a/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java +++ b/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java @@ -1,5 +1,7 @@ package minetweaker.api.tooltip; +import java.util.List; + import minetweaker.*; import minetweaker.api.formatting.IFormattedText; import minetweaker.api.item.*; @@ -7,83 +9,81 @@ import minetweaker.api.util.IngredientMap; import minetweaker.api.util.IngredientMap.IngredientMapEntry; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** * @author Stan */ @ZenExpansion("minetweaker.item.IIngredient") public class IngredientTooltips { - + private static final IngredientMap TOOLTIPS = new IngredientMap<>(); private static final IngredientMap SHIFT_TOOLTIPS = new IngredientMap<>(); - + @ZenMethod public static void addTooltip(IIngredient ingredient, IFormattedText tooltip) { MineTweakerAPI.apply(new AddTooltipAction(ingredient, tooltip, false)); } - + @ZenMethod public static void addShiftTooltip(IIngredient ingredient, IFormattedText tooltip) { MineTweakerAPI.apply(new AddTooltipAction(ingredient, tooltip, true)); } - + public static List getTooltips(IItemStack item) { return TOOLTIPS.getEntries(item); } - + public static List getShiftTooltips(IItemStack item) { return SHIFT_TOOLTIPS.getEntries(item); } - + // ###################### // ### Action classes ### // ###################### - + private static class AddTooltipAction implements IUndoableAction { - + private final IIngredient ingredient; private final IFormattedText tooltip; private final boolean shift; private IngredientMapEntry entry; - + public AddTooltipAction(IIngredient ingredient, IFormattedText tooltip, boolean shift) { this.ingredient = ingredient; this.tooltip = tooltip; this.shift = shift; } - + @Override public void apply() { entry = (shift ? SHIFT_TOOLTIPS : TOOLTIPS).register(ingredient, tooltip); MineTweakerAPI.getIjeiRecipeRegistry().invalidateTooltips(ingredient); } - + @Override public boolean canUndo() { return true; } - + @Override public void undo() { - if(shift) { + if (shift) { SHIFT_TOOLTIPS.unregister(entry); } else { TOOLTIPS.unregister(entry); } MineTweakerAPI.getIjeiRecipeRegistry().invalidateTooltips(ingredient); } - + @Override public String describe() { return "Adding tooltip for " + ingredient + ": " + tooltip; } - + @Override public String describeUndo() { return "Removing tooltip for " + ingredient + ": " + tooltip; } - + @Override public Object getOverrideKey() { return null; diff --git a/src/main/java/minetweaker/api/util/IngredientMap.java b/src/main/java/minetweaker/api/util/IngredientMap.java index 814b0e1..9bd4841 100644 --- a/src/main/java/minetweaker/api/util/IngredientMap.java +++ b/src/main/java/minetweaker/api/util/IngredientMap.java @@ -1,10 +1,10 @@ package minetweaker.api.util; -import minetweaker.api.item.*; - import java.util.*; import java.util.stream.Collectors; +import minetweaker.api.item.*; + /** * @author Stan */ @@ -17,12 +17,13 @@ public class IngredientMap { } public IngredientMapEntry register(IIngredient ingredient, T entry) { - Set items = ingredient.getItems().stream().map(IItemStack::getDefinition).collect(Collectors.toSet()); + Set items = ingredient.getItems().stream().map(IItemStack::getDefinition) + .collect(Collectors.toSet()); IngredientMapEntry actualEntry = new IngredientMapEntry<>(ingredient, entry); - for(IItemDefinition item : items) { - if(!entries.containsKey(item)) { + for (IItemDefinition item : items) { + if (!entries.containsKey(item)) { entries.put(item, new ArrayList<>()); } @@ -33,18 +34,19 @@ public class IngredientMap { } public void unregister(IngredientMapEntry entry) { - Set items = entry.ingredient.getItems().stream().map(IItemStack::getDefinition).collect(Collectors.toSet()); + Set items = entry.ingredient.getItems().stream().map(IItemStack::getDefinition) + .collect(Collectors.toSet()); - for(IItemDefinition item : items) { - if(entries.containsKey(item)) { + for (IItemDefinition item : items) { + if (entries.containsKey(item)) { entries.get(item).remove(entry); } } } public T getFirstEntry(IItemStack item) { - for(IngredientMapEntry entry : entries.get(item.getDefinition())) { - if(entry.ingredient.matches(item)) { + for (IngredientMapEntry entry : entries.get(item.getDefinition())) { + if (entry.ingredient.matches(item)) { return entry.entry; } } @@ -53,12 +55,13 @@ public class IngredientMap { } public List getEntries(IItemStack item) { - if(item == null || item.getDefinition() == null){ + if (item == null || item.getDefinition() == null) { return Collections.EMPTY_LIST; } List> entries = this.entries.get(item.getDefinition()); - if(entries != null) { - return entries.stream().filter(entry -> entry.ingredient.matches(item)).map(entry -> entry.entry).collect(Collectors.toCollection(ArrayList::new)); + if (entries != null) { + return entries.stream().filter(entry -> entry.ingredient.matches(item)).map(entry -> entry.entry) + .collect(Collectors.toCollection(ArrayList::new)); } else { return Collections.EMPTY_LIST; } diff --git a/src/main/java/minetweaker/api/vanilla/ILootRegistry.java b/src/main/java/minetweaker/api/vanilla/ILootRegistry.java index 30315bd..8fc562d 100644 --- a/src/main/java/minetweaker/api/vanilla/ILootRegistry.java +++ b/src/main/java/minetweaker/api/vanilla/ILootRegistry.java @@ -1,10 +1,10 @@ package minetweaker.api.vanilla; +import java.util.List; + import minetweaker.api.item.*; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** * @author Stan */ diff --git a/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java b/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java index b1f5cf5..754208f 100644 --- a/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java +++ b/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java @@ -1,10 +1,10 @@ package minetweaker.api.vanilla; +import java.util.List; + import minetweaker.api.item.*; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** * @author Stan */ diff --git a/src/main/java/minetweaker/api/vanilla/IVanilla.java b/src/main/java/minetweaker/api/vanilla/IVanilla.java index 391ba59..fd45f6d 100644 --- a/src/main/java/minetweaker/api/vanilla/IVanilla.java +++ b/src/main/java/minetweaker/api/vanilla/IVanilla.java @@ -7,10 +7,10 @@ import stanhebben.zenscript.annotations.*; */ @ZenClass("vanilla.IVanilla") public interface IVanilla { - + @ZenGetter("loot") ILootRegistry getLoot(); - + @ZenGetter("seeds") ISeedRegistry getSeeds(); } diff --git a/src/main/java/minetweaker/api/vanilla/IVillagerRegistry.java b/src/main/java/minetweaker/api/vanilla/IVillagerRegistry.java index 2c7f31a..b73b475 100644 --- a/src/main/java/minetweaker/api/vanilla/IVillagerRegistry.java +++ b/src/main/java/minetweaker/api/vanilla/IVillagerRegistry.java @@ -1,10 +1,10 @@ package minetweaker.api.vanilla; +import java.util.List; + import minetweaker.api.item.*; import stanhebben.zenscript.annotations.*; -import java.util.List; - /** * Created by Jared on 5/9/2016. */ diff --git a/src/main/java/minetweaker/api/vanilla/LootEntry.java b/src/main/java/minetweaker/api/vanilla/LootEntry.java index d035f45..7c06343 100644 --- a/src/main/java/minetweaker/api/vanilla/LootEntry.java +++ b/src/main/java/minetweaker/api/vanilla/LootEntry.java @@ -40,7 +40,7 @@ public class LootEntry { message.append(getItem().getStack()); message.append(" (weight "); message.append((int) getItem().getChance()); - if(getMinAmount() != 0 || getMaxAmount() != 1) { + if (getMinAmount() != 0 || getMaxAmount() != 1) { message.append(", "); message.append(getMinAmount()); message.append("-"); diff --git a/src/main/java/minetweaker/expand/ExpandAnyArray.java b/src/main/java/minetweaker/expand/ExpandAnyArray.java index 14c2242..4dca6d4 100644 --- a/src/main/java/minetweaker/expand/ExpandAnyArray.java +++ b/src/main/java/minetweaker/expand/ExpandAnyArray.java @@ -1,6 +1,7 @@ package minetweaker.expand; import java.util.Arrays; + import minetweaker.api.data.DataList; import minetweaker.api.data.IData; import stanhebben.zenscript.annotations.ZenCaster; @@ -13,8 +14,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("any[]") public class ExpandAnyArray { - @ZenCaster - public static IData asData(IData[] values) { - return new DataList(Arrays.asList(values), true); - } + + @ZenCaster + public static IData asData(IData[] values) { + return new DataList(Arrays.asList(values), true); + } } diff --git a/src/main/java/minetweaker/expand/ExpandAnyDict.java b/src/main/java/minetweaker/expand/ExpandAnyDict.java index 477f3c2..a0df9ef 100644 --- a/src/main/java/minetweaker/expand/ExpandAnyDict.java +++ b/src/main/java/minetweaker/expand/ExpandAnyDict.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; import java.util.Map; + import minetweaker.api.data.DataMap; import minetweaker.api.data.IData; import stanhebben.zenscript.annotations.ZenCaster; @@ -18,8 +18,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("any[any]") public class ExpandAnyDict { - @ZenCaster - public static IData asData(Map values) { - return new DataMap(values, true); - } + + @ZenCaster + public static IData asData(Map values) { + return new DataMap(values, true); + } } diff --git a/src/main/java/minetweaker/expand/ExpandBool.java b/src/main/java/minetweaker/expand/ExpandBool.java index d9c899a..c6c9025 100644 --- a/src/main/java/minetweaker/expand/ExpandBool.java +++ b/src/main/java/minetweaker/expand/ExpandBool.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("bool") public class ExpandBool { - @ZenCaster - public static IData asData(boolean value) { - return new DataBool(value); - } + + @ZenCaster + public static IData asData(boolean value) { + return new DataBool(value); + } } diff --git a/src/main/java/minetweaker/expand/ExpandByte.java b/src/main/java/minetweaker/expand/ExpandByte.java index 691267f..c5a41dd 100644 --- a/src/main/java/minetweaker/expand/ExpandByte.java +++ b/src/main/java/minetweaker/expand/ExpandByte.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("byte") public class ExpandByte { - @ZenCaster - public static IData asData(byte value) { - return new DataByte(value); - } + + @ZenCaster + public static IData asData(byte value) { + return new DataByte(value); + } } diff --git a/src/main/java/minetweaker/expand/ExpandDouble.java b/src/main/java/minetweaker/expand/ExpandDouble.java index 93141fd..0950007 100644 --- a/src/main/java/minetweaker/expand/ExpandDouble.java +++ b/src/main/java/minetweaker/expand/ExpandDouble.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("double") public class ExpandDouble { - @ZenCaster - public static IData asData(double value) { - return new DataDouble(value); - } + + @ZenCaster + public static IData asData(double value) { + return new DataDouble(value); + } } diff --git a/src/main/java/minetweaker/expand/ExpandFloat.java b/src/main/java/minetweaker/expand/ExpandFloat.java index cd5cbbd..6a62da6 100644 --- a/src/main/java/minetweaker/expand/ExpandFloat.java +++ b/src/main/java/minetweaker/expand/ExpandFloat.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("float") public class ExpandFloat { - @ZenCaster - public static IData asData(float value) { - return new DataFloat(value); - } + + @ZenCaster + public static IData asData(float value) { + return new DataFloat(value); + } } diff --git a/src/main/java/minetweaker/expand/ExpandInt.java b/src/main/java/minetweaker/expand/ExpandInt.java index b98fe9c..d463eb2 100644 --- a/src/main/java/minetweaker/expand/ExpandInt.java +++ b/src/main/java/minetweaker/expand/ExpandInt.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("int") public class ExpandInt { - @ZenCaster - public static IData toData(int value) { - return new DataInt(value); - } + + @ZenCaster + public static IData toData(int value) { + return new DataInt(value); + } } diff --git a/src/main/java/minetweaker/expand/ExpandItemStack.java b/src/main/java/minetweaker/expand/ExpandItemStack.java index ffac22c..5ec424c 100644 --- a/src/main/java/minetweaker/expand/ExpandItemStack.java +++ b/src/main/java/minetweaker/expand/ExpandItemStack.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("minetweaker.item.IItemStack") public class ExpandItemStack { - @ZenCaster - public static WeightedItemStack asWeightedItemStack(IItemStack value) { - return new WeightedItemStack(value, 1.0f); - } + + @ZenCaster + public static WeightedItemStack asWeightedItemStack(IItemStack value) { + return new WeightedItemStack(value, 1.0f); + } } diff --git a/src/main/java/minetweaker/expand/ExpandLong.java b/src/main/java/minetweaker/expand/ExpandLong.java index 330dd12..b36b39f 100644 --- a/src/main/java/minetweaker/expand/ExpandLong.java +++ b/src/main/java/minetweaker/expand/ExpandLong.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("long") public class ExpandLong { - @ZenCaster - public static IData asData(long value) { - return new DataLong(value); - } + + @ZenCaster + public static IData asData(long value) { + return new DataLong(value); + } } diff --git a/src/main/java/minetweaker/expand/ExpandShort.java b/src/main/java/minetweaker/expand/ExpandShort.java index cdaaf27..1cbe7f2 100644 --- a/src/main/java/minetweaker/expand/ExpandShort.java +++ b/src/main/java/minetweaker/expand/ExpandShort.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; @@ -17,8 +16,9 @@ import stanhebben.zenscript.annotations.ZenExpansion; */ @ZenExpansion("short") public class ExpandShort { - @ZenCaster - public static IData asNBT(short value) { - return new DataShort(value); - } + + @ZenCaster + public static IData asNBT(short value) { + return new DataShort(value); + } } diff --git a/src/main/java/minetweaker/expand/ExpandString.java b/src/main/java/minetweaker/expand/ExpandString.java index 8eccedf..490568a 100644 --- a/src/main/java/minetweaker/expand/ExpandString.java +++ b/src/main/java/minetweaker/expand/ExpandString.java @@ -1,13 +1,13 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.expand; import java.util.ArrayList; import java.util.List; + import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.api.chat.IChatMessage; @@ -27,70 +27,69 @@ import stanhebben.zenscript.annotations.ZenOperator; */ @ZenExpansion("string") public class ExpandString { - @ZenOperator(OperatorType.ADD) - public static IFormattedText add(String str, IFormattedText formattedText) { - return MineTweakerAPI.format.string(str).add(formattedText); - } - @ZenOperator(OperatorType.CAT) - public static IFormattedText cat(String str, IFormattedText formattedText) { - return add(str, formattedText); - } + @ZenOperator(OperatorType.ADD) + public static IFormattedText add(String str, IFormattedText formattedText) { + return MineTweakerAPI.format.string(str).add(formattedText); + } - @ZenCaster - public static IData asData(String value) { - return new DataString(value); - } + @ZenOperator(OperatorType.CAT) + public static IFormattedText cat(String str, IFormattedText formattedText) { + return add(str, formattedText); + } - @ZenCaster - public static IChatMessage asChatMessage(String value) { - return MineTweakerImplementationAPI.platform.getMessage(value); - } + @ZenCaster + public static IData asData(String value) { + return new DataString(value); + } - @ZenCaster - public static IFormattedText asFormattedText(String value) { - return MineTweakerAPI.format.string(value); - } + @ZenCaster + public static IChatMessage asChatMessage(String value) { + return MineTweakerImplementationAPI.platform.getMessage(value); + } - @ZenMethod - public static List split(String value, String separator, @Optional int maximum) { - List result = new ArrayList(); - int minIndex = 0; - int numSplits = 0; + @ZenCaster + public static IFormattedText asFormattedText(String value) { + return MineTweakerAPI.format.string(value); + } - while (minIndex + separator.length() <= value.length()) { - int index = value.indexOf(separator, minIndex); - if (index < 0) - break; - result.add(value.substring(minIndex, index)); - minIndex = index + separator.length(); + @ZenMethod + public static List split(String value, String separator, @Optional int maximum) { + List result = new ArrayList(); + int minIndex = 0; + int numSplits = 0; - numSplits++; - if (maximum > 0 && numSplits >= maximum) - break; - } + while (minIndex + separator.length() <= value.length()) { + int index = value.indexOf(separator, minIndex); + if (index < 0) break; + result.add(value.substring(minIndex, index)); + minIndex = index + separator.length(); - result.add(value.substring(minIndex)); - return result; - } + numSplits++; + if (maximum > 0 && numSplits >= maximum) break; + } - @ZenMethod - public static int indexOf(String value, String needle) { - return value.indexOf(needle); - } + result.add(value.substring(minIndex)); + return result; + } - @ZenMethod - public static int indexOf(String value, String needle, int fromIndex) { - return value.indexOf(needle, fromIndex); - } + @ZenMethod + public static int indexOf(String value, String needle) { + return value.indexOf(needle); + } - @ZenMethod - public static int lastIndexOf(String value, String needle) { - return value.lastIndexOf(needle); - } + @ZenMethod + public static int indexOf(String value, String needle, int fromIndex) { + return value.indexOf(needle, fromIndex); + } - @ZenMethod - public static int lastIndexOf(String value, String needle, int fromIndex) { - return value.lastIndexOf(value, fromIndex); - } + @ZenMethod + public static int lastIndexOf(String value, String needle) { + return value.lastIndexOf(needle); + } + + @ZenMethod + public static int lastIndexOf(String value, String needle, int fromIndex) { + return value.lastIndexOf(value, fromIndex); + } } diff --git a/src/main/java/minetweaker/mc1710/FMLEventHandler.java b/src/main/java/minetweaker/mc1710/FMLEventHandler.java index 650f3ab..2b0257a 100644 --- a/src/main/java/minetweaker/mc1710/FMLEventHandler.java +++ b/src/main/java/minetweaker/mc1710/FMLEventHandler.java @@ -11,7 +11,9 @@ import minetweaker.api.player.IPlayer; import minetweaker.mc1710.network.MineTweakerLoadScriptsPacket; import minetweaker.mc1710.recipes.MCCraftingInventory; import minetweaker.mc1710.recipes.MCRecipeManager; + import net.minecraft.entity.player.EntityPlayerMP; + import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; @@ -20,38 +22,49 @@ import cpw.mods.fml.common.gameevent.PlayerEvent; * @author Stan */ public class FMLEventHandler { - @SubscribeEvent - public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent ev) { - if (ev.player instanceof EntityPlayerMP && MineTweakerConfig.sendLoadScripts) { - EntityPlayerMP player = (EntityPlayerMP) ev.player; - MineTweakerMod.NETWORK.sendTo(new MineTweakerLoadScriptsPacket(MineTweakerAPI.tweaker.getScriptData()), player); - } - MineTweakerImplementationAPI.events.publishPlayerLoggedIn(new PlayerLoggedInEvent(MineTweakerMC.getIPlayer(ev.player))); - } + @SubscribeEvent + public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent ev) { + if (ev.player instanceof EntityPlayerMP && MineTweakerConfig.sendLoadScripts) { + EntityPlayerMP player = (EntityPlayerMP) ev.player; + MineTweakerMod.NETWORK + .sendTo(new MineTweakerLoadScriptsPacket(MineTweakerAPI.tweaker.getScriptData()), player); + } - @SubscribeEvent - public void onPlayerItemCrafted(PlayerEvent.ItemCraftedEvent ev) { - IPlayer iPlayer = MineTweakerMC.getIPlayer(ev.player); - if (MCRecipeManager.hasTransformerRecipes()) { - MCRecipeManager.applyTransformations(MCCraftingInventory.get(ev.craftMatrix, ev.player), iPlayer); - } + MineTweakerImplementationAPI.events + .publishPlayerLoggedIn(new PlayerLoggedInEvent(MineTweakerMC.getIPlayer(ev.player))); + } - if (MineTweakerImplementationAPI.events.hasPlayerCrafted()) { - MineTweakerImplementationAPI.events.publishPlayerCrafted(new PlayerCraftedEvent(iPlayer, MineTweakerMC.getIItemStack(ev.crafting), MCCraftingInventory.get(ev.craftMatrix, ev.player))); - } - } + @SubscribeEvent + public void onPlayerItemCrafted(PlayerEvent.ItemCraftedEvent ev) { + IPlayer iPlayer = MineTweakerMC.getIPlayer(ev.player); + if (MCRecipeManager.hasTransformerRecipes()) { + MCRecipeManager.applyTransformations(MCCraftingInventory.get(ev.craftMatrix, ev.player), iPlayer); + } - @SubscribeEvent - public void onPlayerItemSmelted(PlayerEvent.ItemSmeltedEvent ev) { - if (MineTweakerImplementationAPI.events.hasPlayerSmelted()) { - MineTweakerImplementationAPI.events.publishPlayerSmelted(new PlayerSmeltedEvent(MineTweakerMC.getIPlayer(ev.player), MineTweakerMC.getIItemStack(ev.smelting))); - } - } + if (MineTweakerImplementationAPI.events.hasPlayerCrafted()) { + MineTweakerImplementationAPI.events.publishPlayerCrafted( + new PlayerCraftedEvent( + iPlayer, + MineTweakerMC.getIItemStack(ev.crafting), + MCCraftingInventory.get(ev.craftMatrix, ev.player))); + } + } - @SubscribeEvent - public void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent ev) { - MineTweakerImplementationAPI.events.publishPlayerLoggedOut(new PlayerLoggedOutEvent(MineTweakerMC.getIPlayer(ev.player))); - } + @SubscribeEvent + public void onPlayerItemSmelted(PlayerEvent.ItemSmeltedEvent ev) { + if (MineTweakerImplementationAPI.events.hasPlayerSmelted()) { + MineTweakerImplementationAPI.events.publishPlayerSmelted( + new PlayerSmeltedEvent( + MineTweakerMC.getIPlayer(ev.player), + MineTweakerMC.getIItemStack(ev.smelting))); + } + } + + @SubscribeEvent + public void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent ev) { + MineTweakerImplementationAPI.events + .publishPlayerLoggedOut(new PlayerLoggedOutEvent(MineTweakerMC.getIPlayer(ev.player))); + } } diff --git a/src/main/java/minetweaker/mc1710/ForgeEventHandler.java b/src/main/java/minetweaker/mc1710/ForgeEventHandler.java index 6b19645..f95d456 100644 --- a/src/main/java/minetweaker/mc1710/ForgeEventHandler.java +++ b/src/main/java/minetweaker/mc1710/ForgeEventHandler.java @@ -1,14 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import java.util.*; + import minetweaker.*; import minetweaker.api.entity.*; import minetweaker.api.formatting.IFormattedText; @@ -17,6 +15,7 @@ import minetweaker.api.minecraft.MineTweakerMC; import minetweaker.api.tooltip.IngredientTooltips; import minetweaker.mc1710.formatting.IMCFormattedString; import minetweaker.mc1710.item.*; + import net.minecraft.client.multiplayer.GuiConnecting; import net.minecraft.entity.*; import net.minecraft.entity.item.*; @@ -26,22 +25,27 @@ import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.event.entity.living.*; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import org.lwjgl.input.Keyboard; -import stanhebben.zenscript.value.*; -import java.util.*; +import org.lwjgl.input.Keyboard; + +import stanhebben.zenscript.value.*; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; /** * @author Stan */ public class ForgeEventHandler { + @SubscribeEvent public void onPlayerInteract(PlayerInteractEvent ev) { minetweaker.api.event.PlayerInteractEvent event = new minetweaker.api.event.PlayerInteractEvent( MineTweakerMC.getIPlayer(ev.entityPlayer), MineTweakerMC.getDimension(ev.world), - ev.x, ev.y, ev.z - ); + ev.x, + ev.y, + ev.z); MineTweakerImplementationAPI.events.publishPlayerInteract(event); } @@ -54,64 +58,83 @@ public class ForgeEventHandler { @SubscribeEvent public void onItemTooltip(ItemTooltipEvent ev) { - if(ev.itemStack!= null) { + if (ev.itemStack != null) { IItemStack itemStack = MineTweakerMC.getIItemStack(ev.itemStack); - for(IFormattedText tooltip : IngredientTooltips.getTooltips(itemStack)) { + for (IFormattedText tooltip : IngredientTooltips.getTooltips(itemStack)) { ev.toolTip.add(((IMCFormattedString) tooltip).getTooltipString()); } - if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { - for(IFormattedText tooltip : IngredientTooltips.getShiftTooltips(itemStack)) { + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { + for (IFormattedText tooltip : IngredientTooltips.getShiftTooltips(itemStack)) { ev.toolTip.add(((IMCFormattedString) tooltip).getTooltipString()); } } } } - - + @SubscribeEvent public void onLivingDeathDrops(LivingDropsEvent ev) { final EntityLivingBase entity = ev.entityLiving; final IEntityDefinition iEntity = MineTweakerAPI.game.getEntity(EntityList.getEntityString(entity)); - if(iEntity == null) { + if (iEntity == null) { return; } - - if(!iEntity.getDropsToAdd().isEmpty()) { - for(Map.Entry dropToAdd : iEntity.getDropsToAdd().entrySet()) { + + if (!iEntity.getDropsToAdd().isEmpty()) { + for (Map.Entry dropToAdd : iEntity.getDropsToAdd().entrySet()) { final IItemStack key = dropToAdd.getKey(); final IntRange val = dropToAdd.getValue(); - + final EntityItem item; - if(val.getMin() == 0 && val.getMax() == 0) { - item = new EntityItem(entity.worldObj, entity.posX + 0.5, entity.posY + 0.5, entity.posZ + 0.5, ((ItemStack) key.getInternal()).copy()); + if (val.getMin() == 0 && val.getMax() == 0) { + item = new EntityItem( + entity.worldObj, + entity.posX + 0.5, + entity.posY + 0.5, + entity.posZ + 0.5, + ((ItemStack) key.getInternal()).copy()); } else { - item = new EntityItem(entity.worldObj, entity.posX + 0.5, entity.posY + 0.5, entity.posZ + 0.5, ((ItemStack) key.withAmount(val.getRandom()).getInternal()).copy()); + item = new EntityItem( + entity.worldObj, + entity.posX + 0.5, + entity.posY + 0.5, + entity.posZ + 0.5, + ((ItemStack) key.withAmount(val.getRandom()).getInternal()).copy()); } ev.drops.add(item); } } - - if(!iEntity.getDropsToAddPlayerOnly().isEmpty() && ev.source.getEntity() instanceof EntityPlayer) { - for(Map.Entry dropToAdd : iEntity.getDropsToAddPlayerOnly().entrySet()) { + + if (!iEntity.getDropsToAddPlayerOnly().isEmpty() && ev.source.getEntity() instanceof EntityPlayer) { + for (Map.Entry dropToAdd : iEntity.getDropsToAddPlayerOnly().entrySet()) { final IItemStack key = dropToAdd.getKey(); final IntRange val = dropToAdd.getValue(); - + final EntityItem item; - if(val.getMin() == 0 && val.getMax() == 0) { - item = new EntityItem(entity.worldObj, entity.posX + 0.5, entity.posY + 0.5, entity.posZ + 0.5, ((ItemStack) key.getInternal()).copy()); + if (val.getMin() == 0 && val.getMax() == 0) { + item = new EntityItem( + entity.worldObj, + entity.posX + 0.5, + entity.posY + 0.5, + entity.posZ + 0.5, + ((ItemStack) key.getInternal()).copy()); } else { - item = new EntityItem(entity.worldObj, entity.posX + 0.5, entity.posY + 0.5, entity.posZ + 0.5, ((ItemStack) key.withAmount(val.getRandom()).getInternal()).copy()); + item = new EntityItem( + entity.worldObj, + entity.posX + 0.5, + entity.posY + 0.5, + entity.posZ + 0.5, + ((ItemStack) key.withAmount(val.getRandom()).getInternal()).copy()); } ev.drops.add(item); } } - - if(!iEntity.getDropsToRemove().isEmpty()) { - for(IItemStack iItemStack : iEntity.getDropsToRemove()) { - for(Iterator iterator = ev.drops.iterator(); iterator.hasNext(); ) { + + if (!iEntity.getDropsToRemove().isEmpty()) { + for (IItemStack iItemStack : iEntity.getDropsToRemove()) { + for (Iterator iterator = ev.drops.iterator(); iterator.hasNext();) { EntityItem drop = iterator.next(); - if(iItemStack.matches(new MCItemStack(drop.getEntityItem()))) { + if (iItemStack.matches(new MCItemStack(drop.getEntityItem()))) { iterator.remove(); } } diff --git a/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java b/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java index 452526b..b972414 100644 --- a/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java +++ b/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java @@ -4,57 +4,43 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; /** - * This screen is shown when a client has been modified with a permanent - * modification and the player logs into a game with a different script. It asks - * the player to restart the game. + * This screen is shown when a client has been modified with a permanent modification and the player logs into a game + * with a different script. It asks the player to restart the game. * * @author Stan Hebben */ public class GuiCannotRemodify extends GuiScreen { - private final String message1; - private final String message2; - private final String message3; - public GuiCannotRemodify(String message1, String message2, String message3) { - this.message1 = message1; - this.message2 = message2; - this.message3 = message3; - } + private final String message1; + private final String message2; + private final String message3; - @Override - public void initGui() { - this.buttonList.clear(); - this.buttonList.add( - new GuiButton(0, this.width / 2 - 100, this.height / 4 + 120 + 12, "Close") - ); - } + public GuiCannotRemodify(String message1, String message2, String message3) { + this.message1 = message1; + this.message2 = message2; + this.message3 = message3; + } - @Override - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString( - this.fontRendererObj, - message1, - this.width / 2, this.height / 2 - 40, - 11184810); - this.drawCenteredString( - this.fontRendererObj, - message2, - this.width / 2, this.height / 2 - 20, - 11184810); - this.drawCenteredString( - this.fontRendererObj, - message3, - this.width / 2, this.height / 2 - 0, - 11184810); + @Override + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 120 + 12, "Close")); + } - super.drawScreen(par1, par2, par3); - } + @Override + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, message1, this.width / 2, this.height / 2 - 40, 11184810); + this.drawCenteredString(this.fontRendererObj, message2, this.width / 2, this.height / 2 - 20, 11184810); + this.drawCenteredString(this.fontRendererObj, message3, this.width / 2, this.height / 2 - 0, 11184810); - @Override - protected void actionPerformed(GuiButton par1GuiButton) { - if (par1GuiButton.id == 0) { - System.exit(0); - } - } + super.drawScreen(par1, par2, par3); + } + + @Override + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + System.exit(0); + } + } } diff --git a/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java b/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java index 2f52434..e8c804e 100644 --- a/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java +++ b/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710; @@ -9,10 +8,10 @@ package minetweaker.mc1710; import minetweaker.IPlatformFunctions; import minetweaker.api.chat.IChatMessage; import minetweaker.api.item.IItemDefinition; - +import minetweaker.mc1710.chat.MCChatMessage; import minetweaker.mc1710.item.MCItemDefinition; import minetweaker.mc1710.network.MineTweakerLoadScriptsPacket; -import minetweaker.mc1710.chat.MCChatMessage; + import net.minecraft.item.Item; /** @@ -20,27 +19,27 @@ import net.minecraft.item.Item; * @author Stan */ public class MCPlatformFunctions implements IPlatformFunctions { - public static final MCPlatformFunctions INSTANCE = new MCPlatformFunctions(); - private MCPlatformFunctions() { - } + public static final MCPlatformFunctions INSTANCE = new MCPlatformFunctions(); - @Override - public IChatMessage getMessage(String message) { - return new MCChatMessage(message); - } + private MCPlatformFunctions() {} - @Override - public void distributeScripts(byte[] data) { - if (MineTweakerConfig.sendScriptsOnReloading) MineTweakerMod.NETWORK.sendToAll(new MineTweakerLoadScriptsPacket(data)); - } + @Override + public IChatMessage getMessage(String message) { + return new MCChatMessage(message); + } - @Override - public IItemDefinition getItemDefinition(int id) { - Item item = Item.getItemById(id); - if (item == null) - return null; - String sid = Item.itemRegistry.getNameForObject(item); - return new MCItemDefinition(sid, item); - } + @Override + public void distributeScripts(byte[] data) { + if (MineTweakerConfig.sendScriptsOnReloading) + MineTweakerMod.NETWORK.sendToAll(new MineTweakerLoadScriptsPacket(data)); + } + + @Override + public IItemDefinition getItemDefinition(int id) { + Item item = Item.getItemById(id); + if (item == null) return null; + String sid = Item.itemRegistry.getNameForObject(item); + return new MCItemDefinition(sid, item); + } } diff --git a/src/main/java/minetweaker/mc1710/MineTweakerConfig.java b/src/main/java/minetweaker/mc1710/MineTweakerConfig.java index cc6d14b..ec01260 100644 --- a/src/main/java/minetweaker/mc1710/MineTweakerConfig.java +++ b/src/main/java/minetweaker/mc1710/MineTweakerConfig.java @@ -5,28 +5,45 @@ import java.io.File; import net.minecraftforge.common.config.Configuration; public class MineTweakerConfig { - private MineTweakerConfig() { } - public static boolean handleDesktopPackets = false, handleLoadScripts = true, sendLoadScripts = true, - sendScriptsOnReloading = true, loadScriptsBeforeConnection = false, antiStuck = true; - static File file; - public static void load() { - Configuration config = new Configuration(file, "1"); - config.load(); - handleDesktopPackets = config.getBoolean("handleDesktopPackets", - "network", false, "Handle OpenBrowser and CopyClipboard packets? Insecure."); - handleLoadScripts = config.getBoolean("handleLoadScripts", "network", true, - "Proccess LoadScripts packet on client? Insecure, takes time, but update scripts on the fly..."); + private MineTweakerConfig() {} - sendLoadScripts = config.getBoolean("sendLoadScripts", - "network", true, "Send scripts to players on logging in"); - sendScriptsOnReloading = config.getBoolean("sendScriptsOnReloading", - "network", true, "Send scripts to players on command \"mt reload\""); + public static boolean handleDesktopPackets = false, handleLoadScripts = true, sendLoadScripts = true, + sendScriptsOnReloading = true, loadScriptsBeforeConnection = false, antiStuck = true; + static File file; - loadScriptsBeforeConnection = config.getBoolean("loadScriptsBeforeConnection", - "core", false, "Load scripts before connect to server? Save time and traffic. Requires server with disabled sendLoadScripts."); - antiStuck = config.getBoolean("antiStuck", - "core", false, "Do not reload scripts when relogging, saves time. Usable when playing on one server/singleplayer..."); - config.save(); - } + public static void load() { + Configuration config = new Configuration(file, "1"); + config.load(); + handleDesktopPackets = config.getBoolean( + "handleDesktopPackets", + "network", + false, + "Handle OpenBrowser and CopyClipboard packets? Insecure."); + handleLoadScripts = config.getBoolean( + "handleLoadScripts", + "network", + true, + "Proccess LoadScripts packet on client? Insecure, takes time, but update scripts on the fly..."); + + sendLoadScripts = config + .getBoolean("sendLoadScripts", "network", true, "Send scripts to players on logging in"); + sendScriptsOnReloading = config.getBoolean( + "sendScriptsOnReloading", + "network", + true, + "Send scripts to players on command \"mt reload\""); + + loadScriptsBeforeConnection = config.getBoolean( + "loadScriptsBeforeConnection", + "core", + false, + "Load scripts before connect to server? Save time and traffic. Requires server with disabled sendLoadScripts."); + antiStuck = config.getBoolean( + "antiStuck", + "core", + false, + "Do not reload scripts when relogging, saves time. Usable when playing on one server/singleplayer..."); + config.save(); + } } diff --git a/src/main/java/minetweaker/mc1710/MineTweakerMod.java b/src/main/java/minetweaker/mc1710/MineTweakerMod.java index 5787e6a..619729f 100644 --- a/src/main/java/minetweaker/mc1710/MineTweakerMod.java +++ b/src/main/java/minetweaker/mc1710/MineTweakerMod.java @@ -1,18 +1,13 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Mod; -import cpw.mods.fml.common.Mod.EventHandler; -import cpw.mods.fml.common.event.*; -import cpw.mods.fml.common.network.NetworkRegistry; -import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; -import cpw.mods.fml.relauncher.Side; +import java.io.File; +import java.util.List; + import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.api.logger.FileLogger; @@ -35,159 +30,167 @@ import minetweaker.runtime.*; import minetweaker.runtime.providers.ScriptProviderCascade; import minetweaker.runtime.providers.ScriptProviderCustom; import minetweaker.runtime.providers.ScriptProviderDirectory; -import net.minecraft.client.Minecraft; + import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; -import java.io.File; -import java.util.List; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.Mod; +import cpw.mods.fml.common.Mod.EventHandler; +import cpw.mods.fml.common.event.*; +import cpw.mods.fml.common.network.NetworkRegistry; +import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; +import cpw.mods.fml.relauncher.Side; /** - * Main mod class. Performs some general logic, initialization of the API and - * FML event handling. + * Main mod class. Performs some general logic, initialization of the API and FML event handling. * * @author Stan Hebben */ @Mod(modid = MineTweakerMod.MODID, version = "3.1.0") public class MineTweakerMod { - public static final String MODID = "MineTweaker3"; - public static final String MCVERSION = "1.7.10"; - public static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(MODID); + public static final String MODID = "MineTweaker3"; + public static final String MCVERSION = "1.7.10"; - private static final String[] REGISTRIES = { - "minetweaker.mods.ic2.ClassRegistry", - "minetweaker.mods.nei.ClassRegistry", - "minetweaker.mods.mfr.ClassRegistry", - "minetweaker.mods.gregtech.ClassRegistry", - "minetweaker.mods.buildcraft.ClassRegistry" - }; - private static final String[] REGISTRY_DESCRIPTIONS = { - "IC2 mod support", - "NEI mod support", - "MFR mod support", - "GregTech mod support", - "Buildcraft mod support" - }; + public static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(MODID); - static { - NETWORK.registerMessage(MineTweakerLoadScriptsHandler.class, MineTweakerLoadScriptsPacket.class, 0, Side.CLIENT); - NETWORK.registerMessage(MineTweakerOpenBrowserHandler.class, MineTweakerOpenBrowserPacket.class, 1, Side.CLIENT); - NETWORK.registerMessage(MineTweakerCopyClipboardHandler.class, MineTweakerCopyClipboardPacket.class, 2, Side.CLIENT); - } + private static final String[] REGISTRIES = { "minetweaker.mods.ic2.ClassRegistry", + "minetweaker.mods.nei.ClassRegistry", "minetweaker.mods.mfr.ClassRegistry", + "minetweaker.mods.gregtech.ClassRegistry", "minetweaker.mods.buildcraft.ClassRegistry" }; + private static final String[] REGISTRY_DESCRIPTIONS = { "IC2 mod support", "NEI mod support", "MFR mod support", + "GregTech mod support", "Buildcraft mod support" }; - @Mod.Instance(MODID) - public static MineTweakerMod INSTANCE; + static { + NETWORK.registerMessage( + MineTweakerLoadScriptsHandler.class, + MineTweakerLoadScriptsPacket.class, + 0, + Side.CLIENT); + NETWORK.registerMessage( + MineTweakerOpenBrowserHandler.class, + MineTweakerOpenBrowserPacket.class, + 1, + Side.CLIENT); + NETWORK.registerMessage( + MineTweakerCopyClipboardHandler.class, + MineTweakerCopyClipboardPacket.class, + 2, + Side.CLIENT); + } - private final IScriptProvider scriptsGlobal; - private final ScriptProviderCustom scriptsIMC; - private volatile boolean loaded = false; + @Mod.Instance(MODID) + public static MineTweakerMod INSTANCE; - public MineTweakerMod() { - MCRecipeManager.recipes = (List) CraftingManager.getInstance().getRecipeList(); - MineTweakerImplementationAPI.init( - new MCOreDict(), - new MCRecipeManager(), - new MCFurnaceManager(), - MCGame.INSTANCE, - new MCLoadedMods(), - new MCFormatter(), - new MCVanilla()); + private final IScriptProvider scriptsGlobal; + private final ScriptProviderCustom scriptsIMC; + private volatile boolean loaded = false; + public MineTweakerMod() { + MCRecipeManager.recipes = (List) CraftingManager.getInstance().getRecipeList(); + MineTweakerImplementationAPI.init( + new MCOreDict(), + new MCRecipeManager(), + new MCFurnaceManager(), + MCGame.INSTANCE, + new MCLoadedMods(), + new MCFormatter(), + new MCVanilla()); - MineTweakerImplementationAPI.logger.addLogger(new FileLogger(new File("minetweaker.log"))); - MineTweakerImplementationAPI.platform = MCPlatformFunctions.INSTANCE; + MineTweakerImplementationAPI.logger.addLogger(new FileLogger(new File("minetweaker.log"))); + MineTweakerImplementationAPI.platform = MCPlatformFunctions.INSTANCE; - File globalDir = new File("scripts"); - if (!globalDir.exists()) - globalDir.mkdirs(); + File globalDir = new File("scripts"); + if (!globalDir.exists()) globalDir.mkdirs(); - scriptsIMC = new ScriptProviderCustom("intermod"); - scriptsGlobal = new ScriptProviderDirectory(globalDir); - MineTweakerImplementationAPI.setScriptProvider(scriptsGlobal); - } + scriptsIMC = new ScriptProviderCustom("intermod"); + scriptsGlobal = new ScriptProviderDirectory(globalDir); + MineTweakerImplementationAPI.setScriptProvider(scriptsGlobal); + } - // ########################## - // ### FML Event Handlers ### - // ########################## + // ########################## + // ### FML Event Handlers ### + // ########################## - @EventHandler - public void onIMCEvent(FMLInterModComms.IMCEvent event) { - for (final FMLInterModComms.IMCMessage imcMessage : event.getMessages()) { - if (imcMessage.key.equalsIgnoreCase("addMineTweakerScript")) { - if (imcMessage.isStringMessage()) { - scriptsIMC.add(imcMessage.getSender() + "::imc", imcMessage.getStringValue()); - } else if (imcMessage.isNBTMessage()) { - NBTTagCompound message = imcMessage.getNBTValue(); - scriptsIMC.add(imcMessage.getSender() + "::" + message.getString("name"), message.getString("content")); - } - } - } - } + @EventHandler + public void onIMCEvent(FMLInterModComms.IMCEvent event) { + for (final FMLInterModComms.IMCMessage imcMessage : event.getMessages()) { + if (imcMessage.key.equalsIgnoreCase("addMineTweakerScript")) { + if (imcMessage.isStringMessage()) { + scriptsIMC.add(imcMessage.getSender() + "::imc", imcMessage.getStringValue()); + } else if (imcMessage.isNBTMessage()) { + NBTTagCompound message = imcMessage.getNBTValue(); + scriptsIMC.add( + imcMessage.getSender() + "::" + message.getString("name"), + message.getString("content")); + } + } + } + } - @EventHandler - public void onLoad(FMLPreInitializationEvent ev) { - MineTweakerConfig.file = new File(ev.getModConfigurationDirectory(), MODID + ".cfg"); - MineTweakerConfig.load(); - MinecraftForge.EVENT_BUS.register(new ForgeEventHandler()); - FMLCommonHandler.instance().bus().register(new FMLEventHandler()); - } + @EventHandler + public void onLoad(FMLPreInitializationEvent ev) { + MineTweakerConfig.file = new File(ev.getModConfigurationDirectory(), MODID + ".cfg"); + MineTweakerConfig.load(); + MinecraftForge.EVENT_BUS.register(new ForgeEventHandler()); + FMLCommonHandler.instance().bus().register(new FMLEventHandler()); + } - @EventHandler - public void onPostInit(FMLPostInitializationEvent ev) { - MineTweakerAPI.registerClassRegistry(MineTweakerRegistry.class); + @EventHandler + public void onPostInit(FMLPostInitializationEvent ev) { + MineTweakerAPI.registerClassRegistry(MineTweakerRegistry.class); - for (int i = 0; i < REGISTRIES.length; i++) { - MineTweakerAPI.registerClassRegistry(REGISTRIES[i], REGISTRY_DESCRIPTIONS[i]); - } + for (int i = 0; i < REGISTRIES.length; i++) { + MineTweakerAPI.registerClassRegistry(REGISTRIES[i], REGISTRY_DESCRIPTIONS[i]); + } - FuelTweaker.INSTANCE.register(); - } + FuelTweaker.INSTANCE.register(); + } - @EventHandler - public void onComplete(FMLLoadCompleteEvent ev) { - MineTweakerAPI.logInfo("MineTweaker: Building registry"); - ItemBracketHandler.rebuildItemRegistry(); - LiquidBracketHandler.rebuildLiquidRegistry(); - MineTweakerAPI.logInfo("MineTweaker: Sucessfully built item registry"); - if (MineTweakerPlatformUtils.isClient()) { - MineTweakerAPI.client = new MCClient(); - } - } + @EventHandler + public void onComplete(FMLLoadCompleteEvent ev) { + MineTweakerAPI.logInfo("MineTweaker: Building registry"); + ItemBracketHandler.rebuildItemRegistry(); + LiquidBracketHandler.rebuildLiquidRegistry(); + MineTweakerAPI.logInfo("MineTweaker: Sucessfully built item registry"); + if (MineTweakerPlatformUtils.isClient()) { + MineTweakerAPI.client = new MCClient(); + } + } - @EventHandler - public void onServerAboutToStart(FMLServerAboutToStartEvent ev) { - File scriptsDir = new File(MineTweakerHacks.getWorldDirectory(ev.getServer()), "scripts"); - if (!scriptsDir.exists()) { - scriptsDir.mkdir(); - } + @EventHandler + public void onServerAboutToStart(FMLServerAboutToStartEvent ev) { + File scriptsDir = new File(MineTweakerHacks.getWorldDirectory(ev.getServer()), "scripts"); + if (!scriptsDir.exists()) { + scriptsDir.mkdir(); + } - IScriptProvider scriptsLocal = new ScriptProviderDirectory(scriptsDir); - IScriptProvider cascaded = new ScriptProviderCascade(scriptsIMC, scriptsGlobal,scriptsLocal); + IScriptProvider scriptsLocal = new ScriptProviderDirectory(scriptsDir); + IScriptProvider cascaded = new ScriptProviderCascade(scriptsIMC, scriptsGlobal, scriptsLocal); - MineTweakerImplementationAPI.setScriptProvider(cascaded); - MCServer srv = new MCServer(ev.getServer()); - if (loaded && MineTweakerConfig.antiStuck) MineTweakerAPI.server = srv; - else { - MineTweakerImplementationAPI.onServerStart(srv); - loaded = true; - } - } + MineTweakerImplementationAPI.setScriptProvider(cascaded); + MCServer srv = new MCServer(ev.getServer()); + if (loaded && MineTweakerConfig.antiStuck) MineTweakerAPI.server = srv; + else { + MineTweakerImplementationAPI.onServerStart(srv); + loaded = true; + } + } - public void onClientAboutToConnect() { - if (!MineTweakerConfig.loadScriptsBeforeConnection) return; - IScriptProvider cascaded = new ScriptProviderCascade(scriptsIMC, scriptsGlobal); - MineTweakerImplementationAPI.setScriptProvider(cascaded); - if (loaded && MineTweakerConfig.antiStuck) return; - MineTweakerImplementationAPI.reload(); - loaded = true; - } + public void onClientAboutToConnect() { + if (!MineTweakerConfig.loadScriptsBeforeConnection) return; + IScriptProvider cascaded = new ScriptProviderCascade(scriptsIMC, scriptsGlobal); + MineTweakerImplementationAPI.setScriptProvider(cascaded); + if (loaded && MineTweakerConfig.antiStuck) return; + MineTweakerImplementationAPI.reload(); + loaded = true; + } - @EventHandler - public void onServerStopped(FMLServerStoppedEvent ev) { - MineTweakerImplementationAPI.onServerStop(); - MineTweakerImplementationAPI.setScriptProvider(scriptsGlobal); - } + @EventHandler + public void onServerStopped(FMLServerStoppedEvent ev) { + MineTweakerImplementationAPI.onServerStop(); + MineTweakerImplementationAPI.setScriptProvider(scriptsGlobal); + } } diff --git a/src/main/java/minetweaker/mc1710/MineTweakerRegistry.java b/src/main/java/minetweaker/mc1710/MineTweakerRegistry.java index 464f066..5b204de 100644 --- a/src/main/java/minetweaker/mc1710/MineTweakerRegistry.java +++ b/src/main/java/minetweaker/mc1710/MineTweakerRegistry.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710; @@ -13,7 +12,8 @@ import java.util.List; * @author Stan */ public class MineTweakerRegistry { - public static void getClasses(List classes) { - // method stub, actual content is generated by build process - } + + public static void getClasses(List classes) { + // method stub, actual content is generated by build process + } } diff --git a/src/main/java/minetweaker/mc1710/actions/SetBlockHardnessAction.java b/src/main/java/minetweaker/mc1710/actions/SetBlockHardnessAction.java index 63e2ac1..2667288 100644 --- a/src/main/java/minetweaker/mc1710/actions/SetBlockHardnessAction.java +++ b/src/main/java/minetweaker/mc1710/actions/SetBlockHardnessAction.java @@ -1,13 +1,13 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.actions; import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; + import net.minecraft.block.Block; import net.minecraft.item.ItemStack; @@ -41,8 +41,7 @@ public class SetBlockHardnessAction implements IUndoableAction { @Override public void undo() { - if (isBlock(stack)) - set(stack, oldHardness); + if (isBlock(stack)) set(stack, oldHardness); } @Override diff --git a/src/main/java/minetweaker/mc1710/actions/SetStackSizeAction.java b/src/main/java/minetweaker/mc1710/actions/SetStackSizeAction.java index d0a64c8..0d64b09 100644 --- a/src/main/java/minetweaker/mc1710/actions/SetStackSizeAction.java +++ b/src/main/java/minetweaker/mc1710/actions/SetStackSizeAction.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.actions; import minetweaker.IUndoableAction; + import net.minecraft.item.ItemStack; /** @@ -15,47 +15,47 @@ import net.minecraft.item.ItemStack; */ public class SetStackSizeAction implements IUndoableAction { - private final ItemStack stack; - private final int size; - private final int oldSize; + private final ItemStack stack; + private final int size; + private final int oldSize; - public SetStackSizeAction(ItemStack stack, int size) { - this.stack = stack; - this.size = size; - this.oldSize = stack.getMaxStackSize(); - } + public SetStackSizeAction(ItemStack stack, int size) { + this.stack = stack; + this.size = size; + this.oldSize = stack.getMaxStackSize(); + } - @Override - public void apply() { - set(stack, size); - } + @Override + public void apply() { + set(stack, size); + } - @Override - public boolean canUndo() { - return true; - } + @Override + public boolean canUndo() { + return true; + } - @Override - public void undo() { - set(stack, oldSize); - } + @Override + public void undo() { + set(stack, oldSize); + } - @Override - public String describe() { - return "Setting max stack size of " + stack.getDisplayName() + " to " + size; - } + @Override + public String describe() { + return "Setting max stack size of " + stack.getDisplayName() + " to " + size; + } - @Override - public String describeUndo() { - return "Reverting max stack size of " + stack.getDisplayName() + " to " + oldSize; - } + @Override + public String describeUndo() { + return "Reverting max stack size of " + stack.getDisplayName() + " to " + oldSize; + } - private static void set(ItemStack stack, int size) { - stack.getItem().setMaxStackSize(size); - } + private static void set(ItemStack stack, int size) { + stack.getItem().setMaxStackSize(size); + } - @Override - public Object getOverrideKey() { - return null; - } + @Override + public Object getOverrideKey() { + return null; + } } diff --git a/src/main/java/minetweaker/mc1710/actions/SetStackmaxDamageAction.java b/src/main/java/minetweaker/mc1710/actions/SetStackmaxDamageAction.java index 13fc0b6..0f79411 100644 --- a/src/main/java/minetweaker/mc1710/actions/SetStackmaxDamageAction.java +++ b/src/main/java/minetweaker/mc1710/actions/SetStackmaxDamageAction.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.actions; import minetweaker.IUndoableAction; + import net.minecraft.item.ItemStack; /** @@ -15,47 +15,47 @@ import net.minecraft.item.ItemStack; */ public class SetStackmaxDamageAction implements IUndoableAction { - private final ItemStack stack; - private final int damage; - private final int oldDamage; + private final ItemStack stack; + private final int damage; + private final int oldDamage; - public SetStackmaxDamageAction(ItemStack stack, int damage) { - this.stack = stack; - this.damage= damage; - this.oldDamage= stack.getMaxDamage(); - } + public SetStackmaxDamageAction(ItemStack stack, int damage) { + this.stack = stack; + this.damage = damage; + this.oldDamage = stack.getMaxDamage(); + } - @Override - public void apply() { - set(stack, damage); - } + @Override + public void apply() { + set(stack, damage); + } - @Override - public boolean canUndo() { - return true; - } + @Override + public boolean canUndo() { + return true; + } - @Override - public void undo() { - set(stack, oldDamage); - } + @Override + public void undo() { + set(stack, oldDamage); + } - @Override - public String describe() { - return "Setting max damage of " + stack.getDisplayName() + " to " + damage; - } + @Override + public String describe() { + return "Setting max damage of " + stack.getDisplayName() + " to " + damage; + } - @Override - public String describeUndo() { - return "Reverting max damage of " + stack.getDisplayName() + " to " + oldDamage; - } + @Override + public String describeUndo() { + return "Reverting max damage of " + stack.getDisplayName() + " to " + oldDamage; + } - private static void set(ItemStack stack, int damage) { - stack.getItem().setMaxDamage(damage); - } + private static void set(ItemStack stack, int damage) { + stack.getItem().setMaxDamage(damage); + } - @Override - public Object getOverrideKey() { - return null; - } + @Override + public Object getOverrideKey() { + return null; + } } diff --git a/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java b/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java index 0f889b4..e414268 100644 --- a/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java +++ b/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java @@ -1,15 +1,16 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.actions; import java.io.ByteArrayInputStream; import java.nio.charset.Charset; + import minetweaker.IUndoableAction; import minetweaker.mc1710.util.MineTweakerHacks; + import net.minecraft.util.StringTranslate; /** @@ -17,53 +18,54 @@ import net.minecraft.util.StringTranslate; * @author Stan */ public class SetTranslationAction implements IUndoableAction { - private static final StringTranslate INSTANCE = MineTweakerHacks.getStringTranslateInstance(); - private static final Charset UTF8 = Charset.forName("utf-8"); - private final String key; - private final String newValue; - private final String oldValue; + private static final StringTranslate INSTANCE = MineTweakerHacks.getStringTranslateInstance(); + private static final Charset UTF8 = Charset.forName("utf-8"); - public SetTranslationAction(String key, String value) { - this.key = key; - newValue = value; - oldValue = INSTANCE.translateKey(key); - } + private final String key; + private final String newValue; + private final String oldValue; - @Override - public void apply() { - set(key, newValue); - } + public SetTranslationAction(String key, String value) { + this.key = key; + newValue = value; + oldValue = INSTANCE.translateKey(key); + } - @Override - public boolean canUndo() { - return true; - } + @Override + public void apply() { + set(key, newValue); + } - @Override - public void undo() { - set(key, oldValue); - } + @Override + public boolean canUndo() { + return true; + } - @Override - public String describe() { - return "Translating " + key + " to " + newValue; - } + @Override + public void undo() { + set(key, oldValue); + } - @Override - public String describeUndo() { - return "Reverting " + key + " to " + oldValue; - } + @Override + public String describe() { + return "Translating " + key + " to " + newValue; + } - private static void set(String key, String value) { - if (value.contains("\\\"")) { - value = value.replace("\\\"", "\""); - } - StringTranslate.inject(new ByteArrayInputStream((key + "=" + value).getBytes(UTF8))); - } + @Override + public String describeUndo() { + return "Reverting " + key + " to " + oldValue; + } - @Override - public Object getOverrideKey() { - return null; - } + private static void set(String key, String value) { + if (value.contains("\\\"")) { + value = value.replace("\\\"", "\""); + } + StringTranslate.inject(new ByteArrayInputStream((key + "=" + value).getBytes(UTF8))); + } + + @Override + public Object getOverrideKey() { + return null; + } } diff --git a/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java b/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java index d300b98..4ea3445 100644 --- a/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java +++ b/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.block; import minetweaker.api.block.IBlockDefinition; + import net.minecraft.block.Block; /** @@ -14,23 +14,24 @@ import net.minecraft.block.Block; * @author Stan */ public class MCBlockDefinition implements IBlockDefinition { - private final Block block; - public MCBlockDefinition(Block block) { - this.block = block; - } + private final Block block; - public Block getInternalBlock() { - return block; - } + public MCBlockDefinition(Block block) { + this.block = block; + } - @Override - public String getId() { - return Block.blockRegistry.getNameForObject(block); - } + public Block getInternalBlock() { + return block; + } - @Override - public String getDisplayName() { - return block.getLocalizedName(); - } + @Override + public String getId() { + return Block.blockRegistry.getNameForObject(block); + } + + @Override + public String getDisplayName() { + return block.getLocalizedName(); + } } diff --git a/src/main/java/minetweaker/mc1710/block/MCItemBlock.java b/src/main/java/minetweaker/mc1710/block/MCItemBlock.java index 1cd153e..0b95324 100644 --- a/src/main/java/minetweaker/mc1710/block/MCItemBlock.java +++ b/src/main/java/minetweaker/mc1710/block/MCItemBlock.java @@ -1,19 +1,20 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.block; import java.util.Collections; import java.util.List; + import minetweaker.api.block.BlockPatternOr; import minetweaker.api.block.IBlock; import minetweaker.api.block.IBlockDefinition; import minetweaker.api.block.IBlockPattern; import minetweaker.api.data.IData; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; @@ -23,49 +24,50 @@ import net.minecraftforge.oredict.OreDictionary; * @author Stan */ public class MCItemBlock implements IBlock { - private final ItemStack item; - public MCItemBlock(ItemStack item) { - this.item = item; - } + private final ItemStack item; - @Override - public IBlockDefinition getDefinition() { - return MineTweakerMC.getBlockDefinition(Block.getBlockFromItem(item.getItem())); - } + public MCItemBlock(ItemStack item) { + this.item = item; + } - @Override - public int getMeta() { - return item.getItemDamage(); - } + @Override + public IBlockDefinition getDefinition() { + return MineTweakerMC.getBlockDefinition(Block.getBlockFromItem(item.getItem())); + } - @Override - public IData getTileData() { - if (item.stackTagCompound == null) - return null; + @Override + public int getMeta() { + return item.getItemDamage(); + } - return MineTweakerMC.getIData(item.stackTagCompound); - } + @Override + public IData getTileData() { + if (item.stackTagCompound == null) return null; - @Override - public String getDisplayName() { - return item.getDisplayName(); - } + return MineTweakerMC.getIData(item.stackTagCompound); + } - @Override - public List getBlocks() { - return Collections.singletonList(this); - } + @Override + public String getDisplayName() { + return item.getDisplayName(); + } - @Override - public boolean matches(IBlock block) { - return getDefinition() == block.getDefinition() - && (getMeta() == OreDictionary.WILDCARD_VALUE || getMeta() == block.getMeta()) - && (getTileData() == null || (block.getTileData() != null && block.getTileData().contains(getTileData()))); - } + @Override + public List getBlocks() { + return Collections.singletonList(this); + } - @Override - public IBlockPattern or(IBlockPattern pattern) { - return new BlockPatternOr(this, pattern); - } + @Override + public boolean matches(IBlock block) { + return getDefinition() == block.getDefinition() + && (getMeta() == OreDictionary.WILDCARD_VALUE || getMeta() == block.getMeta()) + && (getTileData() == null + || (block.getTileData() != null && block.getTileData().contains(getTileData()))); + } + + @Override + public IBlockPattern or(IBlockPattern pattern) { + return new BlockPatternOr(this, pattern); + } } diff --git a/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java b/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java index 352101c..821b5bd 100644 --- a/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java +++ b/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java @@ -1,19 +1,20 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.block; import java.util.Collections; import java.util.List; + import minetweaker.api.block.BlockPatternOr; import minetweaker.api.block.IBlock; import minetweaker.api.block.IBlockDefinition; import minetweaker.api.block.IBlockPattern; import minetweaker.api.data.IData; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraft.block.Block; import net.minecraftforge.oredict.OreDictionary; @@ -22,57 +23,57 @@ import net.minecraftforge.oredict.OreDictionary; * @author Stan */ public class MCSpecificBlock implements IBlock { - private final Block block; - private final int meta; - public MCSpecificBlock(Block block, int meta) { - this.block = block; - this.meta = meta; - } + private final Block block; + private final int meta; - @Override - public IBlockDefinition getDefinition() { - return MineTweakerMC.getBlockDefinition(block); - } + public MCSpecificBlock(Block block, int meta) { + this.block = block; + this.meta = meta; + } - @Override - public int getMeta() { - return meta; - } + @Override + public IBlockDefinition getDefinition() { + return MineTweakerMC.getBlockDefinition(block); + } - @Override - public IData getTileData() { - return null; - } + @Override + public int getMeta() { + return meta; + } - @Override - public List getBlocks() { - return Collections.singletonList(this); - } + @Override + public IData getTileData() { + return null; + } - @Override - public boolean matches(IBlock block) { - return block.getDefinition() == getDefinition() - && (meta == OreDictionary.WILDCARD_VALUE || block.getMeta() == meta); - } + @Override + public List getBlocks() { + return Collections.singletonList(this); + } - @Override - public IBlockPattern or(IBlockPattern pattern) { - return new BlockPatternOr(this, pattern); - } + @Override + public boolean matches(IBlock block) { + return block.getDefinition() == getDefinition() + && (meta == OreDictionary.WILDCARD_VALUE || block.getMeta() == meta); + } - @Override - public String getDisplayName() { - return block.getLocalizedName(); - } + @Override + public IBlockPattern or(IBlockPattern pattern) { + return new BlockPatternOr(this, pattern); + } - @Override - public String toString() { - return ""; - } + @Override + public String getDisplayName() { + return block.getLocalizedName(); + } - private static String getBlockId(Block block) - { - return Block.blockRegistry.getNameForObject(block); - } + @Override + public String toString() { + return ""; + } + + private static String getBlockId(Block block) { + return Block.blockRegistry.getNameForObject(block); + } } diff --git a/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java b/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java index 70d659d..6123a88 100644 --- a/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java +++ b/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java @@ -1,19 +1,20 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.block; import java.util.Collections; import java.util.List; + import minetweaker.api.block.BlockPatternOr; import minetweaker.api.block.IBlock; import minetweaker.api.block.IBlockDefinition; import minetweaker.api.block.IBlockPattern; import minetweaker.api.data.IData; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -27,65 +28,66 @@ import net.minecraftforge.oredict.OreDictionary; * @author Stan */ public class MCWorldBlock implements IBlock { - private final IBlockAccess blocks; - private final int x; - private final int y; - private final int z; - public MCWorldBlock(IBlockAccess blocks, int x, int y, int z) { - this.blocks = blocks; - this.x = x; - this.y = y; - this.z = z; - } + private final IBlockAccess blocks; + private final int x; + private final int y; + private final int z; - @Override - public IBlockDefinition getDefinition() { - return MineTweakerMC.getBlockDefinition(blocks.getBlock(x, y, z)); - } + public MCWorldBlock(IBlockAccess blocks, int x, int y, int z) { + this.blocks = blocks; + this.x = x; + this.y = y; + this.z = z; + } - @Override - public int getMeta() { - return blocks.getBlockMetadata(x, y, z); - } + @Override + public IBlockDefinition getDefinition() { + return MineTweakerMC.getBlockDefinition(blocks.getBlock(x, y, z)); + } - @Override - public IData getTileData() { - TileEntity tileEntity = blocks.getTileEntity(x, y, z); + @Override + public int getMeta() { + return blocks.getBlockMetadata(x, y, z); + } - if (tileEntity == null) - return null; + @Override + public IData getTileData() { + TileEntity tileEntity = blocks.getTileEntity(x, y, z); - NBTTagCompound nbt = new NBTTagCompound(); - tileEntity.writeToNBT(nbt); - return MineTweakerMC.getIData(nbt); - } + if (tileEntity == null) return null; - @Override - public String getDisplayName() { - Block block = blocks.getBlock(x, y, z); - Item item = Item.getItemFromBlock(block); - if (item != null) { - return (new ItemStack(item, 1, getMeta())).getDisplayName(); - } else { - return block.getLocalizedName(); - } - } + NBTTagCompound nbt = new NBTTagCompound(); + tileEntity.writeToNBT(nbt); + return MineTweakerMC.getIData(nbt); + } - @Override - public List getBlocks() { - return Collections.singletonList(this); - } + @Override + public String getDisplayName() { + Block block = blocks.getBlock(x, y, z); + Item item = Item.getItemFromBlock(block); + if (item != null) { + return (new ItemStack(item, 1, getMeta())).getDisplayName(); + } else { + return block.getLocalizedName(); + } + } - @Override - public boolean matches(IBlock block) { - return getDefinition() == block.getDefinition() - && (getMeta() == OreDictionary.WILDCARD_VALUE || getMeta() == block.getMeta()) - && (getTileData() == null || (block.getTileData() != null && block.getTileData().contains(getTileData()))); - } + @Override + public List getBlocks() { + return Collections.singletonList(this); + } - @Override - public IBlockPattern or(IBlockPattern pattern) { - return new BlockPatternOr(this, pattern); - } + @Override + public boolean matches(IBlock block) { + return getDefinition() == block.getDefinition() + && (getMeta() == OreDictionary.WILDCARD_VALUE || getMeta() == block.getMeta()) + && (getTileData() == null + || (block.getTileData() != null && block.getTileData().contains(getTileData()))); + } + + @Override + public IBlockPattern or(IBlockPattern pattern) { + return new BlockPatternOr(this, pattern); + } } diff --git a/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java b/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java index 773f50d..b270382 100644 --- a/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java +++ b/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.brackets; @@ -18,8 +17,10 @@ import minetweaker.MineTweakerAPI; import minetweaker.annotations.BracketHandler; import minetweaker.api.item.IItemStack; import minetweaker.api.item.IngredientAny; + import net.minecraft.item.Item; import net.minecraftforge.oredict.OreDictionary; + import stanhebben.zenscript.ZenTokener; import stanhebben.zenscript.compiler.IEnvironmentGlobal; import stanhebben.zenscript.expression.ExpressionCallStatic; @@ -38,106 +39,105 @@ import stanhebben.zenscript.util.ZenPosition; */ @BracketHandler(priority = 100) public class ItemBracketHandler implements IBracketHandler { - private static final Map itemNames = new HashMap(); - @SuppressWarnings("unchecked") - public static void rebuildItemRegistry() - { - itemNames.clear(); - - for (String itemName : (Set) Item.itemRegistry.getKeys()) { - itemNames.put(itemName.replace(" ", "").replace("'", ""), (Item) Item.itemRegistry.getObject(itemName)); - } - } - - public static IItemStack getItem(String name, int meta) { - // Item item = (Item) Item.itemRegistry.getObject(name); - Item item = itemNames.get(name); - if (item != null) { - return getIItemStackWildcardSize(item, meta); - } else { - return null; - } - } + private static final Map itemNames = new HashMap(); - private final IZenSymbol symbolAny; - private final IJavaMethod method; + @SuppressWarnings("unchecked") + public static void rebuildItemRegistry() { + itemNames.clear(); - public ItemBracketHandler() { - symbolAny = MineTweakerAPI.getJavaStaticFieldSymbol(IngredientAny.class, "INSTANCE"); - method = MineTweakerAPI.getJavaMethod( - ItemBracketHandler.class, - "getItem", - String.class, int.class); - } + for (String itemName : (Set) Item.itemRegistry.getKeys()) { + itemNames.put(itemName.replace(" ", "").replace("'", ""), (Item) Item.itemRegistry.getObject(itemName)); + } + } - @Override - public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens) { - // any symbol - if (tokens.size() == 1 && tokens.get(0).getValue().equals("*")) { - return symbolAny; - } + public static IItemStack getItem(String name, int meta) { + // Item item = (Item) Item.itemRegistry.getObject(name); + Item item = itemNames.get(name); + if (item != null) { + return getIItemStackWildcardSize(item, meta); + } else { + return null; + } + } - // detect special cases: - // item: at the start means item-specific syntax - // :xxx with xxx an integer means sub-item syntax - // :* means any-subitem-syntax - int fromIndex = 0; - int toIndex = tokens.size(); - int meta = 0; + private final IZenSymbol symbolAny; + private final IJavaMethod method; - if (tokens.size() > 2) { - if (tokens.get(0).getValue().equals("item") && tokens.get(1).getValue().equals(":")) { - fromIndex = 2; - } - if (tokens.get(tokens.size() - 1).getType() == ZenTokener.T_INTVALUE - && tokens.get(tokens.size() - 2).getValue().equals(":")) { - toIndex = tokens.size() - 2; - meta = Integer.parseInt(tokens.get(tokens.size() - 1).getValue()); - } else if (tokens.get(tokens.size() - 1).getValue().equals("*") - && tokens.get(tokens.size() - 2).getValue().equals(":")) { - toIndex = tokens.size() - 2; - meta = OreDictionary.WILDCARD_VALUE; - } - } + public ItemBracketHandler() { + symbolAny = MineTweakerAPI.getJavaStaticFieldSymbol(IngredientAny.class, "INSTANCE"); + method = MineTweakerAPI.getJavaMethod(ItemBracketHandler.class, "getItem", String.class, int.class); + } - return find(environment, tokens, fromIndex, toIndex, meta); - } + @Override + public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens) { + // any symbol + if (tokens.size() == 1 && tokens.get(0).getValue().equals("*")) { + return symbolAny; + } - private IZenSymbol find(IEnvironmentGlobal environment, List tokens, int startIndex, int endIndex, int meta) { - StringBuilder valueBuilder = new StringBuilder(); - for (int i = startIndex; i < endIndex; i++) { - Token token = tokens.get(i); - valueBuilder.append(token.getValue()); - } + // detect special cases: + // item: at the start means item-specific syntax + // :xxx with xxx an integer means sub-item syntax + // :* means any-subitem-syntax + int fromIndex = 0; + int toIndex = tokens.size(); + int meta = 0; - String itemName = valueBuilder.toString(); - if (itemNames.containsKey(itemName)) { - return new ItemReferenceSymbol(environment, itemName, meta); - } + if (tokens.size() > 2) { + if (tokens.get(0).getValue().equals("item") && tokens.get(1).getValue().equals(":")) { + fromIndex = 2; + } + if (tokens.get(tokens.size() - 1).getType() == ZenTokener.T_INTVALUE + && tokens.get(tokens.size() - 2).getValue().equals(":")) { + toIndex = tokens.size() - 2; + meta = Integer.parseInt(tokens.get(tokens.size() - 1).getValue()); + } else if (tokens.get(tokens.size() - 1).getValue().equals("*") + && tokens.get(tokens.size() - 2).getValue().equals(":")) { + toIndex = tokens.size() - 2; + meta = OreDictionary.WILDCARD_VALUE; + } + } - return null; - } + return find(environment, tokens, fromIndex, toIndex, meta); + } - private class ItemReferenceSymbol implements IZenSymbol { - private final IEnvironmentGlobal environment; - private final String name; - private final int meta; + private IZenSymbol find(IEnvironmentGlobal environment, List tokens, int startIndex, int endIndex, + int meta) { + StringBuilder valueBuilder = new StringBuilder(); + for (int i = startIndex; i < endIndex; i++) { + Token token = tokens.get(i); + valueBuilder.append(token.getValue()); + } - public ItemReferenceSymbol(IEnvironmentGlobal environment, String name, int meta) { - this.environment = environment; - this.name = name; - this.meta = meta; - } + String itemName = valueBuilder.toString(); + if (itemNames.containsKey(itemName)) { + return new ItemReferenceSymbol(environment, itemName, meta); + } - @Override - public IPartialExpression instance(ZenPosition position) { - return new ExpressionCallStatic( - position, - environment, - method, - new ExpressionString(position, name), - new ExpressionInt(position, meta, ZenType.INT)); - } - } + return null; + } + + private class ItemReferenceSymbol implements IZenSymbol { + + private final IEnvironmentGlobal environment; + private final String name; + private final int meta; + + public ItemReferenceSymbol(IEnvironmentGlobal environment, String name, int meta) { + this.environment = environment; + this.name = name; + this.meta = meta; + } + + @Override + public IPartialExpression instance(ZenPosition position) { + return new ExpressionCallStatic( + position, + environment, + method, + new ExpressionString(position, name), + new ExpressionInt(position, meta, ZenType.INT)); + } + } } diff --git a/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java b/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java index 8473478..e4959e7 100644 --- a/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java +++ b/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java @@ -6,12 +6,14 @@ import java.util.Map; import minetweaker.IBracketHandler; import minetweaker.annotations.BracketHandler; -import minetweaker.mc1710.liquid.MCLiquidStack; import minetweaker.api.liquid.ILiquidStack; +import minetweaker.mc1710.liquid.MCLiquidStack; import minetweaker.runtime.GlobalRegistry; + import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; + import stanhebben.zenscript.compiler.IEnvironmentGlobal; import stanhebben.zenscript.expression.ExpressionCallStatic; import stanhebben.zenscript.expression.ExpressionString; @@ -28,6 +30,7 @@ import stanhebben.zenscript.util.ZenPosition; */ @BracketHandler public class LiquidBracketHandler implements IBracketHandler { + private static final Map fluidNames = new HashMap(); @SuppressWarnings("unchecked") @@ -74,6 +77,7 @@ public class LiquidBracketHandler implements IBracketHandler { } private class LiquidReferenceSymbol implements IZenSymbol { + private final IEnvironmentGlobal environment; private final String name; @@ -84,7 +88,8 @@ public class LiquidBracketHandler implements IBracketHandler { @Override public IPartialExpression instance(ZenPosition position) { - IJavaMethod method = JavaMethod.get(GlobalRegistry.getTypeRegistry(), LiquidBracketHandler.class, "getLiquid", String.class); + IJavaMethod method = JavaMethod + .get(GlobalRegistry.getTypeRegistry(), LiquidBracketHandler.class, "getLiquid", String.class); return new ExpressionCallStatic(position, environment, method, new ExpressionString(position, name)); } diff --git a/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java b/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java index 680eb63..fb79c61 100644 --- a/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java +++ b/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.brackets; @@ -9,11 +8,12 @@ package minetweaker.mc1710.brackets; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; + import minetweaker.IBracketHandler; import minetweaker.MineTweakerAPI; import minetweaker.annotations.BracketHandler; -import minetweaker.mc1710.oredict.MCOreDictEntry; import minetweaker.api.oredict.IOreDictEntry; +import minetweaker.mc1710.oredict.MCOreDictEntry; import minetweaker.runtime.GlobalRegistry; import stanhebben.zenscript.compiler.IEnvironmentGlobal; import stanhebben.zenscript.expression.ExpressionCallStatic; @@ -31,67 +31,65 @@ import stanhebben.zenscript.util.ZenPosition; */ @BracketHandler public class OreBracketHandler implements IBracketHandler { - public static IOreDictEntry getOre(String name) { - return new MCOreDictEntry(name); - } - + + public static IOreDictEntry getOre(String name) { + return new MCOreDictEntry(name); + } + public static List getOreList(String wildcardName) { List result = new ArrayList(); Pattern wildcardPattern = Pattern.compile(wildcardName.replaceAll("\\*", ".+")); - + for (IOreDictEntry someOreDict : MineTweakerAPI.oreDict.getEntries()) { String oreDictName = someOreDict.getName(); if (wildcardPattern.matcher(oreDictName).matches()) { result.add(getOre(oreDictName)); } } - + return result; } - @Override - public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens) { - if (tokens.size() > 2) { - if (tokens.get(0).getValue().equals("ore") && tokens.get(1).getValue().equals(":")) { - return find(environment, tokens, 2, tokens.size()); - } - } + @Override + public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens) { + if (tokens.size() > 2) { + if (tokens.get(0).getValue().equals("ore") && tokens.get(1).getValue().equals(":")) { + return find(environment, tokens, 2, tokens.size()); + } + } - return null; - } + return null; + } - private IZenSymbol find(IEnvironmentGlobal environment, List tokens, int startIndex, int endIndex) { - StringBuilder valueBuilder = new StringBuilder(); - for (int i = startIndex; i < endIndex; i++) { - Token token = tokens.get(i); - valueBuilder.append(token.getValue()); - } + private IZenSymbol find(IEnvironmentGlobal environment, List tokens, int startIndex, int endIndex) { + StringBuilder valueBuilder = new StringBuilder(); + for (int i = startIndex; i < endIndex; i++) { + Token token = tokens.get(i); + valueBuilder.append(token.getValue()); + } - return new OreReferenceSymbol(environment, valueBuilder.toString()); - } + return new OreReferenceSymbol(environment, valueBuilder.toString()); + } - private class OreReferenceSymbol implements IZenSymbol { - private final IEnvironmentGlobal environment; - private final String name; + private class OreReferenceSymbol implements IZenSymbol { - public OreReferenceSymbol(IEnvironmentGlobal environment, String name) { - this.environment = environment; - this.name = name; - } + private final IEnvironmentGlobal environment; + private final String name; - @Override - public IPartialExpression instance(ZenPosition position) { - IJavaMethod method = JavaMethod.get( - GlobalRegistry.getTypeRegistry(), - OreBracketHandler.class, - name.contains("*") ? "getOreList" : "getOre", - String.class); + public OreReferenceSymbol(IEnvironmentGlobal environment, String name) { + this.environment = environment; + this.name = name; + } - return new ExpressionCallStatic( - position, - environment, - method, - new ExpressionString(position, name)); - } - } + @Override + public IPartialExpression instance(ZenPosition position) { + IJavaMethod method = JavaMethod.get( + GlobalRegistry.getTypeRegistry(), + OreBracketHandler.class, + name.contains("*") ? "getOreList" : "getOre", + String.class); + + return new ExpressionCallStatic(position, environment, method, new ExpressionString(position, name)); + } + } } diff --git a/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java b/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java index 1085d92..c3d413d 100644 --- a/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java +++ b/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.chat; import minetweaker.api.chat.IChatMessage; + import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; @@ -15,23 +15,24 @@ import net.minecraft.util.IChatComponent; * @author Stan */ public class MCChatMessage implements IChatMessage { - private final IChatComponent data; - public MCChatMessage(String message) { - data = new ChatComponentText(message); - } + private final IChatComponent data; - public MCChatMessage(IChatComponent data) { - this.data = data; - } + public MCChatMessage(String message) { + data = new ChatComponentText(message); + } - @Override - public IChatMessage add(IChatMessage other) { - return new MCChatMessage(data.appendSibling((IChatComponent) other.getInternal())); - } + public MCChatMessage(IChatComponent data) { + this.data = data; + } - @Override - public Object getInternal() { - return data; - } + @Override + public IChatMessage add(IChatMessage other) { + return new MCChatMessage(data.appendSibling((IChatComponent) other.getInternal())); + } + + @Override + public Object getInternal() { + return data; + } } diff --git a/src/main/java/minetweaker/mc1710/client/MCClient.java b/src/main/java/minetweaker/mc1710/client/MCClient.java index 3cb694c..1cd4166 100644 --- a/src/main/java/minetweaker/mc1710/client/MCClient.java +++ b/src/main/java/minetweaker/mc1710/client/MCClient.java @@ -1,29 +1,31 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.client; -import cpw.mods.fml.client.FMLClientHandler; import minetweaker.api.client.IClient; import minetweaker.api.minecraft.MineTweakerMC; import minetweaker.api.player.IPlayer; + import net.minecraft.client.Minecraft; +import cpw.mods.fml.client.FMLClientHandler; + /** * * @author Stan */ public class MCClient implements IClient { - @Override - public IPlayer getPlayer() { - return MineTweakerMC.getIPlayer(Minecraft.getMinecraft().thePlayer); - } - @Override - public String getLanguage() { - return FMLClientHandler.instance().getCurrentLanguage(); - } + @Override + public IPlayer getPlayer() { + return MineTweakerMC.getIPlayer(Minecraft.getMinecraft().thePlayer); + } + + @Override + public String getLanguage() { + return FMLClientHandler.instance().getCurrentLanguage(); + } } diff --git a/src/main/java/minetweaker/mc1710/data/NBTConverter.java b/src/main/java/minetweaker/mc1710/data/NBTConverter.java index bebebbf..5764fe0 100644 --- a/src/main/java/minetweaker/mc1710/data/NBTConverter.java +++ b/src/main/java/minetweaker/mc1710/data/NBTConverter.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.data; @@ -12,7 +11,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import minetweaker.mc1710.util.MineTweakerHacks; import minetweaker.api.data.DataByte; import minetweaker.api.data.DataByteArray; import minetweaker.api.data.DataDouble; @@ -26,6 +24,8 @@ import minetweaker.api.data.DataShort; import minetweaker.api.data.DataString; import minetweaker.api.data.IData; import minetweaker.api.data.IDataConverter; +import minetweaker.mc1710.util.MineTweakerHacks; + import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagByte; import net.minecraft.nbt.NBTTagByteArray; @@ -44,129 +44,128 @@ import net.minecraft.nbt.NBTTagString; * @author Stan */ public class NBTConverter implements IDataConverter { - private static final NBTConverter INSTANCE = new NBTConverter(); - public static NBTBase from(IData data) { - return data.convert(INSTANCE); - } + private static final NBTConverter INSTANCE = new NBTConverter(); - public static IData from(NBTBase nbt, boolean immutable) { - if (nbt == null) - return null; + public static NBTBase from(IData data) { + return data.convert(INSTANCE); + } - switch (nbt.getId()) { - case 1: // byte - return new DataByte(((NBTBase.NBTPrimitive) nbt).func_150290_f()); - case 2: // short - return new DataShort(((NBTBase.NBTPrimitive) nbt).func_150289_e()); - case 3: // int - return new DataInt(((NBTBase.NBTPrimitive) nbt).func_150287_d()); - case 4: // long - return new DataLong(((NBTBase.NBTPrimitive) nbt).func_150291_c()); - case 5: // float - return new DataFloat(((NBTBase.NBTPrimitive) nbt).func_150288_h()); - case 6: // double - return new DataDouble(((NBTBase.NBTPrimitive) nbt).func_150286_g()); - case 7: // byte[] - return new DataByteArray(((NBTTagByteArray) nbt).func_150292_c(), immutable); - case 8: // string - return new DataString(((NBTTagString) nbt).func_150285_a_()); - case 9: { // list - List values = new ArrayList(); - List original = MineTweakerHacks.getTagList((NBTTagList) nbt); - for (NBTBase value : original) { - values.add(from(value, immutable)); - } - return new DataList(values, immutable); - } - case 10: { // compound - Map values = new HashMap(); - NBTTagCompound original = (NBTTagCompound) nbt; - for (String key : (Set) original.func_150296_c()) { - values.put(key, from(original.getTag(key), immutable)); - } - return new DataMap(values, immutable); - } - case 11: // int[] - return new DataIntArray(((NBTTagIntArray) nbt).func_150302_c(), immutable); - default: - throw new RuntimeException("Unknown tag type: " + nbt.getId()); - } - } + public static IData from(NBTBase nbt, boolean immutable) { + if (nbt == null) return null; - public static void updateMap(NBTTagCompound nbt, IData data) { - NBTUpdater updater = new NBTUpdater(nbt); - data.convert(updater); - } + switch (nbt.getId()) { + case 1: // byte + return new DataByte(((NBTBase.NBTPrimitive) nbt).func_150290_f()); + case 2: // short + return new DataShort(((NBTBase.NBTPrimitive) nbt).func_150289_e()); + case 3: // int + return new DataInt(((NBTBase.NBTPrimitive) nbt).func_150287_d()); + case 4: // long + return new DataLong(((NBTBase.NBTPrimitive) nbt).func_150291_c()); + case 5: // float + return new DataFloat(((NBTBase.NBTPrimitive) nbt).func_150288_h()); + case 6: // double + return new DataDouble(((NBTBase.NBTPrimitive) nbt).func_150286_g()); + case 7: // byte[] + return new DataByteArray(((NBTTagByteArray) nbt).func_150292_c(), immutable); + case 8: // string + return new DataString(((NBTTagString) nbt).func_150285_a_()); + case 9: { // list + List values = new ArrayList(); + List original = MineTweakerHacks.getTagList((NBTTagList) nbt); + for (NBTBase value : original) { + values.add(from(value, immutable)); + } + return new DataList(values, immutable); + } + case 10: { // compound + Map values = new HashMap(); + NBTTagCompound original = (NBTTagCompound) nbt; + for (String key : (Set) original.func_150296_c()) { + values.put(key, from(original.getTag(key), immutable)); + } + return new DataMap(values, immutable); + } + case 11: // int[] + return new DataIntArray(((NBTTagIntArray) nbt).func_150302_c(), immutable); + default: + throw new RuntimeException("Unknown tag type: " + nbt.getId()); + } + } - public NBTConverter() { - } + public static void updateMap(NBTTagCompound nbt, IData data) { + NBTUpdater updater = new NBTUpdater(nbt); + data.convert(updater); + } - @Override - public NBTBase fromBool(boolean value) { - return new NBTTagInt(value ? 1 : 0); - } + public NBTConverter() {} - @Override - public NBTBase fromByte(byte value) { - return new NBTTagByte(value); - } + @Override + public NBTBase fromBool(boolean value) { + return new NBTTagInt(value ? 1 : 0); + } - @Override - public NBTBase fromShort(short value) { - return new NBTTagShort(value); - } + @Override + public NBTBase fromByte(byte value) { + return new NBTTagByte(value); + } - @Override - public NBTBase fromInt(int value) { - return new NBTTagInt(value); - } + @Override + public NBTBase fromShort(short value) { + return new NBTTagShort(value); + } - @Override - public NBTBase fromLong(long value) { - return new NBTTagLong(value); - } + @Override + public NBTBase fromInt(int value) { + return new NBTTagInt(value); + } - @Override - public NBTBase fromFloat(float value) { - return new NBTTagFloat(value); - } + @Override + public NBTBase fromLong(long value) { + return new NBTTagLong(value); + } - @Override - public NBTBase fromDouble(double value) { - return new NBTTagDouble(value); - } + @Override + public NBTBase fromFloat(float value) { + return new NBTTagFloat(value); + } - @Override - public NBTBase fromString(String value) { - return new NBTTagString(value); - } + @Override + public NBTBase fromDouble(double value) { + return new NBTTagDouble(value); + } - @Override - public NBTBase fromList(List values) { - NBTTagList result = new NBTTagList(); - for (IData value : values) { - result.appendTag(from(value)); - } - return result; - } + @Override + public NBTBase fromString(String value) { + return new NBTTagString(value); + } - @Override - public NBTBase fromMap(Map values) { - NBTTagCompound result = new NBTTagCompound(); - for (Map.Entry entry : values.entrySet()) { - result.setTag(entry.getKey(), from(entry.getValue())); - } - return result; - } + @Override + public NBTBase fromList(List values) { + NBTTagList result = new NBTTagList(); + for (IData value : values) { + result.appendTag(from(value)); + } + return result; + } - @Override - public NBTBase fromByteArray(byte[] value) { - return new NBTTagByteArray(value); - } + @Override + public NBTBase fromMap(Map values) { + NBTTagCompound result = new NBTTagCompound(); + for (Map.Entry entry : values.entrySet()) { + result.setTag(entry.getKey(), from(entry.getValue())); + } + return result; + } - @Override - public NBTBase fromIntArray(int[] value) { - return new NBTTagIntArray(value); - } + @Override + public NBTBase fromByteArray(byte[] value) { + return new NBTTagByteArray(value); + } + + @Override + public NBTBase fromIntArray(int[] value) { + return new NBTTagIntArray(value); + } } diff --git a/src/main/java/minetweaker/mc1710/data/NBTUpdater.java b/src/main/java/minetweaker/mc1710/data/NBTUpdater.java index da1b6bd..b23b3cb 100644 --- a/src/main/java/minetweaker/mc1710/data/NBTUpdater.java +++ b/src/main/java/minetweaker/mc1710/data/NBTUpdater.java @@ -1,14 +1,15 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.data; import java.util.Map; + import minetweaker.api.data.IData; import minetweaker.api.data.IDataConverter; + import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; @@ -17,31 +18,32 @@ import net.minecraft.nbt.NBTTagCompound; * @author Stan */ public class NBTUpdater extends NBTConverter implements IDataConverter { - private final NBTTagCompound nbt; - public NBTUpdater(NBTTagCompound compound) { - this.nbt = compound; - } + private final NBTTagCompound nbt; - @Override - public NBTBase fromMap(Map map) { - for (Map.Entry entry : map.entrySet()) { - if (nbt.hasKey(entry.getKey())) { - if (entry.getValue() == null) { - nbt.removeTag(entry.getKey()); - } else { - if (nbt.getTag(entry.getKey()).getId() == 10) { - NBTTagCompound tag = (NBTTagCompound) nbt.getTag(entry.getKey()); - nbt.setTag(entry.getKey(), entry.getValue().convert(new NBTUpdater(nbt))); - } else { - nbt.setTag(entry.getKey(), from(entry.getValue())); - } - } - } else if (entry.getValue() != null) { - nbt.setTag(entry.getKey(), from(entry.getValue())); - } - } + public NBTUpdater(NBTTagCompound compound) { + this.nbt = compound; + } - return nbt; - } + @Override + public NBTBase fromMap(Map map) { + for (Map.Entry entry : map.entrySet()) { + if (nbt.hasKey(entry.getKey())) { + if (entry.getValue() == null) { + nbt.removeTag(entry.getKey()); + } else { + if (nbt.getTag(entry.getKey()).getId() == 10) { + NBTTagCompound tag = (NBTTagCompound) nbt.getTag(entry.getKey()); + nbt.setTag(entry.getKey(), entry.getValue().convert(new NBTUpdater(nbt))); + } else { + nbt.setTag(entry.getKey(), from(entry.getValue())); + } + } + } else if (entry.getValue() != null) { + nbt.setTag(entry.getKey(), from(entry.getValue())); + } + } + + return nbt; + } } diff --git a/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java b/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java index e026987..49d7a46 100644 --- a/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java +++ b/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java @@ -1,68 +1,68 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.entity; -import cpw.mods.fml.common.registry.EntityRegistry; +import java.util.*; + import minetweaker.api.entity.IEntityDefinition; import minetweaker.api.item.*; import stanhebben.zenscript.value.*; - -import java.util.*; +import cpw.mods.fml.common.registry.EntityRegistry; /** * * @author Stan */ public class MCEntityDefinition implements IEntityDefinition { - private final EntityRegistry.EntityRegistration registration; - + + private final EntityRegistry.EntityRegistration registration; + private final Map dropsToAdd = new HashMap(); private final Map dropsToAddPlayerOnly = new HashMap(); private final List dropsToRemove = new ArrayList(); - public MCEntityDefinition(EntityRegistry.EntityRegistration registration) { - this.registration = registration; - } + public MCEntityDefinition(EntityRegistry.EntityRegistration registration) { + this.registration = registration; + } - @Override - public String getId() { - return registration.getEntityClass().getName(); - } + @Override + public String getId() { + return registration.getEntityClass().getName(); + } + + @Override + public String getName() { + return registration.getEntityName(); + } - @Override - public String getName() { - return registration.getEntityName(); - } - @Override public void addDrop(IItemStack stack, int min, int max) { - dropsToAdd.put(stack, new IntRange(min, max)); + dropsToAdd.put(stack, new IntRange(min, max)); } - + @Override public void addPlayerOnlyDrop(IItemStack stack, int min, int max) { - dropsToAddPlayerOnly.put(stack, new IntRange(min, max)); + dropsToAddPlayerOnly.put(stack, new IntRange(min, max)); } - + @Override public void removeDrop(IItemStack stack) { - dropsToRemove.add(stack); + dropsToRemove.add(stack); } - + @Override public Map getDropsToAdd() { return dropsToAdd; } - + @Override public Map getDropsToAddPlayerOnly() { return dropsToAddPlayerOnly; } - + @Override public List getDropsToRemove() { return dropsToRemove; diff --git a/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java b/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java index 312ad6f..e1dfa84 100644 --- a/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java +++ b/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.formatting; import minetweaker.api.formatting.IFormattedText; + import net.minecraft.util.EnumChatFormatting; /** @@ -14,31 +14,32 @@ import net.minecraft.util.EnumChatFormatting; * @author Stan */ public class FormattedMarkupString implements IMCFormattedString { - private final EnumChatFormatting markup; - private final IMCFormattedString contents; - public FormattedMarkupString(EnumChatFormatting markup, IMCFormattedString contents) { - this.markup = markup; - this.contents = contents; - } + private final EnumChatFormatting markup; + private final IMCFormattedString contents; - @Override - public String getTooltipString() { - return markup + contents.getTooltipString(markup.toString()); - } + public FormattedMarkupString(EnumChatFormatting markup, IMCFormattedString contents) { + this.markup = markup; + this.contents = contents; + } - @Override - public String getTooltipString(String context) { - return markup + contents.getTooltipString(context + markup); - } + @Override + public String getTooltipString() { + return markup + contents.getTooltipString(markup.toString()); + } - @Override - public IFormattedText add(IFormattedText other) { - return cat(other); - } + @Override + public String getTooltipString(String context) { + return markup + contents.getTooltipString(context + markup); + } - @Override - public IFormattedText cat(IFormattedText other) { - return new FormattedStringJoin(this, (IMCFormattedString) other); - } + @Override + public IFormattedText add(IFormattedText other) { + return cat(other); + } + + @Override + public IFormattedText cat(IFormattedText other) { + return new FormattedStringJoin(this, (IMCFormattedString) other); + } } diff --git a/src/main/java/minetweaker/mc1710/formatting/FormattedString.java b/src/main/java/minetweaker/mc1710/formatting/FormattedString.java index 6920aea..d1f5bad 100644 --- a/src/main/java/minetweaker/mc1710/formatting/FormattedString.java +++ b/src/main/java/minetweaker/mc1710/formatting/FormattedString.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.formatting; @@ -13,29 +12,30 @@ import minetweaker.api.formatting.IFormattedText; * @author Stan */ public class FormattedString implements IMCFormattedString { - private final String value; - public FormattedString(String value) { - this.value = value; - } + private final String value; - @Override - public String getTooltipString() { - return value; - } + public FormattedString(String value) { + this.value = value; + } - @Override - public String getTooltipString(String context) { - return value; - } + @Override + public String getTooltipString() { + return value; + } - @Override - public IFormattedText add(IFormattedText other) { - return cat(other); - } + @Override + public String getTooltipString(String context) { + return value; + } - @Override - public IFormattedText cat(IFormattedText other) { - return new FormattedStringJoin(this, (IMCFormattedString) other); - } + @Override + public IFormattedText add(IFormattedText other) { + return cat(other); + } + + @Override + public IFormattedText cat(IFormattedText other) { + return new FormattedStringJoin(this, (IMCFormattedString) other); + } } diff --git a/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java b/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java index 62fc90c..a96ee63 100644 --- a/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java +++ b/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java @@ -1,13 +1,14 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.formatting; import java.util.Arrays; + import minetweaker.api.formatting.IFormattedText; + import net.minecraft.util.EnumChatFormatting; /** @@ -15,53 +16,54 @@ import net.minecraft.util.EnumChatFormatting; * @author Stan */ public class FormattedStringJoin implements IMCFormattedString { - private final IMCFormattedString[] values; - public FormattedStringJoin(IMCFormattedString first, IMCFormattedString second) { - values = new IMCFormattedString[] { first, second }; - } + private final IMCFormattedString[] values; - public FormattedStringJoin(IMCFormattedString[] values) { - this.values = values; - } + public FormattedStringJoin(IMCFormattedString first, IMCFormattedString second) { + values = new IMCFormattedString[] { first, second }; + } - @Override - public String getTooltipString() { - StringBuilder result = new StringBuilder(); - for (IMCFormattedString value : values) { - result.append(value.getTooltipString()); - } - return result.toString(); - } + public FormattedStringJoin(IMCFormattedString[] values) { + this.values = values; + } - @Override - public String getTooltipString(String context) { - boolean first = true; + @Override + public String getTooltipString() { + StringBuilder result = new StringBuilder(); + for (IMCFormattedString value : values) { + result.append(value.getTooltipString()); + } + return result.toString(); + } - StringBuilder result = new StringBuilder(); - for (IMCFormattedString value : values) { - if (first) { - first = false; - } else { - result.append(context); - } + @Override + public String getTooltipString(String context) { + boolean first = true; - result.append(value.getTooltipString()); - result.append(EnumChatFormatting.RESET); - } + StringBuilder result = new StringBuilder(); + for (IMCFormattedString value : values) { + if (first) { + first = false; + } else { + result.append(context); + } - return result.toString(); - } + result.append(value.getTooltipString()); + result.append(EnumChatFormatting.RESET); + } - @Override - public IFormattedText add(IFormattedText other) { - return cat(other); - } + return result.toString(); + } - @Override - public IFormattedText cat(IFormattedText other) { - IMCFormattedString[] newValues = Arrays.copyOf(values, values.length + 1); - newValues[values.length] = (IMCFormattedString) other; - return new FormattedStringJoin(newValues); - } + @Override + public IFormattedText add(IFormattedText other) { + return cat(other); + } + + @Override + public IFormattedText cat(IFormattedText other) { + IMCFormattedString[] newValues = Arrays.copyOf(values, values.length + 1); + newValues[values.length] = (IMCFormattedString) other; + return new FormattedStringJoin(newValues); + } } diff --git a/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java b/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java index 36912d6..d7c4e5e 100644 --- a/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java +++ b/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.formatting; @@ -13,7 +12,8 @@ import minetweaker.api.formatting.IFormattedText; * @author Stan */ public interface IMCFormattedString extends IFormattedText { - public String getTooltipString(); - public String getTooltipString(String context); + public String getTooltipString(); + + public String getTooltipString(String context); } diff --git a/src/main/java/minetweaker/mc1710/formatting/MCFormatter.java b/src/main/java/minetweaker/mc1710/formatting/MCFormatter.java index 35e89f1..0551dec 100644 --- a/src/main/java/minetweaker/mc1710/formatting/MCFormatter.java +++ b/src/main/java/minetweaker/mc1710/formatting/MCFormatter.java @@ -1,13 +1,13 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.formatting; import minetweaker.api.formatting.IFormattedText; import minetweaker.api.formatting.IFormatter; + import net.minecraft.util.EnumChatFormatting; /** @@ -16,113 +16,113 @@ import net.minecraft.util.EnumChatFormatting; */ public class MCFormatter implements IFormatter { - @Override - public IFormattedText string(String text) { - return new FormattedString(text); - } + @Override + public IFormattedText string(String text) { + return new FormattedString(text); + } - @Override - public IFormattedText black(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.BLACK, (IMCFormattedString) text); - } + @Override + public IFormattedText black(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.BLACK, (IMCFormattedString) text); + } - @Override - public IFormattedText darkBlue(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.DARK_BLUE, (IMCFormattedString) text); - } + @Override + public IFormattedText darkBlue(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.DARK_BLUE, (IMCFormattedString) text); + } - @Override - public IFormattedText darkGreen(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.DARK_GREEN, (IMCFormattedString) text); - } + @Override + public IFormattedText darkGreen(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.DARK_GREEN, (IMCFormattedString) text); + } - @Override - public IFormattedText darkAqua(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.DARK_AQUA, (IMCFormattedString) text); - } + @Override + public IFormattedText darkAqua(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.DARK_AQUA, (IMCFormattedString) text); + } - @Override - public IFormattedText darkRed(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.DARK_RED, (IMCFormattedString) text); - } + @Override + public IFormattedText darkRed(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.DARK_RED, (IMCFormattedString) text); + } - @Override - public IFormattedText darkPurple(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.DARK_PURPLE, (IMCFormattedString) text); - } + @Override + public IFormattedText darkPurple(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.DARK_PURPLE, (IMCFormattedString) text); + } - @Override - public IFormattedText gold(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.GOLD, (IMCFormattedString) text); - } + @Override + public IFormattedText gold(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.GOLD, (IMCFormattedString) text); + } - @Override - public IFormattedText gray(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.GRAY, (IMCFormattedString) text); - } + @Override + public IFormattedText gray(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.GRAY, (IMCFormattedString) text); + } - @Override - public IFormattedText darkGray(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.DARK_GRAY, (IMCFormattedString) text); - } + @Override + public IFormattedText darkGray(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.DARK_GRAY, (IMCFormattedString) text); + } - @Override - public IFormattedText blue(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.BLUE, (IMCFormattedString) text); - } + @Override + public IFormattedText blue(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.BLUE, (IMCFormattedString) text); + } - @Override - public IFormattedText green(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.GREEN, (IMCFormattedString) text); - } + @Override + public IFormattedText green(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.GREEN, (IMCFormattedString) text); + } - @Override - public IFormattedText aqua(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.AQUA, (IMCFormattedString) text); - } + @Override + public IFormattedText aqua(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.AQUA, (IMCFormattedString) text); + } - @Override - public IFormattedText red(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.RED, (IMCFormattedString) text); - } + @Override + public IFormattedText red(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.RED, (IMCFormattedString) text); + } - @Override - public IFormattedText lightPurple(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.LIGHT_PURPLE, (IMCFormattedString) text); - } + @Override + public IFormattedText lightPurple(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.LIGHT_PURPLE, (IMCFormattedString) text); + } - @Override - public IFormattedText yellow(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.YELLOW, (IMCFormattedString) text); - } + @Override + public IFormattedText yellow(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.YELLOW, (IMCFormattedString) text); + } - @Override - public IFormattedText white(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.WHITE, (IMCFormattedString) text); - } + @Override + public IFormattedText white(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.WHITE, (IMCFormattedString) text); + } - @Override - public IFormattedText obfuscated(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.OBFUSCATED, (IMCFormattedString) text); - } + @Override + public IFormattedText obfuscated(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.OBFUSCATED, (IMCFormattedString) text); + } - @Override - public IFormattedText bold(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.BOLD, (IMCFormattedString) text); - } + @Override + public IFormattedText bold(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.BOLD, (IMCFormattedString) text); + } - @Override - public IFormattedText strikethrough(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.STRIKETHROUGH, (IMCFormattedString) text); - } + @Override + public IFormattedText strikethrough(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.STRIKETHROUGH, (IMCFormattedString) text); + } - @Override - public IFormattedText underline(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.UNDERLINE, (IMCFormattedString) text); - } + @Override + public IFormattedText underline(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.UNDERLINE, (IMCFormattedString) text); + } - @Override - public IFormattedText italic(IFormattedText text) { - return new FormattedMarkupString(EnumChatFormatting.ITALIC, (IMCFormattedString) text); - } + @Override + public IFormattedText italic(IFormattedText text) { + return new FormattedMarkupString(EnumChatFormatting.ITALIC, (IMCFormattedString) text); + } } diff --git a/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java b/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java index a05f20e..9b78a2b 100644 --- a/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java +++ b/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java @@ -1,94 +1,100 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.furnace; -import cpw.mods.fml.common.IFuelHandler; -import cpw.mods.fml.common.registry.GameRegistry; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; + import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import cpw.mods.fml.common.IFuelHandler; +import cpw.mods.fml.common.registry.GameRegistry; + public class FuelTweaker { - public static final FuelTweaker INSTANCE = new FuelTweaker(); - private List original; - private final HashMap> quickList = new HashMap>(); + public static final FuelTweaker INSTANCE = new FuelTweaker(); - private FuelTweaker() { - } + private List original; + private final HashMap> quickList = new HashMap>(); - public void register() { - try { - Field fuelHandlers = GameRegistry.class.getDeclaredField("fuelHandlers"); - fuelHandlers.setAccessible(true); - original = (List) fuelHandlers.get(null); - List modified = new ArrayList(); - modified.add(new OverridingFuelHandler()); - fuelHandlers.set(null, modified); - } catch (NoSuchFieldException ex) { - System.out.println("[MineTweaker] Error: could not get GameRegistry fuel handlers field. Cannot use custom fuel values."); - } catch (SecurityException ex) { - System.out.println("[MineTweaker] Error: could not alter GameRegistry fuel handlers field. Cannot use custom fuel values."); - } catch (IllegalAccessException ex) { - System.out.println("[MineTweaker] Error: could not alter GameRegistry fuel handlers field. Cannot use custom fuel values."); - } - } + private FuelTweaker() {} - public void addFuelPattern(SetFuelPattern pattern) { - List items = pattern.getPattern().getItems(); - if (items == null) { - MineTweakerAPI.logError("Cannot set fuel for <*>"); - return; - } + public void register() { + try { + Field fuelHandlers = GameRegistry.class.getDeclaredField("fuelHandlers"); + fuelHandlers.setAccessible(true); + original = (List) fuelHandlers.get(null); + List modified = new ArrayList(); + modified.add(new OverridingFuelHandler()); + fuelHandlers.set(null, modified); + } catch (NoSuchFieldException ex) { + System.out.println( + "[MineTweaker] Error: could not get GameRegistry fuel handlers field. Cannot use custom fuel values."); + } catch (SecurityException ex) { + System.out.println( + "[MineTweaker] Error: could not alter GameRegistry fuel handlers field. Cannot use custom fuel values."); + } catch (IllegalAccessException ex) { + System.out.println( + "[MineTweaker] Error: could not alter GameRegistry fuel handlers field. Cannot use custom fuel values."); + } + } - for (IItemStack item : pattern.getPattern().getItems()) { - ItemStack itemStack = MineTweakerMC.getItemStack(item); - Item mcItem = itemStack.getItem(); - if (!quickList.containsKey(mcItem)) { - quickList.put(mcItem, new ArrayList()); - } - quickList.get(mcItem).add(pattern); - } - } + public void addFuelPattern(SetFuelPattern pattern) { + List items = pattern.getPattern().getItems(); + if (items == null) { + MineTweakerAPI.logError("Cannot set fuel for <*>"); + return; + } - public void removeFuelPattern(SetFuelPattern pattern) { - for (IItemStack item : pattern.getPattern().getItems()) { - ItemStack itemStack = MineTweakerMC.getItemStack(item); - Item mcItem = itemStack.getItem(); - if (quickList.containsKey(mcItem)) { - quickList.get(mcItem).remove(pattern); - } - } - } + for (IItemStack item : pattern.getPattern().getItems()) { + ItemStack itemStack = MineTweakerMC.getItemStack(item); + Item mcItem = itemStack.getItem(); + if (!quickList.containsKey(mcItem)) { + quickList.put(mcItem, new ArrayList()); + } + quickList.get(mcItem).add(pattern); + } + } - private class OverridingFuelHandler implements IFuelHandler { - @Override - public int getBurnTime(ItemStack fuel) { - if (quickList.containsKey(fuel.getItem())) { - IItemStack stack = MineTweakerMC.getIItemStack(fuel); + public void removeFuelPattern(SetFuelPattern pattern) { + for (IItemStack item : pattern.getPattern().getItems()) { + ItemStack itemStack = MineTweakerMC.getItemStack(item); + Item mcItem = itemStack.getItem(); + if (quickList.containsKey(mcItem)) { + quickList.get(mcItem).remove(pattern); + } + } + } - for (SetFuelPattern override : quickList.get(fuel.getItem())) { - if (override.getPattern().matches(stack)) { - return override.getValue(); - } - } - } + private class OverridingFuelHandler implements IFuelHandler { - int max = 0; - for (IFuelHandler handler : original) { - max = Math.max(max, handler.getBurnTime(fuel)); - } - return max; - } - } + @Override + public int getBurnTime(ItemStack fuel) { + if (quickList.containsKey(fuel.getItem())) { + IItemStack stack = MineTweakerMC.getIItemStack(fuel); + + for (SetFuelPattern override : quickList.get(fuel.getItem())) { + if (override.getPattern().matches(stack)) { + return override.getValue(); + } + } + } + + int max = 0; + for (IFuelHandler handler : original) { + max = Math.max(max, handler.getBurnTime(fuel)); + } + return max; + } + } } diff --git a/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java b/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java index aaabd99..ec161ed 100644 --- a/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java +++ b/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java @@ -1,12 +1,18 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.furnace; -import cpw.mods.fml.common.registry.GameRegistry; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; @@ -15,29 +21,24 @@ import minetweaker.api.recipes.FurnaceRecipe; import minetweaker.api.recipes.IFurnaceManager; import minetweaker.api.recipes.IFurnaceRecipe; import minetweaker.mc1710.item.MCItemStack; + import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; +import cpw.mods.fml.common.registry.GameRegistry; /** * @author Stan */ public class MCFurnaceManager implements IFurnaceManager { + public MCFurnaceManager() { } @Override public void remove(IIngredient output, IIngredient input) { - if (output == null) - throw new IllegalArgumentException("output cannot be null"); + if (output == null) throw new IllegalArgumentException("output cannot be null"); Map smeltingList = FurnaceRecipes.smelting().getSmeltingList(); @@ -83,8 +84,13 @@ public class MCFurnaceManager implements IFurnaceManager { @Override public List getAll() { List retList = new ArrayList(); - for (Map.Entry ent : (Set>) FurnaceRecipes.smelting().getSmeltingList().entrySet()) { - retList.add(new FurnaceRecipe(new MCItemStack(ent.getKey()), new MCItemStack(ent.getValue()), FurnaceRecipes.smelting().func_151398_b(ent.getValue()))); + for (Map.Entry ent : (Set>) FurnaceRecipes.smelting() + .getSmeltingList().entrySet()) { + retList.add( + new FurnaceRecipe( + new MCItemStack(ent.getKey()), + new MCItemStack(ent.getValue()), + FurnaceRecipes.smelting().func_151398_b(ent.getValue()))); } return retList; } @@ -94,6 +100,7 @@ public class MCFurnaceManager implements IFurnaceManager { // ###################### private static class RemoveAction implements IUndoableAction { + private final List items; private final List values; @@ -138,6 +145,7 @@ public class MCFurnaceManager implements IFurnaceManager { } private static class AddRecipeAction implements IUndoableAction { + private final IIngredient ingredient; private final ItemStack[] input; private final ItemStack output; @@ -186,6 +194,7 @@ public class MCFurnaceManager implements IFurnaceManager { } private static class SetFuelAction implements IUndoableAction { + private final SetFuelPattern pattern; public SetFuelAction(SetFuelPattern pattern) { diff --git a/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java b/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java index 61e724d..6bd7822 100644 --- a/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java +++ b/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java @@ -3,19 +3,20 @@ package minetweaker.mc1710.furnace; import minetweaker.api.item.IIngredient; public class SetFuelPattern { - private final IIngredient pattern; - private final int value; - public SetFuelPattern(IIngredient pattern, int value) { - this.pattern = pattern; - this.value = value; - } + private final IIngredient pattern; + private final int value; - public IIngredient getPattern() { - return pattern; - } + public SetFuelPattern(IIngredient pattern, int value) { + this.pattern = pattern; + this.value = value; + } - public int getValue() { - return value; - } + public IIngredient getPattern() { + return pattern; + } + + public int getValue() { + return value; + } } diff --git a/src/main/java/minetweaker/mc1710/game/MCGame.java b/src/main/java/minetweaker/mc1710/game/MCGame.java index c1c38ec..9cf79d7 100644 --- a/src/main/java/minetweaker/mc1710/game/MCGame.java +++ b/src/main/java/minetweaker/mc1710/game/MCGame.java @@ -1,18 +1,15 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.game; -import com.google.common.collect.*; -import cpw.mods.fml.common.registry.EntityRegistry; -import cpw.mods.fml.common.registry.LanguageRegistry; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.block.IBlockDefinition; @@ -23,13 +20,12 @@ import minetweaker.api.item.IItemDefinition; import minetweaker.api.liquid.ILiquidDefinition; import minetweaker.api.minecraft.MineTweakerMC; import minetweaker.api.world.IBiome; -// TODO Find this -// import GuiCannotRemodify; import minetweaker.mc1710.entity.MCEntityDefinition; import minetweaker.mc1710.item.MCItemDefinition; import minetweaker.mc1710.liquid.MCLiquidDefinition; import minetweaker.mc1710.util.MineTweakerHacks; import minetweaker.mc1710.util.MineTweakerPlatformUtils; + import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.item.Item; @@ -37,212 +33,213 @@ import net.minecraft.util.*; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; +import com.google.common.collect.*; + +import cpw.mods.fml.common.registry.EntityRegistry; +import cpw.mods.fml.common.registry.LanguageRegistry; + /** * * @author Stan */ public class MCGame implements IGame { - private static final Map TRANSLATIONS = MineTweakerHacks.getTranslations(); - public static final MCGame INSTANCE = new MCGame(); + private static final Map TRANSLATIONS = MineTweakerHacks.getTranslations(); - private boolean locked = false; + public static final MCGame INSTANCE = new MCGame(); + + private boolean locked = false; private static final List ENTITY_DEFINITIONS = new ArrayList(); - - private MCGame() { - } - @Override - public List getItems() { - List result = new ArrayList(); - for (String item : (Set) Item.itemRegistry.getKeys()) { - result.add(new MCItemDefinition(item, (Item) Item.itemRegistry.getObject(item))); - } - return result; - } + private MCGame() {} - @Override - public List getBlocks() { - List result = new ArrayList(); - for (String block : (Set) Block.blockRegistry.getKeys()) { - result.add(MineTweakerMC.getBlockDefinition((Block) Block.blockRegistry.getObject(block))); - } + @Override + public List getItems() { + List result = new ArrayList(); + for (String item : (Set) Item.itemRegistry.getKeys()) { + result.add(new MCItemDefinition(item, (Item) Item.itemRegistry.getObject(item))); + } + return result; + } - return result; - } + @Override + public List getBlocks() { + List result = new ArrayList(); + for (String block : (Set) Block.blockRegistry.getKeys()) { + result.add(MineTweakerMC.getBlockDefinition((Block) Block.blockRegistry.getObject(block))); + } - @Override - public List getLiquids() { - List result = new ArrayList(); - for (Map.Entry entry : FluidRegistry.getRegisteredFluids().entrySet()) { - result.add(new MCLiquidDefinition(entry.getValue())); - } - return result; - } + return result; + } + + @Override + public List getLiquids() { + List result = new ArrayList(); + for (Map.Entry entry : FluidRegistry.getRegisteredFluids().entrySet()) { + result.add(new MCLiquidDefinition(entry.getValue())); + } + return result; + } + + @Override + public List getBiomes() { + List result = new ArrayList(); + for (IBiome biome : MineTweakerMC.biomes) { + if (biome != null) { + result.add(biome); + } + } + return result; + } - @Override - public List getBiomes() { - List result = new ArrayList(); - for (IBiome biome : MineTweakerMC.biomes) { - if (biome != null) { - result.add(biome); - } - } - return result; - } - @Override public List getEntities() { final Set values = MineTweakerHacks.getEntityClassRegistrations().values(); - if(Iterables.size(values) != ENTITY_DEFINITIONS.size()) { + if (Iterables.size(values) != ENTITY_DEFINITIONS.size()) { ENTITY_DEFINITIONS.clear(); - for(EntityRegistry.EntityRegistration entry : values) { + for (EntityRegistry.EntityRegistration entry : values) { ENTITY_DEFINITIONS.add(new MCEntityDefinition(entry)); } } return ENTITY_DEFINITIONS; } - + @Override public IEntityDefinition getEntity(String entityName) { - for(IEntityDefinition ent : getEntities()) { - if(ent.getName().equalsIgnoreCase(entityName)) { + for (IEntityDefinition ent : getEntities()) { + if (ent.getName().equalsIgnoreCase(entityName)) { return ent; } } boolean needsReloading = false; - for(EntityRegistry.EntityRegistration res : MineTweakerHacks.getEntityClassRegistrations().values()) { - if(res.getEntityName().equalsIgnoreCase(entityName)) { + for (EntityRegistry.EntityRegistration res : MineTweakerHacks.getEntityClassRegistrations().values()) { + if (res.getEntityName().equalsIgnoreCase(entityName)) { needsReloading = true; break; } } - if(needsReloading) { + if (needsReloading) { ENTITY_DEFINITIONS.clear(); - for(EntityRegistry.EntityRegistration entry : MineTweakerHacks.getEntityClassRegistrations().values()) { + for (EntityRegistry.EntityRegistration entry : MineTweakerHacks.getEntityClassRegistrations().values()) { ENTITY_DEFINITIONS.add(new MCEntityDefinition(entry)); } } - - for(IEntityDefinition entity : getEntities()) { - if(entity.getName().equalsIgnoreCase(entityName)) { + + for (IEntityDefinition entity : getEntities()) { + if (entity.getName().equalsIgnoreCase(entityName)) { return entity; } } return null; - + } - + @Override - public void setLocalization(String key, String value) { - MineTweakerAPI.apply(new SetTranslation(null, key, value)); - } + public void setLocalization(String key, String value) { + MineTweakerAPI.apply(new SetTranslation(null, key, value)); + } - @Override - public void setLocalization(String lang, String key, String value) { - MineTweakerAPI.apply(new SetTranslation(lang, key, value)); - } + @Override + public void setLocalization(String lang, String key, String value) { + MineTweakerAPI.apply(new SetTranslation(lang, key, value)); + } - @Override - public String localize(String key) { - return LanguageRegistry.instance().getStringLocalization(key); - } + @Override + public String localize(String key) { + return LanguageRegistry.instance().getStringLocalization(key); + } - @Override - public String localize(String key, String lang) { - return LanguageRegistry.instance().getStringLocalization(key, lang); - } + @Override + public String localize(String key, String lang) { + return LanguageRegistry.instance().getStringLocalization(key, lang); + } - @Override - public void lock() - { - locked = true; - } + @Override + public void lock() { + locked = true; + } - @Override - public boolean isLocked() - { - return locked; - } + @Override + public boolean isLocked() { + return locked; + } - @Override - public void signalLockError() - { - MineTweakerAPI.getLogger().logError("Reload of scripts blocked (script lock)"); + @Override + public void signalLockError() { + MineTweakerAPI.getLogger().logError("Reload of scripts blocked (script lock)"); - if (Minecraft.isGuiEnabled()) { - // Commented out due to unresolved import - /** - * Minecraft.getMinecraft().displayGuiScreen( new GuiCannotRemodify( - * "Minecraft has been tweaked for another server", - * "with modifications that cannot be rolled back.", - * "Please restart your game.")); - **/ - } - } + if (Minecraft.isGuiEnabled()) { + // Commented out due to unresolved import + /** + * Minecraft.getMinecraft().displayGuiScreen( new GuiCannotRemodify( "Minecraft has been tweaked for another + * server", "with modifications that cannot be rolled back.", "Please restart your game.")); + **/ + } + } - // ###################### - // ### Action classes ### - // ###################### + // ###################### + // ### Action classes ### + // ###################### - /** - * Ported from ModTweaker. - * - * @author Joshiejack - */ - private static class SetTranslation implements IUndoableAction { - private String original; - private final String lang; - private final String key; - private final String text; - private boolean added; + /** + * Ported from ModTweaker. + * + * @author Joshiejack + */ + private static class SetTranslation implements IUndoableAction { - public SetTranslation(String lang, String key, String text) { - this.lang = lang; - this.key = key; - this.text = text; - } + private String original; + private final String lang; + private final String key; + private final String text; + private boolean added; - @Override - public void apply() { - if (lang == null || MineTweakerPlatformUtils.isLanguageActive(lang)) { - original = TRANSLATIONS.get(key); - TRANSLATIONS.put(key, text); - added = true; - } else { - added = false; - } - } + public SetTranslation(String lang, String key, String text) { + this.lang = lang; + this.key = key; + this.text = text; + } - @Override - public boolean canUndo() { - return TRANSLATIONS != null; - } + @Override + public void apply() { + if (lang == null || MineTweakerPlatformUtils.isLanguageActive(lang)) { + original = TRANSLATIONS.get(key); + TRANSLATIONS.put(key, text); + added = true; + } else { + added = false; + } + } - @Override - public void undo() { - if (added) { - if (original == null) { - TRANSLATIONS.remove(key); - } else { - TRANSLATIONS.put(key, original); - } - } - } + @Override + public boolean canUndo() { + return TRANSLATIONS != null; + } - @Override - public String describe() { - return "Setting localization for the key: " + key + " to " + text; - } + @Override + public void undo() { + if (added) { + if (original == null) { + TRANSLATIONS.remove(key); + } else { + TRANSLATIONS.put(key, original); + } + } + } - @Override - public String describeUndo() { - return "Setting localization for the key: " + key + " to " + original; - } + @Override + public String describe() { + return "Setting localization for the key: " + key + " to " + text; + } - @Override - public Object getOverrideKey() { - return null; - } - } + @Override + public String describeUndo() { + return "Setting localization for the key: " + key + " to " + original; + } + + @Override + public Object getOverrideKey() { + return null; + } + } } diff --git a/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java b/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java index 892cd37..10beeba 100644 --- a/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java +++ b/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java @@ -1,18 +1,19 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.item; import java.util.ArrayList; import java.util.List; + import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemDefinition; import minetweaker.api.item.IItemStack; import minetweaker.api.minecraft.MineTweakerMC; import minetweaker.api.oredict.IOreDictEntry; + import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; @@ -22,68 +23,69 @@ import net.minecraftforge.oredict.OreDictionary; * @author Stan */ public class MCItemDefinition implements IItemDefinition { - private final String id; - private final Item item; - public MCItemDefinition(String id, Item item) { - this.id = id; - this.item = item; - } + private final String id; + private final Item item; - @Override - public String getId() { - return id; - } + public MCItemDefinition(String id, Item item) { + this.id = id; + this.item = item; + } - @Override - public String getName() { - return item.getUnlocalizedName(); - } + @Override + public String getId() { + return id; + } - @Override - public IItemStack makeStack(int meta) { - return MineTweakerMC.getIItemStackWildcardSize(new ItemStack(item, 1, meta)); - } + @Override + public String getName() { + return item.getUnlocalizedName(); + } - @Override - public List getOres() { - List result = new ArrayList(); + @Override + public IItemStack makeStack(int meta) { + return MineTweakerMC.getIItemStackWildcardSize(new ItemStack(item, 1, meta)); + } - for (String key : OreDictionary.getOreNames()) { - for (ItemStack is : OreDictionary.getOres(key)) { - if (is.getItem() == item) { - result.add(MineTweakerAPI.oreDict.get(key)); - break; - } - } - } + @Override + public List getOres() { + List result = new ArrayList(); - return result; - } + for (String key : OreDictionary.getOreNames()) { + for (ItemStack is : OreDictionary.getOres(key)) { + if (is.getItem() == item) { + result.add(MineTweakerAPI.oreDict.get(key)); + break; + } + } + } - // ############################# - // ### Object implementation ### - // ############################# + return result; + } - @Override - public int hashCode() { - int hash = 7; - hash = 37 * hash + (this.item != null ? this.item.hashCode() : 0); - return hash; - } + // ############################# + // ### Object implementation ### + // ############################# - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MCItemDefinition other = (MCItemDefinition) obj; - if (this.item != other.item && (this.item == null || !this.item.equals(other.item))) { - return false; - } - return true; - } + @Override + public int hashCode() { + int hash = 7; + hash = 37 * hash + (this.item != null ? this.item.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MCItemDefinition other = (MCItemDefinition) obj; + if (this.item != other.item && (this.item == null || !this.item.equals(other.item))) { + return false; + } + return true; + } } diff --git a/src/main/java/minetweaker/mc1710/item/MCItemStack.java b/src/main/java/minetweaker/mc1710/item/MCItemStack.java index b7423cb..e8b3296 100644 --- a/src/main/java/minetweaker/mc1710/item/MCItemStack.java +++ b/src/main/java/minetweaker/mc1710/item/MCItemStack.java @@ -1,12 +1,17 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.item; -import cpw.mods.fml.relauncher.ReflectionHelper; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + import minetweaker.MineTweakerAPI; import minetweaker.api.block.IBlock; import minetweaker.api.data.DataMap; @@ -23,6 +28,7 @@ import minetweaker.mc1710.block.MCItemBlock; import minetweaker.mc1710.data.NBTConverter; import minetweaker.mc1710.liquid.MCLiquidStack; import minetweaker.util.ArrayUtil; + import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -31,198 +37,191 @@ import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import cpw.mods.fml.relauncher.ReflectionHelper; /** * * @author Stan */ public class MCItemStack implements IItemStack { - private final ItemStack stack; - private final List items; - private IData tag = null; - private boolean wildcardSize; - public MCItemStack(ItemStack itemStack) { - if (itemStack == null) - throw new IllegalArgumentException("stack cannot be null"); + private final ItemStack stack; + private final List items; + private IData tag = null; + private boolean wildcardSize; - stack = itemStack.copy(); - items = Collections.singletonList(this); - } + public MCItemStack(ItemStack itemStack) { + if (itemStack == null) throw new IllegalArgumentException("stack cannot be null"); - public MCItemStack(ItemStack itemStack, boolean wildcardSize) { - this(itemStack); + stack = itemStack.copy(); + items = Collections.singletonList(this); + } - this.wildcardSize = wildcardSize; - } + public MCItemStack(ItemStack itemStack, boolean wildcardSize) { + this(itemStack); - private MCItemStack(ItemStack itemStack, IData tag) { - if (itemStack == null) - throw new IllegalArgumentException("stack cannot be null"); + this.wildcardSize = wildcardSize; + } - stack = itemStack; - items = Collections.singletonList(this); - this.tag = tag; - } + private MCItemStack(ItemStack itemStack, IData tag) { + if (itemStack == null) throw new IllegalArgumentException("stack cannot be null"); - private MCItemStack(ItemStack itemStack, IData tag, boolean wildcardSize) { - stack = itemStack; - items = Collections.singletonList(this); - this.tag = tag; - this.wildcardSize = wildcardSize; - } + stack = itemStack; + items = Collections.singletonList(this); + this.tag = tag; + } - @Override - public IItemDefinition getDefinition() { - return new MCItemDefinition(Item.itemRegistry.getNameForObject(stack.getItem()), stack.getItem()); - } + private MCItemStack(ItemStack itemStack, IData tag, boolean wildcardSize) { + stack = itemStack; + items = Collections.singletonList(this); + this.tag = tag; + this.wildcardSize = wildcardSize; + } - @Override - public String getName() { - return stack.getUnlocalizedName(); - } + @Override + public IItemDefinition getDefinition() { + return new MCItemDefinition(Item.itemRegistry.getNameForObject(stack.getItem()), stack.getItem()); + } - @Override - public String getDisplayName() { - return stack.getDisplayName(); - } + @Override + public String getName() { + return stack.getUnlocalizedName(); + } - @Override - public void setDisplayName(String name) { - MineTweakerAPI.apply(new SetTranslationAction(getName() + ".name", name)); - } + @Override + public String getDisplayName() { + return stack.getDisplayName(); + } + @Override + public void setDisplayName(String name) { + MineTweakerAPI.apply(new SetTranslationAction(getName() + ".name", name)); + } - @Override - public void setMaxDamage(int damage) { - MineTweakerAPI.apply(new SetStackmaxDamageAction(stack, damage)); - } + @Override + public void setMaxDamage(int damage) { + MineTweakerAPI.apply(new SetStackmaxDamageAction(stack, damage)); + } - @Override - public int getMaxStackSize() { - return stack.getMaxStackSize(); - } + @Override + public int getMaxStackSize() { + return stack.getMaxStackSize(); + } - @Override - public void setMaxStackSize(int size) { - MineTweakerAPI.apply(new SetStackSizeAction((ItemStack) getInternal(), size)); - } + @Override + public void setMaxStackSize(int size) { + MineTweakerAPI.apply(new SetStackSizeAction((ItemStack) getInternal(), size)); + } - @Override - public float getBlockHardness() { - return ReflectionHelper.getPrivateValue(Block.class, Block.getBlockFromItem(stack.getItem()), "blockHardness"); - } + @Override + public float getBlockHardness() { + return ReflectionHelper.getPrivateValue(Block.class, Block.getBlockFromItem(stack.getItem()), "blockHardness"); + } - @Override - public void setBlockHardness(float hardness) { - MineTweakerAPI.apply(new SetBlockHardnessAction(stack, hardness)); - } + @Override + public void setBlockHardness(float hardness) { + MineTweakerAPI.apply(new SetBlockHardnessAction(stack, hardness)); + } - @Override - public int getDamage() { - return stack.getItemDamage(); - } + @Override + public int getDamage() { + return stack.getItemDamage(); + } - @Override - public IData getTag() { - if (tag == null) { - if (stack.stackTagCompound == null) { - return DataMap.EMPTY; - } + @Override + public IData getTag() { + if (tag == null) { + if (stack.stackTagCompound == null) { + return DataMap.EMPTY; + } - tag = NBTConverter.from(stack.stackTagCompound, true); - } - return tag; - } + tag = NBTConverter.from(stack.stackTagCompound, true); + } + return tag; + } - @Override - public int getMaxDamage() { - return stack.getMaxDamage(); - } + @Override + public int getMaxDamage() { + return stack.getMaxDamage(); + } - @Override - public ILiquidStack getLiquid() { - FluidStack liquid = FluidContainerRegistry.getFluidForFilledItem(stack); - return liquid == null ? null : new MCLiquidStack(liquid); - } + @Override + public ILiquidStack getLiquid() { + FluidStack liquid = FluidContainerRegistry.getFluidForFilledItem(stack); + return liquid == null ? null : new MCLiquidStack(liquid); + } - @Override - public IIngredient anyDamage() { - if (stack.getItem().getHasSubtypes()) { - MineTweakerAPI.logWarning("subitems don't have damaged states"); - return this; - } else { - ItemStack result = new ItemStack(stack.getItem(), stack.stackSize, OreDictionary.WILDCARD_VALUE); - result.stackTagCompound = stack.stackTagCompound; - return new MCItemStack(result, tag); - } - } + @Override + public IIngredient anyDamage() { + if (stack.getItem().getHasSubtypes()) { + MineTweakerAPI.logWarning("subitems don't have damaged states"); + return this; + } else { + ItemStack result = new ItemStack(stack.getItem(), stack.stackSize, OreDictionary.WILDCARD_VALUE); + result.stackTagCompound = stack.stackTagCompound; + return new MCItemStack(result, tag); + } + } - @Override - public IItemStack withDamage(int damage) { - if (stack.getItem().getHasSubtypes()) { - MineTweakerAPI.logWarning("subitems don't have damaged states"); - return this; - } else { - ItemStack result = new ItemStack(stack.getItem(), stack.stackSize, damage); - result.stackTagCompound = stack.stackTagCompound; - return new MCItemStack(result, tag); - } - } + @Override + public IItemStack withDamage(int damage) { + if (stack.getItem().getHasSubtypes()) { + MineTweakerAPI.logWarning("subitems don't have damaged states"); + return this; + } else { + ItemStack result = new ItemStack(stack.getItem(), stack.stackSize, damage); + result.stackTagCompound = stack.stackTagCompound; + return new MCItemStack(result, tag); + } + } - @Override - public IItemStack anyAmount() { - ItemStack result = new ItemStack(stack.getItem(), 1, stack.getItemDamage()); - result.stackTagCompound = stack.stackTagCompound; - return new MCItemStack(result, tag, true); - } + @Override + public IItemStack anyAmount() { + ItemStack result = new ItemStack(stack.getItem(), 1, stack.getItemDamage()); + result.stackTagCompound = stack.stackTagCompound; + return new MCItemStack(result, tag, true); + } - @Override - public IItemStack withAmount(int amount) { - ItemStack result = new ItemStack(stack.getItem(), amount, stack.getItemDamage()); - result.stackTagCompound = stack.stackTagCompound; - return new MCItemStack(result, tag); - } + @Override + public IItemStack withAmount(int amount) { + ItemStack result = new ItemStack(stack.getItem(), amount, stack.getItemDamage()); + result.stackTagCompound = stack.stackTagCompound; + return new MCItemStack(result, tag); + } + + @Override + public IItemStack withTag(IData tag) { + ItemStack result = new ItemStack(stack.getItem(), stack.stackSize, stack.getItemDamage()); + if (tag == null) { + result.stackTagCompound = null; + } else { + result.stackTagCompound = (NBTTagCompound) NBTConverter.from(tag); + } + return new MCItemStack(result, tag); + } - @Override - public IItemStack withTag(IData tag) { - ItemStack result = new ItemStack(stack.getItem(), stack.stackSize, stack.getItemDamage()); - if (tag == null) { - result.stackTagCompound = null; - } else { - result.stackTagCompound = (NBTTagCompound) NBTConverter.from(tag); - } - return new MCItemStack(result, tag); - } - @Override public IItemStack withEmptyTag() { final ItemStack itemStack = new ItemStack(stack.getItem(), stack.stackSize, stack.getItemDamage()); itemStack.stackTagCompound = null; return new MCItemStack(itemStack); } - + @Override - public IItemStack updateTag(IData tagUpdate) { - if (tag == null) { - if (stack.stackTagCompound == null) { - return withTag(tagUpdate); - } + public IItemStack updateTag(IData tagUpdate) { + if (tag == null) { + if (stack.stackTagCompound == null) { + return withTag(tagUpdate); + } - tag = NBTConverter.from(stack.stackTagCompound, true); - } + tag = NBTConverter.from(stack.stackTagCompound, true); + } - IData updated = tag.update(tagUpdate); - return withTag(updated); - } + IData updated = tag.update(tagUpdate); + return withTag(updated); + } - @Override + @Override public IItemStack removeTag(String tag) { ItemStack result = new ItemStack(stack.getItem(), stack.stackSize, stack.getItemDamage()); @@ -234,199 +233,204 @@ public class MCItemStack implements IItemStack { IData dataTag = NBTConverter.from(result.stackTagCompound, false); return new MCItemStack(result, dataTag); } - @Override - public String getMark() { - return null; - } - @Override - public int getAmount() { - return stack.stackSize; - } + @Override + public String getMark() { + return null; + } - @Override - public List getItems() { - return items; - } + @Override + public int getAmount() { + return stack.stackSize; + } - @Override - public List getLiquids() { - return Collections.emptyList(); - } + @Override + public List getItems() { + return items; + } - @Override - public IItemStack amount(int amount) { - return withAmount(amount); - } + @Override + public List getLiquids() { + return Collections.emptyList(); + } - @Override - public WeightedItemStack percent(float chance) { - return new WeightedItemStack(this, chance * 0.01f); - } + @Override + public IItemStack amount(int amount) { + return withAmount(amount); + } - @Override - public WeightedItemStack weight(float chance) { - return new WeightedItemStack(this, chance); - } + @Override + public WeightedItemStack percent(float chance) { + return new WeightedItemStack(this, chance * 0.01f); + } - @Override - public IIngredient transform(IItemTransformer transformer) { - return new IngredientItem(this, null, ArrayUtil.EMPTY_CONDITIONS, new IItemTransformer[] { transformer }); - } + @Override + public WeightedItemStack weight(float chance) { + return new WeightedItemStack(this, chance); + } - @Override - public IIngredient only(IItemCondition condition) { - return new IngredientItem(this, null, new IItemCondition[] { condition }, ArrayUtil.EMPTY_TRANSFORMERS); - } + @Override + public IIngredient transform(IItemTransformer transformer) { + return new IngredientItem(this, null, ArrayUtil.EMPTY_CONDITIONS, new IItemTransformer[] { transformer }); + } - @Override - public IIngredient marked(String mark) { - return new IngredientItem(this, mark, ArrayUtil.EMPTY_CONDITIONS, ArrayUtil.EMPTY_TRANSFORMERS); - } + @Override + public IIngredient only(IItemCondition condition) { + return new IngredientItem(this, null, new IItemCondition[] { condition }, ArrayUtil.EMPTY_TRANSFORMERS); + } - @Override - public IIngredient or(IIngredient ingredient) { - return new IngredientOr(this, ingredient); - } + @Override + public IIngredient marked(String mark) { + return new IngredientItem(this, mark, ArrayUtil.EMPTY_CONDITIONS, ArrayUtil.EMPTY_TRANSFORMERS); + } - @Override - public boolean matches(IItemStack item) { - ItemStack internal = getItemStack(item); - return internal !=null && stack !=null &&internal.getItem() == stack.getItem() && (wildcardSize || internal.stackSize >= stack.stackSize) && (stack.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack.getItemDamage() == internal.getItemDamage() || (!stack.getHasSubtypes() && !stack.getItem().isDamageable())); - } + @Override + public IIngredient or(IIngredient ingredient) { + return new IngredientOr(this, ingredient); + } - @Override - public boolean matchesExact(IItemStack item) { - ItemStack internal = getItemStack(item); - if (internal.getTagCompound() != null && stack.getTagCompound() == null) { - return false; - } - if (internal.getTagCompound() == null && stack.getTagCompound() != null) { - return false; - } - if (internal.getTagCompound() == null && stack.getTagCompound() == null) { - return stack.getItem() == internal.getItem() && (internal.getItemDamage() == 32767 || stack.getItemDamage() == internal.getItemDamage()); - } - if (internal.getTagCompound().func_150296_c().equals(stack.getTagCompound().func_150296_c())) { - for (String s : (Set)internal.getTagCompound().func_150296_c()) { - if (!internal.getTagCompound().getTag(s).equals(stack.getTagCompound().getTag(s))) { - return false; - } - } - } - return stack.getItem() == internal.getItem() && (internal.getItemDamage() == 32767 || stack.getItemDamage() == internal.getItemDamage()); - } + @Override + public boolean matches(IItemStack item) { + ItemStack internal = getItemStack(item); + return internal != null && stack != null + && internal.getItem() == stack.getItem() + && (wildcardSize || internal.stackSize >= stack.stackSize) + && (stack.getItemDamage() == OreDictionary.WILDCARD_VALUE + || stack.getItemDamage() == internal.getItemDamage() + || (!stack.getHasSubtypes() && !stack.getItem().isDamageable())); + } - @Override - public boolean matches(ILiquidStack liquid) { - return false; - } + @Override + public boolean matchesExact(IItemStack item) { + ItemStack internal = getItemStack(item); + if (internal.getTagCompound() != null && stack.getTagCompound() == null) { + return false; + } + if (internal.getTagCompound() == null && stack.getTagCompound() != null) { + return false; + } + if (internal.getTagCompound() == null && stack.getTagCompound() == null) { + return stack.getItem() == internal.getItem() + && (internal.getItemDamage() == 32767 || stack.getItemDamage() == internal.getItemDamage()); + } + if (internal.getTagCompound().func_150296_c().equals(stack.getTagCompound().func_150296_c())) { + for (String s : (Set) internal.getTagCompound().func_150296_c()) { + if (!internal.getTagCompound().getTag(s).equals(stack.getTagCompound().getTag(s))) { + return false; + } + } + } + return stack.getItem() == internal.getItem() + && (internal.getItemDamage() == 32767 || stack.getItemDamage() == internal.getItemDamage()); + } - @Override - public boolean contains(IIngredient ingredient) { - List iitems = ingredient.getItems(); - if (iitems == null || iitems.size() != 1) - return false; - return matches(iitems.get(0)); - } + @Override + public boolean matches(ILiquidStack liquid) { + return false; + } - @Override - public IItemStack applyTransform(IItemStack item, IPlayer byPlayer) { - return item; - } + @Override + public boolean contains(IIngredient ingredient) { + List iitems = ingredient.getItems(); + if (iitems == null || iitems.size() != 1) return false; + return matches(iitems.get(0)); + } - @Override - public boolean hasTransformers() { - return false; - } + @Override + public IItemStack applyTransform(IItemStack item, IPlayer byPlayer) { + return item; + } - @Override - public Object getInternal() { - return stack; - } + @Override + public boolean hasTransformers() { + return false; + } - @Override - public IBlock asBlock() { - String name = Block.blockRegistry.getNameForObject(Block.getBlockFromItem(stack.getItem())); - if (Block.blockRegistry.containsKey(name)) { - return new MCItemBlock(stack); - } else { - throw new ClassCastException("This item is not a block"); - } - } + @Override + public Object getInternal() { + return stack; + } - @Override - public List getOres() { - List result = new ArrayList(); + @Override + public IBlock asBlock() { + String name = Block.blockRegistry.getNameForObject(Block.getBlockFromItem(stack.getItem())); + if (Block.blockRegistry.containsKey(name)) { + return new MCItemBlock(stack); + } else { + throw new ClassCastException("This item is not a block"); + } + } - for (String key : OreDictionary.getOreNames()) { - for (ItemStack is : OreDictionary.getOres(key)) { - if (is.getItem() == stack.getItem() && (is.getItemDamage() == OreDictionary.WILDCARD_VALUE || is.getItemDamage() == stack.getItemDamage())) { - result.add(MineTweakerAPI.oreDict.get(key)); - break; - } - } - } + @Override + public List getOres() { + List result = new ArrayList(); - return result; - } + for (String key : OreDictionary.getOreNames()) { + for (ItemStack is : OreDictionary.getOres(key)) { + if (is.getItem() == stack.getItem() && (is.getItemDamage() == OreDictionary.WILDCARD_VALUE + || is.getItemDamage() == stack.getItemDamage())) { + result.add(MineTweakerAPI.oreDict.get(key)); + break; + } + } + } - // ############################# - // ### Object implementation ### - // ############################# + return result; + } - @Override - public int hashCode() { - int hash = 7; - hash = 41 * hash + stack.getItem().hashCode(); - hash = 41 * hash + stack.getItemDamage(); - hash = 41 * hash + stack.stackSize; - hash = 41 * hash + (stack.stackTagCompound == null ? 0 : stack.stackTagCompound.hashCode()); - hash = 41 * hash + (this.wildcardSize ? 1 : 0); - return hash; - } + // ############################# + // ### Object implementation ### + // ############################# - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MCItemStack other = (MCItemStack) obj; - if (this.stack.getItem() != other.stack.getItem()) - return false; - if (this.stack.getItemDamage() != other.stack.getItemDamage()) - return false; - if (this.stack.stackSize != other.stack.stackSize) - return false; - if (this.stack.stackTagCompound != other.stack.stackTagCompound && (this.stack == null || this.stack.equals(other.stack))) - return false; - if (this.wildcardSize != other.wildcardSize) - return false; - return true; - } + @Override + public int hashCode() { + int hash = 7; + hash = 41 * hash + stack.getItem().hashCode(); + hash = 41 * hash + stack.getItemDamage(); + hash = 41 * hash + stack.stackSize; + hash = 41 * hash + (stack.stackTagCompound == null ? 0 : stack.stackTagCompound.hashCode()); + hash = 41 * hash + (this.wildcardSize ? 1 : 0); + return hash; + } - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - result.append('<'); - result.append(Item.itemRegistry.getNameForObject(stack.getItem())); + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MCItemStack other = (MCItemStack) obj; + if (this.stack.getItem() != other.stack.getItem()) return false; + if (this.stack.getItemDamage() != other.stack.getItemDamage()) return false; + if (this.stack.stackSize != other.stack.stackSize) return false; + if (this.stack.stackTagCompound != other.stack.stackTagCompound + && (this.stack == null || this.stack.equals(other.stack))) + return false; + if (this.wildcardSize != other.wildcardSize) return false; + return true; + } - if (stack.getItemDamage() == OreDictionary.WILDCARD_VALUE) { - result.append(":*"); - } else if (stack.getItemDamage() > 0) { - result.append(':').append(stack.getItemDamage()); - } - result.append('>'); + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + result.append('<'); + result.append(Item.itemRegistry.getNameForObject(stack.getItem())); - if (stack.getTagCompound() != null) { - result.append(".withTag("); - result.append(NBTConverter.from(stack.getTagCompound(), wildcardSize).toString()); - result.append(")"); - } + if (stack.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + result.append(":*"); + } else if (stack.getItemDamage() > 0) { + result.append(':').append(stack.getItemDamage()); + } + result.append('>'); - return result.toString(); - } + if (stack.getTagCompound() != null) { + result.append(".withTag("); + result.append(NBTConverter.from(stack.getTagCompound(), wildcardSize).toString()); + result.append(")"); + } + + return result.toString(); + } } diff --git a/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java b/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java index fb52167..b7df8f5 100644 --- a/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java +++ b/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java @@ -1,19 +1,20 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.liquid; import java.util.ArrayList; import java.util.List; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import minetweaker.api.liquid.ILiquidDefinition; import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; @@ -23,401 +24,389 @@ import net.minecraftforge.fluids.FluidStack; * @author Stan */ public class MCLiquidDefinition implements ILiquidDefinition { - private final Fluid fluid; - - public MCLiquidDefinition(Fluid fluid) { - this.fluid = fluid; - } - - @Override - public String getName() { - return fluid.getName(); - } - - @Override - public String getDisplayName() { - return fluid.getLocalizedName(); - } - - @Override - public ILiquidStack asStack(int millibuckets) { - return new MCLiquidStack(new FluidStack(fluid, millibuckets)); - } - - @Override - public int getLuminosity() { - return fluid.getLuminosity(); - } - - @Override - public void setLuminosity(int value) { - MineTweakerAPI.apply(new ActionSetLuminosity(value)); - } - - @Override - public int getDensity() { - return fluid.getDensity(); - } - - @Override - public void setDensity(int density) { - MineTweakerAPI.apply(new ActionSetDensity(density)); - } - - @Override - public int getTemperature() { - return fluid.getTemperature(); - } - - @Override - public void setTemperature(int temperature) { - MineTweakerAPI.apply(new ActionSetTemperature(temperature)); - } - - @Override - public int getViscosity() { - return fluid.getViscosity(); - } - - @Override - public void setViscosity(int viscosity) { - MineTweakerAPI.apply(new ActionSetViscosity(viscosity)); - } - - @Override - public boolean isGaseous() { - return fluid.isGaseous(); - } - - @Override - public void setGaseous(boolean gaseous) { - MineTweakerAPI.apply(new ActionSetGaseous(gaseous)); - } - - @Override - public List getContainers() { - List result = new ArrayList(); - for (FluidContainerRegistry.FluidContainerData data : FluidContainerRegistry.getRegisteredFluidContainerData()) { - if (data.fluid.getFluid() == fluid) { - result.add(MineTweakerMC.getIItemStack(data.filledContainer)); - } - } - return result; - } - - @Override - public void addContainer(IItemStack filled, IItemStack empty, int amount) { - MineTweakerAPI.apply(new AddContainerAction(filled, empty, amount)); - } - - @Override - public void removeContainer(IItemStack filled) { - // MineTweakerAPI.apply(new RemoveContainerAction(filled)); - MineTweakerAPI.logError("Cannot remove container items in MineCraft 1.7.X"); - } - - // ####################### - // ### Private methods ### - // ####################### - - /* - * private void removeContainerInner(IItemStack filled) { ItemStack - * filledItem = MineTweakerMC.getItemStack(filled); - * FluidContainerRegistry.FluidContainerData data = - * filledContainerMap.get(Arrays.asList(filledItem.itemID, - * filledItem.getItemDamage())); if (data != null) { - * filledContainerMap.remove(Arrays.asList(filledItem.itemID, - * filledItem.getItemDamage())); - * containerFluidMap.remove(Arrays.asList(data.emptyContainer.itemID, - * data.emptyContainer.getItemDamage())); - * - * // rebuild empty containers set emptyContainers.clear(); for - * (FluidContainerRegistry.FluidContainerData fdata : - * filledContainerMap.values()) { - * emptyContainers.add(Arrays.asList(fdata.emptyContainer.itemID, - * fdata.emptyContainer.getItemDamage())); } } - * MineTweakerAPI.logError("Removal of containers is not possible in 1.7.X" - * ); } - */ - - /* - * private FluidContainerRegistry.FluidContainerData getData(IItemStack - * filled) { ItemStack filledStack = MineTweakerMC.getItemStack(filled); - * return filledContainerMap.get(Arrays.asList(filledStack.itemID, - * filledStack.getItemDamage())); } - */ - - // ###################### - // ### Action classes ### - // ###################### - - private class AddContainerAction implements IUndoableAction { - private final IItemStack filled; - private final IItemStack empty; - private final int amount; - - public AddContainerAction(IItemStack filled, IItemStack empty, int amount) { - this.filled = filled; - this.empty = empty; - this.amount = amount; - } - - @Override - public void apply() { - FluidContainerRegistry.registerFluidContainer(new FluidStack(fluid, amount), MineTweakerMC.getItemStack(filled), MineTweakerMC.getItemStack(empty)); - } - - @Override - public boolean canUndo() { - return false; - // return true; - } - - @Override - public void undo() { - // removeContainerInner(filled); - } - - @Override - public String describe() { - return "Adding " + filled.getDisplayName() + " as liquid container for " + fluid.getLocalizedName(); - } - - @Override - public String describeUndo() { - return "Removing liquid container " + filled; - } - - @Override - public Object getOverrideKey() { - return null; - } - } - - /* - * private class RemoveContainerAction implements IUndoableAction { private - * final IItemStack filled; private final IItemStack empty; private final - * FluidStack amount; - * - * public RemoveContainerAction(IItemStack filled) { this.filled = filled; - * - * FluidContainerRegistry.FluidContainerData data = getData(filled); empty = - * MineTweakerMC.getIItemStack(data.emptyContainer); amount = data.fluid; } - * - * @Override public void apply() { removeContainerInner(filled); } - * - * @Override public boolean canUndo() { return true; } - * - * @Override public void undo() { - * FluidContainerRegistry.registerFluidContainer(amount, - * MineTweakerMC.getItemStack(filled), MineTweakerMC.getItemStack(empty)); } - * - * @Override public String describe() { return "Removing liquid container " - * + filled; } - * - * @Override public String describeUndo() { return - * "Restoring liquid container " + filled; } - * - * @Override public Object getOverrideKey() { return null; } } - */ - - private class ActionSetLuminosity implements IUndoableAction { - private final int oldValue; - private final int newValue; - - public ActionSetLuminosity(int newValue) { - oldValue = getLuminosity(); - this.newValue = newValue; - } - - @Override - public void apply() { - fluid.setLuminosity(newValue); - } - - @Override - public boolean canUndo() { - return true; - } - - @Override - public void undo() { - fluid.setLuminosity(oldValue); - } - - @Override - public String describe() { - return "Setting " + fluid.getName() + " luminosity to " + newValue; - } - - @Override - public String describeUndo() { - return "Restoring " + fluid.getName() + " luminosity to " + oldValue; - } - - @Override - public Object getOverrideKey() { - return null; - } - } - - private class ActionSetDensity implements IUndoableAction { - private final int oldValue; - private final int newValue; - - public ActionSetDensity(int newValue) { - oldValue = getDensity(); - this.newValue = newValue; - } - - @Override - public void apply() { - fluid.setDensity(newValue); - } - - @Override - public boolean canUndo() { - return true; - } - - @Override - public void undo() { - fluid.setDensity(oldValue); - } - - @Override - public String describe() { - return "Setting " + fluid.getName() + " density to " + newValue; - } - - @Override - public String describeUndo() { - return "Restoring " + fluid.getName() + " density to " + oldValue; - } - - @Override - public Object getOverrideKey() { - return null; - } - } - - private class ActionSetTemperature implements IUndoableAction { - private final int oldValue; - private final int newValue; - - public ActionSetTemperature(int newValue) { - oldValue = getTemperature(); - this.newValue = newValue; - } - - @Override - public void apply() { - fluid.setTemperature(newValue); - } - - @Override - public boolean canUndo() { - return true; - } - - @Override - public void undo() { - fluid.setTemperature(oldValue); - } - - @Override - public String describe() { - return "Setting " + fluid.getName() + " temperature to " + newValue; - } - - @Override - public String describeUndo() { - return "Restoring " + fluid.getName() + " temperature to " + oldValue; - } - - @Override - public Object getOverrideKey() { - return null; - } - } - - private class ActionSetViscosity implements IUndoableAction { - private final int oldValue; - private final int newValue; - - public ActionSetViscosity(int newValue) { - oldValue = getViscosity(); - this.newValue = newValue; - } - - @Override - public void apply() { - fluid.setViscosity(newValue); - } - - @Override - public boolean canUndo() { - return true; - } - - @Override - public void undo() { - fluid.setViscosity(oldValue); - } - - @Override - public String describe() { - return "Setting " + fluid.getName() + " viscosity to " + newValue; - } - - @Override - public String describeUndo() { - return "Restoring " + fluid.getName() + " viscosity to " + oldValue; - } - - @Override - public Object getOverrideKey() { - return null; - } - } - - private class ActionSetGaseous implements IUndoableAction { - private final boolean oldValue; - private final boolean newValue; - - public ActionSetGaseous(boolean newValue) { - oldValue = isGaseous(); - this.newValue = newValue; - } - - @Override - public void apply() { - fluid.setGaseous(newValue); - } - - @Override - public boolean canUndo() { - return true; - } - - @Override - public void undo() { - fluid.setGaseous(oldValue); - } - - @Override - public String describe() { - return "Setting " + fluid.getName() + " gaseous to " + newValue; - } - - @Override - public String describeUndo() { - return "Restoring " + fluid.getName() + " gaseous to " + oldValue; - } - - @Override - public Object getOverrideKey() { - return null; - } - } + + private final Fluid fluid; + + public MCLiquidDefinition(Fluid fluid) { + this.fluid = fluid; + } + + @Override + public String getName() { + return fluid.getName(); + } + + @Override + public String getDisplayName() { + return fluid.getLocalizedName(); + } + + @Override + public ILiquidStack asStack(int millibuckets) { + return new MCLiquidStack(new FluidStack(fluid, millibuckets)); + } + + @Override + public int getLuminosity() { + return fluid.getLuminosity(); + } + + @Override + public void setLuminosity(int value) { + MineTweakerAPI.apply(new ActionSetLuminosity(value)); + } + + @Override + public int getDensity() { + return fluid.getDensity(); + } + + @Override + public void setDensity(int density) { + MineTweakerAPI.apply(new ActionSetDensity(density)); + } + + @Override + public int getTemperature() { + return fluid.getTemperature(); + } + + @Override + public void setTemperature(int temperature) { + MineTweakerAPI.apply(new ActionSetTemperature(temperature)); + } + + @Override + public int getViscosity() { + return fluid.getViscosity(); + } + + @Override + public void setViscosity(int viscosity) { + MineTweakerAPI.apply(new ActionSetViscosity(viscosity)); + } + + @Override + public boolean isGaseous() { + return fluid.isGaseous(); + } + + @Override + public void setGaseous(boolean gaseous) { + MineTweakerAPI.apply(new ActionSetGaseous(gaseous)); + } + + @Override + public List getContainers() { + List result = new ArrayList(); + for (FluidContainerRegistry.FluidContainerData data : FluidContainerRegistry + .getRegisteredFluidContainerData()) { + if (data.fluid.getFluid() == fluid) { + result.add(MineTweakerMC.getIItemStack(data.filledContainer)); + } + } + return result; + } + + @Override + public void addContainer(IItemStack filled, IItemStack empty, int amount) { + MineTweakerAPI.apply(new AddContainerAction(filled, empty, amount)); + } + + @Override + public void removeContainer(IItemStack filled) { + // MineTweakerAPI.apply(new RemoveContainerAction(filled)); + MineTweakerAPI.logError("Cannot remove container items in MineCraft 1.7.X"); + } + + // ####################### + // ### Private methods ### + // ####################### + + /* + * private void removeContainerInner(IItemStack filled) { ItemStack filledItem = MineTweakerMC.getItemStack(filled); + * FluidContainerRegistry.FluidContainerData data = filledContainerMap.get(Arrays.asList(filledItem.itemID, + * filledItem.getItemDamage())); if (data != null) { filledContainerMap.remove(Arrays.asList(filledItem.itemID, + * filledItem.getItemDamage())); containerFluidMap.remove(Arrays.asList(data.emptyContainer.itemID, + * data.emptyContainer.getItemDamage())); // rebuild empty containers set emptyContainers.clear(); for + * (FluidContainerRegistry.FluidContainerData fdata : filledContainerMap.values()) { + * emptyContainers.add(Arrays.asList(fdata.emptyContainer.itemID, fdata.emptyContainer.getItemDamage())); } } + * MineTweakerAPI.logError("Removal of containers is not possible in 1.7.X" ); } + */ + + /* + * private FluidContainerRegistry.FluidContainerData getData(IItemStack filled) { ItemStack filledStack = + * MineTweakerMC.getItemStack(filled); return filledContainerMap.get(Arrays.asList(filledStack.itemID, + * filledStack.getItemDamage())); } + */ + + // ###################### + // ### Action classes ### + // ###################### + + private class AddContainerAction implements IUndoableAction { + + private final IItemStack filled; + private final IItemStack empty; + private final int amount; + + public AddContainerAction(IItemStack filled, IItemStack empty, int amount) { + this.filled = filled; + this.empty = empty; + this.amount = amount; + } + + @Override + public void apply() { + FluidContainerRegistry.registerFluidContainer( + new FluidStack(fluid, amount), + MineTweakerMC.getItemStack(filled), + MineTweakerMC.getItemStack(empty)); + } + + @Override + public boolean canUndo() { + return false; + // return true; + } + + @Override + public void undo() { + // removeContainerInner(filled); + } + + @Override + public String describe() { + return "Adding " + filled.getDisplayName() + " as liquid container for " + fluid.getLocalizedName(); + } + + @Override + public String describeUndo() { + return "Removing liquid container " + filled; + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + /* + * private class RemoveContainerAction implements IUndoableAction { private final IItemStack filled; private final + * IItemStack empty; private final FluidStack amount; public RemoveContainerAction(IItemStack filled) { this.filled + * = filled; FluidContainerRegistry.FluidContainerData data = getData(filled); empty = + * MineTweakerMC.getIItemStack(data.emptyContainer); amount = data.fluid; } + * @Override public void apply() { removeContainerInner(filled); } + * @Override public boolean canUndo() { return true; } + * @Override public void undo() { FluidContainerRegistry.registerFluidContainer(amount, + * MineTweakerMC.getItemStack(filled), MineTweakerMC.getItemStack(empty)); } + * @Override public String describe() { return "Removing liquid container " + filled; } + * @Override public String describeUndo() { return "Restoring liquid container " + filled; } + * @Override public Object getOverrideKey() { return null; } } + */ + + private class ActionSetLuminosity implements IUndoableAction { + + private final int oldValue; + private final int newValue; + + public ActionSetLuminosity(int newValue) { + oldValue = getLuminosity(); + this.newValue = newValue; + } + + @Override + public void apply() { + fluid.setLuminosity(newValue); + } + + @Override + public boolean canUndo() { + return true; + } + + @Override + public void undo() { + fluid.setLuminosity(oldValue); + } + + @Override + public String describe() { + return "Setting " + fluid.getName() + " luminosity to " + newValue; + } + + @Override + public String describeUndo() { + return "Restoring " + fluid.getName() + " luminosity to " + oldValue; + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + private class ActionSetDensity implements IUndoableAction { + + private final int oldValue; + private final int newValue; + + public ActionSetDensity(int newValue) { + oldValue = getDensity(); + this.newValue = newValue; + } + + @Override + public void apply() { + fluid.setDensity(newValue); + } + + @Override + public boolean canUndo() { + return true; + } + + @Override + public void undo() { + fluid.setDensity(oldValue); + } + + @Override + public String describe() { + return "Setting " + fluid.getName() + " density to " + newValue; + } + + @Override + public String describeUndo() { + return "Restoring " + fluid.getName() + " density to " + oldValue; + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + private class ActionSetTemperature implements IUndoableAction { + + private final int oldValue; + private final int newValue; + + public ActionSetTemperature(int newValue) { + oldValue = getTemperature(); + this.newValue = newValue; + } + + @Override + public void apply() { + fluid.setTemperature(newValue); + } + + @Override + public boolean canUndo() { + return true; + } + + @Override + public void undo() { + fluid.setTemperature(oldValue); + } + + @Override + public String describe() { + return "Setting " + fluid.getName() + " temperature to " + newValue; + } + + @Override + public String describeUndo() { + return "Restoring " + fluid.getName() + " temperature to " + oldValue; + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + private class ActionSetViscosity implements IUndoableAction { + + private final int oldValue; + private final int newValue; + + public ActionSetViscosity(int newValue) { + oldValue = getViscosity(); + this.newValue = newValue; + } + + @Override + public void apply() { + fluid.setViscosity(newValue); + } + + @Override + public boolean canUndo() { + return true; + } + + @Override + public void undo() { + fluid.setViscosity(oldValue); + } + + @Override + public String describe() { + return "Setting " + fluid.getName() + " viscosity to " + newValue; + } + + @Override + public String describeUndo() { + return "Restoring " + fluid.getName() + " viscosity to " + oldValue; + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + private class ActionSetGaseous implements IUndoableAction { + + private final boolean oldValue; + private final boolean newValue; + + public ActionSetGaseous(boolean newValue) { + oldValue = isGaseous(); + this.newValue = newValue; + } + + @Override + public void apply() { + fluid.setGaseous(newValue); + } + + @Override + public boolean canUndo() { + return true; + } + + @Override + public void undo() { + fluid.setGaseous(oldValue); + } + + @Override + public String describe() { + return "Setting " + fluid.getName() + " gaseous to " + newValue; + } + + @Override + public String describeUndo() { + return "Restoring " + fluid.getName() + " gaseous to " + oldValue; + } + + @Override + public Object getOverrideKey() { + return null; + } + } } diff --git a/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java b/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java index 3c25edd..194cebf 100644 --- a/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java +++ b/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java @@ -1,27 +1,28 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.liquid; +import java.util.Collections; +import java.util.List; + import minetweaker.api.data.IData; import minetweaker.api.item.*; import minetweaker.api.liquid.ILiquidDefinition; import minetweaker.api.liquid.ILiquidStack; import minetweaker.api.player.IPlayer; import minetweaker.mc1710.data.NBTConverter; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; -import java.util.Collections; -import java.util.List; - /** * @author Stan */ public class MCLiquidStack implements ILiquidStack { + private final FluidStack stack; private IData tag = null; @@ -162,8 +163,7 @@ public class MCLiquidStack implements ILiquidStack { @Override public boolean matches(ILiquidStack liquid) { - return getDefinition().equals(liquid.getDefinition()) - && getAmount() <= liquid.getAmount(); + return getDefinition().equals(liquid.getDefinition()) && getAmount() <= liquid.getAmount(); } @Override @@ -173,12 +173,10 @@ public class MCLiquidStack implements ILiquidStack { @Override public boolean contains(IIngredient ingredient) { - if (!ingredient.getItems().isEmpty()) - return false; + if (!ingredient.getItems().isEmpty()) return false; for (ILiquidStack liquid : ingredient.getLiquids()) { - if (!matches(liquid)) - return false; + if (!matches(liquid)) return false; } return false; diff --git a/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java b/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java index e9517bc..08d47a6 100644 --- a/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java +++ b/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java @@ -1,45 +1,47 @@ package minetweaker.mc1710.mods; -import cpw.mods.fml.common.Loader; -import cpw.mods.fml.common.ModContainer; import java.util.Iterator; import java.util.List; + import minetweaker.api.mods.ILoadedMods; import minetweaker.api.mods.IMod; import stanhebben.zenscript.util.MappingIterator; +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.ModContainer; /** * * @author Stan */ public class MCLoadedMods implements ILoadedMods { - public MCLoadedMods() { - } - @Override - public boolean contains(String name) { - return Loader.isModLoaded(name); - } + public MCLoadedMods() {} - @Override - public IMod get(String name) { - for (ModContainer mod : Loader.instance().getActiveModList()) { - if (mod.getModId().equals(name)) { - return new MCMod(mod); - } - } + @Override + public boolean contains(String name) { + return Loader.isModLoaded(name); + } - return null; - } + @Override + public IMod get(String name) { + for (ModContainer mod : Loader.instance().getActiveModList()) { + if (mod.getModId().equals(name)) { + return new MCMod(mod); + } + } - @Override - public Iterator iterator() { - List mods = Loader.instance().getActiveModList(); - return new MappingIterator(mods.iterator()) { - @Override - public IMod map(ModContainer value) { - return new MCMod(value); - } - }; - } + return null; + } + + @Override + public Iterator iterator() { + List mods = Loader.instance().getActiveModList(); + return new MappingIterator(mods.iterator()) { + + @Override + public IMod map(ModContainer value) { + return new MCMod(value); + } + }; + } } diff --git a/src/main/java/minetweaker/mc1710/mods/MCMod.java b/src/main/java/minetweaker/mc1710/mods/MCMod.java index 3ec189a..da463bd 100644 --- a/src/main/java/minetweaker/mc1710/mods/MCMod.java +++ b/src/main/java/minetweaker/mc1710/mods/MCMod.java @@ -1,42 +1,42 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.mods; -import cpw.mods.fml.common.ModContainer; import minetweaker.api.mods.IMod; +import cpw.mods.fml.common.ModContainer; /** * * @author Stan */ public class MCMod implements IMod { - private final ModContainer mod; - public MCMod(ModContainer mod) { - this.mod = mod; - } + private final ModContainer mod; - @Override - public String getId() { - return mod.getModId(); - } + public MCMod(ModContainer mod) { + this.mod = mod; + } - @Override - public String getName() { - return mod.getName(); - } + @Override + public String getId() { + return mod.getModId(); + } - @Override - public String getVersion() { - return mod.getVersion(); - } + @Override + public String getName() { + return mod.getName(); + } - @Override - public String getDescription() { - return mod.getMetadata().description; - } + @Override + public String getVersion() { + return mod.getVersion(); + } + + @Override + public String getDescription() { + return mod.getMetadata().description; + } } diff --git a/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java b/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java index 127f718..d9cedf5 100644 --- a/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java +++ b/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java @@ -1,34 +1,34 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.network; -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 minetweaker.mc1710.MineTweakerConfig; - import java.awt.Desktop; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; +import minetweaker.mc1710.MineTweakerConfig; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; + /** * * @author Stan */ public class MineTweakerCopyClipboardHandler implements IMessageHandler { - @Override - public IMessage onMessage(MineTweakerCopyClipboardPacket message, MessageContext ctx) { - if (Desktop.isDesktopSupported() && MineTweakerConfig.handleDesktopPackets) { - StringSelection stringSelection = new StringSelection(message.getData()); - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - clipboard.setContents(stringSelection, null); - } - return null; - } + @Override + public IMessage onMessage(MineTweakerCopyClipboardPacket message, MessageContext ctx) { + if (Desktop.isDesktopSupported() && MineTweakerConfig.handleDesktopPackets) { + StringSelection stringSelection = new StringSelection(message.getData()); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(stringSelection, null); + } + + return null; + } } diff --git a/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardPacket.java b/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardPacket.java index d04e81d..0b20020 100644 --- a/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardPacket.java +++ b/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardPacket.java @@ -1,42 +1,42 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.network; import static com.google.common.base.Charsets.UTF_8; + +import java.nio.ByteBuffer; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import io.netty.buffer.ByteBuf; -import java.nio.ByteBuffer; /** * * @author Stan */ -public class MineTweakerCopyClipboardPacket implements IMessage -{ - private String data; +public class MineTweakerCopyClipboardPacket implements IMessage { - public MineTweakerCopyClipboardPacket() { - } + private String data; - public MineTweakerCopyClipboardPacket(String data) { - this.data = data; - } + public MineTweakerCopyClipboardPacket() {} - public String getData() { - return data; - } + public MineTweakerCopyClipboardPacket(String data) { + this.data = data; + } - @Override - public void fromBytes(ByteBuf buf) { - data = UTF_8.decode(ByteBuffer.wrap(buf.array())).toString().trim(); - } + public String getData() { + return data; + } - @Override - public void toBytes(ByteBuf buf) { - buf.writeBytes(UTF_8.encode(data).array()); - } + @Override + public void fromBytes(ByteBuf buf) { + data = UTF_8.decode(ByteBuffer.wrap(buf.array())).toString().trim(); + } + + @Override + public void toBytes(ByteBuf buf) { + buf.writeBytes(UTF_8.encode(data).array()); + } } diff --git a/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsHandler.java b/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsHandler.java index ef9244a..3c89fce 100644 --- a/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsHandler.java +++ b/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsHandler.java @@ -1,30 +1,30 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.network; -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 minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.mc1710.MineTweakerConfig; import minetweaker.runtime.providers.ScriptProviderMemory; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; /** * * @author Stan */ public class MineTweakerLoadScriptsHandler implements IMessageHandler { - @Override - public IMessage onMessage(MineTweakerLoadScriptsPacket message, MessageContext ctx) { - if (MineTweakerAPI.server == null && MineTweakerConfig.handleLoadScripts) { - MineTweakerImplementationAPI.setScriptProvider(new ScriptProviderMemory(message.getData())); - MineTweakerImplementationAPI.reload(); - } - return null; - } + + @Override + public IMessage onMessage(MineTweakerLoadScriptsPacket message, MessageContext ctx) { + if (MineTweakerAPI.server == null && MineTweakerConfig.handleLoadScripts) { + MineTweakerImplementationAPI.setScriptProvider(new ScriptProviderMemory(message.getData())); + MineTweakerImplementationAPI.reload(); + } + return null; + } } diff --git a/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsPacket.java b/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsPacket.java index 69f9d65..c7f6f57 100644 --- a/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsPacket.java +++ b/src/main/java/minetweaker/mc1710/network/MineTweakerLoadScriptsPacket.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.network; @@ -14,30 +13,31 @@ import io.netty.buffer.ByteBuf; * @author Stan */ public class MineTweakerLoadScriptsPacket implements IMessage { - private byte[] data; - public MineTweakerLoadScriptsPacket() { - // used for deserialization - } + private byte[] data; - public MineTweakerLoadScriptsPacket(byte[] data) { - this.data = data; - } + public MineTweakerLoadScriptsPacket() { + // used for deserialization + } - public byte[] getData() { - return data; - } + public MineTweakerLoadScriptsPacket(byte[] data) { + this.data = data; + } - @Override - public void fromBytes(ByteBuf buf) { - int size = buf.readInt(); - data = new byte[size]; - buf.readBytes(data); - } + public byte[] getData() { + return data; + } - @Override - public void toBytes(ByteBuf buf) { - buf.writeInt(data.length); - buf.writeBytes(data); - } + @Override + public void fromBytes(ByteBuf buf) { + int size = buf.readInt(); + data = new byte[size]; + buf.readBytes(data); + } + + @Override + public void toBytes(ByteBuf buf) { + buf.writeInt(data.length); + buf.writeBytes(data); + } } diff --git a/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserHandler.java b/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserHandler.java index 2148b9b..7b32fc3 100644 --- a/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserHandler.java +++ b/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserHandler.java @@ -1,37 +1,35 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.network; -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 minetweaker.mc1710.MineTweakerConfig; - import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import minetweaker.mc1710.MineTweakerConfig; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; + /** * * @author Stan */ public class MineTweakerOpenBrowserHandler implements IMessageHandler { - @Override - public IMessage onMessage(MineTweakerOpenBrowserPacket message, MessageContext ctx) { - if (Desktop.isDesktopSupported() && MineTweakerConfig.handleDesktopPackets) { - Desktop desktop = Desktop.getDesktop(); - try { - desktop.browse(new URI(message.getUrl())); - } catch (IOException e) { - } catch (URISyntaxException e) { - } - } - return null; - } + @Override + public IMessage onMessage(MineTweakerOpenBrowserPacket message, MessageContext ctx) { + if (Desktop.isDesktopSupported() && MineTweakerConfig.handleDesktopPackets) { + Desktop desktop = Desktop.getDesktop(); + try { + desktop.browse(new URI(message.getUrl())); + } catch (IOException e) {} catch (URISyntaxException e) {} + } + + return null; + } } diff --git a/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserPacket.java b/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserPacket.java index 05766cc..ddba517 100644 --- a/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserPacket.java +++ b/src/main/java/minetweaker/mc1710/network/MineTweakerOpenBrowserPacket.java @@ -1,44 +1,45 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.network; -import cpw.mods.fml.common.network.simpleimpl.IMessage; -import io.netty.buffer.ByteBuf; import java.nio.ByteBuffer; import java.nio.charset.Charset; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import io.netty.buffer.ByteBuf; + /** * * @author Stan */ public class MineTweakerOpenBrowserPacket implements IMessage { - private static final Charset UTF8 = Charset.forName("utf-8"); - private String url; + private static final Charset UTF8 = Charset.forName("utf-8"); - public MineTweakerOpenBrowserPacket() { + private String url; - } + public MineTweakerOpenBrowserPacket() { - public MineTweakerOpenBrowserPacket(String url) { - this.url = url; - } + } - public String getUrl() { - return url; - } + public MineTweakerOpenBrowserPacket(String url) { + this.url = url; + } - @Override - public void fromBytes(ByteBuf buf) { - url = UTF8.decode(ByteBuffer.wrap(buf.array())).toString().trim(); - } + public String getUrl() { + return url; + } - @Override - public void toBytes(ByteBuf buf) { - buf.writeBytes(UTF8.encode(url).array()); - } + @Override + public void fromBytes(ByteBuf buf) { + url = UTF8.decode(ByteBuffer.wrap(buf.array())).toString().trim(); + } + + @Override + public void toBytes(ByteBuf buf) { + buf.writeBytes(UTF8.encode(url).array()); + } } diff --git a/src/main/java/minetweaker/mc1710/oredict/MCOreDict.java b/src/main/java/minetweaker/mc1710/oredict/MCOreDict.java index 42d2203..edd9aa9 100644 --- a/src/main/java/minetweaker/mc1710/oredict/MCOreDict.java +++ b/src/main/java/minetweaker/mc1710/oredict/MCOreDict.java @@ -1,17 +1,19 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.oredict; +import static minetweaker.api.minecraft.MineTweakerMC.getOreDict; + import java.util.ArrayList; import java.util.List; + import minetweaker.api.minecraft.MineTweakerMC; -import static minetweaker.api.minecraft.MineTweakerMC.getOreDict; import minetweaker.api.oredict.IOreDict; import minetweaker.api.oredict.IOreDictEntry; + import net.minecraftforge.oredict.OreDictionary; /** @@ -19,19 +21,20 @@ import net.minecraftforge.oredict.OreDictionary; * @author Stan */ public class MCOreDict implements IOreDict { - @Override - public IOreDictEntry get(String name) { - return getOreDict(name); - } - @Override - public List getEntries() { - List entries = new ArrayList(); - for (String key : OreDictionary.getOreNames()) { - if (!OreDictionary.getOres(key).isEmpty()) { - entries.add(MineTweakerMC.getOreDict(key)); - } - } - return entries; - } + @Override + public IOreDictEntry get(String name) { + return getOreDict(name); + } + + @Override + public List getEntries() { + List entries = new ArrayList(); + for (String key : OreDictionary.getOreNames()) { + if (!OreDictionary.getOres(key).isEmpty()) { + entries.add(MineTweakerMC.getOreDict(key)); + } + } + return entries; + } } diff --git a/src/main/java/minetweaker/mc1710/oredict/MCOreDictEntry.java b/src/main/java/minetweaker/mc1710/oredict/MCOreDictEntry.java index b341c80..8036d5c 100644 --- a/src/main/java/minetweaker/mc1710/oredict/MCOreDictEntry.java +++ b/src/main/java/minetweaker/mc1710/oredict/MCOreDictEntry.java @@ -1,11 +1,17 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.oredict; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStackWildcardSize; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.*; @@ -15,20 +21,15 @@ import minetweaker.api.oredict.IngredientOreDict; import minetweaker.api.player.IPlayer; import minetweaker.mc1710.util.MineTweakerHacks; import minetweaker.util.ArrayUtil; + import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStackWildcardSize; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; - /** * @author Stan */ public class MCOreDictEntry implements IOreDictEntry { + private static final List> OREDICT_CONTENTS = MineTweakerHacks.getOreIdStacks(); private static final List> OREDICT_CONTENTS_UN = MineTweakerHacks.getOreIdStacksUn(); @@ -175,12 +176,12 @@ public class MCOreDictEntry implements IOreDictEntry { @Override public IIngredient transform(IItemTransformer transformer) { - return new IngredientOreDict(this, null, ArrayUtil.EMPTY_CONDITIONS, new IItemTransformer[]{transformer}); + return new IngredientOreDict(this, null, ArrayUtil.EMPTY_CONDITIONS, new IItemTransformer[] { transformer }); } @Override public IIngredient only(IItemCondition condition) { - return new IngredientOreDict(this, null, new IItemCondition[]{condition}, ArrayUtil.EMPTY_TRANSFORMERS); + return new IngredientOreDict(this, null, new IItemCondition[] { condition }, ArrayUtil.EMPTY_TRANSFORMERS); } @Override @@ -212,8 +213,7 @@ public class MCOreDictEntry implements IOreDictEntry { public boolean contains(IIngredient ingredient) { List items = ingredient.getItems(); for (IItemStack item : items) { - if (!matches(item)) - return false; + if (!matches(item)) return false; } return true; @@ -250,8 +250,7 @@ public class MCOreDictEntry implements IOreDictEntry { @Override public boolean equals(Object other) { - if (!(other instanceof MCOreDictEntry)) - return false; + if (!(other instanceof MCOreDictEntry)) return false; return ((MCOreDictEntry) other).id == id; } @@ -260,6 +259,7 @@ public class MCOreDictEntry implements IOreDictEntry { // ###################### private static class ActionAddItem implements IUndoableAction { + private final Integer id; private final ItemStack item; @@ -300,6 +300,7 @@ public class MCOreDictEntry implements IOreDictEntry { } private static class ActionMirror implements IUndoableAction { + private final Integer idTarget; private final Integer idSource; @@ -338,7 +339,9 @@ public class MCOreDictEntry implements IOreDictEntry { @Override public String describeUndo() { - return "Undoing mirror of " + OreDictionary.getOreName(idSource) + " to " + OreDictionary.getOreName(idTarget); + return "Undoing mirror of " + OreDictionary.getOreName(idSource) + + " to " + + OreDictionary.getOreName(idTarget); } @Override @@ -348,6 +351,7 @@ public class MCOreDictEntry implements IOreDictEntry { } private static class ActionRemoveItem implements IUndoableAction { + private final Integer id; private final ItemStack item; @@ -388,6 +392,7 @@ public class MCOreDictEntry implements IOreDictEntry { } private static class ActionAddAll implements IUndoableAction { + private final Integer idTarget; private final Integer idSource; @@ -417,12 +422,16 @@ public class MCOreDictEntry implements IOreDictEntry { @Override public String describe() { - return "Copying contents of ore dictionary entry " + OreDictionary.getOreName(idSource) + " to " + OreDictionary.getOreName(idTarget); + return "Copying contents of ore dictionary entry " + OreDictionary.getOreName(idSource) + + " to " + + OreDictionary.getOreName(idTarget); } @Override public String describeUndo() { - return "Removing contents of ore dictionary entry " + OreDictionary.getOreName(idSource) + " from " + OreDictionary.getOreName(idTarget); + return "Removing contents of ore dictionary entry " + OreDictionary.getOreName(idSource) + + " from " + + OreDictionary.getOreName(idTarget); } @Override diff --git a/src/main/java/minetweaker/mc1710/player/CommandBlockPlayer.java b/src/main/java/minetweaker/mc1710/player/CommandBlockPlayer.java index 084990a..cb7698a 100644 --- a/src/main/java/minetweaker/mc1710/player/CommandBlockPlayer.java +++ b/src/main/java/minetweaker/mc1710/player/CommandBlockPlayer.java @@ -5,6 +5,7 @@ import minetweaker.api.chat.IChatMessage; import minetweaker.api.data.IData; import minetweaker.api.item.IItemStack; import minetweaker.api.player.IPlayer; + import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; @@ -12,29 +13,30 @@ import net.minecraft.util.IChatComponent; /** * @author Jared */ -public class CommandBlockPlayer implements IPlayer{ +public class CommandBlockPlayer implements IPlayer { + private final ICommandSender sender; - public CommandBlockPlayer(ICommandSender sender){ + public CommandBlockPlayer(ICommandSender sender) { this.sender = sender; } - public ICommandSender getInternal(){ + public ICommandSender getInternal() { return sender; } @Override - public String getId(){ + public String getId() { return null; // TODO: we should be having this for MC 1.7.10, right? } @Override - public String getName(){ + public String getName() { return sender.getCommandSenderName(); } @Override - public IData getData(){ + public IData getData() { return null; } @@ -54,14 +56,14 @@ public class CommandBlockPlayer implements IPlayer{ } @Override - public void update(IData data){ + public void update(IData data) { } @Override - public void sendChat(IChatMessage message){ + public void sendChat(IChatMessage message) { Object internal = message.getInternal(); - if(!(internal instanceof IChatComponent)){ + if (!(internal instanceof IChatComponent)) { MineTweakerAPI.logError("not a valid chat message"); return; } @@ -69,73 +71,68 @@ public class CommandBlockPlayer implements IPlayer{ } @Override - public void sendChat(String message){ - if (message.length() > MAX_CHAT_MESSAGE_LENGTH) - { + public void sendChat(String message) { + if (message.length() > MAX_CHAT_MESSAGE_LENGTH) { message = message.substring(0, MAX_CHAT_MESSAGE_LENGTH); } sender.addChatMessage(new ChatComponentText(message)); } @Override - public int getHotbarSize(){ + public int getHotbarSize() { return 0; } @Override - public IItemStack getHotbarStack(int i){ + public IItemStack getHotbarStack(int i) { return null; } @Override - public int getInventorySize(){ + public int getInventorySize() { return 0; } @Override - public IItemStack getInventoryStack(int i){ + public IItemStack getInventoryStack(int i) { return null; } @Override - public IItemStack getCurrentItem(){ + public IItemStack getCurrentItem() { return null; } @Override - public boolean isCreative(){ + public boolean isCreative() { return false; } @Override - public boolean isAdventure(){ + public boolean isAdventure() { return false; } @Override - public void openBrowser(String url){ - } + public void openBrowser(String url) {} @Override - public void copyToClipboard(String value){ - } + public void copyToClipboard(String value) {} @Override - public boolean equals(Object other){ - if(other.getClass() != this.getClass()) - return false; + public boolean equals(Object other) { + if (other.getClass() != this.getClass()) return false; return ((CommandBlockPlayer) other).sender.equals(sender); } @Override - public int hashCode(){ + public int hashCode() { int hash = 5; hash = 23 * hash + (this.sender != null ? this.sender.hashCode() : 0); return hash; } @Override - public void give(IItemStack stack){ - } + public void give(IItemStack stack) {} } diff --git a/src/main/java/minetweaker/mc1710/player/MCPlayer.java b/src/main/java/minetweaker/mc1710/player/MCPlayer.java index 08c26b1..d5f6156 100644 --- a/src/main/java/minetweaker/mc1710/player/MCPlayer.java +++ b/src/main/java/minetweaker/mc1710/player/MCPlayer.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.player; @@ -17,6 +16,7 @@ import minetweaker.mc1710.MineTweakerMod; import minetweaker.mc1710.data.NBTConverter; import minetweaker.mc1710.network.MineTweakerCopyClipboardPacket; import minetweaker.mc1710.network.MineTweakerOpenBrowserPacket; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; @@ -27,30 +27,31 @@ import net.minecraft.util.IChatComponent; * @author Stan */ public class MCPlayer implements IPlayer { - private final EntityPlayer player; - public MCPlayer(EntityPlayer player) { - this.player = player; - } + private final EntityPlayer player; - public EntityPlayer getInternal() { - return player; - } + public MCPlayer(EntityPlayer player) { + this.player = player; + } - @Override - public String getId() { - return null; // TODO: we should be having this for MC 1.7.10, right? - } + public EntityPlayer getInternal() { + return player; + } - @Override - public String getName() { - return player.getCommandSenderName(); - } + @Override + public String getId() { + return null; // TODO: we should be having this for MC 1.7.10, right? + } - @Override - public IData getData() { - return NBTConverter.from(player.getEntityData(), true); - } + @Override + public String getName() { + return player.getCommandSenderName(); + } + + @Override + public IData getData() { + return NBTConverter.from(player.getEntityData(), true); + } @Override public int getXP() { @@ -71,99 +72,93 @@ public class MCPlayer implements IPlayer { } @Override - public void update(IData data) { - NBTConverter.updateMap(player.getEntityData(), data); - } + public void update(IData data) { + NBTConverter.updateMap(player.getEntityData(), data); + } - @Override - public void sendChat(IChatMessage message) { - Object internal = message.getInternal(); - if (!(internal instanceof IChatComponent)) { - MineTweakerAPI.logError("not a valid chat message"); - return; - } - player.addChatMessage((IChatComponent) internal); - } + @Override + public void sendChat(IChatMessage message) { + Object internal = message.getInternal(); + if (!(internal instanceof IChatComponent)) { + MineTweakerAPI.logError("not a valid chat message"); + return; + } + player.addChatMessage((IChatComponent) internal); + } - @Override - public void sendChat(String message) { - if (message.length() > MAX_CHAT_MESSAGE_LENGTH) - { + @Override + public void sendChat(String message) { + if (message.length() > MAX_CHAT_MESSAGE_LENGTH) { message = message.substring(0, MAX_CHAT_MESSAGE_LENGTH); } - player.addChatMessage(new ChatComponentText(message)); - } + player.addChatMessage(new ChatComponentText(message)); + } - @Override - public int getHotbarSize() { - return 9; - } + @Override + public int getHotbarSize() { + return 9; + } - @Override - public IItemStack getHotbarStack(int i) { - return i < 0 || i >= 9 ? null : MineTweakerMC.getIItemStack(player.inventory.getStackInSlot(i)); - } + @Override + public IItemStack getHotbarStack(int i) { + return i < 0 || i >= 9 ? null : MineTweakerMC.getIItemStack(player.inventory.getStackInSlot(i)); + } - @Override - public int getInventorySize() { - return player.inventory.getSizeInventory(); - } + @Override + public int getInventorySize() { + return player.inventory.getSizeInventory(); + } - @Override - public IItemStack getInventoryStack(int i) { - return MineTweakerMC.getIItemStack(player.inventory.getStackInSlot(i)); - } + @Override + public IItemStack getInventoryStack(int i) { + return MineTweakerMC.getIItemStack(player.inventory.getStackInSlot(i)); + } - @Override - public IItemStack getCurrentItem() { - return MineTweakerMC.getIItemStack(player.getCurrentEquippedItem()); - } + @Override + public IItemStack getCurrentItem() { + return MineTweakerMC.getIItemStack(player.getCurrentEquippedItem()); + } - @Override - public boolean isCreative() { - return player.capabilities.isCreativeMode; - } + @Override + public boolean isCreative() { + return player.capabilities.isCreativeMode; + } - @Override - public boolean isAdventure() { - return !player.capabilities.allowEdit; - } + @Override + public boolean isAdventure() { + return !player.capabilities.allowEdit; + } - @Override - public void openBrowser(String url) { - if (player instanceof EntityPlayerMP && MineTweakerConfig.handleDesktopPackets) { - MineTweakerMod.NETWORK.sendTo( - new MineTweakerOpenBrowserPacket(url), - (EntityPlayerMP) player); - } - } + @Override + public void openBrowser(String url) { + if (player instanceof EntityPlayerMP && MineTweakerConfig.handleDesktopPackets) { + MineTweakerMod.NETWORK.sendTo(new MineTweakerOpenBrowserPacket(url), (EntityPlayerMP) player); + } + } - @Override - public void copyToClipboard(String value) { - if (player instanceof EntityPlayerMP && MineTweakerConfig.handleDesktopPackets) { - MineTweakerMod.NETWORK.sendTo( - new MineTweakerCopyClipboardPacket(value), - (EntityPlayerMP) player); - } - } + @Override + public void copyToClipboard(String value) { + if (player instanceof EntityPlayerMP && MineTweakerConfig.handleDesktopPackets) { + MineTweakerMod.NETWORK.sendTo(new MineTweakerCopyClipboardPacket(value), (EntityPlayerMP) player); + } + } - @Override - public boolean equals(Object other) { - if (other.getClass() != this.getClass()) - return false; + @Override + public boolean equals(Object other) { + if (other.getClass() != this.getClass()) return false; - return ((MCPlayer) other).player == player; - } + return ((MCPlayer) other).player == player; + } - @Override - public int hashCode() { - int hash = 5; - hash = 23 * hash + (this.player != null ? this.player.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 5; + hash = 23 * hash + (this.player != null ? this.player.hashCode() : 0); + return hash; + } - @Override - public void give(IItemStack stack) { - player.inventory.addItemStackToInventory(MineTweakerMC.getItemStack(stack).copy()); - } + @Override + public void give(IItemStack stack) { + player.inventory.addItemStackToInventory(MineTweakerMC.getItemStack(stack).copy()); + } } diff --git a/src/main/java/minetweaker/mc1710/player/RconPlayer.java b/src/main/java/minetweaker/mc1710/player/RconPlayer.java index d5e61d3..663e181 100644 --- a/src/main/java/minetweaker/mc1710/player/RconPlayer.java +++ b/src/main/java/minetweaker/mc1710/player/RconPlayer.java @@ -5,6 +5,7 @@ import minetweaker.api.chat.IChatMessage; import minetweaker.api.data.IData; import minetweaker.api.item.IItemStack; import minetweaker.api.player.IPlayer; + import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; @@ -14,6 +15,7 @@ import net.minecraft.util.IChatComponent; * @author Jared */ public class RconPlayer implements IPlayer { + private final ICommandSender sender; public RconPlayer(ICommandSender sender) { @@ -110,17 +112,14 @@ public class RconPlayer implements IPlayer { } @Override - public void openBrowser(String url) { - } + public void openBrowser(String url) {} @Override - public void copyToClipboard(String value) { - } + public void copyToClipboard(String value) {} @Override public boolean equals(Object other) { - if (other.getClass() != this.getClass()) - return false; + if (other.getClass() != this.getClass()) return false; return ((RconPlayer) other).sender == sender; } @@ -133,6 +132,5 @@ public class RconPlayer implements IPlayer { } @Override - public void give(IItemStack stack) { - } + public void give(IItemStack stack) {} } diff --git a/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java b/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java index 2eda6d3..77b2692 100644 --- a/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java +++ b/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java @@ -1,21 +1,22 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; -import java.util.List; - -import minetweaker.mc1710.player.MCPlayer; -import minetweaker.mc1710.util.MineTweakerHacks; -import minetweaker.api.item.IItemStack; import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; import static minetweaker.api.minecraft.MineTweakerMC.getIPlayer; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + +import java.util.List; + +import minetweaker.api.item.IItemStack; import minetweaker.api.player.IPlayer; import minetweaker.api.recipes.ICraftingInventory; +import minetweaker.mc1710.player.MCPlayer; +import minetweaker.mc1710.util.MineTweakerHacks; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; @@ -29,185 +30,182 @@ import net.minecraft.item.ItemStack; * @author Stan */ public class MCCraftingInventory implements ICraftingInventory { - private static final ThreadLocal cache = new ThreadLocal(); - private static final ThreadLocal cache2 = new ThreadLocal(); - public static MCCraftingInventory get(InventoryCrafting inventory) { - if (cache.get() == null || cache.get().inventory != inventory) { - MCCraftingInventory result = new MCCraftingInventory(inventory); - cache.set(result); - return result; - } else { - MCCraftingInventory result = cache.get(); - result.update(); - return result; - } - } + private static final ThreadLocal cache = new ThreadLocal(); + private static final ThreadLocal cache2 = new ThreadLocal(); - public static MCCraftingInventory get(IInventory inventory, EntityPlayer player) { - if (cache2.get() == null || cache2.get().inventory != inventory || cache2.get().player != player) { - MCCraftingInventory result = new MCCraftingInventory(inventory, player); - cache2.set(result); - return result; - } else { - MCCraftingInventory result = cache2.get(); - result.update(); - return result; - } - } + public static MCCraftingInventory get(InventoryCrafting inventory) { + if (cache.get() == null || cache.get().inventory != inventory) { + MCCraftingInventory result = new MCCraftingInventory(inventory); + cache.set(result); + return result; + } else { + MCCraftingInventory result = cache.get(); + result.update(); + return result; + } + } - private int width; - private int height; - private final IInventory inventory; - private IItemStack[] stacks; - private ItemStack[] original; - private int stackCount; - private final IPlayer player; - private final EntityPlayer playerOrig; + public static MCCraftingInventory get(IInventory inventory, EntityPlayer player) { + if (cache2.get() == null || cache2.get().inventory != inventory || cache2.get().player != player) { + MCCraftingInventory result = new MCCraftingInventory(inventory, player); + cache2.set(result); + return result; + } else { + MCCraftingInventory result = cache2.get(); + result.update(); + return result; + } + } - private MCCraftingInventory(InventoryCrafting inventory) { - this.inventory = inventory; - width = height = (int) Math.sqrt(inventory.getSizeInventory()); - stacks = new IItemStack[width * height]; - original = new ItemStack[stacks.length]; - stackCount = 0; - update(); + private int width; + private int height; + private final IInventory inventory; + private IItemStack[] stacks; + private ItemStack[] original; + private int stackCount; + private final IPlayer player; + private final EntityPlayer playerOrig; - Container container = MineTweakerHacks.getCraftingContainer(inventory); - if (container != null) { - List slots = container.inventorySlots; - if (!slots.isEmpty() && slots.get(0) instanceof SlotCrafting) { - SlotCrafting slotCrafting = (SlotCrafting) slots.get(0); - playerOrig = MineTweakerHacks.getCraftingSlotPlayer(slotCrafting); - player = getIPlayer(playerOrig); - } else { - playerOrig = null; - player = null; - } - } else { - playerOrig = null; - player = null; - } - } + private MCCraftingInventory(InventoryCrafting inventory) { + this.inventory = inventory; + width = height = (int) Math.sqrt(inventory.getSizeInventory()); + stacks = new IItemStack[width * height]; + original = new ItemStack[stacks.length]; + stackCount = 0; + update(); - public MCCraftingInventory(IInventory inventory, EntityPlayer player) { - this.inventory = inventory; - width = height = (int) Math.sqrt(inventory.getSizeInventory()); - stacks = new IItemStack[width * height]; - original = new ItemStack[stacks.length]; - stackCount = 0; - update(); + Container container = MineTweakerHacks.getCraftingContainer(inventory); + if (container != null) { + List slots = container.inventorySlots; + if (!slots.isEmpty() && slots.get(0) instanceof SlotCrafting) { + SlotCrafting slotCrafting = (SlotCrafting) slots.get(0); + playerOrig = MineTweakerHacks.getCraftingSlotPlayer(slotCrafting); + player = getIPlayer(playerOrig); + } else { + playerOrig = null; + player = null; + } + } else { + playerOrig = null; + player = null; + } + } - playerOrig = player; - this.player = player == null ? null : new MCPlayer(player); - } + public MCCraftingInventory(IInventory inventory, EntityPlayer player) { + this.inventory = inventory; + width = height = (int) Math.sqrt(inventory.getSizeInventory()); + stacks = new IItemStack[width * height]; + original = new ItemStack[stacks.length]; + stackCount = 0; + update(); - private void update() { - if (inventory.getSizeInventory() != original.length) { - width = height = (int) Math.sqrt(inventory.getSizeInventory()); - stacks = new IItemStack[inventory.getSizeInventory()]; - original = new ItemStack[stacks.length]; - stackCount = 0; - } + playerOrig = player; + this.player = player == null ? null : new MCPlayer(player); + } - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (changed(i)) { - // System.out.println("Slot " + i + " changed"); - original[i] = inventory.getStackInSlot(i); - if (inventory.getStackInSlot(i) != null) { - if (stacks[i] == null) - stackCount++; - stacks[i] = getIItemStack(original[i]); - } else { - if (stacks[i] != null) - stackCount--; - stacks[i] = null; - } - } - } - // System.out.println("Num stack count: " + stackCount); - } + private void update() { + if (inventory.getSizeInventory() != original.length) { + width = height = (int) Math.sqrt(inventory.getSizeInventory()); + stacks = new IItemStack[inventory.getSizeInventory()]; + original = new ItemStack[stacks.length]; + stackCount = 0; + } - @Override - public IPlayer getPlayer() { - return player; - } + for (int i = 0; i < inventory.getSizeInventory(); i++) { + if (changed(i)) { + // System.out.println("Slot " + i + " changed"); + original[i] = inventory.getStackInSlot(i); + if (inventory.getStackInSlot(i) != null) { + if (stacks[i] == null) stackCount++; + stacks[i] = getIItemStack(original[i]); + } else { + if (stacks[i] != null) stackCount--; + stacks[i] = null; + } + } + } + // System.out.println("Num stack count: " + stackCount); + } - @Override - public int getSize() { - return width * height; - } + @Override + public IPlayer getPlayer() { + return player; + } - @Override - public int getWidth() { - return width; - } + @Override + public int getSize() { + return width * height; + } - @Override - public int getHeight() { - return height; - } + @Override + public int getWidth() { + return width; + } - @Override - public int getStackCount() { - return stackCount; - } + @Override + public int getHeight() { + return height; + } - @Override - public IItemStack getStack(int i) { - return stacks[i]; - } + @Override + public int getStackCount() { + return stackCount; + } - @Override - public IItemStack getStack(int x, int y) { - return stacks[y * width + x]; - } + @Override + public IItemStack getStack(int i) { + return stacks[i]; + } - @Override - public void setStack(int x, int y, IItemStack stack) { - // System.out.println("SetStack(" + x + ", " + y + ") " + stack); + @Override + public IItemStack getStack(int x, int y) { + return stacks[y * width + x]; + } - int ix = y * width + x; - if (stack != stacks[ix]) { - if (stack == null) { - stackCount--; - inventory.setInventorySlotContents(ix, null); - } else { - inventory.setInventorySlotContents(ix, getItemStack(stack)); + @Override + public void setStack(int x, int y, IItemStack stack) { + // System.out.println("SetStack(" + x + ", " + y + ") " + stack); - if (stacks[ix] == null) { - stackCount++; - } - } - stacks[ix] = stack; - } - } + int ix = y * width + x; + if (stack != stacks[ix]) { + if (stack == null) { + stackCount--; + inventory.setInventorySlotContents(ix, null); + } else { + inventory.setInventorySlotContents(ix, getItemStack(stack)); - @Override - public void setStack(int i, IItemStack stack) { - // System.out.println("SetStack(" + i + ") " + stack); + if (stacks[ix] == null) { + stackCount++; + } + } + stacks[ix] = stack; + } + } - if (stack != stacks[i]) { - if (stack == null) { - stackCount--; - inventory.setInventorySlotContents(i, null); - } else { - inventory.setInventorySlotContents(i, getItemStack(stack)); + @Override + public void setStack(int i, IItemStack stack) { + // System.out.println("SetStack(" + i + ") " + stack); - if (stacks[i] == null) { - stackCount++; - } - } - stacks[i] = stack; - } - } + if (stack != stacks[i]) { + if (stack == null) { + stackCount--; + inventory.setInventorySlotContents(i, null); + } else { + inventory.setInventorySlotContents(i, getItemStack(stack)); - private boolean changed(int i) { - if (original[i] != inventory.getStackInSlot(i)) - return true; - if (original[i] != null && stacks[i].getAmount() != original[i].stackSize) - return true; + if (stacks[i] == null) { + stackCount++; + } + } + stacks[i] = stack; + } + } - return false; - } + private boolean changed(int i) { + if (original[i] != inventory.getStackInSlot(i)) return true; + if (original[i] != null && stacks[i].getAmount() != original[i].stackSize) return true; + + return false; + } } diff --git a/src/main/java/minetweaker/mc1710/recipes/MCRecipeManager.java b/src/main/java/minetweaker/mc1710/recipes/MCRecipeManager.java index 097b218..155efcf 100644 --- a/src/main/java/minetweaker/mc1710/recipes/MCRecipeManager.java +++ b/src/main/java/minetweaker/mc1710/recipes/MCRecipeManager.java @@ -1,5 +1,14 @@ package minetweaker.mc1710.recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getOreDict; + +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.RecursiveAction; +import java.util.stream.Collectors; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; @@ -18,6 +27,7 @@ import minetweaker.mc1710.item.MCItemStack; import minetweaker.mc1710.util.MineTweakerHacks; import minetweaker.mc1710.util.ThreadSafeBitSet; import minetweaker.util.IEventHandler; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.InventoryCrafting; @@ -28,23 +38,16 @@ import net.minecraft.item.crafting.ShapedRecipes; import net.minecraft.item.crafting.ShapelessRecipes; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; + import org.apache.commons.lang3.tuple.Pair; + import stanhebben.zenscript.annotations.Optional; -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.RecursiveAction; -import java.util.concurrent.RecursiveTask; -import java.util.stream.Collectors; - -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getOreDict; - /** * @author Stan */ public final class MCRecipeManager implements IRecipeManager { + public static final List recipesToAdd = new ArrayList<>(); public static final List recipesToRemove = new ArrayList<>(); public static final ActionRemoveRecipesNoIngredients actionRemoveRecipesNoIngredients = new ActionRemoveRecipesNoIngredients(); @@ -118,7 +121,7 @@ public final class MCRecipeManager implements IRecipeManager { @Override public int remove(IIngredient output, @Optional boolean nbtMatch) { - if(output == null) { + if (output == null) { MineTweakerAPI.logError("Cannot remove recipes for a null item!"); return 0; } @@ -142,7 +145,8 @@ public final class MCRecipeManager implements IRecipeManager { } @Override - public void addShaped(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, IRecipeAction action) { + public void addShaped(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, + IRecipeAction action) { recipesToAdd.add(new ActionAddShapedRecipe(output, ingredients, function, action, false)); } @@ -162,35 +166,36 @@ public final class MCRecipeManager implements IRecipeManager { } @Override - public void addShapedMirrored(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, IRecipeAction action) { + public void addShapedMirrored(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, + IRecipeAction action) { recipesToAdd.add(new ActionAddShapedRecipe(output, ingredients, function, action, true)); } @Override - public void addShapeless(IItemStack output, IIngredient[] ingredients, IRecipeFunction function, IRecipeAction action) { - if(checkShapelessNulls(output, ingredients)) - return; + public void addShapeless(IItemStack output, IIngredient[] ingredients, IRecipeFunction function, + IRecipeAction action) { + if (checkShapelessNulls(output, ingredients)) return; recipesToAdd.add(new ActionAddShapelessRecipe(output, ingredients, function, action)); } @Override - public void addShapeless(IItemStack output, IIngredient[] ingredients, IRecipeFunction function){ + public void addShapeless(IItemStack output, IIngredient[] ingredients, IRecipeFunction function) { addShapeless(output, ingredients, function, null); } @Override - public void addShapeless(IItemStack output, IIngredient[] ingredients, IRecipeAction action){ + public void addShapeless(IItemStack output, IIngredient[] ingredients, IRecipeAction action) { addShapeless(output, ingredients, null, action); } @Override - public void addShapeless(IItemStack output, IIngredient[] ingredients){ + public void addShapeless(IItemStack output, IIngredient[] ingredients) { addShapeless(output, ingredients, null, null); } private boolean checkShapelessNulls(IItemStack output, IIngredient[] ingredients) { - if(output != null && Arrays.stream(ingredients).allMatch(Objects::isNull)) { + if (output != null && Arrays.stream(ingredients).allMatch(Objects::isNull)) { MineTweakerAPI.logError("Null not allowed in shapeless recipes! Recipe for: " + output + " not created!"); return true; } @@ -199,7 +204,7 @@ public final class MCRecipeManager implements IRecipeManager { @Override public int removeShaped(IIngredient output, IIngredient[][] ingredients) { - if(output == null) { + if (output == null) { MineTweakerAPI.logError("Cannot remove recipes for a null item!"); return 0; } @@ -214,7 +219,7 @@ public final class MCRecipeManager implements IRecipeManager { @Override public int removeShapeless(IIngredient output, IIngredient[] ingredients, boolean wildcard) { - if(output == null) { + if (output == null) { MineTweakerAPI.logError("Cannot remove recipes for a null item!"); return 0; } @@ -269,14 +274,18 @@ public final class MCRecipeManager implements IRecipeManager { } public abstract static class ActionBaseRemoveRecipes implements IUndoableAction { + public abstract boolean matches(IRecipe r); + public abstract Set find(); - public void removeRecipes(Set toRemove ) { + + public void removeRecipes(Set toRemove) { recipes.removeIf(toRemove::contains); } } public static class ActionRemoveRecipesNoIngredients extends ActionBaseRemoveRecipes implements IUndoableAction { + // pair of output, nbtMatch private final List> outputs = new ArrayList<>(); private Set toRemove = new HashSet<>(); @@ -297,11 +306,10 @@ public final class MCRecipeManager implements IRecipeManager { @Override public Set find() { - return recipes.parallelStream() - .filter(r -> { - ItemStack recipeOutput = r.getRecipeOutput(); - return recipeOutput != null && matches(getIItemStack(recipeOutput)); - }).collect(Collectors.toSet()); + return recipes.parallelStream().filter(r -> { + ItemStack recipeOutput = r.getRecipeOutput(); + return recipeOutput != null && matches(getIItemStack(recipeOutput)); + }).collect(Collectors.toSet()); } @Override @@ -318,7 +326,7 @@ public final class MCRecipeManager implements IRecipeManager { @Override public void undo() { - for(IRecipe recipe: toRemove) { + for (IRecipe recipe : toRemove) { recipesToAdd.add(new ActionBaseAddRecipe(recipe)); } } @@ -339,10 +347,10 @@ public final class MCRecipeManager implements IRecipeManager { } private boolean matches(IItemStack stack) { - for(Pair entry : outputs) { + for (Pair entry : outputs) { IIngredient output = entry.getKey(); Boolean nbtMatch = entry.getValue(); - if(nbtMatch ? output.matchesExact(stack) : output.matches(stack)) { + if (nbtMatch ? output.matchesExact(stack) : output.matches(stack)) { return true; } } @@ -352,6 +360,7 @@ public final class MCRecipeManager implements IRecipeManager { } public static class ActionRemoveShapelessRecipes extends ActionBaseRemoveRecipes implements IUndoableAction { + final IIngredient output; final IIngredient[] ingredients; final boolean wildcard; @@ -384,8 +393,7 @@ public final class MCRecipeManager implements IRecipeManager { return false; } - checkIngredient: - for (IIngredient ingredient : ingredients) { + checkIngredient: for (IIngredient ingredient : ingredients) { for (int k = 0; k < srecipe.getRecipeSize(); k++) { if (MCRecipeManager.matches(srecipe.recipeItems.get(k), ingredient)) { continue checkIngredient; @@ -405,8 +413,7 @@ public final class MCRecipeManager implements IRecipeManager { return false; } - checkIngredient: - for (IIngredient ingredient : ingredients) { + checkIngredient: for (IIngredient ingredient : ingredients) { for (int k = 0; k < srecipe.getRecipeSize(); k++) { if (MCRecipeManager.matches(inputs.get(k), ingredient)) { continue checkIngredient; @@ -424,8 +431,7 @@ public final class MCRecipeManager implements IRecipeManager { public Set find() { Set toRemove = new HashSet<>(); for (IRecipe recipe : recipes) { - if (matches(recipe)) - toRemove.add(recipe); + if (matches(recipe)) toRemove.add(recipe); } return toRemove; } @@ -444,14 +450,14 @@ public final class MCRecipeManager implements IRecipeManager { @Override public void undo() { - for(IRecipe recipe: toRemove) { + for (IRecipe recipe : toRemove) { recipesToAdd.add(new ActionBaseAddRecipe(recipe)); } } @Override public String describe() { - if(output != null) { + if (output != null) { return "Removing Shapeless recipes for " + output.toString(); } else { return "Trying to remove recipes for invalid output"; @@ -470,14 +476,13 @@ public final class MCRecipeManager implements IRecipeManager { } public static class ActionRemoveShapedRecipes extends ActionBaseRemoveRecipes implements IUndoableAction { + final IIngredient output; final IIngredient[][] ingredients; final int ingredientsWidth; final int ingredientsHeight; Set toRemove = new HashSet<>(); - - public ActionRemoveShapedRecipes(IIngredient output, IIngredient[][] ingredients) { this.output = output; this.ingredients = ingredients; @@ -501,16 +506,17 @@ public final class MCRecipeManager implements IRecipeManager { if (output == null || !this.output.matches(new MCItemStack(output))) { return false; } - if (!(recipe instanceof ShapedRecipes || recipe instanceof ShapedOreRecipe)) - return false; + if (!(recipe instanceof ShapedRecipes || recipe instanceof ShapedOreRecipe)) return false; if (ingredients != null) { boolean ore = recipe instanceof ShapedOreRecipe; final ShapedRecipes shapedRecipe = !ore ? (ShapedRecipes) recipe : null; final ShapedOreRecipe shapedOreRecipe = ore ? (ShapedOreRecipe) recipe : null; - final int recipeWidth = ore ? MineTweakerHacks.getShapedOreRecipeWidth(shapedOreRecipe) : shapedRecipe.recipeWidth; - final int recipeHeight = ore ? shapedOreRecipe.getRecipeSize() / recipeWidth : shapedRecipe.recipeHeight; + final int recipeWidth = ore ? MineTweakerHacks.getShapedOreRecipeWidth(shapedOreRecipe) + : shapedRecipe.recipeWidth; + final int recipeHeight = ore ? shapedOreRecipe.getRecipeSize() / recipeWidth + : shapedRecipe.recipeHeight; if (ingredientsWidth != recipeWidth || ingredientsHeight != recipeHeight) { return false; @@ -520,7 +526,8 @@ public final class MCRecipeManager implements IRecipeManager { final IIngredient[] row = ingredients[j]; for (int k = 0; k < ingredientsWidth; k++) { final IIngredient ingredient = k > row.length ? null : row[k]; - final Object input = (ore ? shapedOreRecipe.getInput() : shapedRecipe.recipeItems)[j * recipeWidth + k]; + final Object input = (ore ? shapedOreRecipe.getInput() : shapedRecipe.recipeItems)[j + * recipeWidth + k]; if (!MCRecipeManager.matches(input, ingredient)) { return false; @@ -537,8 +544,7 @@ public final class MCRecipeManager implements IRecipeManager { Set toRemove = new HashSet<>(); for (final IRecipe recipe : recipes) { - if (matches(recipe)) - toRemove.add(recipe); + if (matches(recipe)) toRemove.add(recipe); } return toRemove; } @@ -558,14 +564,14 @@ public final class MCRecipeManager implements IRecipeManager { @Override public void undo() { - for(IRecipe recipe: toRemove) { + for (IRecipe recipe : toRemove) { recipesToAdd.add(new ActionBaseAddRecipe(recipe)); } } @Override public String describe() { - if(output != null) { + if (output != null) { return "Removing Shaped recipes for " + output.toString(); } else { return "Trying to remove recipes for invalid output"; @@ -584,6 +590,7 @@ public final class MCRecipeManager implements IRecipeManager { } public static class ActionBaseAddRecipe implements IUndoableAction { + private final IRecipe iRecipe; private final ICraftingRecipe craftingRecipe; @@ -613,8 +620,7 @@ public final class MCRecipeManager implements IRecipeManager { @Override public void apply() { recipes.add(iRecipe); - if (craftingRecipe != null && craftingRecipe.hasTransformers()) - transformerRecipes.add(craftingRecipe); + if (craftingRecipe != null && craftingRecipe.hasTransformers()) transformerRecipes.add(craftingRecipe); } @Override @@ -630,8 +636,11 @@ public final class MCRecipeManager implements IRecipeManager { @Override public String describe() { - if(output != null) { - return "" + (this.isRestoring ? "Restoring" : "Adding ") + (isShaped ? "shaped" : "shapeless") + " recipe for " + output.getDisplayName(); + if (output != null) { + return "" + (this.isRestoring ? "Restoring" : "Adding ") + + (isShaped ? "shaped" : "shapeless") + + " recipe for " + + output.getDisplayName(); } else { return "Trying to add " + (isShaped ? "shaped" : "shapeless") + "recipe without correct output"; } @@ -649,18 +658,23 @@ public final class MCRecipeManager implements IRecipeManager { } private static class ActionAddShapedRecipe extends ActionBaseAddRecipe { - public ActionAddShapedRecipe(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, IRecipeAction action, boolean mirrored) { + + public ActionAddShapedRecipe(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, + IRecipeAction action, boolean mirrored) { super(new ShapedRecipe(output, ingredients, function, action, mirrored), output, true); } } private static class ActionAddShapelessRecipe extends ActionBaseAddRecipe { - public ActionAddShapelessRecipe(IItemStack output, IIngredient[] ingredients, IRecipeFunction function, IRecipeAction action) { + + public ActionAddShapelessRecipe(IItemStack output, IIngredient[] ingredients, IRecipeFunction function, + IRecipeAction action) { super(new ShapelessRecipe(output, ingredients, function, action), output, false); } } private static class ActionBatchRemoveRecipe implements IUndoableAction { + private final Set recipes; private ActionBatchRemoveRecipe(Set recipes) { @@ -702,7 +716,7 @@ public final class MCRecipeManager implements IRecipeManager { public static void applyAdditionsAndRemovals() { System.out.println("MineTweaker: Applying additions and removals"); MineTweakerAPI.apply(MCRecipeManager.actionRemoveRecipesNoIngredients); - if(recipesToUndo.size() > 0) { + if (recipesToUndo.size() > 0) { recipes.removeIf(recipesToUndo::contains); } int commonPoolParallelism = getCommonPoolParallelism(); @@ -710,17 +724,18 @@ public final class MCRecipeManager implements IRecipeManager { // if thread == 1, then we have parallel overhead but doesn't have parallel speedup. // never do this recipesToRemove.forEach(ActionBaseRemoveRecipes::apply); - } else - try { - ThreadSafeBitSet removed = new ThreadSafeBitSet(); - new FindRecipeToRemoveTask(removed, recipesToRemove).fork().get(); - MineTweakerAPI.apply(new ActionBatchRemoveRecipe(removed.toBitSet().stream().mapToObj(recipes::get).collect(Collectors.toSet()))); - } catch (InterruptedException | ExecutionException e) { - System.err.println("MineTweaker: Parallel Removal failed. Falling back to sequential remove"); - e.printStackTrace(); - // try it sequentially - recipesToRemove.forEach(ActionBaseRemoveRecipes::apply); - } + } else try { + ThreadSafeBitSet removed = new ThreadSafeBitSet(); + new FindRecipeToRemoveTask(removed, recipesToRemove).fork().get(); + MineTweakerAPI.apply( + new ActionBatchRemoveRecipe( + removed.toBitSet().stream().mapToObj(recipes::get).collect(Collectors.toSet()))); + } catch (InterruptedException | ExecutionException e) { + System.err.println("MineTweaker: Parallel Removal failed. Falling back to sequential remove"); + e.printStackTrace(); + // try it sequentially + recipesToRemove.forEach(ActionBaseRemoveRecipes::apply); + } MCRecipeManager.recipesToAdd.forEach(MineTweakerAPI::apply); actionRemoveRecipesNoIngredients.clearOutputs(); @@ -730,19 +745,22 @@ public final class MCRecipeManager implements IRecipeManager { } private static int getCommonPoolParallelism() { - return Integer.getInteger("java.util.concurrent.ForkJoinPool.common.parallelism", Runtime.getRuntime().availableProcessors() - 1); + return Integer.getInteger( + "java.util.concurrent.ForkJoinPool.common.parallelism", + Runtime.getRuntime().availableProcessors() - 1); } - public static class HandleLateAdditionsAndRemovals implements IEventHandler - { + public static class HandleLateAdditionsAndRemovals + implements IEventHandler { + @Override - public void handle(MineTweakerImplementationAPI.ReloadEvent event) - { + public void handle(MineTweakerImplementationAPI.ReloadEvent event) { MCRecipeManager.applyAdditionsAndRemovals(); } } private class ContainerVirtual extends Container { + @Override public boolean canInteractWith(EntityPlayer var1) { return false; @@ -777,9 +795,12 @@ public final class MCRecipeManager implements IRecipeManager { } } } else { - FindRecipeToRemoveTask left = new FindRecipeToRemoveTask(removed, workList.subList(0, workList.size() / 2)); + FindRecipeToRemoveTask left = new FindRecipeToRemoveTask( + removed, + workList.subList(0, workList.size() / 2)); left.fork(); - new FindRecipeToRemoveTask(removed, workList.subList(workList.size() / 2, workList.size())).fork().join(); + new FindRecipeToRemoveTask(removed, workList.subList(workList.size() / 2, workList.size())).fork() + .join(); left.join(); } } diff --git a/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java b/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java index 975e9f5..016da36 100644 --- a/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java +++ b/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java @@ -1,21 +1,23 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; -import minetweaker.api.recipes.ShapedRecipe; -import minetweaker.api.recipes.ShapelessRecipe; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import java.util.ArrayList; import java.util.Arrays; + import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; import minetweaker.api.minecraft.MineTweakerMC; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; import minetweaker.api.recipes.ICraftingRecipe; +import minetweaker.api.recipes.ShapedRecipe; +import minetweaker.api.recipes.ShapelessRecipe; import minetweaker.api.recipes.UnknownRecipe; + import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.ShapedRecipes; @@ -28,160 +30,159 @@ import net.minecraftforge.oredict.ShapelessOreRecipe; * @author Stan */ public class RecipeConverter { - private RecipeConverter() { - } - public static final int TYPE_ADVANCED = 0; - public static final int TYPE_ORE = 1; - public static final int TYPE_BASIC = 2; + private RecipeConverter() {} - private static int getIngredientType(IIngredient pattern) { - Object internal = pattern.getInternal(); - if (internal == null) { - return TYPE_ADVANCED; - } else if (internal instanceof ItemStack) { - return TYPE_BASIC; - } else { - return TYPE_ORE; - } - } + public static final int TYPE_ADVANCED = 0; + public static final int TYPE_ORE = 1; + public static final int TYPE_BASIC = 2; - private static int getRecipeType(IIngredient[] ingredients) { - int type = TYPE_BASIC; - for (IIngredient ingredient : ingredients) { - type = Math.min(type, getIngredientType(ingredient)); - } - return type; - } - public static IRecipe convert(ICraftingRecipe recipe) { - if (recipe instanceof ShapedRecipe) - return RecipeConverter.convert((ShapedRecipe)recipe); - else - return RecipeConverter.convert((ShapelessRecipe) recipe); - } - - public static IRecipe convert(ShapelessRecipe recipe) { - IIngredient[] ingredients = recipe.getIngredients(); - int type = getRecipeType(ingredients); + private static int getIngredientType(IIngredient pattern) { + Object internal = pattern.getInternal(); + if (internal == null) { + return TYPE_ADVANCED; + } else if (internal instanceof ItemStack) { + return TYPE_BASIC; + } else { + return TYPE_ORE; + } + } - if (type == TYPE_BASIC) { - ItemStack[] items = new ItemStack[ingredients.length]; - for (int i = 0; i < ingredients.length; i++) { - items[i] = getItemStack(ingredients[i]); - } - return new ShapelessRecipeBasic(items, recipe); - } else if (type == TYPE_ORE) { - Object[] items = new Object[ingredients.length]; - for (int i = 0; i < ingredients.length; i++) { - items[i] = ingredients[i].getInternal(); - } - return new ShapelessRecipeOre(items, recipe); - } else { - return new ShapelessRecipeAdvanced(recipe); - } - } + private static int getRecipeType(IIngredient[] ingredients) { + int type = TYPE_BASIC; + for (IIngredient ingredient : ingredients) { + type = Math.min(type, getIngredientType(ingredient)); + } + return type; + } - public static IRecipe convert(ShapedRecipe recipe) { - IIngredient[] ingredients = recipe.getIngredients(); - byte[] posx = recipe.getIngredientsX(); - byte[] posy = recipe.getIngredientsY(); + public static IRecipe convert(ICraftingRecipe recipe) { + if (recipe instanceof ShapedRecipe) return RecipeConverter.convert((ShapedRecipe) recipe); + else return RecipeConverter.convert((ShapelessRecipe) recipe); + } - // determine recipe type - int type = getRecipeType(ingredients); + public static IRecipe convert(ShapelessRecipe recipe) { + IIngredient[] ingredients = recipe.getIngredients(); + int type = getRecipeType(ingredients); - // construct recipe - if (type == TYPE_BASIC) { - ItemStack[] basicIngredients = new ItemStack[recipe.getHeight() * recipe.getWidth()]; - for (int i = 0; i < ingredients.length; i++) { - basicIngredients[posx[i] + posy[i] * recipe.getWidth()] = getItemStack(ingredients[i]); - } + if (type == TYPE_BASIC) { + ItemStack[] items = new ItemStack[ingredients.length]; + for (int i = 0; i < ingredients.length; i++) { + items[i] = getItemStack(ingredients[i]); + } + return new ShapelessRecipeBasic(items, recipe); + } else if (type == TYPE_ORE) { + Object[] items = new Object[ingredients.length]; + for (int i = 0; i < ingredients.length; i++) { + items[i] = ingredients[i].getInternal(); + } + return new ShapelessRecipeOre(items, recipe); + } else { + return new ShapelessRecipeAdvanced(recipe); + } + } - return new ShapedRecipeBasic(basicIngredients, recipe); - } else if (type == TYPE_ORE) { - Object[] converted = new Object[recipe.getHeight() * recipe.getWidth()]; - for (int i = 0; i < ingredients.length; i++) { - converted[posx[i] + posy[i] * recipe.getWidth()] = ingredients[i].getInternal(); - } + public static IRecipe convert(ShapedRecipe recipe) { + IIngredient[] ingredients = recipe.getIngredients(); + byte[] posx = recipe.getIngredientsX(); + byte[] posy = recipe.getIngredientsY(); - // arguments contents: - // 1) recipe patterns - // 2) characters + ingredients + // determine recipe type + int type = getRecipeType(ingredients); - int counter = 0; - String[] parts = new String[recipe.getHeight()]; - ArrayList rarguments = new ArrayList(); - for (int i = 0; i < recipe.getHeight(); i++) { - char[] pattern = new char[recipe.getWidth()]; - for (int j = 0; j < recipe.getWidth(); j++) { - int off = i * recipe.getWidth() + j; - if (converted[off] == null) { - pattern[j] = ' '; - } else { - pattern[j] = (char) ('A' + counter); - rarguments.add(pattern[j]); - rarguments.add(converted[off]); - counter++; - } - } - parts[i] = new String(pattern); - } + // construct recipe + if (type == TYPE_BASIC) { + ItemStack[] basicIngredients = new ItemStack[recipe.getHeight() * recipe.getWidth()]; + for (int i = 0; i < ingredients.length; i++) { + basicIngredients[posx[i] + posy[i] * recipe.getWidth()] = getItemStack(ingredients[i]); + } - rarguments.addAll(0, Arrays.asList(parts)); + return new ShapedRecipeBasic(basicIngredients, recipe); + } else if (type == TYPE_ORE) { + Object[] converted = new Object[recipe.getHeight() * recipe.getWidth()]; + for (int i = 0; i < ingredients.length; i++) { + converted[posx[i] + posy[i] * recipe.getWidth()] = ingredients[i].getInternal(); + } - return new ShapedRecipeOre(rarguments.toArray(), recipe); - } else { - return new ShapedRecipeAdvanced(recipe); - } - } + // arguments contents: + // 1) recipe patterns + // 2) characters + ingredients - public static ICraftingRecipe toCraftingRecipe(IRecipe recipe) { - IItemStack output = MineTweakerMC.getIItemStack(recipe.getRecipeOutput()); + int counter = 0; + String[] parts = new String[recipe.getHeight()]; + ArrayList rarguments = new ArrayList(); + for (int i = 0; i < recipe.getHeight(); i++) { + char[] pattern = new char[recipe.getWidth()]; + for (int j = 0; j < recipe.getWidth(); j++) { + int off = i * recipe.getWidth() + j; + if (converted[off] == null) { + pattern[j] = ' '; + } else { + pattern[j] = (char) ('A' + counter); + rarguments.add(pattern[j]); + rarguments.add(converted[off]); + counter++; + } + } + parts[i] = new String(pattern); + } - if (recipe instanceof ShapelessRecipes) { - ShapelessRecipes shapeless = (ShapelessRecipes) recipe; + rarguments.addAll(0, Arrays.asList(parts)); - IIngredient[] ingredients = new IIngredient[shapeless.recipeItems.size()]; - for (int i = 0; i < ingredients.length; i++) { - ingredients[i] = MineTweakerMC.getIIngredient(shapeless.recipeItems.get(i)); - } + return new ShapedRecipeOre(rarguments.toArray(), recipe); + } else { + return new ShapedRecipeAdvanced(recipe); + } + } - return new ShapelessRecipe(output, ingredients, null, null); - } else if (recipe instanceof ShapedRecipes) { - ShapedRecipes shaped = (ShapedRecipes) recipe; + public static ICraftingRecipe toCraftingRecipe(IRecipe recipe) { + IItemStack output = MineTweakerMC.getIItemStack(recipe.getRecipeOutput()); - IIngredient[][] ingredients = new IIngredient[shaped.recipeHeight][shaped.recipeWidth]; - for (int i = 0; i < shaped.recipeHeight; i++) { - for (int j = 0; j < shaped.recipeWidth; j++) { - ingredients[i][j] = MineTweakerMC.getIItemStack(shaped.recipeItems[i * shaped.recipeWidth + j]); - } - } + if (recipe instanceof ShapelessRecipes) { + ShapelessRecipes shapeless = (ShapelessRecipes) recipe; - return new ShapedRecipe(output, ingredients, null, null, false); - } else if (recipe instanceof ShapedOreRecipe) { - ShapedOreRecipe shaped = (ShapedOreRecipe) recipe; + IIngredient[] ingredients = new IIngredient[shapeless.recipeItems.size()]; + for (int i = 0; i < ingredients.length; i++) { + ingredients[i] = MineTweakerMC.getIIngredient(shapeless.recipeItems.get(i)); + } - int width = (int) Math.sqrt(recipe.getRecipeSize()); - int height = recipe.getRecipeSize() / width; + return new ShapelessRecipe(output, ingredients, null, null); + } else if (recipe instanceof ShapedRecipes) { + ShapedRecipes shaped = (ShapedRecipes) recipe; - IIngredient[][] recipeIngredients = new IIngredient[height][width]; - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j++) { - recipeIngredients[i][j] = MineTweakerMC.getIIngredient(shaped.getInput()[i * width + j]); - } - } + IIngredient[][] ingredients = new IIngredient[shaped.recipeHeight][shaped.recipeWidth]; + for (int i = 0; i < shaped.recipeHeight; i++) { + for (int j = 0; j < shaped.recipeWidth; j++) { + ingredients[i][j] = MineTweakerMC.getIItemStack(shaped.recipeItems[i * shaped.recipeWidth + j]); + } + } - return new ShapedRecipe(output, recipeIngredients, null, null, false); - } else if (recipe instanceof ShapelessOreRecipe) { - ShapelessOreRecipe shapeless = (ShapelessOreRecipe) recipe; + return new ShapedRecipe(output, ingredients, null, null, false); + } else if (recipe instanceof ShapedOreRecipe) { + ShapedOreRecipe shaped = (ShapedOreRecipe) recipe; - IIngredient[] ingredients = new IIngredient[shapeless.getRecipeSize()]; - for (int i = 0; i < ingredients.length; i++) { - ingredients[i] = MineTweakerMC.getIIngredient(shapeless.getInput().get(i)); - } + int width = (int) Math.sqrt(recipe.getRecipeSize()); + int height = recipe.getRecipeSize() / width; - return new ShapelessRecipe(output, ingredients, null, null); - } else { - return new UnknownRecipe(output); - } - } + IIngredient[][] recipeIngredients = new IIngredient[height][width]; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { + recipeIngredients[i][j] = MineTweakerMC.getIIngredient(shaped.getInput()[i * width + j]); + } + } + + return new ShapedRecipe(output, recipeIngredients, null, null, false); + } else if (recipe instanceof ShapelessOreRecipe) { + ShapelessOreRecipe shapeless = (ShapelessOreRecipe) recipe; + + IIngredient[] ingredients = new IIngredient[shapeless.getRecipeSize()]; + for (int i = 0; i < ingredients.length; i++) { + ingredients[i] = MineTweakerMC.getIIngredient(shapeless.getInput().get(i)); + } + + return new ShapelessRecipe(output, ingredients, null, null); + } else { + return new UnknownRecipe(output); + } + } } diff --git a/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java b/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java index 34196ae..05a4f60 100644 --- a/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java +++ b/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java @@ -1,13 +1,14 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.api.recipes.ShapedRecipe; + import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; @@ -19,29 +20,30 @@ import net.minecraft.world.World; * @author Stan */ public class ShapedRecipeAdvanced implements IRecipe { - private final ShapedRecipe recipe; - public ShapedRecipeAdvanced(ShapedRecipe recipe) { - this.recipe = recipe; - } + private final ShapedRecipe recipe; - @Override - public boolean matches(InventoryCrafting inventory, World world) { - return recipe.matches(MCCraftingInventory.get(inventory)); - } + public ShapedRecipeAdvanced(ShapedRecipe recipe) { + this.recipe = recipe; + } - @Override - public ItemStack getCraftingResult(InventoryCrafting inventory) { - return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); - } + @Override + public boolean matches(InventoryCrafting inventory, World world) { + return recipe.matches(MCCraftingInventory.get(inventory)); + } - @Override - public int getRecipeSize() { - return recipe.getWidth() * recipe.getHeight(); - } + @Override + public ItemStack getCraftingResult(InventoryCrafting inventory) { + return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); + } - @Override - public ItemStack getRecipeOutput() { - return getItemStack(recipe.getOutput()); - } + @Override + public int getRecipeSize() { + return recipe.getWidth() * recipe.getHeight(); + } + + @Override + public ItemStack getRecipeOutput() { + return getItemStack(recipe.getOutput()); + } } diff --git a/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java b/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java index 8910351..1541c38 100644 --- a/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java +++ b/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java @@ -1,14 +1,15 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; -import minetweaker.api.item.IItemStack; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + +import minetweaker.api.item.IItemStack; import minetweaker.api.recipes.ShapedRecipe; + import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.ShapedRecipes; @@ -19,26 +20,27 @@ import net.minecraft.world.World; * @author Stan */ public class ShapedRecipeBasic extends ShapedRecipes { - private final ShapedRecipe recipe; - public ShapedRecipeBasic(ItemStack[] basicInputs, ShapedRecipe recipe) { - super(recipe.getWidth(), recipe.getHeight(), basicInputs, getItemStack(recipe.getOutput())); + private final ShapedRecipe recipe; - this.recipe = recipe; - } + public ShapedRecipeBasic(ItemStack[] basicInputs, ShapedRecipe recipe) { + super(recipe.getWidth(), recipe.getHeight(), basicInputs, getItemStack(recipe.getOutput())); - @Override - public boolean matches(InventoryCrafting inventory, World world) { - return recipe.matches(MCCraftingInventory.get(inventory)); - } + this.recipe = recipe; + } - @Override - public ItemStack getCraftingResult(InventoryCrafting inventory) { - IItemStack result = recipe.getCraftingResult(MCCraftingInventory.get(inventory)); - if (result == null) { - return null; - } else { - return getItemStack(result).copy(); - } - } + @Override + public boolean matches(InventoryCrafting inventory, World world) { + return recipe.matches(MCCraftingInventory.get(inventory)); + } + + @Override + public ItemStack getCraftingResult(InventoryCrafting inventory) { + IItemStack result = recipe.getCraftingResult(MCCraftingInventory.get(inventory)); + if (result == null) { + return null; + } else { + return getItemStack(result).copy(); + } + } } diff --git a/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java b/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java index 8b90305..1992bca 100644 --- a/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java +++ b/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java @@ -1,13 +1,14 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.api.recipes.ShapedRecipe; + import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -18,6 +19,7 @@ import net.minecraftforge.oredict.ShapedOreRecipe; * @author Stan */ public class ShapedRecipeOre extends ShapedOreRecipe { + private final ShapedRecipe recipe; public ShapedRecipeOre(Object[] contents, ShapedRecipe recipe) { @@ -33,8 +35,8 @@ public class ShapedRecipeOre extends ShapedOreRecipe { @Override public ItemStack getCraftingResult(InventoryCrafting inventory) { - if(recipe !=null){ - if(recipe.getCraftingResult(MCCraftingInventory.get(inventory))!=null){ + if (recipe != null) { + if (recipe.getCraftingResult(MCCraftingInventory.get(inventory)) != null) { return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); } } diff --git a/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java b/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java index e2a9850..c0fa2aa 100644 --- a/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java +++ b/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java @@ -1,13 +1,14 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.api.recipes.ShapelessRecipe; + import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; @@ -18,29 +19,30 @@ import net.minecraft.world.World; * @author Stan */ public class ShapelessRecipeAdvanced implements IRecipe { - private final ShapelessRecipe recipe; - public ShapelessRecipeAdvanced(ShapelessRecipe recipe) { - this.recipe = recipe; - } + private final ShapelessRecipe recipe; - @Override - public boolean matches(InventoryCrafting inventory, World world) { - return recipe.matches(MCCraftingInventory.get(inventory)); - } + public ShapelessRecipeAdvanced(ShapelessRecipe recipe) { + this.recipe = recipe; + } - @Override - public ItemStack getCraftingResult(InventoryCrafting inventory) { - return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); - } + @Override + public boolean matches(InventoryCrafting inventory, World world) { + return recipe.matches(MCCraftingInventory.get(inventory)); + } - @Override - public int getRecipeSize() { - return recipe.getSize(); - } + @Override + public ItemStack getCraftingResult(InventoryCrafting inventory) { + return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); + } - @Override - public ItemStack getRecipeOutput() { - return getItemStack(recipe.getOutput()); - } + @Override + public int getRecipeSize() { + return recipe.getSize(); + } + + @Override + public ItemStack getRecipeOutput() { + return getItemStack(recipe.getOutput()); + } } diff --git a/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java b/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java index 6997da1..cf89ad3 100644 --- a/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java +++ b/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java @@ -1,14 +1,16 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; -import minetweaker.api.recipes.ShapelessRecipe; -import java.util.Arrays; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + +import java.util.Arrays; + +import minetweaker.api.recipes.ShapelessRecipe; + import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.ShapelessRecipes; @@ -19,21 +21,22 @@ import net.minecraft.world.World; * @author Stan */ public class ShapelessRecipeBasic extends ShapelessRecipes { - private final ShapelessRecipe recipe; - public ShapelessRecipeBasic(ItemStack[] ingredients, ShapelessRecipe recipe) { - super(getItemStack(recipe.getOutput()), Arrays.asList(ingredients)); + private final ShapelessRecipe recipe; - this.recipe = recipe; - } + public ShapelessRecipeBasic(ItemStack[] ingredients, ShapelessRecipe recipe) { + super(getItemStack(recipe.getOutput()), Arrays.asList(ingredients)); - @Override - public boolean matches(InventoryCrafting inventory, World world) { - return recipe.matches(MCCraftingInventory.get(inventory)); - } + this.recipe = recipe; + } - @Override - public ItemStack getCraftingResult(InventoryCrafting inventory) { - return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); - } + @Override + public boolean matches(InventoryCrafting inventory, World world) { + return recipe.matches(MCCraftingInventory.get(inventory)); + } + + @Override + public ItemStack getCraftingResult(InventoryCrafting inventory) { + return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); + } } diff --git a/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java b/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java index 3a8bd43..b7c1657 100644 --- a/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java +++ b/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java @@ -1,13 +1,14 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.recipes; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.api.recipes.ShapelessRecipe; + import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -18,21 +19,22 @@ import net.minecraftforge.oredict.ShapelessOreRecipe; * @author Stan */ public class ShapelessRecipeOre extends ShapelessOreRecipe { - private final ShapelessRecipe recipe; - public ShapelessRecipeOre(Object[] ingredients, ShapelessRecipe recipe) { - super(getItemStack(recipe.getOutput()), ingredients); + private final ShapelessRecipe recipe; - this.recipe = recipe; - } + public ShapelessRecipeOre(Object[] ingredients, ShapelessRecipe recipe) { + super(getItemStack(recipe.getOutput()), ingredients); - @Override - public boolean matches(InventoryCrafting inventory, World world) { - return recipe.matches(MCCraftingInventory.get(inventory)); - } + this.recipe = recipe; + } - @Override - public ItemStack getCraftingResult(InventoryCrafting inventory) { - return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); - } + @Override + public boolean matches(InventoryCrafting inventory, World world) { + return recipe.matches(MCCraftingInventory.get(inventory)); + } + + @Override + public ItemStack getCraftingResult(InventoryCrafting inventory) { + return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); + } } diff --git a/src/main/java/minetweaker/mc1710/server/MCServer.java b/src/main/java/minetweaker/mc1710/server/MCServer.java index ceba492..87b69ca 100644 --- a/src/main/java/minetweaker/mc1710/server/MCServer.java +++ b/src/main/java/minetweaker/mc1710/server/MCServer.java @@ -1,11 +1,13 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.server; +import java.util.Arrays; +import java.util.List; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.minecraft.MineTweakerMC; @@ -16,6 +18,7 @@ import minetweaker.api.server.ICommandTabCompletion; import minetweaker.api.server.ICommandValidator; import minetweaker.mc1710.player.CommandBlockPlayer; import minetweaker.mc1710.player.RconPlayer; + import net.minecraft.command.CommandHandler; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; @@ -26,13 +29,11 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.server.management.UserListOps; -import java.util.Arrays; -import java.util.List; - /** * @author Stan */ public class MCServer extends AbstractServer { + private final MinecraftServer server; public MCServer(MinecraftServer server) { @@ -40,15 +41,15 @@ public class MCServer extends AbstractServer { } @Override - public void addCommand(String name, String usage, String[] aliases, ICommandFunction function, ICommandValidator validator, ICommandTabCompletion completion) { + public void addCommand(String name, String usage, String[] aliases, ICommandFunction function, + ICommandValidator validator, ICommandTabCompletion completion) { ICommand command = new MCCommand(name, usage, aliases, function, validator, completion); MineTweakerAPI.apply(new AddCommandAction(command)); } @Override public boolean isOp(IPlayer player) { - if (player == ServerPlayer.INSTANCE) - return true; + if (player == ServerPlayer.INSTANCE) return true; UserListOps ops = MinecraftServer.getServer().getConfigurationManager().func_152603_m(); if (server.isDedicatedServer() && ops != null) { @@ -60,7 +61,7 @@ public class MCServer extends AbstractServer { @Override public boolean isCommandAdded(String name) { - return MinecraftServer.getServer().getCommandManager().getCommands().containsKey(name); + return MinecraftServer.getServer().getCommandManager().getCommands().containsKey(name); } private static IPlayer getPlayer(ICommandSender commandSender) { @@ -70,9 +71,9 @@ public class MCServer extends AbstractServer { return ServerPlayer.INSTANCE; } else if (commandSender instanceof RConConsoleSource) { return new RconPlayer(commandSender); - } else if(commandSender instanceof CommandBlockLogic){ + } else if (commandSender instanceof CommandBlockLogic) { return new CommandBlockPlayer(commandSender); - }else { + } else { System.out.println("Unsupported command sender: " + commandSender); System.out.println("player name: " + commandSender.getCommandSenderName()); return null; @@ -80,6 +81,7 @@ public class MCServer extends AbstractServer { } private class MCCommand implements ICommand { + private final String name; private final String usage; private final List aliases; @@ -87,7 +89,8 @@ public class MCServer extends AbstractServer { private final ICommandValidator validator; private final ICommandTabCompletion completion; - public MCCommand(String name, String usage, String[] aliases, ICommandFunction function, ICommandValidator validator, ICommandTabCompletion completion) { + public MCCommand(String name, String usage, String[] aliases, ICommandFunction function, + ICommandValidator validator, ICommandTabCompletion completion) { this.name = name; this.usage = usage; this.aliases = Arrays.asList(aliases); @@ -146,16 +149,17 @@ public class MCServer extends AbstractServer { } private class AddCommandAction implements IUndoableAction { + private final ICommand command; public AddCommandAction(ICommand command) { this.command = command; } + @Override public void apply() { CommandHandler ch = (CommandHandler) MinecraftServer.getServer().getCommandManager(); - if (!ch.getCommands().containsValue(command)) - ch.registerCommand(command); + if (!ch.getCommands().containsValue(command)) ch.registerCommand(command); } @Override @@ -171,8 +175,7 @@ public class MCServer extends AbstractServer { @Override public String describe() { CommandHandler ch = (CommandHandler) MinecraftServer.getServer().getCommandManager(); - if (!ch.getCommands().containsValue(command)) - return "Adding command " + command.getCommandName(); + if (!ch.getCommands().containsValue(command)) return "Adding command " + command.getCommandName(); return ""; } diff --git a/src/main/java/minetweaker/mc1710/server/ServerPlayer.java b/src/main/java/minetweaker/mc1710/server/ServerPlayer.java index 0a18a4f..bf9a4fb 100644 --- a/src/main/java/minetweaker/mc1710/server/ServerPlayer.java +++ b/src/main/java/minetweaker/mc1710/server/ServerPlayer.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.server; @@ -14,10 +13,12 @@ import java.io.IOException; import java.net.URI; import java.util.logging.Level; import java.util.logging.Logger; + import minetweaker.api.chat.IChatMessage; import minetweaker.api.data.IData; import minetweaker.api.item.IItemStack; import minetweaker.api.player.IPlayer; + import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; @@ -27,27 +28,28 @@ import net.minecraft.util.IChatComponent; * @author Stan */ public class ServerPlayer implements IPlayer { - public static final ServerPlayer INSTANCE = new ServerPlayer(); - private ServerPlayer() { + public static final ServerPlayer INSTANCE = new ServerPlayer(); - } + private ServerPlayer() { - @Override - public String getId() { - return "server"; - } + } - @Override - public String getName() { - return "Server"; - } + @Override + public String getId() { + return "server"; + } - @Override - public IData getData() { - // TODO: implement - return null; - } + @Override + public String getName() { + return "Server"; + } + + @Override + public IData getData() { + // TODO: implement + return null; + } @Override public int getXP() { @@ -65,77 +67,77 @@ public class ServerPlayer implements IPlayer { } @Override - public void update(IData data) { - // TODO: implement - } + public void update(IData data) { + // TODO: implement + } - @Override - public void sendChat(IChatMessage message) { - DedicatedServer.getServer().addChatMessage((IChatComponent) message.getInternal()); - } + @Override + public void sendChat(IChatMessage message) { + DedicatedServer.getServer().addChatMessage((IChatComponent) message.getInternal()); + } - @Override - public void sendChat(String message) { - DedicatedServer.getServer().addChatMessage(new ChatComponentText(message)); - } + @Override + public void sendChat(String message) { + DedicatedServer.getServer().addChatMessage(new ChatComponentText(message)); + } - @Override - public int getHotbarSize() { - return 0; - } + @Override + public int getHotbarSize() { + return 0; + } - @Override - public IItemStack getHotbarStack(int i) { - return null; - } + @Override + public IItemStack getHotbarStack(int i) { + return null; + } - @Override - public int getInventorySize() { - return 0; - } + @Override + public int getInventorySize() { + return 0; + } - @Override - public IItemStack getInventoryStack(int i) { - return null; - } + @Override + public IItemStack getInventoryStack(int i) { + return null; + } - @Override - public IItemStack getCurrentItem() { - return null; - } + @Override + public IItemStack getCurrentItem() { + return null; + } - @Override - public boolean isCreative() { - return true; - } + @Override + public boolean isCreative() { + return true; + } - @Override - public boolean isAdventure() { - return false; - } + @Override + public boolean isAdventure() { + return false; + } - @Override - public void openBrowser(String url) { - if (Desktop.isDesktopSupported()) { - try { - Desktop.getDesktop().browse(URI.create(url)); - } catch (IOException ex) { - Logger.getLogger(ServerPlayer.class.getName()).log(Level.SEVERE, null, ex); - } - } - } + @Override + public void openBrowser(String url) { + if (Desktop.isDesktopSupported()) { + try { + Desktop.getDesktop().browse(URI.create(url)); + } catch (IOException ex) { + Logger.getLogger(ServerPlayer.class.getName()).log(Level.SEVERE, null, ex); + } + } + } - @Override - public void copyToClipboard(String value) { - if (Desktop.isDesktopSupported()) { - StringSelection stringSelection = new StringSelection(value); - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - clipboard.setContents(stringSelection, null); - } - } + @Override + public void copyToClipboard(String value) { + if (Desktop.isDesktopSupported()) { + StringSelection stringSelection = new StringSelection(value); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(stringSelection, null); + } + } - @Override - public void give(IItemStack stack) { + @Override + public void give(IItemStack stack) { - } + } } diff --git a/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java b/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java index 243eb50..b1fae80 100644 --- a/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java +++ b/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java @@ -1,13 +1,10 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.util; -import com.google.common.collect.BiMap; -import cpw.mods.fml.common.registry.EntityRegistry; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -17,9 +14,11 @@ import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; + import minetweaker.MineTweakerAPI; import minetweaker.api.item.WeightedItemStack; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; @@ -37,253 +36,256 @@ import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; +import com.google.common.collect.BiMap; +import cpw.mods.fml.common.registry.EntityRegistry; + /** - * Common class for all runtime hacks (stuff requiring reflection). It is not - * unexpected to have it break with new minecraft versions and may need regular - * adjustment - as such, those have been collected here. + * Common class for all runtime hacks (stuff requiring reflection). It is not unexpected to have it break with new + * minecraft versions and may need regular adjustment - as such, those have been collected here. * * @author Stan Hebben */ public class MineTweakerHacks { - private static final Field NBTTAGLIST_TAGLIST; - private static final Field OREDICTIONARY_IDTOSTACK; - private static final Field OREDICTIONARY_IDTOSTACKUN; - private static final Field MINECRAFTSERVER_ANVILFILE; - private static final Field SHAPEDORERECIPE_WIDTH; - private static final Field INVENTORYCRAFTING_EVENTHANDLER; - private static final Field SLOTCRAFTING_PLAYER; - private static final Field ENTITYREGISTRY_CLASSREGISTRATIONS; - private static final Field SEEDENTRY_SEED; - private static final Constructor SEEDENTRY_CONSTRUCTOR; + private static final Field NBTTAGLIST_TAGLIST; + private static final Field OREDICTIONARY_IDTOSTACK; + private static final Field OREDICTIONARY_IDTOSTACKUN; + private static final Field MINECRAFTSERVER_ANVILFILE; + private static final Field SHAPEDORERECIPE_WIDTH; + private static final Field INVENTORYCRAFTING_EVENTHANDLER; + private static final Field SLOTCRAFTING_PLAYER; - static { - NBTTAGLIST_TAGLIST = getField(NBTTagList.class, MineTweakerObfuscation.NBTTAGLIST_TAGLIST); - OREDICTIONARY_IDTOSTACK = getField(OreDictionary.class, MineTweakerObfuscation.OREDICTIONARY_IDTOSTACK); - OREDICTIONARY_IDTOSTACKUN = getField(OreDictionary.class, MineTweakerObfuscation.OREDICTIONARY_IDTOSTACKUN); - MINECRAFTSERVER_ANVILFILE = getField(MinecraftServer.class, MineTweakerObfuscation.MINECRAFTSERVER_ANVILFILE); - SHAPEDORERECIPE_WIDTH = getField(ShapedOreRecipe.class, new String[] { "width" }); - INVENTORYCRAFTING_EVENTHANDLER = getField(InventoryCrafting.class, MineTweakerObfuscation.INVENTORYCRAFTING_EVENTHANDLER); - SLOTCRAFTING_PLAYER = getField(SlotCrafting.class, MineTweakerObfuscation.SLOTCRAFTING_PLAYER); + private static final Field ENTITYREGISTRY_CLASSREGISTRATIONS; + private static final Field SEEDENTRY_SEED; + private static final Constructor SEEDENTRY_CONSTRUCTOR; - ENTITYREGISTRY_CLASSREGISTRATIONS = getField(EntityRegistry.class, new String[] { "entityClassRegistrations" }); + static { + NBTTAGLIST_TAGLIST = getField(NBTTagList.class, MineTweakerObfuscation.NBTTAGLIST_TAGLIST); + OREDICTIONARY_IDTOSTACK = getField(OreDictionary.class, MineTweakerObfuscation.OREDICTIONARY_IDTOSTACK); + OREDICTIONARY_IDTOSTACKUN = getField(OreDictionary.class, MineTweakerObfuscation.OREDICTIONARY_IDTOSTACKUN); + MINECRAFTSERVER_ANVILFILE = getField(MinecraftServer.class, MineTweakerObfuscation.MINECRAFTSERVER_ANVILFILE); + SHAPEDORERECIPE_WIDTH = getField(ShapedOreRecipe.class, new String[] { "width" }); + INVENTORYCRAFTING_EVENTHANDLER = getField( + InventoryCrafting.class, + MineTweakerObfuscation.INVENTORYCRAFTING_EVENTHANDLER); + SLOTCRAFTING_PLAYER = getField(SlotCrafting.class, MineTweakerObfuscation.SLOTCRAFTING_PLAYER); - Class forgeSeedEntry = null; - try { - forgeSeedEntry = (Class) Class.forName("net.minecraftforge.common.ForgeHooks$SeedEntry"); - } catch (ClassNotFoundException ex) { - } + ENTITYREGISTRY_CLASSREGISTRATIONS = getField(EntityRegistry.class, new String[] { "entityClassRegistrations" }); - SEEDENTRY_SEED = getField(forgeSeedEntry, "seed"); + Class forgeSeedEntry = null; + try { + forgeSeedEntry = (Class) Class + .forName("net.minecraftforge.common.ForgeHooks$SeedEntry"); + } catch (ClassNotFoundException ex) {} - Constructor seedEntryConstructor = null; + SEEDENTRY_SEED = getField(forgeSeedEntry, "seed"); - try { - seedEntryConstructor = forgeSeedEntry.getConstructor(ItemStack.class, int.class); - seedEntryConstructor.setAccessible(true); - } catch (NoSuchMethodException ex) { - Logger.getLogger(MineTweakerHacks.class.getName()).log(Level.SEVERE, null, ex); - } catch (SecurityException ex) { - Logger.getLogger(MineTweakerHacks.class.getName()).log(Level.SEVERE, null, ex); - } + Constructor seedEntryConstructor = null; - SEEDENTRY_CONSTRUCTOR = seedEntryConstructor; - } + try { + seedEntryConstructor = forgeSeedEntry.getConstructor(ItemStack.class, int.class); + seedEntryConstructor.setAccessible(true); + } catch (NoSuchMethodException ex) { + Logger.getLogger(MineTweakerHacks.class.getName()).log(Level.SEVERE, null, ex); + } catch (SecurityException ex) { + Logger.getLogger(MineTweakerHacks.class.getName()).log(Level.SEVERE, null, ex); + } - private MineTweakerHacks() { - } + SEEDENTRY_CONSTRUCTOR = seedEntryConstructor; + } - public static BiMap, EntityRegistry.EntityRegistration> getEntityClassRegistrations() { - try { - return (BiMap, EntityRegistry.EntityRegistration>) ENTITYREGISTRY_CLASSREGISTRATIONS.get(EntityRegistry.instance()); - } catch (IllegalArgumentException ex) { - return null; - } catch (IllegalAccessException ex) { - return null; - } - } + private MineTweakerHacks() {} - public static List getTagList(NBTTagList list) { - if (NBTTAGLIST_TAGLIST == null) { - return null; - } - try { - return (List) NBTTAGLIST_TAGLIST.get(list); - } catch (IllegalArgumentException ex) { - return null; - } catch (IllegalAccessException ex) { - return null; - } - } + public static BiMap, EntityRegistry.EntityRegistration> getEntityClassRegistrations() { + try { + return (BiMap, EntityRegistry.EntityRegistration>) ENTITYREGISTRY_CLASSREGISTRATIONS + .get(EntityRegistry.instance()); + } catch (IllegalArgumentException ex) { + return null; + } catch (IllegalAccessException ex) { + return null; + } + } - public static List getSeeds() { - return getPrivateStaticObject(ForgeHooks.class, "seedList"); - } + public static List getTagList(NBTTagList list) { + if (NBTTAGLIST_TAGLIST == null) { + return null; + } + try { + return (List) NBTTAGLIST_TAGLIST.get(list); + } catch (IllegalArgumentException ex) { + return null; + } catch (IllegalAccessException ex) { + return null; + } + } - public static Map getChestLoot() { - return getPrivateStaticObject(ChestGenHooks.class, "chestInfo"); - } + public static List getSeeds() { + return getPrivateStaticObject(ForgeHooks.class, "seedList"); + } - public static Map getTranslations() { - return getPrivateObject( - getPrivateStaticObject(StatCollector.class, "localizedName", "field_74839_a"), - "languageList", - "field_74816_c"); - } + public static Map getChestLoot() { + return getPrivateStaticObject(ChestGenHooks.class, "chestInfo"); + } - public static List> getOreIdStacks() { - try { - return (List>) OREDICTIONARY_IDTOSTACK.get(null); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("ERROR - could not load ore dictionary stacks!"); - return null; - } - } + public static Map getTranslations() { + return getPrivateObject( + getPrivateStaticObject(StatCollector.class, "localizedName", "field_74839_a"), + "languageList", + "field_74816_c"); + } - public static List> getOreIdStacksUn() { - try { - return (List>) OREDICTIONARY_IDTOSTACKUN.get(null); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("ERROR - could not load ore dictionary stacks!"); - return null; - } - } + public static List> getOreIdStacks() { + try { + return (List>) OREDICTIONARY_IDTOSTACK.get(null); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("ERROR - could not load ore dictionary stacks!"); + return null; + } + } - public static File getAnvilFile(MinecraftServer server) { - try { - return (File) MINECRAFTSERVER_ANVILFILE.get(server); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("could not load anvil file!"); - return null; - } - } + public static List> getOreIdStacksUn() { + try { + return (List>) OREDICTIONARY_IDTOSTACKUN.get(null); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("ERROR - could not load ore dictionary stacks!"); + return null; + } + } - public static File getWorldDirectory(MinecraftServer server) { - if (server.isDedicatedServer()) { - return server.getFile("world"); - } else { - File worldsDir = getAnvilFile(server); - if (worldsDir == null) - return null; + public static File getAnvilFile(MinecraftServer server) { + try { + return (File) MINECRAFTSERVER_ANVILFILE.get(server); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("could not load anvil file!"); + return null; + } + } - return new File(worldsDir, server.getFolderName()); - } - } + public static File getWorldDirectory(MinecraftServer server) { + if (server.isDedicatedServer()) { + return server.getFile("world"); + } else { + File worldsDir = getAnvilFile(server); + if (worldsDir == null) return null; - public static int getShapedOreRecipeWidth(ShapedOreRecipe recipe) { - try { - return SHAPEDORERECIPE_WIDTH.getInt(recipe); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("could not load anvil file!"); - return 3; - } - } + return new File(worldsDir, server.getFolderName()); + } + } - public static Container getCraftingContainer(InventoryCrafting inventory) { - try { - return (Container) INVENTORYCRAFTING_EVENTHANDLER.get(inventory); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("could not get inventory eventhandler"); - return null; - } - } + public static int getShapedOreRecipeWidth(ShapedOreRecipe recipe) { + try { + return SHAPEDORERECIPE_WIDTH.getInt(recipe); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("could not load anvil file!"); + return 3; + } + } - public static EntityPlayer getCraftingSlotPlayer(SlotCrafting slot) { - try { - return (EntityPlayer) SLOTCRAFTING_PLAYER.get(slot); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("could not get inventory eventhandler"); - return null; - } - } + public static Container getCraftingContainer(InventoryCrafting inventory) { + try { + return (Container) INVENTORYCRAFTING_EVENTHANDLER.get(inventory); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("could not get inventory eventhandler"); + return null; + } + } - public static StringTranslate getStringTranslateInstance() { - try { - Field field = getField(StringTranslate.class, MineTweakerObfuscation.STRINGTRANSLATE_INSTANCE); - return (StringTranslate) field.get(null); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("could not get string translator"); - return null; - } - } + public static EntityPlayer getCraftingSlotPlayer(SlotCrafting slot) { + try { + return (EntityPlayer) SLOTCRAFTING_PLAYER.get(slot); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("could not get inventory eventhandler"); + return null; + } + } - public static ItemStack getSeedEntrySeed(Object entry) { - try { - return (ItemStack) SEEDENTRY_SEED.get(entry); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("could not get SeedEntry seed"); - return null; - } - } + public static StringTranslate getStringTranslateInstance() { + try { + Field field = getField(StringTranslate.class, MineTweakerObfuscation.STRINGTRANSLATE_INSTANCE); + return (StringTranslate) field.get(null); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("could not get string translator"); + return null; + } + } - public static WeightedRandom.Item constructSeedEntry(WeightedItemStack stack) { - try { - return SEEDENTRY_CONSTRUCTOR.newInstance(MineTweakerMC.getItemStack(stack.getStack()), (int) stack.getChance()); - } catch (InstantiationException ex) { - MineTweakerAPI.logError("could not construct SeedEntry"); - } catch (IllegalAccessException ex) { - MineTweakerAPI.logError("could not construct SeedEntry"); - } catch (IllegalArgumentException ex) { - MineTweakerAPI.logError("could not construct SeedEntry"); - } catch (InvocationTargetException ex) { - MineTweakerAPI.logError("could not construct SeedEntry"); - } + public static ItemStack getSeedEntrySeed(Object entry) { + try { + return (ItemStack) SEEDENTRY_SEED.get(entry); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("could not get SeedEntry seed"); + return null; + } + } - return null; - } + public static WeightedRandom.Item constructSeedEntry(WeightedItemStack stack) { + try { + return SEEDENTRY_CONSTRUCTOR + .newInstance(MineTweakerMC.getItemStack(stack.getStack()), (int) stack.getChance()); + } catch (InstantiationException ex) { + MineTweakerAPI.logError("could not construct SeedEntry"); + } catch (IllegalAccessException ex) { + MineTweakerAPI.logError("could not construct SeedEntry"); + } catch (IllegalArgumentException ex) { + MineTweakerAPI.logError("could not construct SeedEntry"); + } catch (InvocationTargetException ex) { + MineTweakerAPI.logError("could not construct SeedEntry"); + } - public static T getPrivateStaticObject(Class cls, String... names) { - for (String name : names) { - try { - Field field = cls.getDeclaredField(name); - field.setAccessible(true); - return (T) field.get(null); - } catch (NoSuchFieldException ex) { + return null; + } - } catch (SecurityException ex) { + public static T getPrivateStaticObject(Class cls, String... names) { + for (String name : names) { + try { + Field field = cls.getDeclaredField(name); + field.setAccessible(true); + return (T) field.get(null); + } catch (NoSuchFieldException ex) { - } catch (IllegalAccessException ex) { + } catch (SecurityException ex) { - } - } + } catch (IllegalAccessException ex) { - return null; - } + } + } - public static T getPrivateObject(Object object, String... names) { - Class cls = object.getClass(); - for (String name : names) { - try { - Field field = cls.getDeclaredField(name); - field.setAccessible(true); - return (T) field.get(object); - } catch (NoSuchFieldException ex) { + return null; + } - } catch (SecurityException ex) { + public static T getPrivateObject(Object object, String... names) { + Class cls = object.getClass(); + for (String name : names) { + try { + Field field = cls.getDeclaredField(name); + field.setAccessible(true); + return (T) field.get(object); + } catch (NoSuchFieldException ex) { - } catch (IllegalAccessException ex) { + } catch (SecurityException ex) { - } - } + } catch (IllegalAccessException ex) { - return null; - } + } + } - // ####################### - // ### Private Methods ### - // ####################### + return null; + } - private static Field getField(Class cls, String... names) { - for (String name : names) { - try { - Field field = cls.getDeclaredField(name); - field.setAccessible(true); - return field; - } catch (NoSuchFieldException ex) { - } catch (SecurityException ex) { - } - } + // ####################### + // ### Private Methods ### + // ####################### - return null; - } + private static Field getField(Class cls, String... names) { + for (String name : names) { + try { + Field field = cls.getDeclaredField(name); + field.setAccessible(true); + return field; + } catch (NoSuchFieldException ex) {} catch (SecurityException ex) {} + } + + return null; + } } diff --git a/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java b/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java index 0c7eb62..228df29 100644 --- a/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java +++ b/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.util; @@ -11,15 +10,15 @@ package minetweaker.mc1710.util; * @author Stanneke */ public class MineTweakerObfuscation { - private MineTweakerObfuscation() { - } - public static final String[] NBTTAGLIST_TAGLIST = { "tagList", "field_74747_a" }; - public static final String[] CRAFTINGMANAGER_RECIPES = { "recipes", "field_77597_b" }; - public static final String[] OREDICTIONARY_IDTOSTACK = { "idToStack" }; - public static final String[] OREDICTIONARY_IDTOSTACKUN = { "idToStackUn" }; - public static final String[] MINECRAFTSERVER_ANVILFILE = { "anvilFile", "field_71308_o" }; - public static final String[] INVENTORYCRAFTING_EVENTHANDLER = { "eventHandler", "field_70465_c" }; - public static final String[] SLOTCRAFTING_PLAYER = { "thePlayer", "field_75238_b" }; - public static final String[] STRINGTRANSLATE_INSTANCE = { "instance", "field_74817_a" }; + private MineTweakerObfuscation() {} + + public static final String[] NBTTAGLIST_TAGLIST = { "tagList", "field_74747_a" }; + public static final String[] CRAFTINGMANAGER_RECIPES = { "recipes", "field_77597_b" }; + public static final String[] OREDICTIONARY_IDTOSTACK = { "idToStack" }; + public static final String[] OREDICTIONARY_IDTOSTACKUN = { "idToStackUn" }; + public static final String[] MINECRAFTSERVER_ANVILFILE = { "anvilFile", "field_71308_o" }; + public static final String[] INVENTORYCRAFTING_EVENTHANDLER = { "eventHandler", "field_70465_c" }; + public static final String[] SLOTCRAFTING_PLAYER = { "thePlayer", "field_75238_b" }; + public static final String[] STRINGTRANSLATE_INSTANCE = { "instance", "field_74817_a" }; } diff --git a/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java b/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java index 036f90c..411f7d0 100644 --- a/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java +++ b/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java @@ -1,46 +1,47 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.util; +import net.minecraft.entity.EntityLivingBase; + import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; -import net.minecraft.entity.EntityLivingBase; /** * * @author Stan */ public class MineTweakerPlatformUtils { - private MineTweakerPlatformUtils() { - } - public static Class getLivingEntityClass(String entityClassName) { - try { - Class entityClass = Class.forName(entityClassName); - if (!EntityLivingBase.class.isAssignableFrom(entityClass)) { - throw new RuntimeException("Not an entity class: " + entityClassName); - } - return (Class) entityClass; - } catch (ClassNotFoundException ex) { - throw new RuntimeException("entity class not found: " + entityClassName); - } - } + private MineTweakerPlatformUtils() {} - public static String getLanguage() { - return FMLCommonHandler.instance().getSide() == Side.SERVER ? null : FMLClientHandler.instance().getCurrentLanguage(); - } + public static Class getLivingEntityClass(String entityClassName) { + try { + Class entityClass = Class.forName(entityClassName); + if (!EntityLivingBase.class.isAssignableFrom(entityClass)) { + throw new RuntimeException("Not an entity class: " + entityClassName); + } + return (Class) entityClass; + } catch (ClassNotFoundException ex) { + throw new RuntimeException("entity class not found: " + entityClassName); + } + } - public static boolean isLanguageActive(String lang) { - String current = getLanguage(); - return current != null && current.equals(lang); - } + public static String getLanguage() { + return FMLCommonHandler.instance().getSide() == Side.SERVER ? null + : FMLClientHandler.instance().getCurrentLanguage(); + } - public static boolean isClient() { - return FMLCommonHandler.instance().getSide() == Side.CLIENT; - } + public static boolean isLanguageActive(String lang) { + String current = getLanguage(); + return current != null && current.equals(lang); + } + + public static boolean isClient() { + return FMLCommonHandler.instance().getSide() == Side.CLIENT; + } } diff --git a/src/main/java/minetweaker/mc1710/util/ThreadSafeBitSet.java b/src/main/java/minetweaker/mc1710/util/ThreadSafeBitSet.java index 8c6465b..a1dd9e7 100644 --- a/src/main/java/minetweaker/mc1710/util/ThreadSafeBitSet.java +++ b/src/main/java/minetweaker/mc1710/util/ThreadSafeBitSet.java @@ -1,18 +1,10 @@ /* - * Copyright 2016-2019 Netflix, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * + * Copyright 2016-2019 Netflix, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions and limitations under the + * License. */ package minetweaker.mc1710.util; @@ -24,10 +16,11 @@ import java.util.concurrent.atomic.AtomicLongArray; import java.util.concurrent.atomic.AtomicReference; /** - * This is a lock-free, thread-safe version of a {@link java.util.BitSet}.

+ * This is a lock-free, thread-safe version of a {@link java.util.BitSet}. + *

* - * Instead of a long array to hold the bits, this implementation uses an AtomicLongArray, then - * does the appropriate compare-and-swap operations when setting the bits. + * Instead of a long array to hold the bits, this implementation uses an AtomicLongArray, then does the appropriate + * compare-and-swap operations when setting the bits. * * @author dkoszewnik * @@ -50,15 +43,16 @@ public class ThreadSafeBitSet { } public ThreadSafeBitSet(int log2SegmentSizeInBits, int numBitsToPreallocate) { - if(log2SegmentSizeInBits < 6) + if (log2SegmentSizeInBits < 6) throw new IllegalArgumentException("Cannot specify fewer than 64 bits in each segment!"); this.log2SegmentSize = log2SegmentSizeInBits; this.numLongsPerSegment = (1 << (log2SegmentSizeInBits - 6)); this.segmentMask = numLongsPerSegment - 1; - + long numBitsPerSegment = numLongsPerSegment * 64; - int numSegmentsToPreallocate = numBitsToPreallocate == 0 ? 1 : (int)(((numBitsToPreallocate - 1) / numBitsPerSegment) + 1); + int numSegmentsToPreallocate = numBitsToPreallocate == 0 ? 1 + : (int) (((numBitsToPreallocate - 1) / numBitsPerSegment) + 1); segments = new AtomicReference(); segments.set(new ThreadSafeBitSetSegments(numSegmentsToPreallocate, numLongsPerSegment)); @@ -66,7 +60,8 @@ public class ThreadSafeBitSet { public void set(int position) { int segmentPosition = position >>> log2SegmentSize; /// which segment -- div by num bits per segment - int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits per segment + int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits + /// per segment int bitPosition = position & 0x3F; /// which bit in the long -- remainder of div by num bits in long (64) AtomicLongArray segment = getSegment(segmentPosition); @@ -74,20 +69,20 @@ public class ThreadSafeBitSet { long mask = 1L << bitPosition; // Thread safety: we need to loop until we win the race to set the long value. - while(true) { + while (true) { // determine what the new long value will be after we set the appropriate bit. long currentLongValue = segment.get(longPosition); long newLongValue = currentLongValue | mask; // if no other thread has modified the value since we read it, we won the race and we are done. - if(segment.compareAndSet(longPosition, currentLongValue, newLongValue)) - break; + if (segment.compareAndSet(longPosition, currentLongValue, newLongValue)) break; } } public void clear(int position) { int segmentPosition = position >>> log2SegmentSize; /// which segment -- div by num bits per segment - int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits per segment + int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits + /// per segment int bitPosition = position & 0x3F; /// which bit in the long -- remainder of div by num bits in long (64) AtomicLongArray segment = getSegment(segmentPosition); @@ -95,20 +90,20 @@ public class ThreadSafeBitSet { long mask = ~(1L << bitPosition); // Thread safety: we need to loop until we win the race to set the long value. - while(true) { + while (true) { // determine what the new long value will be after we set the appropriate bit. long currentLongValue = segment.get(longPosition); long newLongValue = currentLongValue & mask; // if no other thread has modified the value since we read it, we won the race and we are done. - if(segment.compareAndSet(longPosition, currentLongValue, newLongValue)) - break; + if (segment.compareAndSet(longPosition, currentLongValue, newLongValue)) break; } } public boolean get(int position) { int segmentPosition = position >>> log2SegmentSize; /// which segment -- div by num bits per segment - int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits per segment + int longPosition = (position >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits + /// per segment int bitPosition = position & 0x3F; /// which bit in the long -- remainder of div by num bits in long (64) AtomicLongArray segment = getSegment(segmentPosition); @@ -123,11 +118,11 @@ public class ThreadSafeBitSet { int segmentIdx = segments.numSegments() - 1; - for(;segmentIdx >= 0; segmentIdx--) { + for (; segmentIdx >= 0; segmentIdx--) { AtomicLongArray segment = segments.getSegment(segmentIdx); - for(int longIdx=segment.length() - 1; longIdx >= 0; longIdx--) { + for (int longIdx = segment.length() - 1; longIdx >= 0; longIdx--) { long l = segment.get(longIdx); - if(l != 0) + if (l != 0) return (segmentIdx << log2SegmentSize) + (longIdx * 64) + (63 - Long.numberOfLeadingZeros(l)); } } @@ -136,17 +131,16 @@ public class ThreadSafeBitSet { } public int nextSetBit(int fromIndex) { - if (fromIndex < 0) - throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); + if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); int segmentPosition = fromIndex >>> log2SegmentSize; /// which segment -- div by num bits per segment ThreadSafeBitSetSegments segments = this.segments.get(); - if(segmentPosition >= segments.numSegments()) - return -1; + if (segmentPosition >= segments.numSegments()) return -1; - int longPosition = (fromIndex >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num bits per segment + int longPosition = (fromIndex >>> 6) & segmentMask; /// which long in the segment -- remainder of div by num + /// bits per segment int bitPosition = fromIndex & 0x3F; /// which bit in the long -- remainder of div by num bits in long (64) AtomicLongArray segment = segments.getSegment(segmentPosition); @@ -157,8 +151,7 @@ public class ThreadSafeBitSet { return (segmentPosition << (log2SegmentSize)) + (longPosition << 6) + Long.numberOfTrailingZeros(word); if (++longPosition > segmentMask) { segmentPosition++; - if(segmentPosition >= segments.numSegments()) - return -1; + if (segmentPosition >= segments.numSegments()) return -1; segment = segments.getSegment(segmentPosition); longPosition = 0; } @@ -167,7 +160,6 @@ public class ThreadSafeBitSet { } } - /** * @return the number of bits which are set in this bit set. */ @@ -176,9 +168,9 @@ public class ThreadSafeBitSet { int numSetBits = 0; - for(int i=0;iother bit set.

+ * Return a new bit set which contains all bits which are contained in this bit set, and which are NOT contained in + * the other bit set. + *

* * In other words, return a new bit set, which is a bitwise and with the bitwise not of the other bit set. * @@ -218,19 +212,21 @@ public class ThreadSafeBitSet { * @return the resulting bit set */ public ThreadSafeBitSet andNot(ThreadSafeBitSet other) { - if(other.log2SegmentSize != log2SegmentSize) + if (other.log2SegmentSize != log2SegmentSize) throw new IllegalArgumentException("Segment sizes must be the same"); ThreadSafeBitSetSegments thisSegments = this.segments.get(); ThreadSafeBitSetSegments otherSegments = other.segments.get(); - ThreadSafeBitSetSegments newSegments = new ThreadSafeBitSetSegments(thisSegments.numSegments(), numLongsPerSegment); + ThreadSafeBitSetSegments newSegments = new ThreadSafeBitSetSegments( + thisSegments.numSegments(), + numLongsPerSegment); - for(int i=0;i maxNumSegments) - maxNumSegments = segments[i].numSegments(); + if (segments[i].numSegments() > maxNumSegments) maxNumSegments = segments[i].numSegments(); } ThreadSafeBitSetSegments newSegments = new ThreadSafeBitSetSegments(maxNumSegments, numLongsPerSegment); AtomicLongArray segment[] = new AtomicLongArray[segments.length]; - for(int i=0;isegmentIndex. If this segment does not yet exist, create it. + * Get the segment at segmentIndex. If this segment does not yet exist, create it. * * @param segmentIndex the segment index * @return the segment @@ -303,18 +296,24 @@ public class ThreadSafeBitSet { private AtomicLongArray getSegment(int segmentIndex) { ThreadSafeBitSetSegments visibleSegments = segments.get(); - while(visibleSegments.numSegments() <= segmentIndex) { - /// Thread safety: newVisibleSegments contains all of the segments from the currently visible segments, plus extra. + while (visibleSegments.numSegments() <= segmentIndex) { + /// Thread safety: newVisibleSegments contains all of the segments from the currently visible segments, plus + /// extra. /// all of the segments in the currently visible segments are canonical and will not change. - ThreadSafeBitSetSegments newVisibleSegments = new ThreadSafeBitSetSegments(visibleSegments, segmentIndex + 1, numLongsPerSegment); + ThreadSafeBitSetSegments newVisibleSegments = new ThreadSafeBitSetSegments( + visibleSegments, + segmentIndex + 1, + numLongsPerSegment); - /// because we are using a compareAndSet, if this thread "wins the race" and successfully sets this variable, then the segments + /// because we are using a compareAndSet, if this thread "wins the race" and successfully sets this + /// variable, then the segments /// which are newly defined in newVisibleSegments become canonical. - if(segments.compareAndSet(visibleSegments, newVisibleSegments)) { + if (segments.compareAndSet(visibleSegments, newVisibleSegments)) { visibleSegments = newVisibleSegments; } else { /// If we "lose the race" and are growing the ThreadSafeBitSet segments larger, - /// then we will gather the new canonical sets from the update which we missed on the next iteration of this loop. + /// then we will gather the new canonical sets from the update which we missed on the next iteration of + /// this loop. /// Newly defined segments in newVisibleSegments will be discarded, they do not get to become canonical. visibleSegments = segments.get(); } @@ -330,11 +329,12 @@ public class ThreadSafeBitSet { private ThreadSafeBitSetSegments(int numSegments, int segmentLength) { AtomicLongArray segments[] = new AtomicLongArray[numSegments]; - for(int i=0;i LOOT = MineTweakerHacks.getChestLoot(); - @Override - public void addChestLoot(String type, WeightedItemStack item) { - WeightedRandomChestContent content = new WeightedRandomChestContent( - MineTweakerMC.getItemStack(item.getStack()), - 1, - 1, - (int) item.getChance()); - MineTweakerAPI.apply(new AddLootAction(type, content)); - } + private static final Map LOOT = MineTweakerHacks.getChestLoot(); - @Override - public void addChestLoot(String type, WeightedItemStack item, int min, int max) { - WeightedRandomChestContent content = new WeightedRandomChestContent( - MineTweakerMC.getItemStack(item.getStack()), - min, - max, - (int) item.getChance()); - MineTweakerAPI.apply(new AddLootAction(type, content)); - } + @Override + public void addChestLoot(String type, WeightedItemStack item) { + WeightedRandomChestContent content = new WeightedRandomChestContent( + MineTweakerMC.getItemStack(item.getStack()), + 1, + 1, + (int) item.getChance()); + MineTweakerAPI.apply(new AddLootAction(type, content)); + } - @Override - public void removeChestLoot(String type, IIngredient pattern) { - MineTweakerAPI.apply(new RemoveLootAction(type, pattern)); - } + @Override + public void addChestLoot(String type, WeightedItemStack item, int min, int max) { + WeightedRandomChestContent content = new WeightedRandomChestContent( + MineTweakerMC.getItemStack(item.getStack()), + min, + max, + (int) item.getChance()); + MineTweakerAPI.apply(new AddLootAction(type, content)); + } - @Override - public List getLoot(String type) { - ChestGenHooks recipe = LOOT.get(type); - List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); + @Override + public void removeChestLoot(String type, IIngredient pattern) { + MineTweakerAPI.apply(new RemoveLootAction(type, pattern)); + } - List results = new ArrayList(); - for (WeightedRandomChestContent content : contents) { - results.add(new LootEntry(new WeightedItemStack( - MineTweakerMC.getIItemStack(content.theItemId), - content.itemWeight), - content.theMinimumChanceToGenerateItem, - content.theMaximumChanceToGenerateItem)); - } - return results; - } + @Override + public List getLoot(String type) { + ChestGenHooks recipe = LOOT.get(type); + List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - @Override - public List getLootTypes() { - Set keys = LOOT.keySet(); - List keyList = new ArrayList(); - keyList.addAll(keys); - return keyList; - } + List results = new ArrayList(); + for (WeightedRandomChestContent content : contents) { + results.add( + new LootEntry( + new WeightedItemStack(MineTweakerMC.getIItemStack(content.theItemId), content.itemWeight), + content.theMinimumChanceToGenerateItem, + content.theMaximumChanceToGenerateItem)); + } + return results; + } - // ###################### - // ### Action Classes ### - // ###################### + @Override + public List getLootTypes() { + Set keys = LOOT.keySet(); + List keyList = new ArrayList(); + keyList.addAll(keys); + return keyList; + } - /** - * Ported from ModTweaker. - * - * @author JoshieJack - */ - private static class AddLootAction implements IUndoableAction { - private final String chest; - private final WeightedRandomChestContent content; + // ###################### + // ### Action Classes ### + // ###################### - public AddLootAction(String chest, WeightedRandomChestContent content) { - this.chest = chest; - this.content = content; - } + /** + * Ported from ModTweaker. + * + * @author JoshieJack + */ + private static class AddLootAction implements IUndoableAction { - @Override - public void apply() { - ChestGenHooks recipe = LOOT.get(chest); - List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); + private final String chest; + private final WeightedRandomChestContent content; - contents.add(content); - } + public AddLootAction(String chest, WeightedRandomChestContent content) { + this.chest = chest; + this.content = content; + } - @Override - public boolean canUndo() { - return true; - } + @Override + public void apply() { + ChestGenHooks recipe = LOOT.get(chest); + List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - @Override - public void undo() { - ChestGenHooks recipe = LOOT.get(chest); - List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); + contents.add(content); + } - contents.remove(content); - } + @Override + public boolean canUndo() { + return true; + } - public String getRecipeInfo() { - return content.theItemId.getDisplayName(); - } + @Override + public void undo() { + ChestGenHooks recipe = LOOT.get(chest); + List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - @Override - public String describe() { - return "Adding chest loot " + content.theItemId.getDisplayName() + " to loot class " + chest; - } + contents.remove(content); + } - @Override - public String describeUndo() { - return "Removing chest loot " + content.theItemId.getDisplayName() + " from loot class " + chest; - } + public String getRecipeInfo() { + return content.theItemId.getDisplayName(); + } - @Override - public Object getOverrideKey() { - return null; - } - } + @Override + public String describe() { + return "Adding chest loot " + content.theItemId.getDisplayName() + " to loot class " + chest; + } - /** - * Ported from ModTweaker. - * - * @author JoshieJack - */ - private static class RemoveLootAction implements IUndoableAction { - private final String chest; - private final IIngredient pattern; - private final List removed; + @Override + public String describeUndo() { + return "Removing chest loot " + content.theItemId.getDisplayName() + " from loot class " + chest; + } - public RemoveLootAction(String chest, IIngredient pattern) { - this.chest = chest; - this.pattern = pattern; - removed = new ArrayList(); - } + @Override + public Object getOverrideKey() { + return null; + } + } - @Override - public void apply() { - removed.clear(); + /** + * Ported from ModTweaker. + * + * @author JoshieJack + */ + private static class RemoveLootAction implements IUndoableAction { - ChestGenHooks recipe = LOOT.get(chest); - List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); + private final String chest; + private final IIngredient pattern; + private final List removed; - for (WeightedRandomChestContent r : contents) { - if (pattern.matches(MineTweakerMC.getIItemStack(r.theItemId))) { - removed.add(r); - } - } + public RemoveLootAction(String chest, IIngredient pattern) { + this.chest = chest; + this.pattern = pattern; + removed = new ArrayList(); + } - for (WeightedRandomChestContent r : removed) { - contents.remove(r); - } - } + @Override + public void apply() { + removed.clear(); - @Override - public boolean canUndo() { - return true; - } + ChestGenHooks recipe = LOOT.get(chest); + List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - @Override - public void undo() { - ChestGenHooks recipe = LOOT.get(chest); - List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); + for (WeightedRandomChestContent r : contents) { + if (pattern.matches(MineTweakerMC.getIItemStack(r.theItemId))) { + removed.add(r); + } + } - for (WeightedRandomChestContent entry : removed) { - contents.add(entry); - } - } + for (WeightedRandomChestContent r : removed) { + contents.remove(r); + } + } - @Override - public String describe() { - return "Removing chest loot " + pattern + " for loot type " + chest; - } + @Override + public boolean canUndo() { + return true; + } - @Override - public String describeUndo() { - return "Restoring chest loot " + pattern + " for loot type " + chest + " (" + removed.size() + " entries)"; - } + @Override + public void undo() { + ChestGenHooks recipe = LOOT.get(chest); + List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - @Override - public Object getOverrideKey() { - return null; - } - } + for (WeightedRandomChestContent entry : removed) { + contents.add(entry); + } + } + + @Override + public String describe() { + return "Removing chest loot " + pattern + " for loot type " + chest; + } + + @Override + public String describeUndo() { + return "Restoring chest loot " + pattern + " for loot type " + chest + " (" + removed.size() + " entries)"; + } + + @Override + public Object getOverrideKey() { + return null; + } + } } diff --git a/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java b/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java index 0340b52..42dc9dd 100644 --- a/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java +++ b/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java @@ -1,13 +1,13 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.vanilla; import java.util.ArrayList; import java.util.List; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; @@ -16,6 +16,7 @@ import minetweaker.api.item.WeightedItemStack; import minetweaker.api.minecraft.MineTweakerMC; import minetweaker.api.vanilla.ISeedRegistry; import minetweaker.mc1710.util.MineTweakerHacks; + import net.minecraft.item.ItemStack; import net.minecraft.util.WeightedRandom; @@ -24,126 +25,129 @@ import net.minecraft.util.WeightedRandom; * @author Stan */ public class MCSeedRegistry implements ISeedRegistry { - private static final List SEEDS = MineTweakerHacks.getSeeds(); - @Override - public void addSeed(WeightedItemStack item) { - MineTweakerAPI.apply(new AddSeedAction(item)); - } + private static final List SEEDS = MineTweakerHacks.getSeeds(); - @Override - public void removeSeed(IIngredient pattern) { - MineTweakerAPI.apply(new RemoveSeedAction(pattern)); - } + @Override + public void addSeed(WeightedItemStack item) { + MineTweakerAPI.apply(new AddSeedAction(item)); + } - @Override - public List getSeeds() { - List entries = (List) SEEDS; + @Override + public void removeSeed(IIngredient pattern) { + MineTweakerAPI.apply(new RemoveSeedAction(pattern)); + } - List results = new ArrayList(); - for (WeightedRandom.Item entry : entries) { - results.add(new WeightedItemStack( - MineTweakerMC.getIItemStack(MineTweakerHacks.getSeedEntrySeed(entry)), - entry.itemWeight - )); - } - return results; - } + @Override + public List getSeeds() { + List entries = (List) SEEDS; - // ###################### - // ### Action classes ### - // ###################### + List results = new ArrayList(); + for (WeightedRandom.Item entry : entries) { + results.add( + new WeightedItemStack( + MineTweakerMC.getIItemStack(MineTweakerHacks.getSeedEntrySeed(entry)), + entry.itemWeight)); + } + return results; + } - private static class AddSeedAction implements IUndoableAction { - private final IItemStack item; - private final WeightedRandom.Item entry; + // ###################### + // ### Action classes ### + // ###################### - public AddSeedAction(WeightedItemStack item) { - this.item = item.getStack(); - entry = MineTweakerHacks.constructSeedEntry(item); - } + private static class AddSeedAction implements IUndoableAction { - @Override - public void apply() { - SEEDS.add(entry); - } + private final IItemStack item; + private final WeightedRandom.Item entry; - @Override - public boolean canUndo() { - return true; - } + public AddSeedAction(WeightedItemStack item) { + this.item = item.getStack(); + entry = MineTweakerHacks.constructSeedEntry(item); + } - @Override - public void undo() { - SEEDS.remove(entry); - } + @Override + public void apply() { + SEEDS.add(entry); + } - @Override - public String describe() { - return "Adding seed entry " + item; - } + @Override + public boolean canUndo() { + return true; + } - @Override - public String describeUndo() { - return "Removing seed entry " + item; - } + @Override + public void undo() { + SEEDS.remove(entry); + } - @Override - public Object getOverrideKey() { - return null; - } - } + @Override + public String describe() { + return "Adding seed entry " + item; + } - private static class RemoveSeedAction implements IUndoableAction { - private final IIngredient pattern; - private final List removed; + @Override + public String describeUndo() { + return "Removing seed entry " + item; + } - public RemoveSeedAction(IIngredient ingredient) { - this.pattern = ingredient; - removed = new ArrayList(); - } + @Override + public Object getOverrideKey() { + return null; + } + } - @Override - public void apply() { - removed.clear(); + private static class RemoveSeedAction implements IUndoableAction { - for (Object entry : SEEDS) { - ItemStack itemStack = MineTweakerHacks.getSeedEntrySeed(entry); - if (pattern.matches(MineTweakerMC.getIItemStack(itemStack))) { - removed.add(entry); - } - } + private final IIngredient pattern; + private final List removed; - for (Object entry : removed) { - SEEDS.remove(entry); - } - } + public RemoveSeedAction(IIngredient ingredient) { + this.pattern = ingredient; + removed = new ArrayList(); + } - @Override - public boolean canUndo() { - return true; - } + @Override + public void apply() { + removed.clear(); - @Override - public void undo() { - for (Object entry : removed) { - SEEDS.add(entry); - } - } + for (Object entry : SEEDS) { + ItemStack itemStack = MineTweakerHacks.getSeedEntrySeed(entry); + if (pattern.matches(MineTweakerMC.getIItemStack(itemStack))) { + removed.add(entry); + } + } - @Override - public String describe() { - return "Removing seeds " + pattern; - } + for (Object entry : removed) { + SEEDS.remove(entry); + } + } - @Override - public String describeUndo() { - return "Restoring seeds " + pattern + " (" + removed.size() + " entries)"; - } + @Override + public boolean canUndo() { + return true; + } - @Override - public Object getOverrideKey() { - return null; - } - } + @Override + public void undo() { + for (Object entry : removed) { + SEEDS.add(entry); + } + } + + @Override + public String describe() { + return "Removing seeds " + pattern; + } + + @Override + public String describeUndo() { + return "Restoring seeds " + pattern + " (" + removed.size() + " entries)"; + } + + @Override + public Object getOverrideKey() { + return null; + } + } } diff --git a/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java b/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java index f906614..6906155 100644 --- a/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java +++ b/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.vanilla; @@ -15,16 +14,17 @@ import minetweaker.api.vanilla.IVanilla; * @author Stan */ public class MCVanilla implements IVanilla { - private final MCLootRegistry lootRegistry = new MCLootRegistry(); - private final MCSeedRegistry seedRegistry = new MCSeedRegistry(); - @Override - public ILootRegistry getLoot() { - return lootRegistry; - } + private final MCLootRegistry lootRegistry = new MCLootRegistry(); + private final MCSeedRegistry seedRegistry = new MCSeedRegistry(); - @Override - public ISeedRegistry getSeeds() { - return seedRegistry; - } + @Override + public ILootRegistry getLoot() { + return lootRegistry; + } + + @Override + public ISeedRegistry getSeeds() { + return seedRegistry; + } } diff --git a/src/main/java/minetweaker/mc1710/world/MCBiome.java b/src/main/java/minetweaker/mc1710/world/MCBiome.java index f355077..1b7c744 100644 --- a/src/main/java/minetweaker/mc1710/world/MCBiome.java +++ b/src/main/java/minetweaker/mc1710/world/MCBiome.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.world; import minetweaker.api.world.IBiome; + import net.minecraft.world.biome.BiomeGenBase; /** @@ -14,14 +14,15 @@ import net.minecraft.world.biome.BiomeGenBase; * @author Stan */ public class MCBiome implements IBiome { - private final BiomeGenBase biome; - public MCBiome(BiomeGenBase biome) { - this.biome = biome; - } + private final BiomeGenBase biome; - @Override - public String getName() { - return biome.biomeName; - } + public MCBiome(BiomeGenBase biome) { + this.biome = biome; + } + + @Override + public String getName() { + return biome.biomeName; + } } diff --git a/src/main/java/minetweaker/mc1710/world/MCDimension.java b/src/main/java/minetweaker/mc1710/world/MCDimension.java index 8c28ddb..f5f7157 100644 --- a/src/main/java/minetweaker/mc1710/world/MCDimension.java +++ b/src/main/java/minetweaker/mc1710/world/MCDimension.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mc1710.world; @@ -9,6 +8,7 @@ package minetweaker.mc1710.world; import minetweaker.api.block.IBlock; import minetweaker.api.minecraft.MineTweakerMC; import minetweaker.api.world.IDimension; + import net.minecraft.world.World; /** @@ -16,29 +16,30 @@ import net.minecraft.world.World; * @author Stan */ public class MCDimension implements IDimension { - private final World world; - public MCDimension(World world) { - this.world = world; - } + private final World world; - @Override - public boolean isDay() { - return world.isDaytime(); - } + public MCDimension(World world) { + this.world = world; + } - @Override - public int getBrightness(int x, int y, int z) { - return world.getBlockLightValue(x, y, z); - } + @Override + public boolean isDay() { + return world.isDaytime(); + } - @Override - public IDimension getDimension() { - return this; - } + @Override + public int getBrightness(int x, int y, int z) { + return world.getBlockLightValue(x, y, z); + } - @Override - public IBlock getBlock(int x, int y, int z) { - return MineTweakerMC.getBlock(world, x, y, z); - } + @Override + public IDimension getDimension() { + return this; + } + + @Override + public IBlock getBlock(int x, int y, int z) { + return MineTweakerMC.getBlock(world, x, y, z); + } } diff --git a/src/main/java/minetweaker/mods/ic2/IC2BracketHandler.java b/src/main/java/minetweaker/mods/ic2/IC2BracketHandler.java index b8f842a..1f3e3a3 100644 --- a/src/main/java/minetweaker/mods/ic2/IC2BracketHandler.java +++ b/src/main/java/minetweaker/mods/ic2/IC2BracketHandler.java @@ -1,19 +1,22 @@ package minetweaker.mods.ic2; -import ic2.api.item.IC2Items; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; + import java.util.List; + import minetweaker.IBracketHandler; import minetweaker.MineTweakerAPI; import minetweaker.annotations.BracketHandler; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; + import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; + import stanhebben.zenscript.ZenTokener; import stanhebben.zenscript.compiler.IEnvironmentGlobal; -import stanhebben.zenscript.expression.ExpressionInt; import stanhebben.zenscript.expression.ExpressionCallStatic; +import stanhebben.zenscript.expression.ExpressionInt; import stanhebben.zenscript.expression.ExpressionString; import stanhebben.zenscript.expression.partial.IPartialExpression; import stanhebben.zenscript.parser.Token; @@ -21,6 +24,7 @@ import stanhebben.zenscript.symbols.IZenSymbol; import stanhebben.zenscript.type.ZenType; import stanhebben.zenscript.type.natives.IJavaMethod; import stanhebben.zenscript.util.ZenPosition; +import ic2.api.item.IC2Items; /** * Makes a ic2-item specific item syntax available in the form <item-ic2:name[:meta]>. @@ -30,74 +34,75 @@ import stanhebben.zenscript.util.ZenPosition; @BracketHandler @ModOnly("IC2") public class IC2BracketHandler implements IBracketHandler { - public static IItemStack getItem(String name, int meta) { - ItemStack stack = IC2Items.getItem(name); - stack.setItemDamage(meta); - return getIItemStack(stack); - } - - private final IJavaMethod method; - - public IC2BracketHandler() { - method = MineTweakerAPI.getJavaMethod(IC2BracketHandler.class, "getItem", String.class, int.class); - } - - @Override - public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens) { - if (tokens.size() >= 5) { - if (tokens.get(0).getValue().equals("ic2") - && tokens.get(1).getValue().equals("-") - && tokens.get(2).getValue().equals("item") - && tokens.get(3).getValue().equals(":")) { - String name = tokens.get(4).getValue(); - int meta = 0; - if (tokens.size() > 6 && tokens.get(5).getValue().equals(":")) { - if (tokens.get(6).getType() == ZenTokener.T_INTVALUE) { - meta = Integer.parseInt(tokens.get(6).getValue()); - } else if (tokens.get(6).getValue().equals("*")) { - meta = OreDictionary.WILDCARD_VALUE; - } else { - MineTweakerAPI.logError("Not a valid meta value: " + tokens.get(6).getValue()); - } - } - ItemStack item = IC2Items.getItem(name); - if (item == null) { - MineTweakerAPI.logError("Not a valid IC2 item: " + name); - return null; - } else { - return new ItemReferenceSymbol(environment, name, meta); - } - } else { - return null; - } - } else { - return null; - } - } - - // ############################# - // ### Private inner classes ### - // ############################# - - private class ItemReferenceSymbol implements IZenSymbol { - private final IEnvironmentGlobal environment; - private final String name; - private final int meta; - - public ItemReferenceSymbol(IEnvironmentGlobal environment, String name, int meta) { - this.environment = environment; - this.name = name; - this.meta = meta; - } - - @Override - public IPartialExpression instance(ZenPosition position) { - return new ExpressionCallStatic( - position, - environment, - method, - new ExpressionString(position, name), - new ExpressionInt(position, meta, ZenType.INT)); - } - } + + public static IItemStack getItem(String name, int meta) { + ItemStack stack = IC2Items.getItem(name); + stack.setItemDamage(meta); + return getIItemStack(stack); + } + + private final IJavaMethod method; + + public IC2BracketHandler() { + method = MineTweakerAPI.getJavaMethod(IC2BracketHandler.class, "getItem", String.class, int.class); + } + + @Override + public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens) { + if (tokens.size() >= 5) { + if (tokens.get(0).getValue().equals("ic2") && tokens.get(1).getValue().equals("-") + && tokens.get(2).getValue().equals("item") + && tokens.get(3).getValue().equals(":")) { + String name = tokens.get(4).getValue(); + int meta = 0; + if (tokens.size() > 6 && tokens.get(5).getValue().equals(":")) { + if (tokens.get(6).getType() == ZenTokener.T_INTVALUE) { + meta = Integer.parseInt(tokens.get(6).getValue()); + } else if (tokens.get(6).getValue().equals("*")) { + meta = OreDictionary.WILDCARD_VALUE; + } else { + MineTweakerAPI.logError("Not a valid meta value: " + tokens.get(6).getValue()); + } + } + ItemStack item = IC2Items.getItem(name); + if (item == null) { + MineTweakerAPI.logError("Not a valid IC2 item: " + name); + return null; + } else { + return new ItemReferenceSymbol(environment, name, meta); + } + } else { + return null; + } + } else { + return null; + } + } + + // ############################# + // ### Private inner classes ### + // ############################# + + private class ItemReferenceSymbol implements IZenSymbol { + + private final IEnvironmentGlobal environment; + private final String name; + private final int meta; + + public ItemReferenceSymbol(IEnvironmentGlobal environment, String name, int meta) { + this.environment = environment; + this.name = name; + this.meta = meta; + } + + @Override + public IPartialExpression instance(ZenPosition position) { + return new ExpressionCallStatic( + position, + environment, + method, + new ExpressionString(position, name), + new ExpressionInt(position, meta, ZenType.INT)); + } + } } diff --git a/src/main/java/minetweaker/mods/ic2/IC2ExplosionWhitelist.java b/src/main/java/minetweaker/mods/ic2/IC2ExplosionWhitelist.java index ed5c0a8..03d3a57 100644 --- a/src/main/java/minetweaker/mods/ic2/IC2ExplosionWhitelist.java +++ b/src/main/java/minetweaker/mods/ic2/IC2ExplosionWhitelist.java @@ -1,161 +1,165 @@ package minetweaker.mods.ic2; -import ic2.api.tile.ExplosionWhitelist; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import net.minecraft.block.Block; import net.minecraft.item.ItemStack; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.tile.ExplosionWhitelist; /** - * Manages the explosion whitelist in IC2. Blocks on this whitelist will not resist - * an explosion but won't be destroyed. + * Manages the explosion whitelist in IC2. Blocks on this whitelist will not resist an explosion but won't be destroyed. * - * The explosion code by default ignores blocks which absorb more than 1000 explosion power to - * prevent abusing personal safes, Trade-O-Mats and other blocks to serve as a cheap and - * invulnerable reactor chambers. Said blocks will not shield the explosion and won't get - * destroyed. + * The explosion code by default ignores blocks which absorb more than 1000 explosion power to prevent abusing personal + * safes, Trade-O-Mats and other blocks to serve as a cheap and invulnerable reactor chambers. Said blocks will not + * shield the explosion and won't get destroyed. * * @author Stan Hebben */ @ZenClass("mods.ic2.ExplosionWhitelist") @ModOnly("IC2") public class IC2ExplosionWhitelist { - /** - * Adds a block to the explosion whitelist. - * - * @param item item to add - */ - @ZenMethod - public static void add(IItemStack item) { - ItemStack iStack = getItemStack(item); - Block block = Block.getBlockFromItem(iStack.getItem()); - if (block == null) { - MineTweakerAPI.logError("This item is not a block"); - } else { - MineTweakerAPI.apply(new AddAction(block)); - } - } - - /** - * Removes a block from the explosion whitelist. - * - * @param item item to remove - */ - @ZenMethod - public static void remove(IItemStack item) { - ItemStack iStack = getItemStack(item); - Block block = Block.getBlockFromItem(iStack.getItem()); - if (block == null) { - MineTweakerAPI.logError("This item is not a block"); - } else { - if (ExplosionWhitelist.isBlockWhitelisted(block)) { - MineTweakerAPI.logWarning("This block is not in the whitelist"); - } else { - MineTweakerAPI.apply(new RemoveAction(block)); - } - } - } - - /** - * Checks if the given item is already whitelisted. - * - * @param item item to check - * @return true if whitelisted - */ - @ZenMethod - public static boolean isWhitelisted(IItemStack item) { - ItemStack iStack = getItemStack(item); - Block block = Block.getBlockFromItem(iStack.getItem()); - if (block == null) { - MineTweakerAPI.logWarning("This item is not a block"); - return false; - } else { - return ExplosionWhitelist.isBlockWhitelisted(block); - } - } - - // ###################### - // ### Action classes ### - // ###################### - - private static class AddAction implements IUndoableAction { - private final Block block; - - public AddAction(Block block) { - this.block = block; - } - - @Override - public void apply() { - ExplosionWhitelist.addWhitelistedBlock(block); - } - @Override - public boolean canUndo() { - return true; - } + /** + * Adds a block to the explosion whitelist. + * + * @param item item to add + */ + @ZenMethod + public static void add(IItemStack item) { + ItemStack iStack = getItemStack(item); + Block block = Block.getBlockFromItem(iStack.getItem()); + if (block == null) { + MineTweakerAPI.logError("This item is not a block"); + } else { + MineTweakerAPI.apply(new AddAction(block)); + } + } - @Override - public void undo() { - ExplosionWhitelist.removeWhitelistedBlock(block); - } + /** + * Removes a block from the explosion whitelist. + * + * @param item item to remove + */ + @ZenMethod + public static void remove(IItemStack item) { + ItemStack iStack = getItemStack(item); + Block block = Block.getBlockFromItem(iStack.getItem()); + if (block == null) { + MineTweakerAPI.logError("This item is not a block"); + } else { + if (ExplosionWhitelist.isBlockWhitelisted(block)) { + MineTweakerAPI.logWarning("This block is not in the whitelist"); + } else { + MineTweakerAPI.apply(new RemoveAction(block)); + } + } + } - @Override - public String describe() { - return "Adding block to IC2 explosion whitelist: " + block.getLocalizedName(); - } + /** + * Checks if the given item is already whitelisted. + * + * @param item item to check + * @return true if whitelisted + */ + @ZenMethod + public static boolean isWhitelisted(IItemStack item) { + ItemStack iStack = getItemStack(item); + Block block = Block.getBlockFromItem(iStack.getItem()); + if (block == null) { + MineTweakerAPI.logWarning("This item is not a block"); + return false; + } else { + return ExplosionWhitelist.isBlockWhitelisted(block); + } + } - @Override - public String describeUndo() { - return "Removing block from IC2 explosion whitelist: " + block.getLocalizedName(); - } + // ###################### + // ### Action classes ### + // ###################### - @Override - public Object getOverrideKey() { - return null; - } - } - - private static class RemoveAction implements IUndoableAction { - private final Block block; - - public RemoveAction(Block block) { - this.block = block; - } - - @Override - public void apply() { - ExplosionWhitelist.removeWhitelistedBlock(block); - } + private static class AddAction implements IUndoableAction { - @Override - public boolean canUndo() { - return true; - } + private final Block block; - @Override - public void undo() { - ExplosionWhitelist.addWhitelistedBlock(block); - } + public AddAction(Block block) { + this.block = block; + } - @Override - public String describe() { - return "Removing block from IC2 explosion whitelist: " + block.getLocalizedName(); - } + @Override + public void apply() { + ExplosionWhitelist.addWhitelistedBlock(block); + } - @Override - public String describeUndo() { - return "Adding block to IC2 explosion whitelist: " + block.getLocalizedName(); - } + @Override + public boolean canUndo() { + return true; + } - @Override - public Object getOverrideKey() { - return null; - } - } + @Override + public void undo() { + ExplosionWhitelist.removeWhitelistedBlock(block); + } + + @Override + public String describe() { + return "Adding block to IC2 explosion whitelist: " + block.getLocalizedName(); + } + + @Override + public String describeUndo() { + return "Removing block from IC2 explosion whitelist: " + block.getLocalizedName(); + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + private static class RemoveAction implements IUndoableAction { + + private final Block block; + + public RemoveAction(Block block) { + this.block = block; + } + + @Override + public void apply() { + ExplosionWhitelist.removeWhitelistedBlock(block); + } + + @Override + public boolean canUndo() { + return true; + } + + @Override + public void undo() { + ExplosionWhitelist.addWhitelistedBlock(block); + } + + @Override + public String describe() { + return "Removing block from IC2 explosion whitelist: " + block.getLocalizedName(); + } + + @Override + public String describeUndo() { + return "Adding block to IC2 explosion whitelist: " + block.getLocalizedName(); + } + + @Override + public Object getOverrideKey() { + return null; + } + } } diff --git a/src/main/java/minetweaker/mods/ic2/IC2RecipeInput.java b/src/main/java/minetweaker/mods/ic2/IC2RecipeInput.java index 315d0d6..bea8d3f 100644 --- a/src/main/java/minetweaker/mods/ic2/IC2RecipeInput.java +++ b/src/main/java/minetweaker/mods/ic2/IC2RecipeInput.java @@ -1,70 +1,75 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2; -import ic2.api.recipe.IRecipeInput; -import java.util.ArrayList; -import java.util.List; import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + +import java.util.ArrayList; +import java.util.List; + import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; + import net.minecraft.item.ItemStack; +import ic2.api.recipe.IRecipeInput; + /** * Wrapper class for ITweakerItemStackPatterns to IC2 recipe inputs. * * @author Stan Hebben */ public class IC2RecipeInput implements IRecipeInput { - private final IIngredient ingredient; - - public IC2RecipeInput(IIngredient ingredient) { - this.ingredient = ingredient; - } - @Override - public boolean matches(ItemStack subject) { - return ingredient.matches(getIItemStack(subject)); - } + private final IIngredient ingredient; - @Override - public int getAmount() { - return ingredient.getAmount(); - } + public IC2RecipeInput(IIngredient ingredient) { + this.ingredient = ingredient; + } - @Override - public List getInputs() { - List items = new ArrayList(); - for (IItemStack item : ingredient.getItems()) { - items.add(getItemStack(item)); - } - return items; - } + @Override + public boolean matches(ItemStack subject) { + return ingredient.matches(getIItemStack(subject)); + } - @Override - public int hashCode() { - int hash = 7; - hash = 89 * hash + (this.ingredient != null ? this.ingredient.hashCode() : 0); - return hash; - } + @Override + public int getAmount() { + return ingredient.getAmount(); + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final IC2RecipeInput other = (IC2RecipeInput) obj; - if (this.ingredient != other.ingredient && (this.ingredient == null || !this.ingredient.equals(other.ingredient))) { - return false; - } - return true; - } + @Override + public List getInputs() { + List items = new ArrayList(); + for (IItemStack item : ingredient.getItems()) { + items.add(getItemStack(item)); + } + return items; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 89 * hash + (this.ingredient != null ? this.ingredient.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final IC2RecipeInput other = (IC2RecipeInput) obj; + if (this.ingredient != other.ingredient + && (this.ingredient == null || !this.ingredient.equals(other.ingredient))) { + return false; + } + return true; + } } diff --git a/src/main/java/minetweaker/mods/ic2/MachineAddRecipeAction.java b/src/main/java/minetweaker/mods/ic2/MachineAddRecipeAction.java index d9600ac..3b5b221 100644 --- a/src/main/java/minetweaker/mods/ic2/MachineAddRecipeAction.java +++ b/src/main/java/minetweaker/mods/ic2/MachineAddRecipeAction.java @@ -1,105 +1,110 @@ package minetweaker.mods.ic2; +import java.util.Arrays; + +import minetweaker.MineTweakerAPI; +import minetweaker.OneWayAction; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + import ic2.api.recipe.IMachineRecipeManager; import ic2.api.recipe.IMachineRecipeManagerExt; -import java.util.Arrays; -import minetweaker.MineTweakerAPI; -import minetweaker.OneWayAction; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; /** * * @author Stan Hebben */ public class MachineAddRecipeAction extends OneWayAction { - private final String name; - private final IMachineRecipeManager machine; - private final ItemStack[] output; - private final IC2RecipeInput input; - private final NBTTagCompound tag; - - public MachineAddRecipeAction(String name, IMachineRecipeManager machine, ItemStack[] output, NBTTagCompound tag, IC2RecipeInput input) { - this.name = name; - this.machine = machine; - this.output = output; - this.input = input; - this.tag = tag; - } - @Override - public void apply() { - try { - if (machine instanceof IMachineRecipeManagerExt) { - ((IMachineRecipeManagerExt) machine).addRecipe(input, tag, true, output); - } else { - machine.addRecipe(input, tag, output); - } - } catch (RuntimeException ex) { - MineTweakerAPI.logError(ex.getMessage()); - } - } + private final String name; + private final IMachineRecipeManager machine; + private final ItemStack[] output; + private final IC2RecipeInput input; + private final NBTTagCompound tag; - @Override - public String describe() { - if (output.length == 1) { - return "Adding " + name + " recipe for " + output[0].getDisplayName(); - } else { - StringBuilder result = new StringBuilder(); - result.append("Adding ").append(name).append(" recipe for "); - result.append("["); - for (int i = 0; i < output.length; i++) { - if (i == 0) { - result.append(", "); - } else { - result.append(output[i].getDisplayName()); - } - } - result.append("]"); - return result.toString(); - } - } + public MachineAddRecipeAction(String name, IMachineRecipeManager machine, ItemStack[] output, NBTTagCompound tag, + IC2RecipeInput input) { + this.name = name; + this.machine = machine; + this.output = output; + this.input = input; + this.tag = tag; + } - @Override - public Object getOverrideKey() { - return null; - } + @Override + public void apply() { + try { + if (machine instanceof IMachineRecipeManagerExt) { + ((IMachineRecipeManagerExt) machine).addRecipe(input, tag, true, output); + } else { + machine.addRecipe(input, tag, output); + } + } catch (RuntimeException ex) { + MineTweakerAPI.logError(ex.getMessage()); + } + } - @Override - public int hashCode() { - int hash = 7; - hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0); - hash = 47 * hash + (this.machine != null ? this.machine.hashCode() : 0); - hash = 47 * hash + Arrays.deepHashCode(this.output); - hash = 47 * hash + (this.input != null ? this.input.hashCode() : 0); - hash = 47 * hash + (this.tag != null ? this.tag.hashCode() : 0); - return hash; - } + @Override + public String describe() { + if (output.length == 1) { + return "Adding " + name + " recipe for " + output[0].getDisplayName(); + } else { + StringBuilder result = new StringBuilder(); + result.append("Adding ").append(name).append(" recipe for "); + result.append("["); + for (int i = 0; i < output.length; i++) { + if (i == 0) { + result.append(", "); + } else { + result.append(output[i].getDisplayName()); + } + } + result.append("]"); + return result.toString(); + } + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MachineAddRecipeAction other = (MachineAddRecipeAction) obj; - if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { - return false; - } - if (this.machine != other.machine && (this.machine == null || !this.machine.equals(other.machine))) { - return false; - } - if (!Arrays.deepEquals(this.output, other.output)) { - return false; - } - if (this.input != other.input && (this.input == null || !this.input.equals(other.input))) { - return false; - } - if (this.tag != other.tag && (this.tag == null || !this.tag.equals(other.tag))) { - return false; - } - return true; - } + @Override + public Object getOverrideKey() { + return null; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0); + hash = 47 * hash + (this.machine != null ? this.machine.hashCode() : 0); + hash = 47 * hash + Arrays.deepHashCode(this.output); + hash = 47 * hash + (this.input != null ? this.input.hashCode() : 0); + hash = 47 * hash + (this.tag != null ? this.tag.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final MachineAddRecipeAction other = (MachineAddRecipeAction) obj; + if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { + return false; + } + if (this.machine != other.machine && (this.machine == null || !this.machine.equals(other.machine))) { + return false; + } + if (!Arrays.deepEquals(this.output, other.output)) { + return false; + } + if (this.input != other.input && (this.input == null || !this.input.equals(other.input))) { + return false; + } + if (this.tag != other.tag && (this.tag == null || !this.tag.equals(other.tag))) { + return false; + } + return true; + } } diff --git a/src/main/java/minetweaker/mods/ic2/crops/Crop.java b/src/main/java/minetweaker/mods/ic2/crops/Crop.java index 066d165..135e409 100644 --- a/src/main/java/minetweaker/mods/ic2/crops/Crop.java +++ b/src/main/java/minetweaker/mods/ic2/crops/Crop.java @@ -1,84 +1,85 @@ package minetweaker.mods.ic2.crops; -import ic2.api.crops.CropCard; import stanhebben.zenscript.annotations.ZenCaster; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenGetter; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.crops.CropCard; /** * Read-only data accessor for crops + * * @author ben * */ @ZenClass("mods.ic2.Crop") public class Crop { - private CropCard cc; - @ZenGetter("name") - public String name() { - return cc.name(); - } + private CropCard cc; - @ZenGetter("owner") - public String owner() { - return cc.owner(); - } + @ZenGetter("name") + public String name() { + return cc.name(); + } - @ZenGetter("displayName") - public String displayName() { - return cc.displayName(); - } + @ZenGetter("owner") + public String owner() { + return cc.owner(); + } - @ZenGetter("hashCode") - public int hashCode() { - return cc.hashCode(); - } + @ZenGetter("displayName") + public String displayName() { + return cc.displayName(); + } - @ZenGetter("discoveredBy") - public String discoveredBy() { - return cc.discoveredBy(); - } + @ZenGetter("hashCode") + public int hashCode() { + return cc.hashCode(); + } - @ZenMethod - public String desc(int i) { - return cc.desc(i); - } + @ZenGetter("discoveredBy") + public String discoveredBy() { + return cc.discoveredBy(); + } - @ZenGetter("tier") - public int tier() { - return cc.tier(); - } + @ZenMethod + public String desc(int i) { + return cc.desc(i); + } - @ZenMethod - public int stat(int n) { - return cc.stat(n); - } - - @ZenGetter("attributes") - public String[] attributes() { - return cc.attributes(); - } + @ZenGetter("tier") + public int tier() { + return cc.tier(); + } - @ZenGetter("maxSize") - public int maxSize() { - return cc.maxSize(); - } + @ZenMethod + public int stat(int n) { + return cc.stat(n); + } - @ZenGetter("dropGainChance") - public float dropGainChance() { - return cc.dropGainChance(); - } + @ZenGetter("attributes") + public String[] attributes() { + return cc.attributes(); + } - @ZenCaster - public String toString() { - return cc.toString(); - } + @ZenGetter("maxSize") + public int maxSize() { + return cc.maxSize(); + } - public Crop(CropCard cc) { - super(); - this.cc = cc; - } + @ZenGetter("dropGainChance") + public float dropGainChance() { + return cc.dropGainChance(); + } + + @ZenCaster + public String toString() { + return cc.toString(); + } + + public Crop(CropCard cc) { + super(); + this.cc = cc; + } - } diff --git a/src/main/java/minetweaker/mods/ic2/crops/CropsConfig.java b/src/main/java/minetweaker/mods/ic2/crops/CropsConfig.java index 5159d13..ed227f1 100644 --- a/src/main/java/minetweaker/mods/ic2/crops/CropsConfig.java +++ b/src/main/java/minetweaker/mods/ic2/crops/CropsConfig.java @@ -4,259 +4,259 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import ic2.api.crops.CropCard; -import ic2.api.crops.Crops; import minetweaker.MineTweakerAPI; import minetweaker.OneWayAction; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IItemStack; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraftforge.common.BiomeDictionary; -import stanhebben.zenscript.annotations.ZenCaster; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenGetter; -/** - * Provides access to IC2 crop system in general - * @author ben - * - */ import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.crops.CropCard; +import ic2.api.crops.Crops; + @ZenClass("mods.ic2.CropsConfig") @ModOnly("IC2") public class CropsConfig { - /** - * Action to add a new seed for a base crop - * @author ben - * - */ - private static final class RegisterBaseSeedAction extends OneWayAction { - private IItemStack seed; - private CropCard c; - private int sz; - private int growth; - private int gain; - private int resist; - public RegisterBaseSeedAction(IItemStack seed, CropCard c, int sz, int growth, int gain, int resist) { - this.seed = seed; - this.c = c; - this.sz = sz; - this.growth = growth; - this.gain = gain; - this.resist = resist; - } + /** + * Action to add a new seed for a base crop + * + * @author ben + * + */ + private static final class RegisterBaseSeedAction extends OneWayAction { - @Override - public Object getOverrideKey() { - return null; - } + private IItemStack seed; + private CropCard c; + private int sz; + private int growth; + private int gain; + private int resist; - @Override - public String describe() { - return "Registering base seed for crop " + c.name(); - } + public RegisterBaseSeedAction(IItemStack seed, CropCard c, int sz, int growth, int gain, int resist) { + this.seed = seed; + this.c = c; + this.sz = sz; + this.growth = growth; + this.gain = gain; + this.resist = resist; + } - @Override - public void apply() { - Crops.instance.registerBaseSeed(MineTweakerMC.getItemStack(seed), c, sz, growth, gain, resist); - } - } - + @Override + public Object getOverrideKey() { + return null; + } + @Override + public String describe() { + return "Registering base seed for crop " + c.name(); + } - /** - * Action to register a new crop - * @author ben - * - */ - private static final class RegisterCropCardAction extends OneWayAction { - private CropCard c; + @Override + public void apply() { + Crops.instance.registerBaseSeed(MineTweakerMC.getItemStack(seed), c, sz, growth, gain, resist); + } + } - public RegisterCropCardAction(CropCard c) { - this.c = c; - } + /** + * Action to register a new crop + * + * @author ben + * + */ + private static final class RegisterCropCardAction extends OneWayAction { - @Override - public Object getOverrideKey() { - return null; - } + private CropCard c; - @Override - public String describe() { - // TODO Auto-generated method stub - return "Registering crop " + c.name(); - } + public RegisterCropCardAction(CropCard c) { + this.c = c; + } - @Override - public void apply() { - Crops.instance.registerCrop(c); - } - } - + @Override + public Object getOverrideKey() { + return null; + } - /** - * Action to add a biome nutrient bonus - * @author ben - * - */ - private static final class AddBiomeNutrientBonusAction extends OneWayAction { - private String biomeType; - private int nutrientBonus; + @Override + public String describe() { + // TODO Auto-generated method stub + return "Registering crop " + c.name(); + } - public AddBiomeNutrientBonusAction(String biomeType, int nutrientBonus) { - this.biomeType = biomeType; - this.nutrientBonus = nutrientBonus; - } + @Override + public void apply() { + Crops.instance.registerCrop(c); + } + } - @Override - public Object getOverrideKey() { - // TODO Auto-generated method stub - return null; - } + /** + * Action to add a biome nutrient bonus + * + * @author ben + * + */ + private static final class AddBiomeNutrientBonusAction extends OneWayAction { - @Override - public String describe() { - return "Setting biome nutrient bonus for " + biomeType + " biomes to " + - nutrientBonus; - } + private String biomeType; + private int nutrientBonus; - @Override - public void apply() { - Crops.instance.addBiomenutrientsBonus(BiomeDictionary.Type.valueOf(biomeType), - nutrientBonus); - } - } - - /** - * Action to add a biome humidity bonus - * @author ben - * - */ - private static final class AddBiomeHumidityBonusAction extends OneWayAction { - private String biomeType; - private int humidityBonus; + public AddBiomeNutrientBonusAction(String biomeType, int nutrientBonus) { + this.biomeType = biomeType; + this.nutrientBonus = nutrientBonus; + } - public AddBiomeHumidityBonusAction(String biomeType, int humidityBonus) { - this.biomeType = biomeType; - this.humidityBonus = humidityBonus; - } + @Override + public Object getOverrideKey() { + // TODO Auto-generated method stub + return null; + } - @Override - public Object getOverrideKey() { - // TODO Auto-generated method stub - return null; - } + @Override + public String describe() { + return "Setting biome nutrient bonus for " + biomeType + " biomes to " + nutrientBonus; + } - @Override - public String describe() { - return "Setting biome humidity bonus for " + biomeType + " biomes to " + - humidityBonus; - } + @Override + public void apply() { + Crops.instance.addBiomenutrientsBonus(BiomeDictionary.Type.valueOf(biomeType), nutrientBonus); + } + } - @Override - public void apply() { - Crops.instance.addBiomehumidityBonus(BiomeDictionary.Type.valueOf(biomeType), - humidityBonus); - } - } - - /** - * Add a nutrient bonus to crops in a specific biome - */ - @ZenMethod - public static void addBiomeNutrientBonus(String biomeType, int nutrientBonus) { - if(BiomeDictionary.Type.valueOf(biomeType) == null) { - MineTweakerAPI.logWarning("invalid biome type: " + biomeType); - } else if (nutrientBonus < -10 || nutrientBonus > 10) { - MineTweakerAPI.logWarning("nutrient bonus " + nutrientBonus + - " not in -10, +10 range"); - } else { - MineTweakerAPI.apply(new AddBiomeNutrientBonusAction(biomeType, nutrientBonus)); - } - } - - /** - * Add a humidity bonus to crops in a specific biome - */ - @ZenMethod - public static void addBiomeHumidityBonus(String biomeType, int humidityBonus) { - if(BiomeDictionary.Type.valueOf(biomeType) == null) { - MineTweakerAPI.logWarning("invalid biome type: " + biomeType); - } else if (humidityBonus < -10 || humidityBonus > 10) { - MineTweakerAPI.logWarning("humidity bonus " + humidityBonus + - " not in -10, +10 range"); - } else { - MineTweakerAPI.apply(new AddBiomeHumidityBonusAction(biomeType, humidityBonus)); - } - } + /** + * Action to add a biome humidity bonus + * + * @author ben + * + */ + private static final class AddBiomeHumidityBonusAction extends OneWayAction { - /** - * Creates a new synthetic crop to manipulate - * @param cropOwner The mod that owns the crop - * @param cropName The name of the crop - */ - @ZenMethod - public static SyntheticCrop newCrop(String cropName, String cropOwner) { - return new SyntheticCrop(cropName, cropOwner); - } - - /** - * Register a crop into the crop system - */ - @ZenMethod - public static void registerCrop(CropCard c) { - MineTweakerAPI.apply(new RegisterCropCardAction(c)); - } - - /** - * Register a new base seed item to plant a crop - * - * @param seed The item to plant with - * @param c The crop being planted - * @param sz The initial size of the planted crop - * @param growth The initial growth stat of the planted crop - * @param gain The initial gain stat of the planted crop - * @param resist The initial resistance of the planted crop - */ - public static void registerBaseSeed(IItemStack seed, CropCard c, int sz, - int growth, int gain, int resist) { - MineTweakerAPI.apply(new RegisterBaseSeedAction(seed, c, sz, growth, gain, resist)); - } + private String biomeType; + private int humidityBonus; - /** - * Get a crop by its name and owning mod - * @param owner The mod that owns the crop - * @param name The name of the crop - * @return A crop with the given name, owned by the given mod - */ - @ZenMethod - public static Crop getCrop(String owner, String name) { - return new Crop(Crops.instance.getCropCard(owner, name)); - } - - /** - * Get a crop by the seed that plants it - * @param seed The seed that plants the crop - * @return The crop planted by the seed - */ - @ZenMethod - public static Crop getCrop(IItemStack seed) { - return new Crop(Crops.instance.getCropCard(MineTweakerMC.getItemStack(seed))); - } + public AddBiomeHumidityBonusAction(String biomeType, int humidityBonus) { + this.biomeType = biomeType; + this.humidityBonus = humidityBonus; + } - /** - * Get all of the currently registered crops - * @return All of the currently registered crops - */ - @ZenGetter("crops") - public static List getAllCrops() { - Collection ccList = Crops.instance.getCrops(); - - List cList = new ArrayList(ccList.size()); - for (CropCard cropCard : ccList) { - cList.add(new Crop(cropCard)); - } - - return cList; - } + @Override + public Object getOverrideKey() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String describe() { + return "Setting biome humidity bonus for " + biomeType + " biomes to " + humidityBonus; + } + + @Override + public void apply() { + Crops.instance.addBiomehumidityBonus(BiomeDictionary.Type.valueOf(biomeType), humidityBonus); + } + } + + /** + * Add a nutrient bonus to crops in a specific biome + */ + @ZenMethod + public static void addBiomeNutrientBonus(String biomeType, int nutrientBonus) { + if (BiomeDictionary.Type.valueOf(biomeType) == null) { + MineTweakerAPI.logWarning("invalid biome type: " + biomeType); + } else if (nutrientBonus < -10 || nutrientBonus > 10) { + MineTweakerAPI.logWarning("nutrient bonus " + nutrientBonus + " not in -10, +10 range"); + } else { + MineTweakerAPI.apply(new AddBiomeNutrientBonusAction(biomeType, nutrientBonus)); + } + } + + /** + * Add a humidity bonus to crops in a specific biome + */ + @ZenMethod + public static void addBiomeHumidityBonus(String biomeType, int humidityBonus) { + if (BiomeDictionary.Type.valueOf(biomeType) == null) { + MineTweakerAPI.logWarning("invalid biome type: " + biomeType); + } else if (humidityBonus < -10 || humidityBonus > 10) { + MineTweakerAPI.logWarning("humidity bonus " + humidityBonus + " not in -10, +10 range"); + } else { + MineTweakerAPI.apply(new AddBiomeHumidityBonusAction(biomeType, humidityBonus)); + } + } + + /** + * Creates a new synthetic crop to manipulate + * + * @param cropOwner The mod that owns the crop + * @param cropName The name of the crop + */ + @ZenMethod + public static SyntheticCrop newCrop(String cropName, String cropOwner) { + return new SyntheticCrop(cropName, cropOwner); + } + + /** + * Register a crop into the crop system + */ + @ZenMethod + public static void registerCrop(CropCard c) { + MineTweakerAPI.apply(new RegisterCropCardAction(c)); + } + + /** + * Register a new base seed item to plant a crop + * + * @param seed The item to plant with + * @param c The crop being planted + * @param sz The initial size of the planted crop + * @param growth The initial growth stat of the planted crop + * @param gain The initial gain stat of the planted crop + * @param resist The initial resistance of the planted crop + */ + public static void registerBaseSeed(IItemStack seed, CropCard c, int sz, int growth, int gain, int resist) { + MineTweakerAPI.apply(new RegisterBaseSeedAction(seed, c, sz, growth, gain, resist)); + } + + /** + * Get a crop by its name and owning mod + * + * @param owner The mod that owns the crop + * @param name The name of the crop + * @return A crop with the given name, owned by the given mod + */ + @ZenMethod + public static Crop getCrop(String owner, String name) { + return new Crop(Crops.instance.getCropCard(owner, name)); + } + + /** + * Get a crop by the seed that plants it + * + * @param seed The seed that plants the crop + * @return The crop planted by the seed + */ + @ZenMethod + public static Crop getCrop(IItemStack seed) { + return new Crop(Crops.instance.getCropCard(MineTweakerMC.getItemStack(seed))); + } + + /** + * Get all of the currently registered crops + * + * @return All of the currently registered crops + */ + @ZenGetter("crops") + public static List getAllCrops() { + Collection ccList = Crops.instance.getCrops(); + + List cList = new ArrayList(ccList.size()); + for (CropCard cropCard : ccList) { + cList.add(new Crop(cropCard)); + } + + return cList; + } } diff --git a/src/main/java/minetweaker/mods/ic2/crops/GrowthRequirements.java b/src/main/java/minetweaker/mods/ic2/crops/GrowthRequirements.java index c7d9ea1..10a3c62 100644 --- a/src/main/java/minetweaker/mods/ic2/crops/GrowthRequirements.java +++ b/src/main/java/minetweaker/mods/ic2/crops/GrowthRequirements.java @@ -7,138 +7,150 @@ import stanhebben.zenscript.annotations.ZenSetter; /** * Contains all of the growth requirements for an IC2 crop in one easy place + * * @author ben * */ @ZenClass("mods.ic2.GrowthRequirements") public class GrowthRequirements { - - private int minNutrients; - private int minHumidity; - private int minAirQuality; - - private int minLight; - private int maxLight = 17; - - private IItemStack requiredBlock; - /** - * Get the minimum amount of nutrients this plant needs to grow - * @return The minimum amount of nutrients this plant needs - */ - @ZenGetter("minNutrients") - public int getMinNutrients() { - return minNutrients; - } + private int minNutrients; + private int minHumidity; + private int minAirQuality; - /** - * Set the minimum amount of nutrients this plant needs to grow - * @param minNutrients The new minimum amount of nutrients this plant requires - */ - @ZenSetter("minNutrients") - public void setMinNutrients(int minNutrients) { - this.minNutrients = minNutrients; - } + private int minLight; + private int maxLight = 17; - /** - * Get the minimum amount of humidity this plant requires - * @return The minimum amount of humidity this plant requires - */ - @ZenGetter("minHumidity") - public int getMinHumidity() { - return minHumidity; - } + private IItemStack requiredBlock; - /** - * Set the minimum amount of humidity this plant requires - * @param minHumidity The new minimum amount of humidity this plant requires - */ - @ZenSetter("minHumidity") - public void setMinHumidity(int minHumidity) { - this.minHumidity = minHumidity; - } + /** + * Get the minimum amount of nutrients this plant needs to grow + * + * @return The minimum amount of nutrients this plant needs + */ + @ZenGetter("minNutrients") + public int getMinNutrients() { + return minNutrients; + } - /** - * Get the minimum air quality this plant requires - * @return The minimum air quality this plant requires - */ - @ZenGetter("minAirQuality") - public int getMinAirQuality() { - return minAirQuality; - } + /** + * Set the minimum amount of nutrients this plant needs to grow + * + * @param minNutrients The new minimum amount of nutrients this plant requires + */ + @ZenSetter("minNutrients") + public void setMinNutrients(int minNutrients) { + this.minNutrients = minNutrients; + } - /** - * Set the minimum air quality this plant requires - * @param minAirQuality The new amount of air quality this plant requires - */ - @ZenSetter("minAirQuality") - public void setMinAirQuality(int minAirQuality) { - this.minAirQuality = minAirQuality; - } + /** + * Get the minimum amount of humidity this plant requires + * + * @return The minimum amount of humidity this plant requires + */ + @ZenGetter("minHumidity") + public int getMinHumidity() { + return minHumidity; + } - /** - * Get the minimum amount of light this plant requires - * @return The minimum amount of light this plant requires - */ - @ZenGetter("minLight") - public int getMinLight() { - return minLight; - } + /** + * Set the minimum amount of humidity this plant requires + * + * @param minHumidity The new minimum amount of humidity this plant requires + */ + @ZenSetter("minHumidity") + public void setMinHumidity(int minHumidity) { + this.minHumidity = minHumidity; + } - /** - * Set the minimum amount of light this plant requires - * @param minLight The new minimum amount of light this plant requires - */ - @ZenSetter("minLight") - public void setMinLight(int minLight) { - this.minLight = minLight; - } + /** + * Get the minimum air quality this plant requires + * + * @return The minimum air quality this plant requires + */ + @ZenGetter("minAirQuality") + public int getMinAirQuality() { + return minAirQuality; + } - /** - * Get the maximum amount of light this plant can have - * @return The maximum amount of light this plant can have - */ - @ZenGetter("maxLight") - public int getMaxLight() { - return maxLight; - } + /** + * Set the minimum air quality this plant requires + * + * @param minAirQuality The new amount of air quality this plant requires + */ + @ZenSetter("minAirQuality") + public void setMinAirQuality(int minAirQuality) { + this.minAirQuality = minAirQuality; + } - /** - * Set the maximum amount of light this plant can have - * @param maxLight The new maximum amount of light thi plant can have - */ - @ZenSetter("maxLight") - public void setMaxLight(int maxLight) { - this.maxLight = maxLight; - } + /** + * Get the minimum amount of light this plant requires + * + * @return The minimum amount of light this plant requires + */ + @ZenGetter("minLight") + public int getMinLight() { + return minLight; + } - /** - * Get the block that is required to be below this one - * @return The block required to be below this one - */ - @ZenGetter("requiredBlock") - public IItemStack getRequiredBlock() { - return requiredBlock; - } + /** + * Set the minimum amount of light this plant requires + * + * @param minLight The new minimum amount of light this plant requires + */ + @ZenSetter("minLight") + public void setMinLight(int minLight) { + this.minLight = minLight; + } - /** - * Set the block required to be below this one - * @param requiredBlock The new block required to be below this one - */ - @ZenSetter("requiredBlock") - public void setRequiredBlock(IItemStack requiredBlock) { - this.requiredBlock = requiredBlock; - } + /** + * Get the maximum amount of light this plant can have + * + * @return The maximum amount of light this plant can have + */ + @ZenGetter("maxLight") + public int getMaxLight() { + return maxLight; + } - - public GrowthRequirements(int minNutrients, int minHumidity, int minAirQuality, int minLight, int maxLight, - IItemStack requiredBlock) { - super(); - this.minNutrients = minNutrients; - this.minHumidity = minHumidity; - this.minAirQuality = minAirQuality; - this.minLight = minLight; - this.maxLight = maxLight; - this.requiredBlock = requiredBlock; - } + /** + * Set the maximum amount of light this plant can have + * + * @param maxLight The new maximum amount of light thi plant can have + */ + @ZenSetter("maxLight") + public void setMaxLight(int maxLight) { + this.maxLight = maxLight; + } + + /** + * Get the block that is required to be below this one + * + * @return The block required to be below this one + */ + @ZenGetter("requiredBlock") + public IItemStack getRequiredBlock() { + return requiredBlock; + } + + /** + * Set the block required to be below this one + * + * @param requiredBlock The new block required to be below this one + */ + @ZenSetter("requiredBlock") + public void setRequiredBlock(IItemStack requiredBlock) { + this.requiredBlock = requiredBlock; + } + + public GrowthRequirements(int minNutrients, int minHumidity, int minAirQuality, int minLight, int maxLight, + IItemStack requiredBlock) { + super(); + this.minNutrients = minNutrients; + this.minHumidity = minHumidity; + this.minAirQuality = minAirQuality; + this.minLight = minLight; + this.maxLight = maxLight; + this.requiredBlock = requiredBlock; + } } diff --git a/src/main/java/minetweaker/mods/ic2/crops/SyntheticCrop.java b/src/main/java/minetweaker/mods/ic2/crops/SyntheticCrop.java index baf287c..798e0bc 100644 --- a/src/main/java/minetweaker/mods/ic2/crops/SyntheticCrop.java +++ b/src/main/java/minetweaker/mods/ic2/crops/SyntheticCrop.java @@ -1,30 +1,30 @@ package minetweaker.mods.ic2.crops; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import ic2.api.crops.CropCard; -import ic2.api.crops.ICropTile; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import minetweaker.api.minecraft.MineTweakerMC; + import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenGetter; import stanhebben.zenscript.annotations.ZenMethod; import stanhebben.zenscript.annotations.ZenSetter; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import ic2.api.crops.CropCard; +import ic2.api.crops.ICropTile; /** * A synthetic crop, created in ZS * - * For your crop textures to be picked up, put them at owner + ":crops/crop" + - * name + "." + size where owner is the mod responsible for the crop name is the - * name of the crop size is the current size of the crop, starting at 0 for new + * For your crop textures to be picked up, put them at owner + ":crops/crop" + name + "." + size where owner is the mod + * responsible for the crop name is the name of the crop size is the current size of the crop, starting at 0 for new * crops * - * Localizations will be looked for at owner + ".crop." + name where each field - * has the value it has above + * Localizations will be looked for at owner + ".crop." + name where each field has the value it has above * * @author ben * @@ -32,264 +32,250 @@ import stanhebben.zenscript.annotations.ZenSetter; @ZenClass("mods.ic2.SyntheticCrop") public class SyntheticCrop extends CropCard { - private String name; - private String owner; + private String name; + private String owner; - private int tier; + private int tier; - private int[] stats = new int[4]; - private String[] attributes; + private int[] stats = new int[4]; + private String[] attributes; - private int maxSize; + private int maxSize; - private float dropChance; - private IItemStack fruit; + private float dropChance; + private IItemStack fruit; - private GrowthRequirements reqs; + private GrowthRequirements reqs; - /** - * Create a new synthetic crop - * - * @param cropName - * The name of this crop - * @param cropOwner - * The mod creating this crop - */ - public SyntheticCrop(String cropName, String cropOwner) { - name = cropName; - } + /** + * Create a new synthetic crop + * + * @param cropName The name of this crop + * @param cropOwner The mod creating this crop + */ + public SyntheticCrop(String cropName, String cropOwner) { + name = cropName; + } - // Required IC2 Interface - /** - * Gets the name of this crop used as a identifier - */ - @Override - @ZenGetter("name") - public String name() { - return name; - } + // Required IC2 Interface + /** + * Gets the name of this crop used as a identifier + */ + @Override + @ZenGetter("name") + public String name() { + return name; + } - /** - * Get the mod that owns this crop - */ - @Override - @ZenGetter("owner") - public String owner() { - return owner; - } + /** + * Get the mod that owns this crop + */ + @Override + @ZenGetter("owner") + public String owner() { + return owner; + } - /** - * Gets the localization key used for this crop - */ - @Override - public String displayName() { - return owner + ".crop." + name; - } + /** + * Gets the localization key used for this crop + */ + @Override + public String displayName() { + return owner + ".crop." + name; + } - /** - * Gets the seed tier of this crop. - */ - @Override - @ZenGetter("tier") - public int tier() { - return tier; - } + /** + * Gets the seed tier of this crop. + */ + @Override + @ZenGetter("tier") + public int tier() { + return tier; + } - /** - * Gets the value of a particular stat for this crop - * - * Stats: - 0: Chemistry (Industrial uses based on chemical plant - * components) - 1: Consumable (Food, potion ingredients, stuff meant to be - * eaten or similarly used) - 2: Defensive (Plants with defense capabilities - * (damaging, explosive, chemical) or special abilities in general) - 3: - * Colorful (How colorful/aesthetically/beautiful is the plant, like - * dye-plants or plants without actual effects) - 4: Weed (Is this plant - * weed-like and rather unwanted/quick-spreading? Rare super-breed plants - * should have low values here) - * - */ - @Override - @ZenMethod - public int stat(int n) { - return stats[n]; - } + /** + * Gets the value of a particular stat for this crop + * + * Stats: - 0: Chemistry (Industrial uses based on chemical plant components) - 1: Consumable (Food, potion + * ingredients, stuff meant to be eaten or similarly used) - 2: Defensive (Plants with defense capabilities + * (damaging, explosive, chemical) or special abilities in general) - 3: Colorful (How + * colorful/aesthetically/beautiful is the plant, like dye-plants or plants without actual effects) - 4: Weed (Is + * this plant weed-like and rather unwanted/quick-spreading? Rare super-breed plants should have low values here) + * + */ + @Override + @ZenMethod + public int stat(int n) { + return stats[n]; + } - /** - * Gets any additional attributes of this crop - */ - @Override - @ZenGetter("attributes") - public String[] attributes() { - return attributes; - } + /** + * Gets any additional attributes of this crop + */ + @Override + @ZenGetter("attributes") + public String[] attributes() { + return attributes; + } - /** - * Gets the maximum size of this crop - */ - @Override - @ZenGetter("maxSize") - public int maxSize() { - return maxSize; - } + /** + * Gets the maximum size of this crop + */ + @Override + @ZenGetter("maxSize") + public int maxSize() { + return maxSize; + } - @Override - @SideOnly(Side.CLIENT) - public void registerSprites(IIconRegister iconRegister) { - textures = new IIcon[maxSize()]; + @Override + @SideOnly(Side.CLIENT) + public void registerSprites(IIconRegister iconRegister) { + textures = new IIcon[maxSize()]; - for (int i = 1; i <= textures.length; i++) { - textures[i - 1] = iconRegister.registerIcon(owner() + ":crop/crop" + name() + "." + i); - } - } + for (int i = 1; i <= textures.length; i++) { + textures[i - 1] = iconRegister.registerIcon(owner() + ":crop/crop" + name() + "." + i); + } + } - @Override - public boolean canGrow(ICropTile crop) { - if (crop.getSize() == maxSize) { - return false; - } else if (reqs == null) { - return true; - } else { - if(!crop.isBlockBelow(MineTweakerMC.getBlock(reqs.getRequiredBlock()))) { - return false; - } else if(crop.getAirQuality() < reqs.getMinAirQuality()){ - return false; - } else if(crop.getHumidity() < reqs.getMinHumidity()) { - return false; - } else if(crop.getNutrients() < reqs.getMinNutrients()) { - return false; - } else { - int lgh = crop.getLightLevel(); - return reqs.getMinLight() < lgh && reqs.getMaxLight() > lgh; - } - } - } + @Override + public boolean canGrow(ICropTile crop) { + if (crop.getSize() == maxSize) { + return false; + } else if (reqs == null) { + return true; + } else { + if (!crop.isBlockBelow(MineTweakerMC.getBlock(reqs.getRequiredBlock()))) { + return false; + } else if (crop.getAirQuality() < reqs.getMinAirQuality()) { + return false; + } else if (crop.getHumidity() < reqs.getMinHumidity()) { + return false; + } else if (crop.getNutrients() < reqs.getMinNutrients()) { + return false; + } else { + int lgh = crop.getLightLevel(); + return reqs.getMinLight() < lgh && reqs.getMaxLight() > lgh; + } + } + } - @Override - public int getOptimalHavestSize(ICropTile crop) { - return maxSize; - } + @Override + public int getOptimalHavestSize(ICropTile crop) { + return maxSize; + } - @Override - public boolean canBeHarvested(ICropTile crop) { - return crop.getSize() == maxSize; - } + @Override + public boolean canBeHarvested(ICropTile crop) { + return crop.getSize() == maxSize; + } - @Override - public ItemStack getGain(ICropTile crop) { - return MineTweakerMC.getItemStack(fruit); - } + @Override + public ItemStack getGain(ICropTile crop) { + return MineTweakerMC.getItemStack(fruit); + } - /** - * Gets the chance for this crop to drop an item - */ - @Override - @ZenGetter("dropChance") - public float dropGainChance() { - return dropChance; - }; + /** + * Gets the chance for this crop to drop an item + */ + @Override + @ZenGetter("dropChance") + public float dropGainChance() { + return dropChance; + }; - // ZS Support + // ZS Support - /** - * Sets the tier of this crop - * - * @param tier - * The new tier of this crop - */ - @ZenSetter("tier") - public void setTier(int tier) { - this.tier = tier; - } + /** + * Sets the tier of this crop + * + * @param tier The new tier of this crop + */ + @ZenSetter("tier") + public void setTier(int tier) { + this.tier = tier; + } - /** - * Sets all of the stats for this crop - * - * @param stats - * The new stats to give to this crop - */ - @ZenSetter("stats") - public void setStats(int[] stats) { - this.stats = stats; - } + /** + * Sets all of the stats for this crop + * + * @param stats The new stats to give to this crop + */ + @ZenSetter("stats") + public void setStats(int[] stats) { + this.stats = stats; + } - /** - * Sets an individual stat for this crop - * - * @param stat - * The stat to set a value for - * @param val - * The new value for this stat - */ - @ZenMethod - public void setStat(int stat, int val) { - if (stat < 0 || stat > 3) { - MineTweakerAPI.logWarning("invalid stat index " + stat); - } else { - stats[stat] = val; - } - } + /** + * Sets an individual stat for this crop + * + * @param stat The stat to set a value for + * @param val The new value for this stat + */ + @ZenMethod + public void setStat(int stat, int val) { + if (stat < 0 || stat > 3) { + MineTweakerAPI.logWarning("invalid stat index " + stat); + } else { + stats[stat] = val; + } + } - /** - * Sets the additional attributes for this crop - * - * @param attributes - * Sets the attributes of this crop - */ - @ZenSetter("attributes") - public void setAttributes(String[] attributes) { - this.attributes = attributes; - } + /** + * Sets the additional attributes for this crop + * + * @param attributes Sets the attributes of this crop + */ + @ZenSetter("attributes") + public void setAttributes(String[] attributes) { + this.attributes = attributes; + } - /** - * Sets the maximum size this crop goes to - * - * @param maxSize - * The new max size of this crop - */ - @ZenSetter("maxSize") - public void setMaxSize(int maxSize) { - this.maxSize = maxSize; - } + /** + * Sets the maximum size this crop goes to + * + * @param maxSize The new max size of this crop + */ + @ZenSetter("maxSize") + public void setMaxSize(int maxSize) { + this.maxSize = maxSize; + } - /** - * Sets the item this crop gives when harvested - * - * @param fruit - * The item to give from the crop - */ - @ZenSetter("fruit") - public void setFruit(IItemStack fruit) { - this.fruit = fruit; - } + /** + * Sets the item this crop gives when harvested + * + * @param fruit The item to give from the crop + */ + @ZenSetter("fruit") + public void setFruit(IItemStack fruit) { + this.fruit = fruit; + } - /** - * Sets the chance for this plant to yield its fruit - * - * @param dropChance - * The new chance for this plant to yield fruit - */ - @ZenSetter("dropChance") - public void setDropChance(int dropChance) { - this.dropChance = dropChance; - } + /** + * Sets the chance for this plant to yield its fruit + * + * @param dropChance The new chance for this plant to yield fruit + */ + @ZenSetter("dropChance") + public void setDropChance(int dropChance) { + this.dropChance = dropChance; + } - /** - * Get the current requirements for this plant to grow - * - * @return The current growth requirements for this plant - */ - public GrowthRequirements getReqs() { - return reqs; - } + /** + * Get the current requirements for this plant to grow + * + * @return The current growth requirements for this plant + */ + public GrowthRequirements getReqs() { + return reqs; + } - /** - * Set the current growth requirements for this plant to grow - * - * @param reqs - * The new requirements for this plant to grow - */ - public void setReqs(GrowthRequirements reqs) { - this.reqs = reqs; - } + /** + * Set the current growth requirements for this plant to grow + * + * @param reqs The new requirements for this plant to grow + */ + public void setReqs(GrowthRequirements reqs) { + this.reqs = reqs; + } } diff --git a/src/main/java/minetweaker/mods/ic2/expand/IngredientExpansion.java b/src/main/java/minetweaker/mods/ic2/expand/IngredientExpansion.java index 864766a..02cd9ef 100644 --- a/src/main/java/minetweaker/mods/ic2/expand/IngredientExpansion.java +++ b/src/main/java/minetweaker/mods/ic2/expand/IngredientExpansion.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.expand; @@ -22,33 +21,37 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenExpansion("minetweaker.item.IIngredient") @ModOnly("IC2") public class IngredientExpansion { - @ZenMethod - public static IIngredient onlyIC2ChargeAtLeast(IIngredient ingredient, final int charge) { - return ingredient.only(new IItemCondition() { - @Override - public boolean matches(IItemStack stack) { - return ItemExpansion.getIC2Charge(stack) >= charge; - } - }); - } - - @ZenMethod - public static IIngredient onlyIC2ChargeAtMost(IIngredient ingredient, final int charge) { - return ingredient.only(new IItemCondition() { - @Override - public boolean matches(IItemStack stack) { - return ItemExpansion.getIC2Charge(stack) <= charge; - } - }); - } - - @ZenMethod - public static IIngredient transformIC2Discharge(IIngredient ingredient, final int amount) { - return ingredient.transform(new IItemTransformer() { - @Override - public IItemStack transform(IItemStack item, IPlayer byPlayer) { - return ItemExpansion.ic2Discharge(item, amount, 0).withAmount(item.getAmount() + 1); - } - }); - } + + @ZenMethod + public static IIngredient onlyIC2ChargeAtLeast(IIngredient ingredient, final int charge) { + return ingredient.only(new IItemCondition() { + + @Override + public boolean matches(IItemStack stack) { + return ItemExpansion.getIC2Charge(stack) >= charge; + } + }); + } + + @ZenMethod + public static IIngredient onlyIC2ChargeAtMost(IIngredient ingredient, final int charge) { + return ingredient.only(new IItemCondition() { + + @Override + public boolean matches(IItemStack stack) { + return ItemExpansion.getIC2Charge(stack) <= charge; + } + }); + } + + @ZenMethod + public static IIngredient transformIC2Discharge(IIngredient ingredient, final int amount) { + return ingredient.transform(new IItemTransformer() { + + @Override + public IItemStack transform(IItemStack item, IPlayer byPlayer) { + return ItemExpansion.ic2Discharge(item, amount, 0).withAmount(item.getAmount() + 1); + } + }); + } } diff --git a/src/main/java/minetweaker/mods/ic2/expand/ItemExpansion.java b/src/main/java/minetweaker/mods/ic2/expand/ItemExpansion.java index cf26337..849ccde 100644 --- a/src/main/java/minetweaker/mods/ic2/expand/ItemExpansion.java +++ b/src/main/java/minetweaker/mods/ic2/expand/ItemExpansion.java @@ -1,17 +1,20 @@ package minetweaker.mods.ic2.expand; -import ic2.api.item.ElectricItem; -import ic2.api.item.IElectricItem; -import minetweaker.annotations.ModOnly; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + +import minetweaker.annotations.ModOnly; import minetweaker.api.item.IItemStack; + import net.minecraft.item.Item; import net.minecraft.item.ItemStack; + import stanhebben.zenscript.annotations.Optional; import stanhebben.zenscript.annotations.ZenExpansion; import stanhebben.zenscript.annotations.ZenGetter; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.item.ElectricItem; +import ic2.api.item.IElectricItem; /** * @@ -20,122 +23,123 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenExpansion("minecraft.item.IItemStack") @ModOnly("IC2") public class ItemExpansion { - /** - * Gets the charge level of this item. - * - * @param stack target - * @return charge level - */ - @ZenGetter("ic2getCharge") - public static double getIC2Charge(IItemStack stack) { - return ElectricItem.manager.getCharge(getItemStack(stack)); - } - - /** - * Gets the tier level of this item. - * - * @param stack target - * @return tier level - */ - @ZenGetter("ic2tier") - public static int getIC2Tier(IItemStack stack) { - ItemStack iStack = getItemStack(stack); - if (iStack.getItem() instanceof IElectricItem) { - return ((IElectricItem) iStack.getItem()).getTier(iStack); - } else { - return 0; - } - } - - /** - * Gets the transfer limit of the specified stack. - * - * @param stack target - * @return - */ - @ZenGetter("ic2transferLimit") - public static double getIC2TransferLimit(IItemStack stack) { - ItemStack iStack = getItemStack(stack); - if (iStack.getItem() instanceof IElectricItem) { - return ((IElectricItem) iStack.getItem()).getTransferLimit(iStack); - } else { - return 0; - } - } - - /** - * Gets the fully charged IC2 item. - * - * @param stack target - * @return charged item - */ - @ZenGetter("ic2charged") - public static IItemStack getIC2Charged(IItemStack stack) { - ItemStack iStack = getItemStack(stack); - if (iStack.getItem() instanceof IElectricItem) { - IElectricItem eItem = (IElectricItem) iStack.getItem(); - Item item = eItem.getChargedItem(iStack); - ItemStack stack2 = new ItemStack(item, 1, 0); - ElectricItem.manager.charge(stack2, eItem.getMaxCharge(stack2), eItem.getTier(stack2), true, false); - return getIItemStack(stack2); - } else { - return null; - } - } - - /** - * Gets the fully discharged IC2 item. - * - * @param stack target - * @return discharged item - */ - @ZenGetter("ic2discharged") - public static IItemStack getIC2Discharged(IItemStack stack) { - ItemStack iStack = getItemStack(stack); - if (iStack.getItem() instanceof IElectricItem) { - IElectricItem eItem = (IElectricItem) iStack.getItem(); - Item item = eItem.getEmptyItem(iStack); - return getItemStack(item, 1, 0); - } else { - return null; - } - } - - /** - * Charges the item with the specified amount and returns the charged item. - * - * @param stack target - * @param amount charge amount - * @param tier charge tier - * @return charged item - */ - @ZenMethod("ic2charge") - public static IItemStack ic2Charge(IItemStack stack, double amount, @Optional int tier) { - if (tier == 0) { - tier = getIC2Tier(stack); - } - - ItemStack iStack = getItemStack(stack).copy(); - ElectricItem.manager.charge(iStack, amount, tier, true, false); - return getIItemStack(iStack); - } - - /** - * Discharges the item with the specified amount and returns the discharged item. - * - * @param stack target - * @param amount discharge amount - * @param tier charge tier - * @return discharged item - */ - @ZenMethod("ic2discharge") - public static IItemStack ic2Discharge(IItemStack stack, int amount, @Optional int tier) { - if (tier == 0) { - tier = getIC2Tier(stack); - } - - ItemStack iStack = getItemStack(stack).copy(); - ElectricItem.manager.discharge(iStack, amount, tier, true, false, false); - return getIItemStack(iStack); - } + + /** + * Gets the charge level of this item. + * + * @param stack target + * @return charge level + */ + @ZenGetter("ic2getCharge") + public static double getIC2Charge(IItemStack stack) { + return ElectricItem.manager.getCharge(getItemStack(stack)); + } + + /** + * Gets the tier level of this item. + * + * @param stack target + * @return tier level + */ + @ZenGetter("ic2tier") + public static int getIC2Tier(IItemStack stack) { + ItemStack iStack = getItemStack(stack); + if (iStack.getItem() instanceof IElectricItem) { + return ((IElectricItem) iStack.getItem()).getTier(iStack); + } else { + return 0; + } + } + + /** + * Gets the transfer limit of the specified stack. + * + * @param stack target + * @return + */ + @ZenGetter("ic2transferLimit") + public static double getIC2TransferLimit(IItemStack stack) { + ItemStack iStack = getItemStack(stack); + if (iStack.getItem() instanceof IElectricItem) { + return ((IElectricItem) iStack.getItem()).getTransferLimit(iStack); + } else { + return 0; + } + } + + /** + * Gets the fully charged IC2 item. + * + * @param stack target + * @return charged item + */ + @ZenGetter("ic2charged") + public static IItemStack getIC2Charged(IItemStack stack) { + ItemStack iStack = getItemStack(stack); + if (iStack.getItem() instanceof IElectricItem) { + IElectricItem eItem = (IElectricItem) iStack.getItem(); + Item item = eItem.getChargedItem(iStack); + ItemStack stack2 = new ItemStack(item, 1, 0); + ElectricItem.manager.charge(stack2, eItem.getMaxCharge(stack2), eItem.getTier(stack2), true, false); + return getIItemStack(stack2); + } else { + return null; + } + } + + /** + * Gets the fully discharged IC2 item. + * + * @param stack target + * @return discharged item + */ + @ZenGetter("ic2discharged") + public static IItemStack getIC2Discharged(IItemStack stack) { + ItemStack iStack = getItemStack(stack); + if (iStack.getItem() instanceof IElectricItem) { + IElectricItem eItem = (IElectricItem) iStack.getItem(); + Item item = eItem.getEmptyItem(iStack); + return getItemStack(item, 1, 0); + } else { + return null; + } + } + + /** + * Charges the item with the specified amount and returns the charged item. + * + * @param stack target + * @param amount charge amount + * @param tier charge tier + * @return charged item + */ + @ZenMethod("ic2charge") + public static IItemStack ic2Charge(IItemStack stack, double amount, @Optional int tier) { + if (tier == 0) { + tier = getIC2Tier(stack); + } + + ItemStack iStack = getItemStack(stack).copy(); + ElectricItem.manager.charge(iStack, amount, tier, true, false); + return getIItemStack(iStack); + } + + /** + * Discharges the item with the specified amount and returns the discharged item. + * + * @param stack target + * @param amount discharge amount + * @param tier charge tier + * @return discharged item + */ + @ZenMethod("ic2discharge") + public static IItemStack ic2Discharge(IItemStack stack, int amount, @Optional int tier) { + if (tier == 0) { + tier = getIC2Tier(stack); + } + + ItemStack iStack = getItemStack(stack).copy(); + ElectricItem.manager.discharge(iStack, amount, tier, true, false, false); + return getIItemStack(iStack); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/BlastFurnace.java b/src/main/java/minetweaker/mods/ic2/machines/BlastFurnace.java index ce6b8a6..180c8e6 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/BlastFurnace.java +++ b/src/main/java/minetweaker/mods/ic2/machines/BlastFurnace.java @@ -1,25 +1,25 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; import stanhebben.zenscript.annotations.NotNull; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** * Provides access to the IC2 Blast Furnace recipes. @@ -29,43 +29,41 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.BlastFurnace") @ModOnly("IC2") public class BlastFurnace { - /** - * Adds a new recipe to the blast furnace. - * - * The recipe input can be any pattern, as long as the stack size is determined. - * The output can be any item stack. - * - * @param output recipe output - * @param ingredient recipe input - */ - @ZenMethod - public static void addRecipe( - @NotNull IItemStack output, - @NotNull IIngredient ingredient) { - if (ingredient.getAmount() < 0) { - MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); - } else { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "blast furnace", - Recipes.blastfurance, - getItemStacks(output), - null, - new IC2RecipeInput(ingredient))); - } - } - - /** - * Determines the recipe output for the given input. Will return the output - * of a single item, even if the stack contains multiple items. - * - * @param input recipe input - * @return recipe output - */ - @ZenMethod - public static IItemStack getOutput( - @NotNull IItemStack input) { - RecipeOutput output = Recipes.blastfurance.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStack(output.items.get(0)); - } + + /** + * Adds a new recipe to the blast furnace. + * + * The recipe input can be any pattern, as long as the stack size is determined. The output can be any item stack. + * + * @param output recipe output + * @param ingredient recipe input + */ + @ZenMethod + public static void addRecipe(@NotNull IItemStack output, @NotNull IIngredient ingredient) { + if (ingredient.getAmount() < 0) { + MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); + } else { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "blast furnace", + Recipes.blastfurance, + getItemStacks(output), + null, + new IC2RecipeInput(ingredient))); + } + } + + /** + * Determines the recipe output for the given input. Will return the output of a single item, even if the stack + * contains multiple items. + * + * @param input recipe input + * @return recipe output + */ + @ZenMethod + public static IItemStack getOutput(@NotNull IItemStack input) { + RecipeOutput output = Recipes.blastfurance.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStack(output.items.get(0)); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/BlockCutter.java b/src/main/java/minetweaker/mods/ic2/machines/BlockCutter.java index 06231fd..66a9a76 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/BlockCutter.java +++ b/src/main/java/minetweaker/mods/ic2/machines/BlockCutter.java @@ -1,25 +1,25 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; import stanhebben.zenscript.annotations.NotNull; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** * Provides access to the IC2 Block Cutter recipes. @@ -29,43 +29,41 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.BlockCutter") @ModOnly("IC2") public class BlockCutter { - /** - * Adds a new recipe to the block cutter. - * - * The recipe input can be any pattern, as long as the stack size is determined. - * The output can be any item stack. - * - * @param output recipe output - * @param ingredient recipe input - */ - @ZenMethod - public static void addRecipe( - @NotNull IItemStack output, - @NotNull IIngredient ingredient) { - if (ingredient.getAmount() < 0) { - MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); - } else { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "block cutter", - Recipes.blockcutter, - getItemStacks(output), - null, - new IC2RecipeInput(ingredient))); - } - } - - /** - * Determines the recipe output for the given input. Will return the output - * of a single item, even if the stack contains multiple items. - * - * @param input recipe input - * @return recipe output - */ - @ZenMethod - public static IItemStack getOutput( - @NotNull IItemStack input) { - RecipeOutput output = Recipes.blockcutter.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStack(output.items.get(0)); - } + + /** + * Adds a new recipe to the block cutter. + * + * The recipe input can be any pattern, as long as the stack size is determined. The output can be any item stack. + * + * @param output recipe output + * @param ingredient recipe input + */ + @ZenMethod + public static void addRecipe(@NotNull IItemStack output, @NotNull IIngredient ingredient) { + if (ingredient.getAmount() < 0) { + MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); + } else { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "block cutter", + Recipes.blockcutter, + getItemStacks(output), + null, + new IC2RecipeInput(ingredient))); + } + } + + /** + * Determines the recipe output for the given input. Will return the output of a single item, even if the stack + * contains multiple items. + * + * @param input recipe input + * @return recipe output + */ + @ZenMethod + public static IItemStack getOutput(@NotNull IItemStack input) { + RecipeOutput output = Recipes.blockcutter.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStack(output.items.get(0)); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/Canner.java b/src/main/java/minetweaker/mods/ic2/machines/Canner.java index 6c698be..7439cec 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/Canner.java +++ b/src/main/java/minetweaker/mods/ic2/machines/Canner.java @@ -1,24 +1,26 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeInputFluidContainer; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.MineTweakerAPI; import minetweaker.OneWayAction; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; import minetweaker.api.liquid.ILiquidStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; import minetweaker.mods.ic2.IC2RecipeInput; + import net.minecraftforge.fluids.FluidStack; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeInputFluidContainer; +import ic2.api.recipe.Recipes; /** * @@ -27,233 +29,239 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.Canner") @ModOnly("IC2") public class Canner { - @ZenMethod - public static void addBottleRecipe(IItemStack output, IIngredient container, IIngredient fill) { - MineTweakerAPI.apply(new AddBottleIngredientAction(container, fill, output)); - } - - @ZenMethod - public static void addBottleRecipe(IItemStack output, IIngredient container, ILiquidStack liquid) { - MineTweakerAPI.apply(new AddBottleLiquidAction(container, liquid, output)); - } - - @ZenMethod - public static void addEnrichRecipe(ILiquidStack output, ILiquidStack input, IIngredient additive) { - MineTweakerAPI.apply(new AddEnrichIngredientAction(input, additive, output)); - } - - @ZenMethod - public static void addEnrichRecipe(ILiquidStack output, ILiquidStack input, ILiquidStack additive) { - MineTweakerAPI.apply(new AddEnrichLiquidAction(input, additive, output)); - } - - private static class AddBottleIngredientAction extends OneWayAction { - private final IIngredient container; - private final IIngredient fill; - private final IItemStack output; - - public AddBottleIngredientAction(IIngredient container, IIngredient fill, IItemStack output) { - this.container = container; - this.fill = fill; - this.output = output; - } - - @Override - public void apply() { - Recipes.cannerBottle.addRecipe( - new IC2RecipeInput(container), - new IC2RecipeInput(fill), - getItemStack(output)); - } - @Override - public String describe() { - return "Adding canner bottle recipe " + container + " + " + fill + " => " + output; - } + @ZenMethod + public static void addBottleRecipe(IItemStack output, IIngredient container, IIngredient fill) { + MineTweakerAPI.apply(new AddBottleIngredientAction(container, fill, output)); + } - @Override - public Object getOverrideKey() { - return null; - } + @ZenMethod + public static void addBottleRecipe(IItemStack output, IIngredient container, ILiquidStack liquid) { + MineTweakerAPI.apply(new AddBottleLiquidAction(container, liquid, output)); + } - @Override - public int hashCode() { - int hash = 7; - hash = 67 * hash + (this.container != null ? this.container.hashCode() : 0); - hash = 67 * hash + (this.fill != null ? this.fill.hashCode() : 0); - hash = 67 * hash + (this.output != null ? this.output.hashCode() : 0); - return hash; - } + @ZenMethod + public static void addEnrichRecipe(ILiquidStack output, ILiquidStack input, IIngredient additive) { + MineTweakerAPI.apply(new AddEnrichIngredientAction(input, additive, output)); + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AddBottleIngredientAction other = (AddBottleIngredientAction) obj; - if (this.container != other.container && (this.container == null || !this.container.equals(other.container))) { - return false; - } - if (this.fill != other.fill && (this.fill == null || !this.fill.equals(other.fill))) { - return false; - } - if (this.output != other.output && (this.output == null || !this.output.equals(other.output))) { - return false; - } - return true; - } - } - - private static class AddBottleLiquidAction extends OneWayAction { - private final IIngredient container; - private final ILiquidStack fill; - private final IItemStack output; - - public AddBottleLiquidAction(IIngredient container, ILiquidStack fill, IItemStack output) { - this.container = container; - this.fill = fill; - this.output = output; - } + @ZenMethod + public static void addEnrichRecipe(ILiquidStack output, ILiquidStack input, ILiquidStack additive) { + MineTweakerAPI.apply(new AddEnrichLiquidAction(input, additive, output)); + } - @Override - public void apply() { - Recipes.cannerBottle.addRecipe( - new IC2RecipeInput(container), - new RecipeInputFluidContainer( - ((FluidStack) fill.getInternal()).getFluid(), - fill.getAmount()), - getItemStack(output)); - } + private static class AddBottleIngredientAction extends OneWayAction { - @Override - public String describe() { - return "Adding cannor bottle recipe " + container + " + " + fill + " => " + output; - } + private final IIngredient container; + private final IIngredient fill; + private final IItemStack output; - @Override - public Object getOverrideKey() { - return null; - } - } - - private static class AddEnrichIngredientAction extends OneWayAction { - private final ILiquidStack input; - private final IIngredient additive; - private final ILiquidStack output; - - public AddEnrichIngredientAction(ILiquidStack input, IIngredient additive, ILiquidStack output) { - this.input = input; - this.additive = additive; - this.output = output; - } + public AddBottleIngredientAction(IIngredient container, IIngredient fill, IItemStack output) { + this.container = container; + this.fill = fill; + this.output = output; + } - @Override - public void apply() { - Recipes.cannerEnrich.addRecipe((FluidStack) input.getInternal(), new IC2RecipeInput(additive), (FluidStack) output.getInternal()); - } + @Override + public void apply() { + Recipes.cannerBottle + .addRecipe(new IC2RecipeInput(container), new IC2RecipeInput(fill), getItemStack(output)); + } - @Override - public String describe() { - return "Adding canner enrich recipe " + input + " + " + additive + " => " + output; - } + @Override + public String describe() { + return "Adding canner bottle recipe " + container + " + " + fill + " => " + output; + } - @Override - public Object getOverrideKey() { - return null; - } + @Override + public Object getOverrideKey() { + return null; + } - @Override - public int hashCode() { - int hash = 7; - hash = 47 * hash + (this.input != null ? this.input.hashCode() : 0); - hash = 47 * hash + (this.additive != null ? this.additive.hashCode() : 0); - hash = 47 * hash + (this.output != null ? this.output.hashCode() : 0); - return hash; - } + @Override + public int hashCode() { + int hash = 7; + hash = 67 * hash + (this.container != null ? this.container.hashCode() : 0); + hash = 67 * hash + (this.fill != null ? this.fill.hashCode() : 0); + hash = 67 * hash + (this.output != null ? this.output.hashCode() : 0); + return hash; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AddEnrichIngredientAction other = (AddEnrichIngredientAction) obj; - if (this.input != other.input && (this.input == null || !this.input.equals(other.input))) { - return false; - } - if (this.additive != other.additive && (this.additive == null || !this.additive.equals(other.additive))) { - return false; - } - if (this.output != other.output && (this.output == null || !this.output.equals(other.output))) { - return false; - } - return true; - } - } - - private static class AddEnrichLiquidAction extends OneWayAction { - private final ILiquidStack input; - private final ILiquidStack additive; - private final ILiquidStack output; - - public AddEnrichLiquidAction(ILiquidStack input, ILiquidStack additive, ILiquidStack output) { - this.input = input; - this.additive = additive; - this.output = output; - } + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AddBottleIngredientAction other = (AddBottleIngredientAction) obj; + if (this.container != other.container + && (this.container == null || !this.container.equals(other.container))) { + return false; + } + if (this.fill != other.fill && (this.fill == null || !this.fill.equals(other.fill))) { + return false; + } + if (this.output != other.output && (this.output == null || !this.output.equals(other.output))) { + return false; + } + return true; + } + } - @Override - public void apply() { - Recipes.cannerEnrich.addRecipe( - (FluidStack) input.getInternal(), new RecipeInputFluidContainer( - ((FluidStack) additive.getInternal()).getFluid(), - additive.getAmount()), - (FluidStack) output.getInternal()); - } + private static class AddBottleLiquidAction extends OneWayAction { - @Override - public String describe() { - return "Adding canner enrich recipe " + input + " + " + additive + " => " + output; - } + private final IIngredient container; + private final ILiquidStack fill; + private final IItemStack output; - @Override - public Object getOverrideKey() { - return null; - } + public AddBottleLiquidAction(IIngredient container, ILiquidStack fill, IItemStack output) { + this.container = container; + this.fill = fill; + this.output = output; + } - @Override - public int hashCode() { - int hash = 7; - hash = 19 * hash + (this.input != null ? this.input.hashCode() : 0); - hash = 19 * hash + (this.additive != null ? this.additive.hashCode() : 0); - hash = 19 * hash + (this.output != null ? this.output.hashCode() : 0); - return hash; - } + @Override + public void apply() { + Recipes.cannerBottle.addRecipe( + new IC2RecipeInput(container), + new RecipeInputFluidContainer(((FluidStack) fill.getInternal()).getFluid(), fill.getAmount()), + getItemStack(output)); + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AddEnrichLiquidAction other = (AddEnrichLiquidAction) obj; - if (this.input != other.input && (this.input == null || !this.input.equals(other.input))) { - return false; - } - if (this.additive != other.additive && (this.additive == null || !this.additive.equals(other.additive))) { - return false; - } - if (this.output != other.output && (this.output == null || !this.output.equals(other.output))) { - return false; - } - return true; - } - } + @Override + public String describe() { + return "Adding cannor bottle recipe " + container + " + " + fill + " => " + output; + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + private static class AddEnrichIngredientAction extends OneWayAction { + + private final ILiquidStack input; + private final IIngredient additive; + private final ILiquidStack output; + + public AddEnrichIngredientAction(ILiquidStack input, IIngredient additive, ILiquidStack output) { + this.input = input; + this.additive = additive; + this.output = output; + } + + @Override + public void apply() { + Recipes.cannerEnrich.addRecipe( + (FluidStack) input.getInternal(), + new IC2RecipeInput(additive), + (FluidStack) output.getInternal()); + } + + @Override + public String describe() { + return "Adding canner enrich recipe " + input + " + " + additive + " => " + output; + } + + @Override + public Object getOverrideKey() { + return null; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 47 * hash + (this.input != null ? this.input.hashCode() : 0); + hash = 47 * hash + (this.additive != null ? this.additive.hashCode() : 0); + hash = 47 * hash + (this.output != null ? this.output.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AddEnrichIngredientAction other = (AddEnrichIngredientAction) obj; + if (this.input != other.input && (this.input == null || !this.input.equals(other.input))) { + return false; + } + if (this.additive != other.additive && (this.additive == null || !this.additive.equals(other.additive))) { + return false; + } + if (this.output != other.output && (this.output == null || !this.output.equals(other.output))) { + return false; + } + return true; + } + } + + private static class AddEnrichLiquidAction extends OneWayAction { + + private final ILiquidStack input; + private final ILiquidStack additive; + private final ILiquidStack output; + + public AddEnrichLiquidAction(ILiquidStack input, ILiquidStack additive, ILiquidStack output) { + this.input = input; + this.additive = additive; + this.output = output; + } + + @Override + public void apply() { + Recipes.cannerEnrich.addRecipe( + (FluidStack) input.getInternal(), + new RecipeInputFluidContainer( + ((FluidStack) additive.getInternal()).getFluid(), + additive.getAmount()), + (FluidStack) output.getInternal()); + } + + @Override + public String describe() { + return "Adding canner enrich recipe " + input + " + " + additive + " => " + output; + } + + @Override + public Object getOverrideKey() { + return null; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 19 * hash + (this.input != null ? this.input.hashCode() : 0); + hash = 19 * hash + (this.additive != null ? this.additive.hashCode() : 0); + hash = 19 * hash + (this.output != null ? this.output.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AddEnrichLiquidAction other = (AddEnrichLiquidAction) obj; + if (this.input != other.input && (this.input == null || !this.input.equals(other.input))) { + return false; + } + if (this.additive != other.additive && (this.additive == null || !this.additive.equals(other.additive))) { + return false; + } + if (this.output != other.output && (this.output == null || !this.output.equals(other.output))) { + return false; + } + return true; + } + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/Compressor.java b/src/main/java/minetweaker/mods/ic2/machines/Compressor.java index 24bd1a6..4cfe7df 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/Compressor.java +++ b/src/main/java/minetweaker/mods/ic2/machines/Compressor.java @@ -1,69 +1,67 @@ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; import stanhebben.zenscript.annotations.NotNull; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** - * Provides access to the IC2 compressor recipes. Recipes can be added but not - * removed, due to IC2 API restrictions. + * Provides access to the IC2 compressor recipes. Recipes can be added but not removed, due to IC2 API restrictions. * * @author Stan Hebben */ @ZenClass("mods.ic2.Compressor") @ModOnly("IC2") public class Compressor { - /** - * Adds a new recipe to the compressor. - * - * The recipe input can be any pattern, as long as the stack size is determined. - * The output can be any item stack. - * - * @param output recipe output - * @param ingredient recipe input - */ - @ZenMethod - public static void addRecipe( - @NotNull IItemStack output, - @NotNull IIngredient ingredient) { - if (ingredient.getAmount() < 0) { - MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); - } else { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "compressor", - Recipes.compressor, - getItemStacks(output), - null, - new IC2RecipeInput(ingredient))); - } - } - - /** - * Determines the recipe output for the given input. Will return the output - * of a single item, even if the stack contains multiple items. - * - * @param input recipe input - * @return recipe output - */ - @ZenMethod - public static IItemStack getOutput( - @NotNull IItemStack input) { - RecipeOutput output = Recipes.compressor.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) { - System.out.println("No output"); - return null; - } - return getIItemStack(output.items.get(0)); - } + + /** + * Adds a new recipe to the compressor. + * + * The recipe input can be any pattern, as long as the stack size is determined. The output can be any item stack. + * + * @param output recipe output + * @param ingredient recipe input + */ + @ZenMethod + public static void addRecipe(@NotNull IItemStack output, @NotNull IIngredient ingredient) { + if (ingredient.getAmount() < 0) { + MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); + } else { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "compressor", + Recipes.compressor, + getItemStacks(output), + null, + new IC2RecipeInput(ingredient))); + } + } + + /** + * Determines the recipe output for the given input. Will return the output of a single item, even if the stack + * contains multiple items. + * + * @param input recipe input + * @return recipe output + */ + @ZenMethod + public static IItemStack getOutput(@NotNull IItemStack input) { + RecipeOutput output = Recipes.compressor.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) { + System.out.println("No output"); + return null; + } + return getIItemStack(output.items.get(0)); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/Extractor.java b/src/main/java/minetweaker/mods/ic2/machines/Extractor.java index f83590a..872ac64 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/Extractor.java +++ b/src/main/java/minetweaker/mods/ic2/machines/Extractor.java @@ -1,25 +1,25 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; import stanhebben.zenscript.annotations.NotNull; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** * Provides access to the IC2 Extractor recipes. @@ -29,43 +29,41 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.Extractor") @ModOnly("IC2") public class Extractor { - /** - * Adds a new recipe to the extractor. - * - * The recipe input can be any pattern, as long as the stack size is determined. - * The output can be any item stack. - * - * @param output recipe output - * @param ingredient recipe input - */ - @ZenMethod - public static void addRecipe( - @NotNull IItemStack output, - @NotNull IIngredient ingredient) { - if (ingredient.getAmount() < 0) { - MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); - } else { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "extractor", - Recipes.extractor, - getItemStacks(output), - null, - new IC2RecipeInput(ingredient))); - } - } - - /** - * Determines the recipe output for the given input. Will return the output - * of a single item, even if the stack contains multiple items. - * - * @param input recipe input - * @return recipe output - */ - @ZenMethod - public static IItemStack getOutput( - @NotNull IItemStack input) { - RecipeOutput output = Recipes.extractor.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStack(output.items.get(0)); - } + + /** + * Adds a new recipe to the extractor. + * + * The recipe input can be any pattern, as long as the stack size is determined. The output can be any item stack. + * + * @param output recipe output + * @param ingredient recipe input + */ + @ZenMethod + public static void addRecipe(@NotNull IItemStack output, @NotNull IIngredient ingredient) { + if (ingredient.getAmount() < 0) { + MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); + } else { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "extractor", + Recipes.extractor, + getItemStacks(output), + null, + new IC2RecipeInput(ingredient))); + } + } + + /** + * Determines the recipe output for the given input. Will return the output of a single item, even if the stack + * contains multiple items. + * + * @param input recipe input + * @return recipe output + */ + @ZenMethod + public static IItemStack getOutput(@NotNull IItemStack input) { + RecipeOutput output = Recipes.extractor.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStack(output.items.get(0)); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/FluidHeatGenerator.java b/src/main/java/minetweaker/mods/ic2/machines/FluidHeatGenerator.java index e061463..e90a68b 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/FluidHeatGenerator.java +++ b/src/main/java/minetweaker/mods/ic2/machines/FluidHeatGenerator.java @@ -1,91 +1,95 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.Recipes; import minetweaker.MineTweakerAPI; import minetweaker.OneWayAction; import minetweaker.annotations.ModOnly; import minetweaker.api.liquid.ILiquidStack; + import net.minecraftforge.fluids.FluidRegistry; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.Recipes; /** * Add a fluid to the fluid heat generator + * * @author Stan */ @ZenClass("mods.ic2.FluidHeatGenerator") @ModOnly("IC2") public class FluidHeatGenerator { - @ZenMethod - public static void addFluid(ILiquidStack liquidPerTick, int heatPerTick) { - MineTweakerAPI.apply(new AddFluidAction(liquidPerTick.getName(), liquidPerTick.getAmount(), heatPerTick)); - } - - @ZenMethod - public static boolean accepts(ILiquidStack liquid) { - return Recipes.FluidHeatGenerator.acceptsFluid(FluidRegistry.getFluid(liquid.getName())); - } - - private static class AddFluidAction extends OneWayAction { - private final String name; - private final int liquidPerTick; - private final int heatPerTick; - - public AddFluidAction(String name, int liquidPerTick, int heatPerTick) { - this.name = name; - this.liquidPerTick = liquidPerTick; - this.heatPerTick = heatPerTick; - } - - @Override - public void apply() { - Recipes.FluidHeatGenerator.addFluid(name, liquidPerTick, heatPerTick); - } - @Override - public String describe() { - return "Adding liquid " + name + " as fluid heat generator fuel"; - } + @ZenMethod + public static void addFluid(ILiquidStack liquidPerTick, int heatPerTick) { + MineTweakerAPI.apply(new AddFluidAction(liquidPerTick.getName(), liquidPerTick.getAmount(), heatPerTick)); + } - @Override - public Object getOverrideKey() { - return null; - } + @ZenMethod + public static boolean accepts(ILiquidStack liquid) { + return Recipes.FluidHeatGenerator.acceptsFluid(FluidRegistry.getFluid(liquid.getName())); + } - @Override - public int hashCode() { - int hash = 7; - hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0); - hash = 47 * hash + this.liquidPerTick; - hash = 47 * hash + this.heatPerTick; - return hash; - } + private static class AddFluidAction extends OneWayAction { - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AddFluidAction other = (AddFluidAction) obj; - if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { - return false; - } - if (this.liquidPerTick != other.liquidPerTick) { - return false; - } - if (this.heatPerTick != other.heatPerTick) { - return false; - } - return true; - } - } + private final String name; + private final int liquidPerTick; + private final int heatPerTick; + + public AddFluidAction(String name, int liquidPerTick, int heatPerTick) { + this.name = name; + this.liquidPerTick = liquidPerTick; + this.heatPerTick = heatPerTick; + } + + @Override + public void apply() { + Recipes.FluidHeatGenerator.addFluid(name, liquidPerTick, heatPerTick); + } + + @Override + public String describe() { + return "Adding liquid " + name + " as fluid heat generator fuel"; + } + + @Override + public Object getOverrideKey() { + return null; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0); + hash = 47 * hash + this.liquidPerTick; + hash = 47 * hash + this.heatPerTick; + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AddFluidAction other = (AddFluidAction) obj; + if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { + return false; + } + if (this.liquidPerTick != other.liquidPerTick) { + return false; + } + if (this.heatPerTick != other.heatPerTick) { + return false; + } + return true; + } + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/Macerator.java b/src/main/java/minetweaker/mods/ic2/machines/Macerator.java index d985d16..99f4318 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/Macerator.java +++ b/src/main/java/minetweaker/mods/ic2/machines/Macerator.java @@ -1,66 +1,64 @@ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; import stanhebben.zenscript.annotations.NotNull; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** - * Provides access to the IC2 macerator recipes. Recipes can be added but not - * removed, due to IC2 API restrictions. + * Provides access to the IC2 macerator recipes. Recipes can be added but not removed, due to IC2 API restrictions. * * @author Stan Hebben */ @ZenClass("mods.ic2.Macerator") @ModOnly("IC2") public class Macerator { - /** - * Adds a new recipe to the macerator. - * - * The recipe input can be any pattern, as long as the stack size is determined. - * The output can be any item stack. - * - * @param output recipe output - * @param ingredient recipe input - */ - @ZenMethod - public static void addRecipe( - @NotNull IItemStack output, - @NotNull IIngredient ingredient) { - if (ingredient.getAmount() < 0) { - MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); - } else { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "macerator", - Recipes.macerator, - getItemStacks(output), - null, - new IC2RecipeInput(ingredient))); - } - } - - /** - * Determines the recipe output for the given input. Will return the output - * of a single item, even if the stack contains multiple items. - * - * @param input recipe input - * @return recipe output - */ - @ZenMethod - public static IItemStack getOutput( - @NotNull IItemStack input) { - RecipeOutput output = Recipes.macerator.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStack(output.items.get(0)); - } + + /** + * Adds a new recipe to the macerator. + * + * The recipe input can be any pattern, as long as the stack size is determined. The output can be any item stack. + * + * @param output recipe output + * @param ingredient recipe input + */ + @ZenMethod + public static void addRecipe(@NotNull IItemStack output, @NotNull IIngredient ingredient) { + if (ingredient.getAmount() < 0) { + MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); + } else { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "macerator", + Recipes.macerator, + getItemStacks(output), + null, + new IC2RecipeInput(ingredient))); + } + } + + /** + * Determines the recipe output for the given input. Will return the output of a single item, even if the stack + * contains multiple items. + * + * @param input recipe input + * @return recipe output + */ + @ZenMethod + public static IItemStack getOutput(@NotNull IItemStack input) { + RecipeOutput output = Recipes.macerator.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStack(output.items.get(0)); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/MatterAmplifier.java b/src/main/java/minetweaker/mods/ic2/machines/MatterAmplifier.java index 1a63967..24a4e1d 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/MatterAmplifier.java +++ b/src/main/java/minetweaker/mods/ic2/machines/MatterAmplifier.java @@ -1,21 +1,22 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.Recipes; import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; + import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.Recipes; /** * @@ -24,12 +25,19 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.MatterAmplifier") @ModOnly("IC2") public class MatterAmplifier { - private MatterAmplifier() {} - - @ZenMethod - public static void setAmplifier(IIngredient item, int amplifier) { - NBTTagCompound data = new NBTTagCompound(); - data.setInteger("amplification", amplifier); - MineTweakerAPI.apply(new MachineAddRecipeAction("matter amplifier", Recipes.matterAmplifier, new ItemStack[0], data, new IC2RecipeInput(item))); - } + + private MatterAmplifier() {} + + @ZenMethod + public static void setAmplifier(IIngredient item, int amplifier) { + NBTTagCompound data = new NBTTagCompound(); + data.setInteger("amplification", amplifier); + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "matter amplifier", + Recipes.matterAmplifier, + new ItemStack[0], + data, + new IC2RecipeInput(item))); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/MetalFormer.java b/src/main/java/minetweaker/mods/ic2/machines/MetalFormer.java index 774f081..a0b41dc 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/MetalFormer.java +++ b/src/main/java/minetweaker/mods/ic2/machines/MetalFormer.java @@ -1,24 +1,24 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** * @@ -27,89 +27,94 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.MetalFormer") @ModOnly("IC2") public class MetalFormer { - /** - * Adds an extruding recipe to the metal former. - * - * @param output output item - * @param input input item - */ - @ZenMethod - public static void addExtrudingRecipe(IItemStack output, IIngredient input) { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "metal former - extruding", - Recipes.metalformerExtruding, - getItemStacks(output), - null, - new IC2RecipeInput(input))); - } - - /** - * Gets the extruding output for the given input. - * - * @param input input item - * @return output item, or null - */ - @ZenMethod - public static IItemStack getExtrudingOutput(IItemStack input) { - RecipeOutput output = Recipes.metalformerExtruding.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStack(output.items.get(0)); - } - - /** - * Adds a rolling recipe to the metal former. - * - * @param output output item - * @param input input item - */ - @ZenMethod - public static void addRollingRecipe(IItemStack output, IIngredient input) { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "metal former - rolling", - Recipes.metalformerRolling, - getItemStacks(output), - null, - new IC2RecipeInput(input))); - } - - /** - * Gets the extruding output for the given input. - * - * @param input input item - * @return output item, or null - */ - @ZenMethod - public static IItemStack getRollingOutput(IItemStack input) { - RecipeOutput output = Recipes.metalformerRolling.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStack(output.items.get(0)); - } - /** - * Adds a extruding recipe to the metal former. - * - * @param output output item - * @param input input item - */ - @ZenMethod - public static void addCuttingRecipe(IItemStack output, IIngredient input) { - MineTweakerAPI.apply(new MachineAddRecipeAction( - "metal former - cutting", - Recipes.metalformerCutting, - getItemStacks(output), - null, - new IC2RecipeInput(input))); - } - - /** - * Gets the cutting output for the given input. - * - * @param input input item - * @return output item, or null - */ - @ZenMethod - public static IItemStack getCuttingOutput(IItemStack input) { - RecipeOutput output = Recipes.metalformerCutting.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStack(output.items.get(0)); - } + + /** + * Adds an extruding recipe to the metal former. + * + * @param output output item + * @param input input item + */ + @ZenMethod + public static void addExtrudingRecipe(IItemStack output, IIngredient input) { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "metal former - extruding", + Recipes.metalformerExtruding, + getItemStacks(output), + null, + new IC2RecipeInput(input))); + } + + /** + * Gets the extruding output for the given input. + * + * @param input input item + * @return output item, or null + */ + @ZenMethod + public static IItemStack getExtrudingOutput(IItemStack input) { + RecipeOutput output = Recipes.metalformerExtruding.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStack(output.items.get(0)); + } + + /** + * Adds a rolling recipe to the metal former. + * + * @param output output item + * @param input input item + */ + @ZenMethod + public static void addRollingRecipe(IItemStack output, IIngredient input) { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "metal former - rolling", + Recipes.metalformerRolling, + getItemStacks(output), + null, + new IC2RecipeInput(input))); + } + + /** + * Gets the extruding output for the given input. + * + * @param input input item + * @return output item, or null + */ + @ZenMethod + public static IItemStack getRollingOutput(IItemStack input) { + RecipeOutput output = Recipes.metalformerRolling.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStack(output.items.get(0)); + } + + /** + * Adds a extruding recipe to the metal former. + * + * @param output output item + * @param input input item + */ + @ZenMethod + public static void addCuttingRecipe(IItemStack output, IIngredient input) { + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "metal former - cutting", + Recipes.metalformerCutting, + getItemStacks(output), + null, + new IC2RecipeInput(input))); + } + + /** + * Gets the cutting output for the given input. + * + * @param input input item + * @return output item, or null + */ + @ZenMethod + public static IItemStack getCuttingOutput(IItemStack input) { + RecipeOutput output = Recipes.metalformerCutting.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStack(output.items.get(0)); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/OreWasher.java b/src/main/java/minetweaker/mods/ic2/machines/OreWasher.java index a0af2f9..b9a2c43 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/OreWasher.java +++ b/src/main/java/minetweaker/mods/ic2/machines/OreWasher.java @@ -1,19 +1,22 @@ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStacks; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStacks; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; + import net.minecraft.nbt.NBTTagCompound; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** * @@ -22,22 +25,24 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.OreWasher") @ModOnly("IC2") public class OreWasher { - @ZenMethod - public static void addRecipe(IItemStack[] output, IIngredient input, int millibuckets) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("amount", millibuckets); - MineTweakerAPI.apply(new MachineAddRecipeAction( - "ore washer", - Recipes.oreWashing, - getItemStacks(output), - nbt, - new IC2RecipeInput(input))); - } - - @ZenMethod - public static IItemStack[] getOutput(IItemStack input) { - RecipeOutput output = Recipes.oreWashing.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStacks(output.items); - } + + @ZenMethod + public static void addRecipe(IItemStack[] output, IIngredient input, int millibuckets) { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("amount", millibuckets); + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "ore washer", + Recipes.oreWashing, + getItemStacks(output), + nbt, + new IC2RecipeInput(input))); + } + + @ZenMethod + public static IItemStack[] getOutput(IItemStack input) { + RecipeOutput output = Recipes.oreWashing.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStacks(output.items); + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/Recycler.java b/src/main/java/minetweaker/mods/ic2/machines/Recycler.java index d7d1d29..826906b 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/Recycler.java +++ b/src/main/java/minetweaker/mods/ic2/machines/Recycler.java @@ -1,21 +1,21 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.MineTweakerAPI; import minetweaker.OneWayAction; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; import minetweaker.mods.ic2.IC2RecipeInput; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.Recipes; /** * @@ -24,58 +24,61 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.Recycler") @ModOnly("IC2") public class Recycler { - @ZenMethod - public static void addBlacklist(IIngredient ingredient) { - MineTweakerAPI.apply(new AddBlacklistAction(ingredient)); - } - - @ZenMethod - public static boolean isBlacklisted(IItemStack item) { - return Recipes.recyclerBlacklist.contains(getItemStack(item)); - } - - private static class AddBlacklistAction extends OneWayAction { - private IIngredient ingredient; - - public AddBlacklistAction(IIngredient ingredient) { - this.ingredient = ingredient; - } - @Override - public void apply() { - Recipes.recyclerBlacklist.add(new IC2RecipeInput(ingredient)); - } + @ZenMethod + public static void addBlacklist(IIngredient ingredient) { + MineTweakerAPI.apply(new AddBlacklistAction(ingredient)); + } - @Override - public String describe() { - return "Adding " + ingredient + " to the recycler blacklist"; - } + @ZenMethod + public static boolean isBlacklisted(IItemStack item) { + return Recipes.recyclerBlacklist.contains(getItemStack(item)); + } - @Override - public Object getOverrideKey() { - return null; - } + private static class AddBlacklistAction extends OneWayAction { - @Override - public int hashCode() { - int hash = 3; - hash = 29 * hash + (this.ingredient != null ? this.ingredient.hashCode() : 0); - return hash; - } + private IIngredient ingredient; - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AddBlacklistAction other = (AddBlacklistAction) obj; - if (this.ingredient != other.ingredient && (this.ingredient == null || !this.ingredient.equals(other.ingredient))) { - return false; - } - return true; - } - } + public AddBlacklistAction(IIngredient ingredient) { + this.ingredient = ingredient; + } + + @Override + public void apply() { + Recipes.recyclerBlacklist.add(new IC2RecipeInput(ingredient)); + } + + @Override + public String describe() { + return "Adding " + ingredient + " to the recycler blacklist"; + } + + @Override + public Object getOverrideKey() { + return null; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 29 * hash + (this.ingredient != null ? this.ingredient.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AddBlacklistAction other = (AddBlacklistAction) obj; + if (this.ingredient != other.ingredient + && (this.ingredient == null || !this.ingredient.equals(other.ingredient))) { + return false; + } + return true; + } + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/ScrapBox.java b/src/main/java/minetweaker/mods/ic2/machines/ScrapBox.java index 943ff5c..1f72b55 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/ScrapBox.java +++ b/src/main/java/minetweaker/mods/ic2/machines/ScrapBox.java @@ -1,19 +1,19 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.MineTweakerAPI; import minetweaker.OneWayAction; import minetweaker.annotations.ModOnly; import minetweaker.api.item.WeightedItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.Recipes; /** * @@ -22,69 +22,65 @@ import stanhebben.zenscript.annotations.ZenMethod; @ZenClass("mods.ic2.ScrapBox") @ModOnly("IC2") public class ScrapBox { - /** - * Adds an item drop. - * - * Reference scrap box chance values: - * - * 0.1: Diamond - * 0.5: Cake, Gold Helmet, Iron Ore, Gold Ore - * 1.0: Wooden tools, Soul Sand, Sign, Leather, Feather, Bone - * 1.5: Apple, Bread - * 2.0: Netherrack, Rotten Flesh - * 3.0: Grass, Gravel - * 4.0: Stick - * 5.0: Dirt, Wooden Hoe - * - * @param stack weighted item stack to add - */ - @ZenMethod - public static void addDrop(WeightedItemStack stack) { - MineTweakerAPI.apply(new AddDropAction(stack)); - } - - private static class AddDropAction extends OneWayAction { - private final WeightedItemStack stack; - - public AddDropAction(WeightedItemStack stack) { - this.stack = stack; - } - @Override - public void apply() { - Recipes.scrapboxDrops.addDrop(getItemStack(stack.getStack()), stack.getChance()); - } + /** + * Adds an item drop. + * + * Reference scrap box chance values: + * + * 0.1: Diamond 0.5: Cake, Gold Helmet, Iron Ore, Gold Ore 1.0: Wooden tools, Soul Sand, Sign, Leather, Feather, + * Bone 1.5: Apple, Bread 2.0: Netherrack, Rotten Flesh 3.0: Grass, Gravel 4.0: Stick 5.0: Dirt, Wooden Hoe + * + * @param stack weighted item stack to add + */ + @ZenMethod + public static void addDrop(WeightedItemStack stack) { + MineTweakerAPI.apply(new AddDropAction(stack)); + } - @Override - public String describe() { - return "Adding scrapbox drop " + stack.getStack(); - } + private static class AddDropAction extends OneWayAction { - @Override - public Object getOverrideKey() { - return null; - } + private final WeightedItemStack stack; - @Override - public int hashCode() { - int hash = 5; - hash = 71 * hash + (this.stack != null ? this.stack.hashCode() : 0); - return hash; - } + public AddDropAction(WeightedItemStack stack) { + this.stack = stack; + } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AddDropAction other = (AddDropAction) obj; - if (this.stack != other.stack && (this.stack == null || !this.stack.equals(other.stack))) { - return false; - } - return true; - } - } + @Override + public void apply() { + Recipes.scrapboxDrops.addDrop(getItemStack(stack.getStack()), stack.getChance()); + } + + @Override + public String describe() { + return "Adding scrapbox drop " + stack.getStack(); + } + + @Override + public Object getOverrideKey() { + return null; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 71 * hash + (this.stack != null ? this.stack.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AddDropAction other = (AddDropAction) obj; + if (this.stack != other.stack && (this.stack == null || !this.stack.equals(other.stack))) { + return false; + } + return true; + } + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/SemiFluidGenerator.java b/src/main/java/minetweaker/mods/ic2/machines/SemiFluidGenerator.java index 348713c..388a381 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/SemiFluidGenerator.java +++ b/src/main/java/minetweaker/mods/ic2/machines/SemiFluidGenerator.java @@ -1,91 +1,95 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.Recipes; import minetweaker.MineTweakerAPI; import minetweaker.OneWayAction; import minetweaker.annotations.ModOnly; import minetweaker.api.liquid.ILiquidStack; + import net.minecraftforge.fluids.FluidRegistry; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.Recipes; /** * Add a fluid to the semi-fluid generator + * * @author Stan */ @ZenClass("mods.ic2.SemiFluidGenerator") @ModOnly("IC2") public class SemiFluidGenerator { - @ZenMethod - public static void addFluid(ILiquidStack liquidPerTick, int energyPerTick) { - MineTweakerAPI.apply(new AddFluidAction(liquidPerTick.getName(), liquidPerTick.getAmount(), energyPerTick)); - } - - @ZenMethod - public static boolean accepts(ILiquidStack liquid) { - return Recipes.semiFluidGenerator.acceptsFluid(FluidRegistry.getFluid(liquid.getName())); - } - - private static class AddFluidAction extends OneWayAction { - private final String name; - private final int liquidPerTick; - private final int energyPerTick; - - public AddFluidAction(String name, int liquidPerTick, int energyPerTick) { - this.name = name; - this.liquidPerTick = liquidPerTick; - this.energyPerTick = energyPerTick; - } - - @Override - public void apply() { - Recipes.semiFluidGenerator.addFluid(name, liquidPerTick, energyPerTick); - } - @Override - public String describe() { - return "Adding liquid " + name + " as semifluid fuel"; - } + @ZenMethod + public static void addFluid(ILiquidStack liquidPerTick, int energyPerTick) { + MineTweakerAPI.apply(new AddFluidAction(liquidPerTick.getName(), liquidPerTick.getAmount(), energyPerTick)); + } - @Override - public Object getOverrideKey() { - return null; - } + @ZenMethod + public static boolean accepts(ILiquidStack liquid) { + return Recipes.semiFluidGenerator.acceptsFluid(FluidRegistry.getFluid(liquid.getName())); + } - @Override - public int hashCode() { - int hash = 7; - hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0); - hash = 47 * hash + this.liquidPerTick; - hash = 47 * hash + this.energyPerTick; - return hash; - } + private static class AddFluidAction extends OneWayAction { - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AddFluidAction other = (AddFluidAction) obj; - if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { - return false; - } - if (this.liquidPerTick != other.liquidPerTick) { - return false; - } - if (this.energyPerTick != other.energyPerTick) { - return false; - } - return true; - } - } + private final String name; + private final int liquidPerTick; + private final int energyPerTick; + + public AddFluidAction(String name, int liquidPerTick, int energyPerTick) { + this.name = name; + this.liquidPerTick = liquidPerTick; + this.energyPerTick = energyPerTick; + } + + @Override + public void apply() { + Recipes.semiFluidGenerator.addFluid(name, liquidPerTick, energyPerTick); + } + + @Override + public String describe() { + return "Adding liquid " + name + " as semifluid fuel"; + } + + @Override + public Object getOverrideKey() { + return null; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0); + hash = 47 * hash + this.liquidPerTick; + hash = 47 * hash + this.energyPerTick; + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AddFluidAction other = (AddFluidAction) obj; + if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { + return false; + } + if (this.liquidPerTick != other.liquidPerTick) { + return false; + } + if (this.energyPerTick != other.energyPerTick) { + return false; + } + return true; + } + } } diff --git a/src/main/java/minetweaker/mods/ic2/machines/ThermalCentrifuge.java b/src/main/java/minetweaker/mods/ic2/machines/ThermalCentrifuge.java index 9d7accf..f094c06 100644 --- a/src/main/java/minetweaker/mods/ic2/machines/ThermalCentrifuge.java +++ b/src/main/java/minetweaker/mods/ic2/machines/ThermalCentrifuge.java @@ -1,81 +1,85 @@ package minetweaker.mods.ic2.machines; -import ic2.api.recipe.RecipeOutput; -import ic2.api.recipe.Recipes; +import static minetweaker.api.minecraft.MineTweakerMC.getIItemStacks; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; + import minetweaker.MineTweakerAPI; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getIItemStacks; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStacks; -import net.minecraft.nbt.NBTTagCompound; import minetweaker.mods.ic2.IC2RecipeInput; import minetweaker.mods.ic2.MachineAddRecipeAction; + +import net.minecraft.nbt.NBTTagCompound; + import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; +import ic2.api.recipe.RecipeOutput; +import ic2.api.recipe.Recipes; /** - * Provides access to the IC2 compressor recipes. Recipes can be added but not - * removed, due to IC2 API restrictions. + * Provides access to the IC2 compressor recipes. Recipes can be added but not removed, due to IC2 API restrictions. * * @author Stan Hebben */ @ZenClass("mods.ic2.ThermalCentrifuge") @ModOnly("IC2") public class ThermalCentrifuge { - /** - * Adds a new recipe to the centrifuge. - * - * The recipe input can be any ingredient, as long as the stack size is determined. - * The output is an array of item stacks. - * - * @param output recipe outputs - * @param ingredient recipe input - * @param minHeat minimum centrifuge heat level - */ - @ZenMethod - public static void addRecipe(IItemStack[] output, IIngredient ingredient, int minHeat) { - if (ingredient.getAmount() < 0) { - MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); - } else { - NBTTagCompound tag = new NBTTagCompound(); - tag.setInteger("minHeat", minHeat); - MineTweakerAPI.apply(new MachineAddRecipeAction( - "thermal centrifuge", - Recipes.centrifuge, - getItemStacks(output), - tag, - new IC2RecipeInput(ingredient))); - } - } - - /** - * Adds a new recipe to the centrifuge. - * - * The recipe input can be any ingredient, as long as the stack size is determined. - * The output can be any item stack. - * - * @param output recipe output - * @param ingredient recipe input - * @param minHeat minimum centrifuge heat level - */ - @ZenMethod - public static void addRecipe(IItemStack output, IIngredient ingredient, int minHeat) { - addRecipe(new IItemStack[] { output }, ingredient, minHeat); - } - - /** - * Determines the recipe output for the given input. Will return the output - * of a single item, even if the stack contains multiple items. - * - * @param input recipe input - * @return recipe output - */ - @ZenMethod - public static IItemStack[] getOutput(IItemStack input) { - RecipeOutput output = Recipes.centrifuge.getOutputFor(getItemStack(input), false); - if (output == null || output.items.isEmpty()) return null; - return getIItemStacks(output.items); - } + + /** + * Adds a new recipe to the centrifuge. + * + * The recipe input can be any ingredient, as long as the stack size is determined. The output is an array of item + * stacks. + * + * @param output recipe outputs + * @param ingredient recipe input + * @param minHeat minimum centrifuge heat level + */ + @ZenMethod + public static void addRecipe(IItemStack[] output, IIngredient ingredient, int minHeat) { + if (ingredient.getAmount() < 0) { + MineTweakerAPI.logWarning("invalid ingredient: " + ingredient + " - stack size not known"); + } else { + NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("minHeat", minHeat); + MineTweakerAPI.apply( + new MachineAddRecipeAction( + "thermal centrifuge", + Recipes.centrifuge, + getItemStacks(output), + tag, + new IC2RecipeInput(ingredient))); + } + } + + /** + * Adds a new recipe to the centrifuge. + * + * The recipe input can be any ingredient, as long as the stack size is determined. The output can be any item + * stack. + * + * @param output recipe output + * @param ingredient recipe input + * @param minHeat minimum centrifuge heat level + */ + @ZenMethod + public static void addRecipe(IItemStack output, IIngredient ingredient, int minHeat) { + addRecipe(new IItemStack[] { output }, ingredient, minHeat); + } + + /** + * Determines the recipe output for the given input. Will return the output of a single item, even if the stack + * contains multiple items. + * + * @param input recipe input + * @return recipe output + */ + @ZenMethod + public static IItemStack[] getOutput(IItemStack input) { + RecipeOutput output = Recipes.centrifuge.getOutputFor(getItemStack(input), false); + if (output == null || output.items.isEmpty()) return null; + return getIItemStacks(output.items); + } } diff --git a/src/main/java/minetweaker/mods/nei/NEI.java b/src/main/java/minetweaker/mods/nei/NEI.java index ed53bca..a9e7da1 100644 --- a/src/main/java/minetweaker/mods/nei/NEI.java +++ b/src/main/java/minetweaker/mods/nei/NEI.java @@ -1,165 +1,170 @@ package minetweaker.mods.nei; -import codechicken.nei.api.API; -import stanhebben.zenscript.annotations.NotNull; -import stanhebben.zenscript.annotations.ZenClass; -import stanhebben.zenscript.annotations.ZenMethod; +import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.OneWayAction; import minetweaker.annotations.ModOnly; import minetweaker.api.item.IItemStack; -import static minetweaker.api.minecraft.MineTweakerMC.getItemStack; + import net.minecraft.item.ItemStack; +import stanhebben.zenscript.annotations.NotNull; +import stanhebben.zenscript.annotations.ZenClass; +import stanhebben.zenscript.annotations.ZenMethod; +import codechicken.nei.api.API; + /** * MineTweaker NEI support. * - * Enables hiding NEI items as well as adding new item stacks. These item stacks - * can then show a custom message or contain NBT data. Can be used to show - * a custom message or lore with certain items, or to provide spawnable items - * with specific NBT tags. + * Enables hiding NEI items as well as adding new item stacks. These item stacks can then show a custom message or + * contain NBT data. Can be used to show a custom message or lore with certain items, or to provide spawnable items with + * specific NBT tags. * * @author Stan Hebben */ @ZenClass("mods.nei.NEI") @ModOnly("NotEnoughItems") public class NEI { - /** - * Hides a specific item in NEI. Will take into account metadata values, if - * any. - * - * @param item item to be hidden - */ - @ZenMethod - public static void hide(@NotNull IItemStack item) { - MineTweakerAPI.apply(new NEIHideItemAction(getItemStack(item))); - } - - /** - * Adds a NEI entry. The item stack can contain damage values and NBT tags. - * - * @param stack item stack to be added - */ - @ZenMethod - public static void addEntry(@NotNull IItemStack stack) { - MineTweakerAPI.apply(new NEIAddEntryAction(getItemStack(stack))); - } - - /** - * Overrides a name in NEI. Note that this will not change the original - * display name, but it will change the way it is displayed in NEI. - * - * @param item item - * @param name item name - */ - @ZenMethod - public static void overrideName(@NotNull IItemStack item, @NotNull String name) { - MineTweakerAPI.apply(new NEIOverrideNameAction(getItemStack(item), name)); - } - - // ############################# - // ### Private inner classes ### - // ############################# - - private static class NEIAddEntryAction implements IUndoableAction { - private final ItemStack item; - public NEIAddEntryAction(ItemStack item) { - this.item = item; - } + /** + * Hides a specific item in NEI. Will take into account metadata values, if any. + * + * @param item item to be hidden + */ + @ZenMethod + public static void hide(@NotNull IItemStack item) { + MineTweakerAPI.apply(new NEIHideItemAction(getItemStack(item))); + } - @Override - public void apply() { - API.addItemListEntry(item); - } + /** + * Adds a NEI entry. The item stack can contain damage values and NBT tags. + * + * @param stack item stack to be added + */ + @ZenMethod + public static void addEntry(@NotNull IItemStack stack) { + MineTweakerAPI.apply(new NEIAddEntryAction(getItemStack(stack))); + } - @Override - public boolean canUndo() { - return true; - } + /** + * Overrides a name in NEI. Note that this will not change the original display name, but it will change the way it + * is displayed in NEI. + * + * @param item item + * @param name item name + */ + @ZenMethod + public static void overrideName(@NotNull IItemStack item, @NotNull String name) { + MineTweakerAPI.apply(new NEIOverrideNameAction(getItemStack(item), name)); + } - @Override - public void undo() { - API.hideItem(item); - } + // ############################# + // ### Private inner classes ### + // ############################# - @Override - public String describe() { - return "Adding " + item.getDisplayName() + " as NEI entry"; - } + private static class NEIAddEntryAction implements IUndoableAction { - @Override - public String describeUndo() { - return "Removing " + item.getDisplayName() + " as NEI entry"; - } + private final ItemStack item; - @Override - public Object getOverrideKey() { - return null; - } - } - - private static class NEIHideItemAction implements IUndoableAction { - private final ItemStack stack; + public NEIAddEntryAction(ItemStack item) { + this.item = item; + } - public NEIHideItemAction(ItemStack stack) { - this.stack = stack; - } + @Override + public void apply() { + API.addItemListEntry(item); + } - @Override - public void apply() { - API.hideItem(stack); - } + @Override + public boolean canUndo() { + return true; + } - @Override - public boolean canUndo() { - return true; - } + @Override + public void undo() { + API.hideItem(item); + } - @Override - public void undo() { - API.addItemListEntry(stack); - } + @Override + public String describe() { + return "Adding " + item.getDisplayName() + " as NEI entry"; + } - @Override - public String describe() { - return "Hiding " + stack.getUnlocalizedName() + " in NEI"; - } + @Override + public String describeUndo() { + return "Removing " + item.getDisplayName() + " as NEI entry"; + } - @Override - public String describeUndo() { - return "Displaying " + stack.getUnlocalizedName() + " in NEI"; - } + @Override + public Object getOverrideKey() { + return null; + } + } - @Override - public Object getOverrideKey() { - return null; - } - } - - private static class NEIOverrideNameAction extends OneWayAction { - private final ItemStack item; - private final String name; + private static class NEIHideItemAction implements IUndoableAction { - public NEIOverrideNameAction(ItemStack item, String name) { - this.item = item; - this.name = name; - } + private final ItemStack stack; - @Override - public void apply() { - API.setOverrideName(item, name); - } + public NEIHideItemAction(ItemStack stack) { + this.stack = stack; + } - @Override - public String describe() { - return "Overriding NEI item name of " + item.getUnlocalizedName() + " to " + name; - } + @Override + public void apply() { + API.hideItem(stack); + } - @Override - public Object getOverrideKey() { - return item; - } - } + @Override + public boolean canUndo() { + return true; + } + + @Override + public void undo() { + API.addItemListEntry(stack); + } + + @Override + public String describe() { + return "Hiding " + stack.getUnlocalizedName() + " in NEI"; + } + + @Override + public String describeUndo() { + return "Displaying " + stack.getUnlocalizedName() + " in NEI"; + } + + @Override + public Object getOverrideKey() { + return null; + } + } + + private static class NEIOverrideNameAction extends OneWayAction { + + private final ItemStack item; + private final String name; + + public NEIOverrideNameAction(ItemStack item, String name) { + this.item = item; + this.name = name; + } + + @Override + public void apply() { + API.setOverrideName(item, name); + } + + @Override + public String describe() { + return "Overriding NEI item name of " + item.getUnlocalizedName() + " to " + name; + } + + @Override + public Object getOverrideKey() { + return item; + } + } } diff --git a/src/main/java/minetweaker/runtime/GlobalFunctions.java b/src/main/java/minetweaker/runtime/GlobalFunctions.java index f357e7a..ec0dc6a 100644 --- a/src/main/java/minetweaker/runtime/GlobalFunctions.java +++ b/src/main/java/minetweaker/runtime/GlobalFunctions.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime; @@ -13,14 +12,14 @@ import minetweaker.MineTweakerAPI; * @author Stan */ public class GlobalFunctions { - private GlobalFunctions() { - } - public static void print(String message) { - MineTweakerAPI.logInfo(message); - } - - public static boolean isNull(Object any){ + private GlobalFunctions() {} + + public static void print(String message) { + MineTweakerAPI.logInfo(message); + } + + public static boolean isNull(Object any) { return any == null; } } diff --git a/src/main/java/minetweaker/runtime/GlobalRegistry.java b/src/main/java/minetweaker/runtime/GlobalRegistry.java index ea76318..33f9dbb 100644 --- a/src/main/java/minetweaker/runtime/GlobalRegistry.java +++ b/src/main/java/minetweaker/runtime/GlobalRegistry.java @@ -1,11 +1,15 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime; +import java.lang.annotation.*; +import java.lang.reflect.*; +import java.util.*; +import java.util.logging.*; + import minetweaker.*; import minetweaker.api.item.*; import stanhebben.zenscript.*; @@ -18,150 +22,146 @@ import stanhebben.zenscript.type.*; import stanhebben.zenscript.type.natives.*; import stanhebben.zenscript.util.*; -import java.lang.annotation.*; -import java.lang.reflect.*; -import java.util.*; -import java.util.logging.*; - /** * * @author Stan */ public class GlobalRegistry { - private static final Map globals = new HashMap(); - private static final List removers = new ArrayList(); - private static final List bracketHandlers = new ArrayList(); - private static final TypeRegistry types = new TypeRegistry(); - private static final SymbolPackage root = new SymbolPackage(""); - private static final IZenErrorLogger errors = new MyErrorLogger(); - private static final IZenCompileEnvironment environment = new MyCompileEnvironment(); - private static final Map expansions = new HashMap(); - static { - registerGlobal("print", getStaticFunction(GlobalFunctions.class, "print", String.class)); + private static final Map globals = new HashMap(); + private static final List removers = new ArrayList(); + private static final List bracketHandlers = new ArrayList(); + private static final TypeRegistry types = new TypeRegistry(); + private static final SymbolPackage root = new SymbolPackage(""); + private static final IZenErrorLogger errors = new MyErrorLogger(); + private static final IZenCompileEnvironment environment = new MyCompileEnvironment(); + private static final Map expansions = new HashMap(); + + static { + registerGlobal("print", getStaticFunction(GlobalFunctions.class, "print", String.class)); registerGlobal("isNull", getStaticFunction(GlobalFunctions.class, "isNull", Object.class)); registerGlobal("max", getStaticFunction(Math.class, "max", int.class, int.class)); registerGlobal("min", getStaticFunction(Math.class, "min", int.class, int.class)); registerGlobal("pow", getStaticFunction(Math.class, "pow", double.class, double.class)); - } + } + public static IZenErrorLogger getErrors() { return errors; } - - private GlobalRegistry() { - } - public static void registerGlobal(String name, IZenSymbol symbol) { - if (globals.containsKey(name)) { - throw new IllegalArgumentException("symbol already exists: " + name); - } + private GlobalRegistry() {} - globals.put(name, symbol); - } + public static void registerGlobal(String name, IZenSymbol symbol) { + if (globals.containsKey(name)) { + throw new IllegalArgumentException("symbol already exists: " + name); + } - public static void registerExpansion(Class cls) { - try { - for (Annotation annotation : cls.getAnnotations()) { - if (annotation instanceof ZenExpansion) { - ZenExpansion eAnnotation = (ZenExpansion) annotation; - if (!expansions.containsKey(eAnnotation.value())) { - expansions.put(eAnnotation.value(), new TypeExpansion(eAnnotation.value())); - } - expansions.get(eAnnotation.value()).expand(cls, types); - } - } - } catch (Throwable ex) { + globals.put(name, symbol); + } + + public static void registerExpansion(Class cls) { + try { + for (Annotation annotation : cls.getAnnotations()) { + if (annotation instanceof ZenExpansion) { + ZenExpansion eAnnotation = (ZenExpansion) annotation; + if (!expansions.containsKey(eAnnotation.value())) { + expansions.put(eAnnotation.value(), new TypeExpansion(eAnnotation.value())); + } + expansions.get(eAnnotation.value()).expand(cls, types); + } + } + } catch (Throwable ex) { errors.error("Error while applying expansion", ex); ex.printStackTrace(); - } - } + } + } - public static void registerRemover(IRecipeRemover remover) { - removers.add(remover); - } + public static void registerRemover(IRecipeRemover remover) { + removers.add(remover); + } - public static void registerBracketHandler(IBracketHandler handler) { - bracketHandlers.add(handler); - } + public static void registerBracketHandler(IBracketHandler handler) { + bracketHandlers.add(handler); + } - public static void registerNativeClass(Class cls) { - //MineTweakerAPI.logInfo("Registering class: " + cls); - try { - - ZenTypeNative type = new ZenTypeNative(cls); - type.complete(types); + public static void registerNativeClass(Class cls) { + // MineTweakerAPI.logInfo("Registering class: " + cls); + try { - root.put(type.getName(), new SymbolType(type), errors); - } catch (Throwable ex) { - MineTweakerAPI.logError("Error for " + cls, ex); - ex.printStackTrace(); - } - } + ZenTypeNative type = new ZenTypeNative(cls); + type.complete(types); - public static TypeRegistry getTypeRegistry() { - return types; - } + root.put(type.getName(), new SymbolType(type), errors); + } catch (Throwable ex) { + MineTweakerAPI.logError("Error for " + cls, ex); + ex.printStackTrace(); + } + } - public static void remove(IIngredient ingredient) { - for (IRecipeRemover remover : removers) { - remover.remove(ingredient); - } - } + public static TypeRegistry getTypeRegistry() { + return types; + } - public static IZenSymbol resolveBracket(IEnvironmentGlobal environment, List tokens) { - for (IBracketHandler handler : bracketHandlers) { - IZenSymbol symbol = handler.resolve(environment, tokens); - if (symbol != null) { - return symbol; - } - } + public static void remove(IIngredient ingredient) { + for (IRecipeRemover remover : removers) { + remover.remove(ingredient); + } + } - return null; - } + public static IZenSymbol resolveBracket(IEnvironmentGlobal environment, List tokens) { + for (IBracketHandler handler : bracketHandlers) { + IZenSymbol symbol = handler.resolve(environment, tokens); + if (symbol != null) { + return symbol; + } + } - public static IZenSymbol getStaticFunction(Class cls, String name, Class... arguments) { - IJavaMethod method = JavaMethod.get(types, cls, name, arguments); - if (method == null) - return null; - return new SymbolJavaStaticMethod(method); - } + return null; + } - public static IZenSymbol getStaticField(Class cls, String name) { - try { - Field field = cls.getDeclaredField(name); - return new SymbolJavaStaticField(cls, field, types); - } catch (NoSuchFieldException ex) { - Logger.getLogger(GlobalRegistry.class.getName()).log(Level.SEVERE, null, ex); - return null; - } catch (SecurityException ex) { - Logger.getLogger(GlobalRegistry.class.getName()).log(Level.SEVERE, null, ex); - return null; - } - } + public static IZenSymbol getStaticFunction(Class cls, String name, Class... arguments) { + IJavaMethod method = JavaMethod.get(types, cls, name, arguments); + if (method == null) return null; + return new SymbolJavaStaticMethod(method); + } - public static IEnvironmentGlobal makeGlobalEnvironment(Map classes) { - return new MyGlobalEnvironment(classes); - } + public static IZenSymbol getStaticField(Class cls, String name) { + try { + Field field = cls.getDeclaredField(name); + return new SymbolJavaStaticField(cls, field, types); + } catch (NoSuchFieldException ex) { + Logger.getLogger(GlobalRegistry.class.getName()).log(Level.SEVERE, null, ex); + return null; + } catch (SecurityException ex) { + Logger.getLogger(GlobalRegistry.class.getName()).log(Level.SEVERE, null, ex); + return null; + } + } - private static class MyErrorLogger implements IZenErrorLogger { - @Override - public void error(ZenPosition position, String message) { - if (position == null) { - MineTweakerAPI.logError("system: " + message); - } else { - MineTweakerAPI.logError(position + ": " + message); - } - } + public static IEnvironmentGlobal makeGlobalEnvironment(Map classes) { + return new MyGlobalEnvironment(classes); + } + + private static class MyErrorLogger implements IZenErrorLogger { + + @Override + public void error(ZenPosition position, String message) { + if (position == null) { + MineTweakerAPI.logError("system: " + message); + } else { + MineTweakerAPI.logError(position + ": " + message); + } + } + + @Override + public void warning(ZenPosition position, String message) { + if (position == null) { + MineTweakerAPI.logWarning("system: " + message); + } else { + MineTweakerAPI.logWarning(position + ": " + message); + } + } - @Override - public void warning(ZenPosition position, String message) { - if (position == null) { - MineTweakerAPI.logWarning("system: " + message); - } else { - MineTweakerAPI.logWarning(position + ": " + message); - } - } - @Override public void info(ZenPosition position, String message) { if (position == null) { @@ -170,178 +170,180 @@ public class GlobalRegistry { MineTweakerAPI.logInfo(position + ": " + message); } } - + @Override public void error(String message) { error(null, message); } - + @Override public void error(String message, Throwable e) { error(null, message); } - + @Override public void warning(String message) { warning(null, message); } - + @Override public void info(String message) { info(null, message); } } - private static class MyCompileEnvironment implements IZenCompileEnvironment { - @Override - public IZenErrorLogger getErrorLogger() { - return errors; - } + private static class MyCompileEnvironment implements IZenCompileEnvironment { - @Override - public IZenSymbol getGlobal(String name) { - if (globals.containsKey(name)) { - return globals.get(name); - } else { - return root.get(name); - } - } + @Override + public IZenErrorLogger getErrorLogger() { + return errors; + } - @Override - public IZenSymbol getBracketed(IEnvironmentGlobal environment, List tokens) { - return resolveBracket(environment, tokens); - } + @Override + public IZenSymbol getGlobal(String name) { + if (globals.containsKey(name)) { + return globals.get(name); + } else { + return root.get(name); + } + } - @Override - public TypeRegistry getTypeRegistry() { - return types; - } + @Override + public IZenSymbol getBracketed(IEnvironmentGlobal environment, List tokens) { + return resolveBracket(environment, tokens); + } + + @Override + public TypeRegistry getTypeRegistry() { + return types; + } + + @Override + public TypeExpansion getExpansion(String type) { + return expansions.get(type); + } - @Override - public TypeExpansion getExpansion(String type) { - return expansions.get(type); - } - @Override public void setRegistry(IZenRegistry registry) { - //NO-OP + // NO-OP throw new UnsupportedOperationException("Registry is not local"); } } - private static class MyGlobalEnvironment implements IEnvironmentGlobal { - private final Map classes; - private final Map symbols; - private final ClassNameGenerator generator; + private static class MyGlobalEnvironment implements IEnvironmentGlobal { - public MyGlobalEnvironment(Map classes) { - this.classes = classes; - symbols = new HashMap(); - generator = new ClassNameGenerator(); - } + private final Map classes; + private final Map symbols; + private final ClassNameGenerator generator; - @Override - public IZenCompileEnvironment getEnvironment() { - return environment; - } + public MyGlobalEnvironment(Map classes) { + this.classes = classes; + symbols = new HashMap(); + generator = new ClassNameGenerator(); + } - @Override - public TypeExpansion getExpansion(String name) { - return expansions.get(name); - } + @Override + public IZenCompileEnvironment getEnvironment() { + return environment; + } + + @Override + public TypeExpansion getExpansion(String name) { + return expansions.get(name); + } + + @Override + public String makeClassName() { + return generator.generate(); + } - @Override - public String makeClassName() { - return generator.generate(); - } - @Override public String makeClassNameWithMiddleName(String middleName) { return generator.generateWithMiddleName(middleName); } - + @Override - public boolean containsClass(String name) { - return classes.containsKey(name); - } + public boolean containsClass(String name) { + return classes.containsKey(name); + } - @Override - public void putClass(String name, byte[] data) { - classes.put(name, data); - } + @Override + public void putClass(String name, byte[] data) { + classes.put(name, data); + } - @Override - public IPartialExpression getValue(String name, ZenPosition position) { - if (symbols.containsKey(name)) { - return symbols.get(name).instance(position); - } else if (globals.containsKey(name)) { - return globals.get(name).instance(position); - } else { - IZenSymbol pkg = root.get(name); - if (pkg == null) { - return null; - } else { - return pkg.instance(position); - } - } - } + @Override + public IPartialExpression getValue(String name, ZenPosition position) { + if (symbols.containsKey(name)) { + return symbols.get(name).instance(position); + } else if (globals.containsKey(name)) { + return globals.get(name).instance(position); + } else { + IZenSymbol pkg = root.get(name); + if (pkg == null) { + return null; + } else { + return pkg.instance(position); + } + } + } - @Override - public void putValue(String name, IZenSymbol value, ZenPosition position) { - if (symbols.containsKey(name)) { - error(position, "Value already defined in this scope: " + name); - } else { - symbols.put(name, value); - } - } + @Override + public void putValue(String name, IZenSymbol value, ZenPosition position) { + if (symbols.containsKey(name)) { + error(position, "Value already defined in this scope: " + name); + } else { + symbols.put(name, value); + } + } - @Override - public ZenType getType(Type type) { - return types.getType(type); - } + @Override + public ZenType getType(Type type) { + return types.getType(type); + } - @Override - public void error(ZenPosition position, String message) { - MineTweakerAPI.logError(position.toString() + " > " + message); - } + @Override + public void error(ZenPosition position, String message) { + MineTweakerAPI.logError(position.toString() + " > " + message); + } + + @Override + public void warning(ZenPosition position, String message) { + MineTweakerAPI.logWarning(position.toString() + " > " + message); + } - @Override - public void warning(ZenPosition position, String message) { - MineTweakerAPI.logWarning(position.toString() + " > " + message); - } - @Override public void info(ZenPosition position, String message) { MineTweakerAPI.logInfo(position.toString() + " > " + message); } - + public void error(String message) { MineTweakerAPI.logError(message); } - + @Override public void error(String message, Throwable e) { MineTweakerAPI.logError(message, e); } - + @Override public void warning(String message) { MineTweakerAPI.logWarning(message); } - + @Override public void info(String message) { MineTweakerAPI.logInfo(message); } - @Override - public Set getClassNames() { - return classes.keySet(); - } + @Override + public Set getClassNames() { + return classes.keySet(); + } - @Override - public byte[] getClass(String name) { - return classes.get(name); - } - } + @Override + public byte[] getClass(String name) { + return classes.get(name); + } + } } diff --git a/src/main/java/minetweaker/runtime/ILogger.java b/src/main/java/minetweaker/runtime/ILogger.java index 281fd3c..f2a4fdb 100644 --- a/src/main/java/minetweaker/runtime/ILogger.java +++ b/src/main/java/minetweaker/runtime/ILogger.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime; @@ -13,18 +12,19 @@ import stanhebben.zenscript.annotations.ZenMethod; * @author Stan */ public interface ILogger { - @ZenMethod - public void logCommand(String message); - @ZenMethod - public void logInfo(String message); + @ZenMethod + public void logCommand(String message); - @ZenMethod - public void logWarning(String message); + @ZenMethod + public void logInfo(String message); - @ZenMethod - public void logError(String message); + @ZenMethod + public void logWarning(String message); - @ZenMethod - public void logError(String message, Throwable exception); + @ZenMethod + public void logError(String message); + + @ZenMethod + public void logError(String message, Throwable exception); } diff --git a/src/main/java/minetweaker/runtime/IScriptIterator.java b/src/main/java/minetweaker/runtime/IScriptIterator.java index 4df6685..59b28b3 100644 --- a/src/main/java/minetweaker/runtime/IScriptIterator.java +++ b/src/main/java/minetweaker/runtime/IScriptIterator.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime; @@ -14,11 +13,12 @@ import java.io.InputStream; * @author Stan */ public interface IScriptIterator { - public String getGroupName(); - public boolean next(); + public String getGroupName(); - public String getName(); + public boolean next(); - public InputStream open() throws IOException; + public String getName(); + + public InputStream open() throws IOException; } diff --git a/src/main/java/minetweaker/runtime/IScriptProvider.java b/src/main/java/minetweaker/runtime/IScriptProvider.java index 46418ea..1fee408 100644 --- a/src/main/java/minetweaker/runtime/IScriptProvider.java +++ b/src/main/java/minetweaker/runtime/IScriptProvider.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime; @@ -13,5 +12,6 @@ import java.util.Iterator; * @author Stan */ public interface IScriptProvider { - public Iterator getScripts(); + + public Iterator getScripts(); } diff --git a/src/main/java/minetweaker/runtime/ITweaker.java b/src/main/java/minetweaker/runtime/ITweaker.java index e18fd0a..7c8cf9e 100644 --- a/src/main/java/minetweaker/runtime/ITweaker.java +++ b/src/main/java/minetweaker/runtime/ITweaker.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime; import java.util.List; + import minetweaker.IUndoableAction; import minetweaker.api.item.IIngredient; import stanhebben.zenscript.annotations.ZenClass; @@ -18,55 +18,54 @@ import stanhebben.zenscript.annotations.ZenMethod; */ @ZenClass("minetweaker.IMineTweaker") public interface ITweaker { - /** - * Retrieves the script data to be loaded. - * - * @return - */ - public byte[] getStagedScriptData(); - /** - * Executes a specified MineTweaker action. Will print a log message and - * adds the action to the undo list. - * - * @param action action to execute - */ - public void apply(IUndoableAction action); + /** + * Retrieves the script data to be loaded. + * + * @return + */ + public byte[] getStagedScriptData(); - /** - * Removes a specific item from all known recipes handlers. - * - * @param items items to remove - */ - @ZenMethod - public void remove(IIngredient items); + /** + * Executes a specified MineTweaker action. Will print a log message and adds the action to the undo list. + * + * @param action action to execute + */ + public void apply(IUndoableAction action); - /** - * Rolls back all actions performed by MineTweaker. Returns the list of - * actions that could not be rolled back (the "stuck" ones that are not - * undoable). - * - * @return stuck action list - */ - public List rollback(); + /** + * Removes a specific item from all known recipes handlers. + * + * @param items items to remove + */ + @ZenMethod + public void remove(IIngredient items); - /** - * Sets the script provider. - * - * @param provider - * @return - */ - public void setScriptProvider(IScriptProvider provider); + /** + * Rolls back all actions performed by MineTweaker. Returns the list of actions that could not be rolled back (the + * "stuck" ones that are not undoable). + * + * @return stuck action list + */ + public List rollback(); - /** - * Executes all scripts provided by the script provider. - */ - public void load(); + /** + * Sets the script provider. + * + * @param provider + * @return + */ + public void setScriptProvider(IScriptProvider provider); - /** - * Retrieves the data from the scripts that were loaded last. - * - * @return scripts data - */ - public byte[] getScriptData(); + /** + * Executes all scripts provided by the script provider. + */ + public void load(); + + /** + * Retrieves the data from the scripts that were loaded last. + * + * @return scripts data + */ + public byte[] getScriptData(); } diff --git a/src/main/java/minetweaker/runtime/MTTweaker.java b/src/main/java/minetweaker/runtime/MTTweaker.java index 278ea71..d93a5d5 100644 --- a/src/main/java/minetweaker/runtime/MTTweaker.java +++ b/src/main/java/minetweaker/runtime/MTTweaker.java @@ -1,11 +1,20 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime; +import static stanhebben.zenscript.ZenModule.compileScripts; +import static stanhebben.zenscript.ZenModule.extractClassName; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.*; +import java.util.*; + import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; @@ -16,169 +25,162 @@ import stanhebben.zenscript.ZenTokener; import stanhebben.zenscript.compiler.IEnvironmentGlobal; import stanhebben.zenscript.parser.ParseException; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.*; -import java.util.*; - -import static stanhebben.zenscript.ZenModule.compileScripts; -import static stanhebben.zenscript.ZenModule.extractClassName; - /** * * * @author Stan Hebben */ public class MTTweaker implements ITweaker { - private static final boolean DEBUG = false; - private final List actions = new ArrayList(); - private final Set wereStuck = new LinkedHashSet(); - private final Map stuckOverridable = new HashMap(); + private static final boolean DEBUG = false; - private IScriptProvider scriptProvider; - private byte[] scriptData; + private final List actions = new ArrayList(); + private final Set wereStuck = new LinkedHashSet(); + private final Map stuckOverridable = new HashMap(); - @Override - public byte[] getStagedScriptData() { - return ScriptProviderMemory.collect(scriptProvider); - } + private IScriptProvider scriptProvider; + private byte[] scriptData; - @Override - public void apply(IUndoableAction action) { - MineTweakerAPI.logInfo(action.describe()); + @Override + public byte[] getStagedScriptData() { + return ScriptProviderMemory.collect(scriptProvider); + } - Object overrideKey = action.getOverrideKey(); - if (wereStuck.contains(action)) { - MineTweakerAPI.logInfo("WAS STUCK"); - wereStuck.remove(action); + @Override + public void apply(IUndoableAction action) { + MineTweakerAPI.logInfo(action.describe()); - if (overrideKey != null) { - stuckOverridable.remove(overrideKey); - } - } else { - if (overrideKey != null && stuckOverridable.containsKey(overrideKey)) { - wereStuck.remove(stuckOverridable.get(overrideKey)); - stuckOverridable.remove(overrideKey); - } + Object overrideKey = action.getOverrideKey(); + if (wereStuck.contains(action)) { + MineTweakerAPI.logInfo("WAS STUCK"); + wereStuck.remove(action); - action.apply(); - } + if (overrideKey != null) { + stuckOverridable.remove(overrideKey); + } + } else { + if (overrideKey != null && stuckOverridable.containsKey(overrideKey)) { + wereStuck.remove(stuckOverridable.get(overrideKey)); + stuckOverridable.remove(overrideKey); + } - actions.add(action); - } + action.apply(); + } - @Override - public void remove(IIngredient items) { - GlobalRegistry.remove(items); - } + actions.add(action); + } - @Override - public List rollback() { - // Note: Requires a OnRollback event to be fired. If this is called from MineTweakerImplementationAPI it's handled there. - List stuck = new ArrayList<>(); - for (int i = actions.size() - 1; i >= 0; i--) { - IUndoableAction action = actions.get(i); - if (action.canUndo()) { - MineTweakerAPI.logInfo(action.describeUndo()); - action.undo(); - } else { - MineTweakerAPI.logInfo("[Stuck] 1 " + action.describe()); + @Override + public void remove(IIngredient items) { + GlobalRegistry.remove(items); + } + + @Override + public List rollback() { + // Note: Requires a OnRollback event to be fired. If this is called from MineTweakerImplementationAPI it's + // handled there. + List stuck = new ArrayList<>(); + for (int i = actions.size() - 1; i >= 0; i--) { + IUndoableAction action = actions.get(i); + if (action.canUndo()) { + MineTweakerAPI.logInfo(action.describeUndo()); + action.undo(); + } else { + MineTweakerAPI.logInfo("[Stuck] 1 " + action.describe()); MineTweakerAPI.logInfo("[Stuck] 2 " + action.describeUndo()); MineTweakerAPI.logInfo("[Stuck] 3 " + action.toString()); stuck.add(0, action); - wereStuck.add(action); + wereStuck.add(action); - Object overrideKey = action.getOverrideKey(); - if (overrideKey != null) { - stuckOverridable.put(overrideKey, action); - } - } - } - actions.clear(); - return stuck; - } + Object overrideKey = action.getOverrideKey(); + if (overrideKey != null) { + stuckOverridable.put(overrideKey, action); + } + } + } + actions.clear(); + return stuck; + } - @Override - public void setScriptProvider(IScriptProvider provider) { - scriptProvider = provider; - } + @Override + public void setScriptProvider(IScriptProvider provider) { + scriptProvider = provider; + } - @Override - public void load() { - ZenModule.loadedClasses.clear(); - System.out.println("Loading scripts"); + @Override + public void load() { + ZenModule.loadedClasses.clear(); + System.out.println("Loading scripts"); - scriptData = ScriptProviderMemory.collect(scriptProvider); - Set executed = new HashSet<>(); + scriptData = ScriptProviderMemory.collect(scriptProvider); + Set executed = new HashSet<>(); - Iterator scripts = scriptProvider.getScripts(); - while (scripts.hasNext()) { - IScriptIterator script = scripts.next(); + Iterator scripts = scriptProvider.getScripts(); + while (scripts.hasNext()) { + IScriptIterator script = scripts.next(); - if (!executed.contains(script.getGroupName())) { - executed.add(script.getGroupName()); + if (!executed.contains(script.getGroupName())) { + executed.add(script.getGroupName()); - Map classes = new HashMap<>(); - IEnvironmentGlobal environmentGlobal = GlobalRegistry.makeGlobalEnvironment(classes); + Map classes = new HashMap<>(); + IEnvironmentGlobal environmentGlobal = GlobalRegistry.makeGlobalEnvironment(classes); - List files = new ArrayList<>(); + List files = new ArrayList<>(); - while (script.next()) { - Reader reader = null; - try { - reader = new InputStreamReader(new BufferedInputStream(script.open()), StandardCharsets.UTF_8); + while (script.next()) { + Reader reader = null; + try { + reader = new InputStreamReader(new BufferedInputStream(script.open()), StandardCharsets.UTF_8); - String filename = script.getName(); - String className = extractClassName(filename); + String filename = script.getName(); + String className = extractClassName(filename); - ZenTokener parser = new ZenTokener(reader, environmentGlobal.getEnvironment(), filename, false); - ZenParsedFile pfile = new ZenParsedFile(filename, className, parser, environmentGlobal); - files.add(pfile); - } catch (IOException ex) { - MineTweakerAPI.logError("Could not load script " + script.getName() + ": " + ex.getMessage()); - } catch (ParseException ex) { - // ex.printStackTrace(); - MineTweakerAPI.logError("Error parsing " + ex.getFile().getFileName() + ":" + ex.getLine() + " -- " + ex.getExplanation()); - } catch (Exception ex) { - MineTweakerAPI.logError("Error loading " + script.getName() + ": " + ex.toString(), ex); - } + ZenTokener parser = new ZenTokener(reader, environmentGlobal.getEnvironment(), filename, false); + ZenParsedFile pfile = new ZenParsedFile(filename, className, parser, environmentGlobal); + files.add(pfile); + } catch (IOException ex) { + MineTweakerAPI.logError("Could not load script " + script.getName() + ": " + ex.getMessage()); + } catch (ParseException ex) { + // ex.printStackTrace(); + MineTweakerAPI.logError( + "Error parsing " + ex.getFile() + .getFileName() + ":" + ex.getLine() + " -- " + ex.getExplanation()); + } catch (Exception ex) { + MineTweakerAPI.logError("Error loading " + script.getName() + ": " + ex.toString(), ex); + } - if (reader != null) { - try { - reader.close(); - } catch (IOException ignored) { - } - } - } + if (reader != null) { + try { + reader.close(); + } catch (IOException ignored) {} + } + } - try { - String filename = script.getGroupName(); - System.out.println("MineTweaker: Loading " + filename); - compileScripts(filename, files, environmentGlobal, DEBUG); + try { + String filename = script.getGroupName(); + System.out.println("MineTweaker: Loading " + filename); + compileScripts(filename, files, environmentGlobal, DEBUG); - // execute scripts - ZenModule module = new ZenModule(classes, MineTweakerAPI.class.getClassLoader()); - module.getMain().run(); - } catch (Throwable ex) { - MineTweakerAPI.logError("Error executing " + script.getGroupName() + ": " + ex.getMessage(), ex); - } - } - } + // execute scripts + ZenModule module = new ZenModule(classes, MineTweakerAPI.class.getClassLoader()); + module.getMain().run(); + } catch (Throwable ex) { + MineTweakerAPI.logError("Error executing " + script.getGroupName() + ": " + ex.getMessage(), ex); + } + } + } - if (wereStuck.size() > 0) { - MineTweakerAPI.logWarning(Integer.toString(wereStuck.size()) + " modifications were stuck"); - for (IUndoableAction action : wereStuck) { - MineTweakerAPI.logInfo("Stuck: " + action.describe()); - } - } - } + if (wereStuck.size() > 0) { + MineTweakerAPI.logWarning(Integer.toString(wereStuck.size()) + " modifications were stuck"); + for (IUndoableAction action : wereStuck) { + MineTweakerAPI.logInfo("Stuck: " + action.describe()); + } + } + } - @Override - public byte[] getScriptData() { - return scriptData; - } + @Override + public byte[] getScriptData() { + return scriptData; + } } diff --git a/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java b/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java index b57bd7a..450819e 100644 --- a/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java +++ b/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime.providers; @@ -14,6 +13,7 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; + import minetweaker.runtime.IScriptIterator; /** @@ -21,53 +21,54 @@ import minetweaker.runtime.IScriptIterator; * @author Stan */ public class ScriptIteratorDirectory implements IScriptIterator { - private final File directory; - private Iterator contents; - private File current; - public ScriptIteratorDirectory(File directory) { - this.directory = directory; + private final File directory; + private Iterator contents; + private File current; - File scriptDir = new File(directory, "scripts"); - List contentsList = new ArrayList(); - if (scriptDir.exists()) { - iterate(scriptDir, contentsList); - } - contents = contentsList.iterator(); - } + public ScriptIteratorDirectory(File directory) { + this.directory = directory; - @Override - public String getGroupName() { - return directory.getName(); - } + File scriptDir = new File(directory, "scripts"); + List contentsList = new ArrayList(); + if (scriptDir.exists()) { + iterate(scriptDir, contentsList); + } + contents = contentsList.iterator(); + } - @Override - public boolean next() { - if (contents.hasNext()) { - current = contents.next(); - return true; - } else { - return false; - } - } + @Override + public String getGroupName() { + return directory.getName(); + } - @Override - public String getName() { - return current.getAbsolutePath().substring(directory.getAbsolutePath().length()); - } + @Override + public boolean next() { + if (contents.hasNext()) { + current = contents.next(); + return true; + } else { + return false; + } + } - @Override - public InputStream open() throws IOException { - return new BufferedInputStream(new FileInputStream(current)); - } + @Override + public String getName() { + return current.getAbsolutePath().substring(directory.getAbsolutePath().length()); + } - private static void iterate(File directory, List contentsList) { - for (File file : directory.listFiles()) { - if (file.isDirectory()) { - iterate(file, contentsList); - } else if (file.isFile() && file.getName().endsWith(".zs")) { - contentsList.add(file); - } - } - } + @Override + public InputStream open() throws IOException { + return new BufferedInputStream(new FileInputStream(current)); + } + + private static void iterate(File directory, List contentsList) { + for (File file : directory.listFiles()) { + if (file.isDirectory()) { + iterate(file, contentsList); + } else if (file.isFile() && file.getName().endsWith(".zs")) { + contentsList.add(file); + } + } + } } diff --git a/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java b/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java index 086b44e..834b7c0 100644 --- a/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java +++ b/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime.providers; @@ -11,6 +10,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; + import minetweaker.runtime.IScriptIterator; /** @@ -18,35 +18,36 @@ import minetweaker.runtime.IScriptIterator; * @author Stan */ public class ScriptIteratorSingle implements IScriptIterator { - private final File file; - private boolean first = true; - public ScriptIteratorSingle(File file) { - this.file = file; - } + private final File file; + private boolean first = true; - @Override - public String getGroupName() { - return file.getName(); - } + public ScriptIteratorSingle(File file) { + this.file = file; + } - @Override - public boolean next() { - if (first) { - first = false; - return true; - } else { - return false; - } - } + @Override + public String getGroupName() { + return file.getName(); + } - @Override - public String getName() { - return file.getName(); - } + @Override + public boolean next() { + if (first) { + first = false; + return true; + } else { + return false; + } + } - @Override - public InputStream open() throws IOException { - return new BufferedInputStream(new FileInputStream(file)); - } + @Override + public String getName() { + return file.getName(); + } + + @Override + public InputStream open() throws IOException { + return new BufferedInputStream(new FileInputStream(file)); + } } diff --git a/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java b/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java index 9cb87be..def3871 100644 --- a/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java +++ b/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime.providers; @@ -15,6 +14,7 @@ import java.util.Iterator; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import minetweaker.runtime.IScriptIterator; /** @@ -22,49 +22,50 @@ import minetweaker.runtime.IScriptIterator; * @author Stan */ public class ScriptIteratorZip implements IScriptIterator { - private final File file; - private final ZipFile zipFile; - private final Iterator entries; - private ZipEntry current; - public ScriptIteratorZip(File file) throws IOException { - this.file = file; + private final File file; + private final ZipFile zipFile; + private final Iterator entries; + private ZipEntry current; - zipFile = new ZipFile(file); - List entriesList = new ArrayList(); - Enumeration original = zipFile.entries(); - while (original.hasMoreElements()) { - ZipEntry entry = original.nextElement(); - if (entry.getName().startsWith("scripts/") && entry.getName().endsWith(".zs")) { - entriesList.add(entry); - } - } + public ScriptIteratorZip(File file) throws IOException { + this.file = file; - entries = entriesList.iterator(); - } + zipFile = new ZipFile(file); + List entriesList = new ArrayList(); + Enumeration original = zipFile.entries(); + while (original.hasMoreElements()) { + ZipEntry entry = original.nextElement(); + if (entry.getName().startsWith("scripts/") && entry.getName().endsWith(".zs")) { + entriesList.add(entry); + } + } - @Override - public String getGroupName() { - return file.getName().substring(0, file.getName().lastIndexOf('.')); - } + entries = entriesList.iterator(); + } - @Override - public boolean next() { - if (entries.hasNext()) { - current = entries.next(); - return true; - } else { - return false; - } - } + @Override + public String getGroupName() { + return file.getName().substring(0, file.getName().lastIndexOf('.')); + } - @Override - public String getName() { - return current.getName().substring("scripts/".length()); - } + @Override + public boolean next() { + if (entries.hasNext()) { + current = entries.next(); + return true; + } else { + return false; + } + } - @Override - public InputStream open() throws IOException { - return zipFile.getInputStream(current); - } + @Override + public String getName() { + return current.getName().substring("scripts/".length()); + } + + @Override + public InputStream open() throws IOException { + return zipFile.getInputStream(current); + } } diff --git a/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java b/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java index 4d530be..834e2b3 100644 --- a/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java +++ b/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime.providers; @@ -9,6 +8,7 @@ package minetweaker.runtime.providers; import java.util.HashSet; import java.util.Iterator; import java.util.Set; + import minetweaker.runtime.IScriptIterator; import minetweaker.runtime.IScriptProvider; @@ -17,74 +17,74 @@ import minetweaker.runtime.IScriptProvider; * @author Stan Hebben */ public class ScriptProviderCascade implements IScriptProvider { - private final IScriptProvider[] providers; - public ScriptProviderCascade(IScriptProvider... providers) { - this.providers = providers; - } + private final IScriptProvider[] providers; - @Override - public Iterator getScripts() { - return new MyScripterator(); - } + public ScriptProviderCascade(IScriptProvider... providers) { + this.providers = providers; + } - private class MyScripterator implements Iterator { - private final Set executed = new HashSet(); + @Override + public Iterator getScripts() { + return new MyScripterator(); + } - private int currentIndex = providers.length - 1; - private Iterator current; - private IScriptIterator currentValue; + private class MyScripterator implements Iterator { - public MyScripterator() { - currentIndex = providers.length - 1; - current = providers[currentIndex].getScripts(); + private final Set executed = new HashSet(); - advance(); - } + private int currentIndex = providers.length - 1; + private Iterator current; + private IScriptIterator currentValue; - @Override - public boolean hasNext() { - return currentIndex >= 0; - } + public MyScripterator() { + currentIndex = providers.length - 1; + current = providers[currentIndex].getScripts(); - @Override - public IScriptIterator next() { - IScriptIterator result = currentValue; - executed.add(result.getGroupName()); + advance(); + } - advance(); + @Override + public boolean hasNext() { + return currentIndex >= 0; + } - return result; - } + @Override + public IScriptIterator next() { + IScriptIterator result = currentValue; + executed.add(result.getGroupName()); - private void advance() { - do { - while (!current.hasNext()) { - currentIndex--; - if (currentIndex < 0) - return; + advance(); - current = providers[currentIndex].getScripts(); - } - if (currentIndex < 0) - break; + return result; + } - currentValue = current.next(); - } while (executed.contains(currentValue.getGroupName()) && hasNext()); - } + private void advance() { + do { + while (!current.hasNext()) { + currentIndex--; + if (currentIndex < 0) return; - @Override - public void remove() { - throw new UnsupportedOperationException("Not supported yet."); // To - // change - // body - // of - // generated - // methods, - // choose - // Tools - // | - // Templates. - } - } + current = providers[currentIndex].getScripts(); + } + if (currentIndex < 0) break; + + currentValue = current.next(); + } while (executed.contains(currentValue.getGroupName()) && hasNext()); + } + + @Override + public void remove() { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. + } + } } diff --git a/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java b/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java index f1706d3..5537e64 100644 --- a/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java +++ b/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java @@ -1,14 +1,10 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime.providers; -import minetweaker.runtime.IScriptIterator; -import minetweaker.runtime.IScriptProvider; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -18,72 +14,78 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; +import minetweaker.runtime.IScriptIterator; +import minetweaker.runtime.IScriptProvider; + /** * * @author Stan */ public class ScriptProviderCustom implements IScriptProvider { - private static final Charset UTF8 = Charset.forName("UTF-8"); - private final String moduleName; - private final List scripts; + private static final Charset UTF8 = Charset.forName("UTF-8"); - public ScriptProviderCustom(String moduleName) { - this.moduleName = moduleName; - scripts = new ArrayList(); - } + private final String moduleName; + private final List scripts; - public void add(String name, byte[] content) { - scripts.add(new CustomScript(name, content)); - } + public ScriptProviderCustom(String moduleName) { + this.moduleName = moduleName; + scripts = new ArrayList(); + } - public void add(String name, String content) { - add(name, content.getBytes(UTF8)); - } + public void add(String name, byte[] content) { + scripts.add(new CustomScript(name, content)); + } - @Override - public Iterator getScripts() { + public void add(String name, String content) { + add(name, content.getBytes(UTF8)); + } - return Collections.singleton(new CustomScriptIterator()).iterator(); - } + @Override + public Iterator getScripts() { - private class CustomScript { - private final String name; - private final byte[] content; + return Collections.singleton(new CustomScriptIterator()).iterator(); + } - public CustomScript(String name, byte[] content) { - this.name = name; - this.content = content; - } - } + private class CustomScript { - private class CustomScriptIterator implements IScriptIterator { - private CustomScript current; - private final Iterator iterator = scripts.iterator(); + private final String name; + private final byte[] content; - @Override - public String getGroupName() { - return moduleName; - } + public CustomScript(String name, byte[] content) { + this.name = name; + this.content = content; + } + } - @Override - public boolean next() { - if (iterator.hasNext()) { - current = iterator.next(); - return true; - } else { - return false; - } - } + private class CustomScriptIterator implements IScriptIterator { - @Override - public String getName() { - return current.name; - } + private CustomScript current; + private final Iterator iterator = scripts.iterator(); - @Override - public InputStream open() throws IOException { - return new ByteArrayInputStream(current.content); - } - } + @Override + public String getGroupName() { + return moduleName; + } + + @Override + public boolean next() { + if (iterator.hasNext()) { + current = iterator.next(); + return true; + } else { + return false; + } + } + + @Override + public String getName() { + return current.name; + } + + @Override + public InputStream open() throws IOException { + return new ByteArrayInputStream(current.content); + } + } } diff --git a/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java b/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java index 94ea96e..b5ed855 100644 --- a/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java +++ b/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java @@ -1,28 +1,27 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime.providers; -import minetweaker.MineTweakerAPI; -import minetweaker.runtime.IScriptIterator; -import minetweaker.runtime.IScriptProvider; - import java.io.File; import java.io.IOException; import java.util.*; +import minetweaker.MineTweakerAPI; +import minetweaker.runtime.IScriptIterator; +import minetweaker.runtime.IScriptProvider; + /** * @author Stan */ public class ScriptProviderDirectory implements IScriptProvider { + private final File directory; public ScriptProviderDirectory(File directory) { - if(directory == null) - throw new IllegalArgumentException("directory cannot be null"); + if (directory == null) throw new IllegalArgumentException("directory cannot be null"); this.directory = directory; } @@ -30,31 +29,31 @@ public class ScriptProviderDirectory implements IScriptProvider { @Override public Iterator getScripts() { List scripts = new ArrayList(); - if(directory.exists()) { - for(File file : directory.listFiles()) { - if(file.isDirectory()) { + if (directory.exists()) { + for (File file : directory.listFiles()) { + if (file.isDirectory()) { scripts.add(new ScriptIteratorDirectory(file)); - } else if(file.getName().endsWith(".zs")) { + } else if (file.getName().endsWith(".zs")) { scripts.add(new ScriptIteratorSingle(file)); - } else if(file.getName().endsWith(".zip")) { + } else if (file.getName().endsWith(".zip")) { try { scripts.add(new ScriptIteratorZip(file)); - } catch(IOException ex) { + } catch (IOException ex) { MineTweakerAPI.logError("Could not load " + file.getName() + ": " + ex.getMessage()); } } } } - if(scripts.size() > 1) - scripts.sort(new Comparator() { - @Override - public int compare(IScriptIterator sc, IScriptIterator sc1) { - if(sc == null || sc1 == null) { - return -1; - } - return sc.getName().compareTo(sc1.getName()); + if (scripts.size() > 1) scripts.sort(new Comparator() { + + @Override + public int compare(IScriptIterator sc, IScriptIterator sc1) { + if (sc == null || sc1 == null) { + return -1; } - }); + return sc.getName().compareTo(sc1.getName()); + } + }); return scripts.iterator(); } } diff --git a/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java b/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java index 63159fc..cf5ad38 100644 --- a/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java +++ b/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.runtime.providers; @@ -15,175 +14,180 @@ import java.io.InputStream; import java.util.*; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; + import minetweaker.MineTweakerAPI; -import minetweaker.util.FileUtil; import minetweaker.runtime.IScriptIterator; import minetweaker.runtime.IScriptProvider; +import minetweaker.util.FileUtil; /** * * @author Stan */ public class ScriptProviderMemory implements IScriptProvider { - public static byte[] collect(IScriptProvider provider) { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - try { - DeflaterOutputStream deflater = new DeflaterOutputStream(output); - DataOutputStream deflaterData = new DataOutputStream(deflater); - Set executed = new HashSet(); - Iterator scripts = provider.getScripts(); - while (scripts.hasNext()) { - IScriptIterator script = scripts.next(); + public static byte[] collect(IScriptProvider provider) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try { + DeflaterOutputStream deflater = new DeflaterOutputStream(output); + DataOutputStream deflaterData = new DataOutputStream(deflater); + Set executed = new HashSet(); - if (!executed.contains(script.getGroupName())) { - executed.add(script.getGroupName()); + Iterator scripts = provider.getScripts(); + while (scripts.hasNext()) { + IScriptIterator script = scripts.next(); - deflaterData.writeUTF(script.getGroupName()); + if (!executed.contains(script.getGroupName())) { + executed.add(script.getGroupName()); - while (script.next()) { - String name = script.getName(); - byte[] data = FileUtil.read(script.open()); - if (data.length == 0) - continue; // skip empty files + deflaterData.writeUTF(script.getGroupName()); - deflaterData.writeUTF(name); - deflaterData.writeInt(data.length); - deflaterData.write(data); - } + while (script.next()) { + String name = script.getName(); + byte[] data = FileUtil.read(script.open()); + if (data.length == 0) continue; // skip empty files - deflaterData.writeUTF(""); - } - } + deflaterData.writeUTF(name); + deflaterData.writeInt(data.length); + deflaterData.write(data); + } - deflaterData.writeUTF(""); + deflaterData.writeUTF(""); + } + } - deflater.close(); - } catch (IOException ex) { - MineTweakerAPI.logError("Could not collect scripts: " + ex.getMessage()); - } - return output.toByteArray(); - } + deflaterData.writeUTF(""); - private final Map modules; + deflater.close(); + } catch (IOException ex) { + MineTweakerAPI.logError("Could not collect scripts: " + ex.getMessage()); + } + return output.toByteArray(); + } - public ScriptProviderMemory(byte[] scripts) { - modules = new TreeMap(); + private final Map modules; - try { - InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(scripts)); - DataInputStream inflaterData = new DataInputStream(inflater); + public ScriptProviderMemory(byte[] scripts) { + modules = new TreeMap(); - String moduleName = inflaterData.readUTF(); - while (moduleName.length() > 0) { - List files = new ArrayList(); + try { + InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(scripts)); + DataInputStream inflaterData = new DataInputStream(inflater); - String fileName = inflaterData.readUTF(); - while (fileName.length() > 0) { - byte[] data = new byte[inflaterData.readInt()]; - inflaterData.readFully(data); - files.add(new MemoryFile(fileName, data)); + String moduleName = inflaterData.readUTF(); + while (moduleName.length() > 0) { + List files = new ArrayList(); - fileName = inflaterData.readUTF(); - } - modules.put(moduleName, new MemoryModule(moduleName, files)); + String fileName = inflaterData.readUTF(); + while (fileName.length() > 0) { + byte[] data = new byte[inflaterData.readInt()]; + inflaterData.readFully(data); + files.add(new MemoryFile(fileName, data)); - moduleName = inflaterData.readUTF(); - } + fileName = inflaterData.readUTF(); + } + modules.put(moduleName, new MemoryModule(moduleName, files)); - inflaterData.close(); - } catch (IOException ex) { - MineTweakerAPI.logError("Could not load transmitted scripts: " + ex.getMessage()); - } - } + moduleName = inflaterData.readUTF(); + } - @Override - public Iterator getScripts() { - return new ProviderIterator(); - } + inflaterData.close(); + } catch (IOException ex) { + MineTweakerAPI.logError("Could not load transmitted scripts: " + ex.getMessage()); + } + } - private class ProviderIterator implements Iterator { - private final Iterator baseIterator = modules.values().iterator(); + @Override + public Iterator getScripts() { + return new ProviderIterator(); + } - @Override - public boolean hasNext() { - return baseIterator.hasNext(); - } + private class ProviderIterator implements Iterator { - @Override - public IScriptIterator next() { - return new ScriptIterator(baseIterator.next()); - } + private final Iterator baseIterator = modules.values().iterator(); - @Override - public void remove() { - throw new UnsupportedOperationException("Not supported yet."); // To - // change - // body - // of - // generated - // methods, - // choose - // Tools - // | - // Templates. - } - } + @Override + public boolean hasNext() { + return baseIterator.hasNext(); + } - private class ScriptIterator implements IScriptIterator { - private final MemoryModule module; - private final Iterator files; - private MemoryFile current; + @Override + public IScriptIterator next() { + return new ScriptIterator(baseIterator.next()); + } - public ScriptIterator(MemoryModule module) { - this.module = module; - files = module.data.iterator(); - current = null; - } + @Override + public void remove() { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. + } + } - @Override - public String getGroupName() { - return module.name; - } + private class ScriptIterator implements IScriptIterator { - @Override - public boolean next() { - if (files.hasNext()) { - current = files.next(); - return true; - } else { - return false; - } - } + private final MemoryModule module; + private final Iterator files; + private MemoryFile current; - @Override - public String getName() { - return current.name; - } + public ScriptIterator(MemoryModule module) { + this.module = module; + files = module.data.iterator(); + current = null; + } - @Override - public InputStream open() throws IOException { - return new ByteArrayInputStream(current.data); - } - } + @Override + public String getGroupName() { + return module.name; + } - private class MemoryModule { - private final String name; - private final List data; + @Override + public boolean next() { + if (files.hasNext()) { + current = files.next(); + return true; + } else { + return false; + } + } - public MemoryModule(String name, List data) { - this.name = name; - this.data = data; - } - } + @Override + public String getName() { + return current.name; + } - private class MemoryFile { - private final String name; - private final byte[] data; + @Override + public InputStream open() throws IOException { + return new ByteArrayInputStream(current.data); + } + } - public MemoryFile(String name, byte[] data) { - this.name = name; - this.data = data; - } - } + private class MemoryModule { + + private final String name; + private final List data; + + public MemoryModule(String name, List data) { + this.name = name; + this.data = data; + } + } + + private class MemoryFile { + + private final String name; + private final byte[] data; + + public MemoryFile(String name, byte[] data) { + this.name = name; + this.data = data; + } + } } diff --git a/src/main/java/minetweaker/util/ArrayUtil.java b/src/main/java/minetweaker/util/ArrayUtil.java index 618d3ce..1101783 100644 --- a/src/main/java/minetweaker/util/ArrayUtil.java +++ b/src/main/java/minetweaker/util/ArrayUtil.java @@ -1,12 +1,12 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.util; import java.util.Arrays; + import minetweaker.api.block.IBlockPattern; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemCondition; @@ -17,30 +17,31 @@ import minetweaker.api.item.IItemTransformer; * @author Stan */ public class ArrayUtil { - public static final IItemCondition[] EMPTY_CONDITIONS = new IItemCondition[0]; - public static final IItemTransformer[] EMPTY_TRANSFORMERS = new IItemTransformer[0]; - public static IItemCondition[] append(IItemCondition[] values, IItemCondition value) { - IItemCondition[] result = Arrays.copyOf(values, values.length + 1); - result[values.length] = value; - return result; - } + public static final IItemCondition[] EMPTY_CONDITIONS = new IItemCondition[0]; + public static final IItemTransformer[] EMPTY_TRANSFORMERS = new IItemTransformer[0]; - public static IItemTransformer[] append(IItemTransformer[] values, IItemTransformer value) { - IItemTransformer[] result = Arrays.copyOf(values, values.length + 1); - result[values.length] = value; - return result; - } + public static IItemCondition[] append(IItemCondition[] values, IItemCondition value) { + IItemCondition[] result = Arrays.copyOf(values, values.length + 1); + result[values.length] = value; + return result; + } - public static IIngredient[] append(IIngredient[] values, IIngredient value) { - IIngredient[] result = Arrays.copyOf(values, values.length + 1); - result[values.length] = value; - return result; - } + public static IItemTransformer[] append(IItemTransformer[] values, IItemTransformer value) { + IItemTransformer[] result = Arrays.copyOf(values, values.length + 1); + result[values.length] = value; + return result; + } - public static IBlockPattern[] append(IBlockPattern[] values, IBlockPattern value) { - IBlockPattern[] result = Arrays.copyOf(values, values.length + 1); - result[values.length] = value; - return result; - } + public static IIngredient[] append(IIngredient[] values, IIngredient value) { + IIngredient[] result = Arrays.copyOf(values, values.length + 1); + result[values.length] = value; + return result; + } + + public static IBlockPattern[] append(IBlockPattern[] values, IBlockPattern value) { + IBlockPattern[] result = Arrays.copyOf(values, values.length + 1); + result[values.length] = value; + return result; + } } diff --git a/src/main/java/minetweaker/util/CloseablePriorityList.java b/src/main/java/minetweaker/util/CloseablePriorityList.java index 80aeaa3..be2e24d 100644 --- a/src/main/java/minetweaker/util/CloseablePriorityList.java +++ b/src/main/java/minetweaker/util/CloseablePriorityList.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.util; @@ -14,17 +13,17 @@ import java.util.Iterator; * @author Stan */ public class CloseablePriorityList implements Iterable { + private CloseableEntry first; /** - * Adds a new item to the list. The new item will be inserted at the head of - * the list. + * Adds a new item to the list. The new item will be inserted at the head of the list. * * @param value * @return */ public Closeable add(T value) { - if(first == null) { + if (first == null) { first = new CloseableEntry(value); } else { CloseableEntry entry = new CloseableEntry(value); @@ -42,6 +41,7 @@ public class CloseablePriorityList implements Iterable { } private class MyIterator implements Iterator { + private CloseableEntry current = null; @Override @@ -62,6 +62,7 @@ public class CloseablePriorityList implements Iterable { } private class CloseableEntry implements Closeable { + private final T value; private CloseableEntry next; private CloseableEntry prev; @@ -72,10 +73,10 @@ public class CloseablePriorityList implements Iterable { @Override public void close() throws IOException { - if(next != null) { + if (next != null) { next.prev = prev; } - if(prev == null) { + if (prev == null) { first = next; } else { prev.next = next; diff --git a/src/main/java/minetweaker/util/EventList.java b/src/main/java/minetweaker/util/EventList.java index 4e3e62b..37f239e 100644 --- a/src/main/java/minetweaker/util/EventList.java +++ b/src/main/java/minetweaker/util/EventList.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.util; @@ -13,79 +12,81 @@ import minetweaker.api.event.IEventHandle; * @author Stan */ public class EventList { - private EventNode first = null; - private EventNode last = null; - public void clear() { - first = last = null; - } + private EventNode first = null; + private EventNode last = null; - public IEventHandle add(IEventHandler handler) { - EventNode node = new EventNode(handler, last, null); + public void clear() { + first = last = null; + } - synchronized (this) { - if (first == null) { - first = node; - } - if (last != null) { - last.next = node; - } - last = node; - } + public IEventHandle add(IEventHandler handler) { + EventNode node = new EventNode(handler, last, null); - return node; - } + synchronized (this) { + if (first == null) { + first = node; + } + if (last != null) { + last.next = node; + } + last = node; + } - public boolean hasHandlers() { - return first != null; - } + return node; + } - public boolean isEmpty() { - return first == null; - } + public boolean hasHandlers() { + return first != null; + } - public void publish(T event) { - EventNode current = null; + public boolean isEmpty() { + return first == null; + } - synchronized (this) { - current = first; - } + public void publish(T event) { + EventNode current = null; - while (current != null) { - current.handler.handle(event); + synchronized (this) { + current = first; + } - synchronized (this) { - current = current.next; - } - } - } + while (current != null) { + current.handler.handle(event); - private class EventNode implements IEventHandle { - private final IEventHandler handler; - private EventNode next; - private EventNode prev; + synchronized (this) { + current = current.next; + } + } + } - public EventNode(IEventHandler handler, EventNode prev, EventNode next) { - this.handler = handler; - this.prev = prev; - this.next = next; - } + private class EventNode implements IEventHandle { - @Override - public void close() { - synchronized (EventList.this) { - if (prev == null) { - first = next; - } else { - prev.next = next; - } + private final IEventHandler handler; + private EventNode next; + private EventNode prev; - if (next == null) { - last = prev; - } else { - next.prev = prev; - } - } - } - } + public EventNode(IEventHandler handler, EventNode prev, EventNode next) { + this.handler = handler; + this.prev = prev; + this.next = next; + } + + @Override + public void close() { + synchronized (EventList.this) { + if (prev == null) { + first = next; + } else { + prev.next = next; + } + + if (next == null) { + last = prev; + } else { + next.prev = prev; + } + } + } + } } diff --git a/src/main/java/minetweaker/util/FileUtil.java b/src/main/java/minetweaker/util/FileUtil.java index 2b791ec..dfeaba0 100644 --- a/src/main/java/minetweaker/util/FileUtil.java +++ b/src/main/java/minetweaker/util/FileUtil.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.util; @@ -15,13 +14,14 @@ import java.io.InputStream; * @author Stan */ public class FileUtil { - public static final byte[] read(InputStream input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[65536]; - while (input.available() > 0) { - int bytesRead = input.read(buffer); - output.write(buffer, 0, bytesRead); - } - return output.toByteArray(); - } + + public static final byte[] read(InputStream input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[65536]; + while (input.available() > 0) { + int bytesRead = input.read(buffer); + output.write(buffer, 0, bytesRead); + } + return output.toByteArray(); + } } diff --git a/src/main/java/minetweaker/util/IEventHandler.java b/src/main/java/minetweaker/util/IEventHandler.java index 31a3fcf..fa9626d 100644 --- a/src/main/java/minetweaker/util/IEventHandler.java +++ b/src/main/java/minetweaker/util/IEventHandler.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.util; @@ -11,5 +10,6 @@ package minetweaker.util; * @author Stan */ public interface IEventHandler { - public void handle(T event); + + public void handle(T event); } diff --git a/src/main/java/minetweaker/util/StringUtil.java b/src/main/java/minetweaker/util/StringUtil.java index 61295e1..b14652b 100644 --- a/src/main/java/minetweaker/util/StringUtil.java +++ b/src/main/java/minetweaker/util/StringUtil.java @@ -1,7 +1,6 @@ /* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. + * To change this license header, choose License Headers in Project Properties. To change this template file, choose + * Tools | Templates and open the template in the editor. */ package minetweaker.util; @@ -13,20 +12,17 @@ import java.nio.charset.Charset; * * @author Stan */ -public class StringUtil -{ - private static final Charset UTF8 = Charset.forName("UTF-8"); +public class StringUtil { - private StringUtil() { - } + private static final Charset UTF8 = Charset.forName("UTF-8"); - public static String decodeUTF8(byte[] data) - { - return UTF8.decode(ByteBuffer.wrap(data)).toString().trim(); - } + private StringUtil() {} - public static byte[] encodeUTF8(String data) - { - return UTF8.encode(data).array(); - } + public static String decodeUTF8(byte[] data) { + return UTF8.decode(ByteBuffer.wrap(data)).toString().trim(); + } + + public static byte[] encodeUTF8(String data) { + return UTF8.encode(data).array(); + } }